1265236Sken/*-
2265236Sken * Copyright (c) 2009 Yahoo! Inc.
3265236Sken * Copyright (c) 2012-2014 LSI Corp.
4265236Sken * All rights reserved.
5265236Sken *
6265236Sken * Redistribution and use in source and binary forms, with or without
7265236Sken * modification, are permitted provided that the following conditions
8265236Sken * are met:
9265236Sken * 1. Redistributions of source code must retain the above copyright
10265236Sken *    notice, this list of conditions and the following disclaimer.
11265236Sken * 2. Redistributions in binary form must reproduce the above copyright
12265236Sken *    notice, this list of conditions and the following disclaimer in the
13265236Sken *    documentation and/or other materials provided with the distribution.
14265236Sken *
15265236Sken * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16265236Sken * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17265236Sken * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18265236Sken * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19265236Sken * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20265236Sken * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21265236Sken * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22265236Sken * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23265236Sken * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24265236Sken * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25265236Sken * SUCH DAMAGE.
26265236Sken *
27265236Sken */
28265236Sken
29265236Sken#include <sys/cdefs.h>
30265236Sken__FBSDID("$FreeBSD$");
31265236Sken
32265236Sken/* Communications core for LSI MPT2 */
33265236Sken
34265236Sken/* TODO Move headers to mprvar */
35265236Sken#include <sys/types.h>
36265236Sken#include <sys/param.h>
37265236Sken#include <sys/systm.h>
38265236Sken#include <sys/kernel.h>
39265236Sken#include <sys/selinfo.h>
40265236Sken#include <sys/lock.h>
41265236Sken#include <sys/mutex.h>
42265236Sken#include <sys/module.h>
43265236Sken#include <sys/bus.h>
44265236Sken#include <sys/conf.h>
45265236Sken#include <sys/bio.h>
46265236Sken#include <sys/malloc.h>
47265236Sken#include <sys/uio.h>
48265236Sken#include <sys/sysctl.h>
49265236Sken#include <sys/queue.h>
50265236Sken#include <sys/kthread.h>
51265236Sken#include <sys/taskqueue.h>
52265236Sken#include <sys/endian.h>
53265236Sken#include <sys/eventhandler.h>
54265236Sken
55265236Sken#include <machine/bus.h>
56265236Sken#include <machine/resource.h>
57265236Sken#include <sys/rman.h>
58265236Sken#include <sys/proc.h>
59265236Sken
60265236Sken#include <dev/pci/pcivar.h>
61265236Sken
62265236Sken#include <cam/cam.h>
63265236Sken#include <cam/scsi/scsi_all.h>
64265236Sken
65265236Sken#include <dev/mpr/mpi/mpi2_type.h>
66265236Sken#include <dev/mpr/mpi/mpi2.h>
67265236Sken#include <dev/mpr/mpi/mpi2_ioc.h>
68265236Sken#include <dev/mpr/mpi/mpi2_sas.h>
69265236Sken#include <dev/mpr/mpi/mpi2_cnfg.h>
70265236Sken#include <dev/mpr/mpi/mpi2_init.h>
71265236Sken#include <dev/mpr/mpi/mpi2_tool.h>
72265236Sken#include <dev/mpr/mpr_ioctl.h>
73265236Sken#include <dev/mpr/mprvar.h>
74265236Sken#include <dev/mpr/mpr_table.h>
75265236Sken#include <dev/mpr/mpr_sas.h>
76265236Sken
77265236Skenstatic int mpr_diag_reset(struct mpr_softc *sc, int sleep_flag);
78265236Skenstatic int mpr_init_queues(struct mpr_softc *sc);
79265236Skenstatic int mpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag);
80265236Skenstatic int mpr_transition_operational(struct mpr_softc *sc);
81265236Skenstatic int mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching);
82265236Skenstatic void mpr_iocfacts_free(struct mpr_softc *sc);
83265236Skenstatic void mpr_startup(void *arg);
84265236Skenstatic int mpr_send_iocinit(struct mpr_softc *sc);
85265236Skenstatic int mpr_alloc_queues(struct mpr_softc *sc);
86265236Skenstatic int mpr_alloc_replies(struct mpr_softc *sc);
87265236Skenstatic int mpr_alloc_requests(struct mpr_softc *sc);
88265236Skenstatic int mpr_attach_log(struct mpr_softc *sc);
89265236Skenstatic __inline void mpr_complete_command(struct mpr_softc *sc,
90265236Sken    struct mpr_command *cm);
91265236Skenstatic void mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
92265236Sken    MPI2_EVENT_NOTIFICATION_REPLY *reply);
93265236Skenstatic void mpr_config_complete(struct mpr_softc *sc,
94265236Sken    struct mpr_command *cm);
95265236Skenstatic void mpr_periodic(void *);
96265236Skenstatic int mpr_reregister_events(struct mpr_softc *sc);
97265236Skenstatic void mpr_enqueue_request(struct mpr_softc *sc,
98265236Sken    struct mpr_command *cm);
99265236Skenstatic int mpr_get_iocfacts(struct mpr_softc *sc,
100265236Sken    MPI2_IOC_FACTS_REPLY *facts);
101265236Skenstatic int mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag);
102265236SkenSYSCTL_NODE(_hw, OID_AUTO, mpr, CTLFLAG_RD, 0, "MPR Driver Parameters");
103265236Sken
104265236SkenMALLOC_DEFINE(M_MPR, "mpr", "mpr driver memory");
105265236Sken
106265236Sken/*
107265236Sken * Do a "Diagnostic Reset" aka a hard reset.  This should get the chip out of
108265236Sken * any state and back to its initialization state machine.
109265236Sken */
110265236Skenstatic char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
111265236Sken
112265236Sken/*
113265236Sken * Added this union to smoothly convert le64toh cm->cm_desc.Words.
114265236Sken * Compiler only supports unint64_t to be passed as an argument.
115265236Sken * Otherwise it will through this error:
116265236Sken * "aggregate value used where an integer was expected"
117265236Sken */
118265236Skentypedef union _reply_descriptor {
119265236Sken        u64 word;
120265236Sken        struct {
121265236Sken                u32 low;
122265236Sken                u32 high;
123265236Sken        } u;
124265236Sken}reply_descriptor,address_descriptor;
125265236Sken
126265236Sken/* Rate limit chain-fail messages to 1 per minute */
127265236Skenstatic struct timeval mpr_chainfail_interval = { 60, 0 };
128265236Sken
129265236Sken/*
130265236Sken * sleep_flag can be either CAN_SLEEP or NO_SLEEP.
131265236Sken * If this function is called from process context, it can sleep
132265236Sken * and there is no harm to sleep, in case if this fuction is called
133265236Sken * from Interrupt handler, we can not sleep and need NO_SLEEP flag set.
134265236Sken * based on sleep flags driver will call either msleep, pause or DELAY.
135265236Sken * msleep and pause are of same variant, but pause is used when mpr_mtx
136265236Sken * is not hold by driver.
137265236Sken */
138265236Skenstatic int
139265236Skenmpr_diag_reset(struct mpr_softc *sc,int sleep_flag)
140265236Sken{
141265236Sken	uint32_t reg;
142265236Sken	int i, error, tries = 0;
143265236Sken	uint8_t first_wait_done = FALSE;
144265236Sken
145265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
146265236Sken
147265236Sken	/* Clear any pending interrupts */
148265236Sken	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
149265236Sken
150265236Sken	/*
151265236Sken	 * Force NO_SLEEP for threads prohibited to sleep
152265236Sken 	 * e.a Thread from interrupt handler are prohibited to sleep.
153265236Sken 	 */
154265236Sken#if __FreeBSD_version >= 1000029
155265236Sken	if (curthread->td_no_sleeping)
156265236Sken#else //__FreeBSD_version < 1000029
157265236Sken	if (curthread->td_pflags & TDP_NOSLEEPING)
158265236Sken#endif //__FreeBSD_version >= 1000029
159265236Sken		sleep_flag = NO_SLEEP;
160265236Sken
161265236Sken	/* Push the magic sequence */
162265236Sken	error = ETIMEDOUT;
163265236Sken	while (tries++ < 20) {
164265236Sken		for (i = 0; i < sizeof(mpt2_reset_magic); i++)
165265236Sken			mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
166265236Sken			    mpt2_reset_magic[i]);
167265236Sken
168265236Sken		/* wait 100 msec */
169265236Sken		if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
170265236Sken			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
171265236Sken			    "mprdiag", hz/10);
172265236Sken		else if (sleep_flag == CAN_SLEEP)
173265236Sken			pause("mprdiag", hz/10);
174265236Sken		else
175265236Sken			DELAY(100 * 1000);
176265236Sken
177265236Sken		reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
178265236Sken		if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
179265236Sken			error = 0;
180265236Sken			break;
181265236Sken		}
182265236Sken	}
183265236Sken	if (error)
184265236Sken		return (error);
185265236Sken
186265236Sken	/* Send the actual reset.  XXX need to refresh the reg? */
187265236Sken	mpr_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET,
188265236Sken	    reg | MPI2_DIAG_RESET_ADAPTER);
189265236Sken
190265236Sken	/* Wait up to 300 seconds in 50ms intervals */
191265236Sken	error = ETIMEDOUT;
192265236Sken	for (i = 0; i < 6000; i++) {
193265236Sken		/*
194265236Sken		 * Wait 50 msec. If this is the first time through, wait 256
195265236Sken		 * msec to satisfy Diag Reset timing requirements.
196265236Sken		 */
197265236Sken		if (first_wait_done) {
198265236Sken			if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
199265236Sken				msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
200265236Sken				    "mprdiag", hz/20);
201265236Sken			else if (sleep_flag == CAN_SLEEP)
202265236Sken				pause("mprdiag", hz/20);
203265236Sken			else
204265236Sken				DELAY(50 * 1000);
205265236Sken		} else {
206265236Sken			DELAY(256 * 1000);
207265236Sken			first_wait_done = TRUE;
208265236Sken		}
209265236Sken		/*
210265236Sken		 * Check for the RESET_ADAPTER bit to be cleared first, then
211265236Sken		 * wait for the RESET state to be cleared, which takes a little
212265236Sken		 * longer.
213265236Sken		 */
214265236Sken		reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
215265236Sken		if (reg & MPI2_DIAG_RESET_ADAPTER) {
216265236Sken			continue;
217265236Sken		}
218265236Sken		reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
219265236Sken		if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
220265236Sken			error = 0;
221265236Sken			break;
222265236Sken		}
223265236Sken	}
224265236Sken	if (error)
225265236Sken		return (error);
226265236Sken
227265236Sken	mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
228265236Sken
229265236Sken	return (0);
230265236Sken}
231265236Sken
232265236Skenstatic int
233265236Skenmpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag)
234265236Sken{
235265236Sken
236265236Sken	MPR_FUNCTRACE(sc);
237265236Sken
238265236Sken	mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
239265236Sken	    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
240265236Sken	    MPI2_DOORBELL_FUNCTION_SHIFT);
241265236Sken
242265236Sken	if (mpr_wait_db_ack(sc, 5, sleep_flag) != 0) {
243265236Sken		mpr_dprint(sc, MPR_FAULT, "Doorbell handshake failed : <%s>\n",
244265236Sken				__func__);
245265236Sken		return (ETIMEDOUT);
246265236Sken	}
247265236Sken
248265236Sken	return (0);
249265236Sken}
250265236Sken
251265236Skenstatic int
252265236Skenmpr_transition_ready(struct mpr_softc *sc)
253265236Sken{
254265236Sken	uint32_t reg, state;
255265236Sken	int error, tries = 0;
256265236Sken	int sleep_flags;
257265236Sken
258265236Sken	MPR_FUNCTRACE(sc);
259265236Sken	/* If we are in attach call, do not sleep */
260265236Sken	sleep_flags = (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE)
261265236Sken	    ? CAN_SLEEP : NO_SLEEP;
262265236Sken
263265236Sken	error = 0;
264265236Sken	while (tries++ < 1200) {
265265236Sken		reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
266265236Sken		mpr_dprint(sc, MPR_INIT, "Doorbell= 0x%x\n", reg);
267265236Sken
268265236Sken		/*
269265236Sken		 * Ensure the IOC is ready to talk.  If it's not, try
270265236Sken		 * resetting it.
271265236Sken		 */
272265236Sken		if (reg & MPI2_DOORBELL_USED) {
273265236Sken			mpr_diag_reset(sc, sleep_flags);
274265236Sken			DELAY(50000);
275265236Sken			continue;
276265236Sken		}
277265236Sken
278265236Sken		/* Is the adapter owned by another peer? */
279265236Sken		if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
280265236Sken		    (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
281265236Sken			device_printf(sc->mpr_dev, "IOC is under the control "
282265236Sken			    "of another peer host, aborting initialization.\n");
283265236Sken			return (ENXIO);
284265236Sken		}
285265236Sken
286265236Sken		state = reg & MPI2_IOC_STATE_MASK;
287265236Sken		if (state == MPI2_IOC_STATE_READY) {
288265236Sken			/* Ready to go! */
289265236Sken			error = 0;
290265236Sken			break;
291265236Sken		} else if (state == MPI2_IOC_STATE_FAULT) {
292265236Sken			mpr_dprint(sc, MPR_FAULT, "IOC in fault state 0x%x\n",
293265236Sken			    state & MPI2_DOORBELL_FAULT_CODE_MASK);
294265236Sken			mpr_diag_reset(sc, sleep_flags);
295265236Sken		} else if (state == MPI2_IOC_STATE_OPERATIONAL) {
296265236Sken			/* Need to take ownership */
297265236Sken			mpr_message_unit_reset(sc, sleep_flags);
298265236Sken		} else if (state == MPI2_IOC_STATE_RESET) {
299265236Sken			/* Wait a bit, IOC might be in transition */
300265236Sken			mpr_dprint(sc, MPR_FAULT,
301265236Sken			    "IOC in unexpected reset state\n");
302265236Sken		} else {
303265236Sken			mpr_dprint(sc, MPR_FAULT,
304265236Sken			    "IOC in unknown state 0x%x\n", state);
305265236Sken			error = EINVAL;
306265236Sken			break;
307265236Sken		}
308265236Sken
309265236Sken		/* Wait 50ms for things to settle down. */
310265236Sken		DELAY(50000);
311265236Sken	}
312265236Sken
313265236Sken	if (error)
314265236Sken		device_printf(sc->mpr_dev, "Cannot transition IOC to ready\n");
315265236Sken
316265236Sken	return (error);
317265236Sken}
318265236Sken
319265236Skenstatic int
320265236Skenmpr_transition_operational(struct mpr_softc *sc)
321265236Sken{
322265236Sken	uint32_t reg, state;
323265236Sken	int error;
324265236Sken
325265236Sken	MPR_FUNCTRACE(sc);
326265236Sken
327265236Sken	error = 0;
328265236Sken	reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
329265236Sken	mpr_dprint(sc, MPR_INIT, "Doorbell= 0x%x\n", reg);
330265236Sken
331265236Sken	state = reg & MPI2_IOC_STATE_MASK;
332265236Sken	if (state != MPI2_IOC_STATE_READY) {
333265236Sken		if ((error = mpr_transition_ready(sc)) != 0) {
334265236Sken			mpr_dprint(sc, MPR_FAULT,
335265236Sken			    "%s failed to transition ready\n", __func__);
336265236Sken			return (error);
337265236Sken		}
338265236Sken	}
339265236Sken
340265236Sken	error = mpr_send_iocinit(sc);
341265236Sken	return (error);
342265236Sken}
343265236Sken
344265236Sken/*
345265236Sken * This is called during attach and when re-initializing due to a Diag Reset.
346265236Sken * IOC Facts is used to allocate many of the structures needed by the driver.
347265236Sken * If called from attach, de-allocation is not required because the driver has
348265236Sken * not allocated any structures yet, but if called from a Diag Reset, previously
349265236Sken * allocated structures based on IOC Facts will need to be freed and re-
350265236Sken * allocated bases on the latest IOC Facts.
351265236Sken */
352265236Skenstatic int
353265236Skenmpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching)
354265236Sken{
355265236Sken	int error, i;
356265236Sken	Mpi2IOCFactsReply_t saved_facts;
357265236Sken	uint8_t saved_mode, reallocating;
358265236Sken	struct mprsas_lun *lun, *lun_tmp;
359265236Sken	struct mprsas_target *targ;
360265236Sken
361265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
362265236Sken
363265236Sken	/* Save old IOC Facts and then only reallocate if Facts have changed */
364265236Sken	if (!attaching) {
365265236Sken		bcopy(sc->facts, &saved_facts, sizeof(MPI2_IOC_FACTS_REPLY));
366265236Sken	}
367265236Sken
368265236Sken	/*
369265236Sken	 * Get IOC Facts.  In all cases throughout this function, panic if doing
370265236Sken	 * a re-initialization and only return the error if attaching so the OS
371265236Sken	 * can handle it.
372265236Sken	 */
373265236Sken	if ((error = mpr_get_iocfacts(sc, sc->facts)) != 0) {
374265236Sken		if (attaching) {
375265236Sken			mpr_dprint(sc, MPR_FAULT, "%s failed to get IOC Facts "
376265236Sken			    "with error %d\n", __func__, error);
377265236Sken			return (error);
378265236Sken		} else {
379265236Sken			panic("%s failed to get IOC Facts with error %d\n",
380265236Sken			    __func__, error);
381265236Sken		}
382265236Sken	}
383265236Sken
384265236Sken	mpr_print_iocfacts(sc, sc->facts);
385265236Sken
386265236Sken	snprintf(sc->fw_version, sizeof(sc->fw_version),
387265236Sken	    "%02d.%02d.%02d.%02d",
388265236Sken	    sc->facts->FWVersion.Struct.Major,
389265236Sken	    sc->facts->FWVersion.Struct.Minor,
390265236Sken	    sc->facts->FWVersion.Struct.Unit,
391265236Sken	    sc->facts->FWVersion.Struct.Dev);
392265236Sken
393265236Sken	mpr_printf(sc, "Firmware: %s, Driver: %s\n", sc->fw_version,
394265236Sken	    MPR_DRIVER_VERSION);
395265236Sken	mpr_printf(sc, "IOCCapabilities: %b\n", sc->facts->IOCCapabilities,
396265236Sken	    "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
397265236Sken	    "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
398265236Sken	    "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc");
399265236Sken
400265236Sken	/*
401265236Sken	 * If the chip doesn't support event replay then a hard reset will be
402265236Sken	 * required to trigger a full discovery.  Do the reset here then
403265236Sken	 * retransition to Ready.  A hard reset might have already been done,
404265236Sken	 * but it doesn't hurt to do it again.  Only do this if attaching, not
405265236Sken	 * for a Diag Reset.
406265236Sken	 */
407265236Sken	if (attaching) {
408265236Sken		if ((sc->facts->IOCCapabilities &
409265236Sken		    MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0) {
410265236Sken			mpr_diag_reset(sc, NO_SLEEP);
411265236Sken			if ((error = mpr_transition_ready(sc)) != 0) {
412265236Sken				mpr_dprint(sc, MPR_FAULT, "%s failed to "
413265236Sken				    "transition to ready with error %d\n",
414265236Sken				    __func__, error);
415265236Sken				return (error);
416265236Sken			}
417265236Sken		}
418265236Sken	}
419265236Sken
420265236Sken	/*
421265236Sken	 * Set flag if IR Firmware is loaded.  If the RAID Capability has
422265236Sken	 * changed from the previous IOC Facts, log a warning, but only if
423265236Sken	 * checking this after a Diag Reset and not during attach.
424265236Sken	 */
425265236Sken	saved_mode = sc->ir_firmware;
426265236Sken	if (sc->facts->IOCCapabilities &
427265236Sken	    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
428265236Sken		sc->ir_firmware = 1;
429265236Sken	if (!attaching) {
430265236Sken		if (sc->ir_firmware != saved_mode) {
431265236Sken			mpr_dprint(sc, MPR_FAULT, "%s new IR/IT mode in IOC "
432265236Sken			    "Facts does not match previous mode\n", __func__);
433265236Sken		}
434265236Sken	}
435265236Sken
436265236Sken	/* Only deallocate and reallocate if relevant IOC Facts have changed */
437265236Sken	reallocating = FALSE;
438265236Sken	if ((!attaching) &&
439265236Sken	    ((saved_facts.MsgVersion != sc->facts->MsgVersion) ||
440265236Sken	    (saved_facts.HeaderVersion != sc->facts->HeaderVersion) ||
441265236Sken	    (saved_facts.MaxChainDepth != sc->facts->MaxChainDepth) ||
442265236Sken	    (saved_facts.RequestCredit != sc->facts->RequestCredit) ||
443265236Sken	    (saved_facts.ProductID != sc->facts->ProductID) ||
444265236Sken	    (saved_facts.IOCCapabilities != sc->facts->IOCCapabilities) ||
445265236Sken	    (saved_facts.IOCRequestFrameSize !=
446265236Sken	    sc->facts->IOCRequestFrameSize) ||
447265236Sken	    (saved_facts.MaxTargets != sc->facts->MaxTargets) ||
448265236Sken	    (saved_facts.MaxSasExpanders != sc->facts->MaxSasExpanders) ||
449265236Sken	    (saved_facts.MaxEnclosures != sc->facts->MaxEnclosures) ||
450265236Sken	    (saved_facts.HighPriorityCredit != sc->facts->HighPriorityCredit) ||
451265236Sken	    (saved_facts.MaxReplyDescriptorPostQueueDepth !=
452265236Sken	    sc->facts->MaxReplyDescriptorPostQueueDepth) ||
453265236Sken	    (saved_facts.ReplyFrameSize != sc->facts->ReplyFrameSize) ||
454265236Sken	    (saved_facts.MaxVolumes != sc->facts->MaxVolumes) ||
455265236Sken	    (saved_facts.MaxPersistentEntries !=
456265236Sken	    sc->facts->MaxPersistentEntries))) {
457265236Sken		reallocating = TRUE;
458265236Sken	}
459265236Sken
460265236Sken	/*
461265236Sken	 * Some things should be done if attaching or re-allocating after a Diag
462265236Sken	 * Reset, but are not needed after a Diag Reset if the FW has not
463265236Sken	 * changed.
464265236Sken	 */
465265236Sken	if (attaching || reallocating) {
466265236Sken		/*
467265236Sken		 * Check if controller supports FW diag buffers and set flag to
468265236Sken		 * enable each type.
469265236Sken		 */
470265236Sken		if (sc->facts->IOCCapabilities &
471265236Sken		    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
472265236Sken			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].
473265236Sken			    enabled = TRUE;
474265236Sken		if (sc->facts->IOCCapabilities &
475265236Sken		    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
476265236Sken			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].
477265236Sken			    enabled = TRUE;
478265236Sken		if (sc->facts->IOCCapabilities &
479265236Sken		    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
480265236Sken			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].
481265236Sken			    enabled = TRUE;
482265236Sken
483265236Sken		/*
484265236Sken		 * Set flag if EEDP is supported and if TLR is supported.
485265236Sken		 */
486265236Sken		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
487265236Sken			sc->eedp_enabled = TRUE;
488265236Sken		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
489265236Sken			sc->control_TLR = TRUE;
490265236Sken
491265236Sken		/*
492265236Sken		 * Size the queues. Since the reply queues always need one free
493265236Sken		 * entry, we'll just deduct one reply message here.
494265236Sken		 */
495265236Sken		sc->num_reqs = MIN(MPR_REQ_FRAMES, sc->facts->RequestCredit);
496265236Sken		sc->num_replies = MIN(MPR_REPLY_FRAMES + MPR_EVT_REPLY_FRAMES,
497265236Sken		    sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
498265236Sken
499265236Sken		/*
500265236Sken		 * Initialize all Tail Queues
501265236Sken		 */
502265236Sken		TAILQ_INIT(&sc->req_list);
503265236Sken		TAILQ_INIT(&sc->high_priority_req_list);
504265236Sken		TAILQ_INIT(&sc->chain_list);
505265236Sken		TAILQ_INIT(&sc->tm_list);
506265236Sken	}
507265236Sken
508265236Sken	/*
509265236Sken	 * If doing a Diag Reset and the FW is significantly different
510265236Sken	 * (reallocating will be set above in IOC Facts comparison), then all
511265236Sken	 * buffers based on the IOC Facts will need to be freed before they are
512265236Sken	 * reallocated.
513265236Sken	 */
514265236Sken	if (reallocating) {
515265236Sken		mpr_iocfacts_free(sc);
516265236Sken
517265236Sken		/*
518265236Sken		 * The number of targets is based on IOC Facts, so free all of
519265236Sken		 * the allocated LUNs for each target and then the target buffer
520265236Sken		 * itself.
521265236Sken		 */
522265236Sken		for (i=0; i< saved_facts.MaxTargets; i++) {
523265236Sken			targ = &sc->sassc->targets[i];
524265236Sken			SLIST_FOREACH_SAFE(lun, &targ->luns, lun_link,
525265236Sken			    lun_tmp) {
526265236Sken				free(lun, M_MPR);
527265236Sken			}
528265236Sken		}
529265236Sken		free(sc->sassc->targets, M_MPR);
530265236Sken
531265236Sken		sc->sassc->targets = malloc(sizeof(struct mprsas_target) *
532265236Sken		    sc->facts->MaxTargets, M_MPR, M_WAITOK|M_ZERO);
533265236Sken		if (!sc->sassc->targets) {
534265236Sken			panic("%s failed to alloc targets with error %d\n",
535265236Sken			    __func__, ENOMEM);
536265236Sken		}
537265236Sken	}
538265236Sken
539265236Sken	/*
540265236Sken	 * Any deallocation has been completed.  Now start reallocating
541265236Sken	 * if needed.  Will only need to reallocate if attaching or if the new
542265236Sken	 * IOC Facts are different from the previous IOC Facts after a Diag
543265236Sken	 * Reset. Targets have already been allocated above if needed.
544265236Sken	 */
545265236Sken	if (attaching || reallocating) {
546265236Sken		if (((error = mpr_alloc_queues(sc)) != 0) ||
547265236Sken		    ((error = mpr_alloc_replies(sc)) != 0) ||
548265236Sken		    ((error = mpr_alloc_requests(sc)) != 0)) {
549265236Sken			if (attaching ) {
550265236Sken				mpr_dprint(sc, MPR_FAULT, "%s failed to alloc "
551265236Sken				    "queues with error %d\n", __func__, error);
552265236Sken				mpr_free(sc);
553265236Sken				return (error);
554265236Sken			} else {
555265236Sken				panic("%s failed to alloc queues with error "
556265236Sken				    "%d\n", __func__, error);
557265236Sken			}
558265236Sken		}
559265236Sken	}
560265236Sken
561265236Sken	/* Always initialize the queues */
562265236Sken	bzero(sc->free_queue, sc->fqdepth * 4);
563265236Sken	mpr_init_queues(sc);
564265236Sken
565265236Sken	/*
566265236Sken	 * Always get the chip out of the reset state, but only panic if not
567265236Sken	 * attaching.  If attaching and there is an error, that is handled by
568265236Sken	 * the OS.
569265236Sken	 */
570265236Sken	error = mpr_transition_operational(sc);
571265236Sken	if (error != 0) {
572265236Sken		if (attaching) {
573265236Sken			mpr_printf(sc, "%s failed to transition to "
574265236Sken			    "operational with error %d\n", __func__, error);
575265236Sken			mpr_free(sc);
576265236Sken			return (error);
577265236Sken		} else {
578265236Sken			panic("%s failed to transition to operational with "
579265236Sken			    "error %d\n", __func__, error);
580265236Sken		}
581265236Sken	}
582265236Sken
583265236Sken	/*
584265236Sken	 * Finish the queue initialization.
585265236Sken	 * These are set here instead of in mpr_init_queues() because the
586265236Sken	 * IOC resets these values during the state transition in
587265236Sken	 * mpr_transition_operational().  The free index is set to 1
588265236Sken	 * because the corresponding index in the IOC is set to 0, and the
589265236Sken	 * IOC treats the queues as full if both are set to the same value.
590265236Sken	 * Hence the reason that the queue can't hold all of the possible
591265236Sken	 * replies.
592265236Sken	 */
593265236Sken	sc->replypostindex = 0;
594265236Sken	mpr_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
595265236Sken	mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
596265236Sken
597265236Sken	/*
598265236Sken	 * Attach the subsystems so they can prepare their event masks.
599265236Sken	 */
600265236Sken	/* XXX Should be dynamic so that IM/IR and user modules can attach */
601265236Sken	if (attaching) {
602265236Sken		if (((error = mpr_attach_log(sc)) != 0) ||
603265236Sken		    ((error = mpr_attach_sas(sc)) != 0) ||
604265236Sken		    ((error = mpr_attach_user(sc)) != 0)) {
605265236Sken			mpr_printf(sc, "%s failed to attach all subsystems: "
606265236Sken			    "error %d\n", __func__, error);
607265236Sken			mpr_free(sc);
608265236Sken			return (error);
609265236Sken		}
610265236Sken
611265236Sken		if ((error = mpr_pci_setup_interrupts(sc)) != 0) {
612265236Sken			mpr_printf(sc, "%s failed to setup interrupts\n",
613265236Sken			    __func__);
614265236Sken			mpr_free(sc);
615265236Sken			return (error);
616265236Sken		}
617265236Sken	}
618265236Sken
619265236Sken	return (error);
620265236Sken}
621265236Sken
622265236Sken/*
623265236Sken * This is called if memory is being free (during detach for example) and when
624265236Sken * buffers need to be reallocated due to a Diag Reset.
625265236Sken */
626265236Skenstatic void
627265236Skenmpr_iocfacts_free(struct mpr_softc *sc)
628265236Sken{
629265236Sken	struct mpr_command *cm;
630265236Sken	int i;
631265236Sken
632265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
633265236Sken
634265236Sken	if (sc->free_busaddr != 0)
635265236Sken		bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
636265236Sken	if (sc->free_queue != NULL)
637265236Sken		bus_dmamem_free(sc->queues_dmat, sc->free_queue,
638265236Sken		    sc->queues_map);
639265236Sken	if (sc->queues_dmat != NULL)
640265236Sken		bus_dma_tag_destroy(sc->queues_dmat);
641265236Sken
642265236Sken	if (sc->chain_busaddr != 0)
643265236Sken		bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
644265236Sken	if (sc->chain_frames != NULL)
645265236Sken		bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
646265236Sken		    sc->chain_map);
647265236Sken	if (sc->chain_dmat != NULL)
648265236Sken		bus_dma_tag_destroy(sc->chain_dmat);
649265236Sken
650265236Sken	if (sc->sense_busaddr != 0)
651265236Sken		bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
652265236Sken	if (sc->sense_frames != NULL)
653265236Sken		bus_dmamem_free(sc->sense_dmat, sc->sense_frames,
654265236Sken		    sc->sense_map);
655265236Sken	if (sc->sense_dmat != NULL)
656265236Sken		bus_dma_tag_destroy(sc->sense_dmat);
657265236Sken
658265236Sken	if (sc->reply_busaddr != 0)
659265236Sken		bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
660265236Sken	if (sc->reply_frames != NULL)
661265236Sken		bus_dmamem_free(sc->reply_dmat, sc->reply_frames,
662265236Sken		    sc->reply_map);
663265236Sken	if (sc->reply_dmat != NULL)
664265236Sken		bus_dma_tag_destroy(sc->reply_dmat);
665265236Sken
666265236Sken	if (sc->req_busaddr != 0)
667265236Sken		bus_dmamap_unload(sc->req_dmat, sc->req_map);
668265236Sken	if (sc->req_frames != NULL)
669265236Sken		bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
670265236Sken	if (sc->req_dmat != NULL)
671265236Sken		bus_dma_tag_destroy(sc->req_dmat);
672265236Sken
673265236Sken	if (sc->chains != NULL)
674265236Sken		free(sc->chains, M_MPR);
675265236Sken	if (sc->commands != NULL) {
676265236Sken		for (i = 1; i < sc->num_reqs; i++) {
677265236Sken			cm = &sc->commands[i];
678265236Sken			bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
679265236Sken		}
680265236Sken		free(sc->commands, M_MPR);
681265236Sken	}
682265236Sken	if (sc->buffer_dmat != NULL)
683265236Sken		bus_dma_tag_destroy(sc->buffer_dmat);
684265236Sken}
685265236Sken
686265236Sken/*
687265236Sken * The terms diag reset and hard reset are used interchangeably in the MPI
688265236Sken * docs to mean resetting the controller chip.  In this code diag reset
689265236Sken * cleans everything up, and the hard reset function just sends the reset
690265236Sken * sequence to the chip.  This should probably be refactored so that every
691265236Sken * subsystem gets a reset notification of some sort, and can clean up
692265236Sken * appropriately.
693265236Sken */
694265236Skenint
695265236Skenmpr_reinit(struct mpr_softc *sc)
696265236Sken{
697265236Sken	int error;
698265236Sken	struct mprsas_softc *sassc;
699265236Sken
700265236Sken	sassc = sc->sassc;
701265236Sken
702265236Sken	MPR_FUNCTRACE(sc);
703265236Sken
704265236Sken	mtx_assert(&sc->mpr_mtx, MA_OWNED);
705265236Sken
706265236Sken	if (sc->mpr_flags & MPR_FLAGS_DIAGRESET) {
707265236Sken		mpr_dprint(sc, MPR_INIT, "%s reset already in progress\n",
708265236Sken			   __func__);
709265236Sken		return 0;
710265236Sken	}
711265236Sken
712265236Sken	mpr_dprint(sc, MPR_INFO, "Reinitializing controller,\n");
713265236Sken	/* make sure the completion callbacks can recognize they're getting
714265236Sken	 * a NULL cm_reply due to a reset.
715265236Sken	 */
716265236Sken	sc->mpr_flags |= MPR_FLAGS_DIAGRESET;
717265236Sken
718265236Sken	/*
719265236Sken	 * Mask interrupts here.
720265236Sken	 */
721265236Sken	mpr_dprint(sc, MPR_INIT, "%s mask interrupts\n", __func__);
722265236Sken	mpr_mask_intr(sc);
723265236Sken
724265236Sken	error = mpr_diag_reset(sc, CAN_SLEEP);
725265236Sken	if (error != 0) {
726265236Sken		panic("%s hard reset failed with error %d\n", __func__, error);
727265236Sken	}
728265236Sken
729265236Sken	/* Restore the PCI state, including the MSI-X registers */
730265236Sken	mpr_pci_restore(sc);
731265236Sken
732265236Sken	/* Give the I/O subsystem special priority to get itself prepared */
733265236Sken	mprsas_handle_reinit(sc);
734265236Sken
735265236Sken	/*
736265236Sken	 * Get IOC Facts and allocate all structures based on this information.
737265236Sken	 * The attach function will also call mpr_iocfacts_allocate at startup.
738265236Sken	 * If relevant values have changed in IOC Facts, this function will free
739265236Sken	 * all of the memory based on IOC Facts and reallocate that memory.
740265236Sken	 */
741265236Sken	if ((error = mpr_iocfacts_allocate(sc, FALSE)) != 0) {
742265236Sken		panic("%s IOC Facts based allocation failed with error %d\n",
743265236Sken		    __func__, error);
744265236Sken	}
745265236Sken
746265236Sken	/*
747265236Sken	 * Mapping structures will be re-allocated after getting IOC Page8, so
748265236Sken	 * free these structures here.
749265236Sken	 */
750265236Sken	mpr_mapping_exit(sc);
751265236Sken
752265236Sken	/*
753265236Sken	 * The static page function currently read is IOC Page8.  Others can be
754265236Sken	 * added in future.  It's possible that the values in IOC Page8 have
755265236Sken	 * changed after a Diag Reset due to user modification, so always read
756265236Sken	 * these.  Interrupts are masked, so unmask them before getting config
757265236Sken	 * pages.
758265236Sken	 */
759265236Sken	mpr_unmask_intr(sc);
760265236Sken	sc->mpr_flags &= ~MPR_FLAGS_DIAGRESET;
761265236Sken	mpr_base_static_config_pages(sc);
762265236Sken
763265236Sken	/*
764265236Sken	 * Some mapping info is based in IOC Page8 data, so re-initialize the
765265236Sken	 * mapping tables.
766265236Sken	 */
767265236Sken	mpr_mapping_initialize(sc);
768265236Sken
769265236Sken	/*
770265236Sken	 * Restart will reload the event masks clobbered by the reset, and
771265236Sken	 * then enable the port.
772265236Sken	 */
773265236Sken	mpr_reregister_events(sc);
774265236Sken
775265236Sken	/* the end of discovery will release the simq, so we're done. */
776265236Sken	mpr_dprint(sc, MPR_INFO, "%s finished sc %p post %u free %u\n",
777265236Sken	    __func__, sc, sc->replypostindex, sc->replyfreeindex);
778265236Sken	mprsas_release_simq_reinit(sassc);
779265236Sken
780265236Sken	return 0;
781265236Sken}
782265236Sken
783265236Sken/* Wait for the chip to ACK a word that we've put into its FIFO
784265236Sken * Wait for <timeout> seconds. In single loop wait for busy loop
785265236Sken * for 500 microseconds.
786265236Sken * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
787265236Sken * */
788265236Skenstatic int
789265236Skenmpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag)
790265236Sken{
791265236Sken	u32 cntdn, count;
792265236Sken	u32 int_status;
793265236Sken	u32 doorbell;
794265236Sken
795265236Sken	count = 0;
796265236Sken	cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
797265236Sken	do {
798265236Sken		int_status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
799265236Sken		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
800265236Sken			mpr_dprint(sc, MPR_INIT, "%s: successful count(%d), "
801265236Sken			    "timeout(%d)\n", __func__, count, timeout);
802265236Sken			return 0;
803265236Sken		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
804265236Sken			doorbell = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
805265236Sken			if ((doorbell & MPI2_IOC_STATE_MASK) ==
806265236Sken			    MPI2_IOC_STATE_FAULT) {
807265236Sken				mpr_dprint(sc, MPR_FAULT,
808265236Sken				    "fault_state(0x%04x)!\n", doorbell);
809265236Sken				return (EFAULT);
810265236Sken			}
811265236Sken		} else if (int_status == 0xFFFFFFFF)
812265236Sken			goto out;
813265236Sken
814265236Sken		/*
815265236Sken		 * If it can sleep, sleep for 1 milisecond, else busy loop for
816265236Sken 		 * 0.5 milisecond
817265236Sken		 */
818265236Sken		if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
819265236Sken			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0, "mprdba",			    hz/1000);
820265236Sken		else if (sleep_flag == CAN_SLEEP)
821265236Sken			pause("mprdba", hz/1000);
822265236Sken		else
823265236Sken			DELAY(500);
824265236Sken		count++;
825265236Sken	} while (--cntdn);
826265236Sken
827265236Sken	out:
828265236Sken	mpr_dprint(sc, MPR_FAULT, "%s: failed due to timeout count(%d), "
829265236Sken		"int_status(%x)!\n", __func__, count, int_status);
830265236Sken	return (ETIMEDOUT);
831265236Sken}
832265236Sken
833265236Sken/* Wait for the chip to signal that the next word in its FIFO can be fetched */
834265236Skenstatic int
835265236Skenmpr_wait_db_int(struct mpr_softc *sc)
836265236Sken{
837265236Sken	int retry;
838265236Sken
839265236Sken	for (retry = 0; retry < MPR_DB_MAX_WAIT; retry++) {
840265236Sken		if ((mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
841265236Sken		    MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
842265236Sken			return (0);
843265236Sken		DELAY(2000);
844265236Sken	}
845265236Sken	return (ETIMEDOUT);
846265236Sken}
847265236Sken
848265236Sken/* Step through the synchronous command state machine, i.e. "Doorbell mode" */
849265236Skenstatic int
850265236Skenmpr_request_sync(struct mpr_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
851265236Sken    int req_sz, int reply_sz, int timeout)
852265236Sken{
853265236Sken	uint32_t *data32;
854265236Sken	uint16_t *data16;
855265236Sken	int i, count, ioc_sz, residual;
856265236Sken	int sleep_flags = CAN_SLEEP;
857265236Sken
858265236Sken#if __FreeBSD_version >= 1000029
859265236Sken	if (curthread->td_no_sleeping)
860265236Sken#else //__FreeBSD_version < 1000029
861265236Sken	if (curthread->td_pflags & TDP_NOSLEEPING)
862265236Sken#endif //__FreeBSD_version >= 1000029
863265236Sken		sleep_flags = NO_SLEEP;
864265236Sken
865265236Sken	/* Step 1 */
866265236Sken	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
867265236Sken
868265236Sken	/* Step 2 */
869265236Sken	if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
870265236Sken		return (EBUSY);
871265236Sken
872265236Sken	/* Step 3
873265236Sken	 * Announce that a message is coming through the doorbell.  Messages
874265236Sken	 * are pushed at 32bit words, so round up if needed.
875265236Sken	 */
876265236Sken	count = (req_sz + 3) / 4;
877265236Sken	mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
878265236Sken	    (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
879265236Sken	    (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
880265236Sken
881265236Sken	/* Step 4 */
882265236Sken	if (mpr_wait_db_int(sc) ||
883265236Sken	    (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
884265236Sken		mpr_dprint(sc, MPR_FAULT, "Doorbell failed to activate\n");
885265236Sken		return (ENXIO);
886265236Sken	}
887265236Sken	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
888265236Sken	if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
889265236Sken		mpr_dprint(sc, MPR_FAULT, "Doorbell handshake failed\n");
890265236Sken		return (ENXIO);
891265236Sken	}
892265236Sken
893265236Sken	/* Step 5 */
894265236Sken	/* Clock out the message data synchronously in 32-bit dwords*/
895265236Sken	data32 = (uint32_t *)req;
896265236Sken	for (i = 0; i < count; i++) {
897265236Sken		mpr_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
898265236Sken		if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
899265236Sken			mpr_dprint(sc, MPR_FAULT,
900265236Sken			    "Timeout while writing doorbell\n");
901265236Sken			return (ENXIO);
902265236Sken		}
903265236Sken	}
904265236Sken
905265236Sken	/* Step 6 */
906265236Sken	/* Clock in the reply in 16-bit words.  The total length of the
907265236Sken	 * message is always in the 4th byte, so clock out the first 2 words
908265236Sken	 * manually, then loop the rest.
909265236Sken	 */
910265236Sken	data16 = (uint16_t *)reply;
911265236Sken	if (mpr_wait_db_int(sc) != 0) {
912265236Sken		mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 0\n");
913265236Sken		return (ENXIO);
914265236Sken	}
915265236Sken	data16[0] =
916265236Sken	    mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
917265236Sken	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
918265236Sken	if (mpr_wait_db_int(sc) != 0) {
919265236Sken		mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 1\n");
920265236Sken		return (ENXIO);
921265236Sken	}
922265236Sken	data16[1] =
923265236Sken	    mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
924265236Sken	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
925265236Sken
926265236Sken	/* Number of 32bit words in the message */
927265236Sken	ioc_sz = reply->MsgLength;
928265236Sken
929265236Sken	/*
930265236Sken	 * Figure out how many 16bit words to clock in without overrunning.
931265236Sken	 * The precision loss with dividing reply_sz can safely be
932265236Sken	 * ignored because the messages can only be multiples of 32bits.
933265236Sken	 */
934265236Sken	residual = 0;
935265236Sken	count = MIN((reply_sz / 4), ioc_sz) * 2;
936265236Sken	if (count < ioc_sz * 2) {
937265236Sken		residual = ioc_sz * 2 - count;
938265236Sken		mpr_dprint(sc, MPR_ERROR, "Driver error, throwing away %d "
939265236Sken		    "residual message words\n", residual);
940265236Sken	}
941265236Sken
942265236Sken	for (i = 2; i < count; i++) {
943265236Sken		if (mpr_wait_db_int(sc) != 0) {
944265236Sken			mpr_dprint(sc, MPR_FAULT,
945265236Sken			    "Timeout reading doorbell %d\n", i);
946265236Sken			return (ENXIO);
947265236Sken		}
948265236Sken		data16[i] = mpr_regread(sc, MPI2_DOORBELL_OFFSET) &
949265236Sken		    MPI2_DOORBELL_DATA_MASK;
950265236Sken		mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
951265236Sken	}
952265236Sken
953265236Sken	/*
954265236Sken	 * Pull out residual words that won't fit into the provided buffer.
955265236Sken	 * This keeps the chip from hanging due to a driver programming
956265236Sken	 * error.
957265236Sken	 */
958265236Sken	while (residual--) {
959265236Sken		if (mpr_wait_db_int(sc) != 0) {
960265236Sken			mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell\n");
961265236Sken			return (ENXIO);
962265236Sken		}
963265236Sken		(void)mpr_regread(sc, MPI2_DOORBELL_OFFSET);
964265236Sken		mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
965265236Sken	}
966265236Sken
967265236Sken	/* Step 7 */
968265236Sken	if (mpr_wait_db_int(sc) != 0) {
969265236Sken		mpr_dprint(sc, MPR_FAULT, "Timeout waiting to exit doorbell\n");
970265236Sken		return (ENXIO);
971265236Sken	}
972265236Sken	if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
973265236Sken		mpr_dprint(sc, MPR_FAULT, "Warning, doorbell still active\n");
974265236Sken	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
975265236Sken
976265236Sken	return (0);
977265236Sken}
978265236Sken
979265236Skenstatic void
980265236Skenmpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm)
981265236Sken{
982265236Sken	reply_descriptor rd;
983265236Sken
984265236Sken	MPR_FUNCTRACE(sc);
985265236Sken	mpr_dprint(sc, MPR_TRACE, "%s SMID %u cm %p ccb %p\n", __func__,
986265236Sken	    cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
987265236Sken
988265236Sken	if (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE && !(sc->mpr_flags &
989265236Sken	    MPR_FLAGS_SHUTDOWN))
990265236Sken		mtx_assert(&sc->mpr_mtx, MA_OWNED);
991265236Sken
992265236Sken	if (++sc->io_cmds_active > sc->io_cmds_highwater)
993265236Sken		sc->io_cmds_highwater++;
994265236Sken
995265236Sken	rd.u.low = cm->cm_desc.Words.Low;
996265236Sken	rd.u.high = cm->cm_desc.Words.High;
997265236Sken	rd.word = htole64(rd.word);
998265236Sken	/* TODO-We may need to make below regwrite atomic */
999265236Sken	mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
1000265236Sken	    rd.u.low);
1001265236Sken	mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
1002265236Sken	    rd.u.high);
1003265236Sken}
1004265236Sken
1005265236Sken/*
1006265236Sken * Just the FACTS, ma'am.
1007265236Sken */
1008265236Skenstatic int
1009265236Skenmpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
1010265236Sken{
1011265236Sken	MPI2_DEFAULT_REPLY *reply;
1012265236Sken	MPI2_IOC_FACTS_REQUEST request;
1013265236Sken	int error, req_sz, reply_sz;
1014265236Sken
1015265236Sken	MPR_FUNCTRACE(sc);
1016265236Sken
1017265236Sken	req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
1018265236Sken	reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
1019265236Sken	reply = (MPI2_DEFAULT_REPLY *)facts;
1020265236Sken
1021265236Sken	bzero(&request, req_sz);
1022265236Sken	request.Function = MPI2_FUNCTION_IOC_FACTS;
1023265236Sken	error = mpr_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
1024265236Sken
1025265236Sken	return (error);
1026265236Sken}
1027265236Sken
1028265236Skenstatic int
1029265236Skenmpr_send_iocinit(struct mpr_softc *sc)
1030265236Sken{
1031265236Sken	MPI2_IOC_INIT_REQUEST	init;
1032265236Sken	MPI2_DEFAULT_REPLY	reply;
1033265236Sken	int req_sz, reply_sz, error;
1034265236Sken	struct timeval now;
1035265236Sken	uint64_t time_in_msec;
1036265236Sken
1037265236Sken	MPR_FUNCTRACE(sc);
1038265236Sken
1039265236Sken	req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
1040265236Sken	reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
1041265236Sken	bzero(&init, req_sz);
1042265236Sken	bzero(&reply, reply_sz);
1043265236Sken
1044265236Sken	/*
1045265236Sken	 * Fill in the init block.  Note that most addresses are
1046265236Sken	 * deliberately in the lower 32bits of memory.  This is a micro-
1047265236Sken	 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
1048265236Sken	 */
1049265236Sken	init.Function = MPI2_FUNCTION_IOC_INIT;
1050265236Sken	init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
1051265236Sken	init.MsgVersion = htole16(MPI2_VERSION);
1052265236Sken	init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
1053265236Sken	init.SystemRequestFrameSize = htole16(sc->facts->IOCRequestFrameSize);
1054265236Sken	init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
1055265236Sken	init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
1056265236Sken	init.SenseBufferAddressHigh = 0;
1057265236Sken	init.SystemReplyAddressHigh = 0;
1058265236Sken	init.SystemRequestFrameBaseAddress.High = 0;
1059265236Sken	init.SystemRequestFrameBaseAddress.Low =
1060265236Sken	    htole32((uint32_t)sc->req_busaddr);
1061265236Sken	init.ReplyDescriptorPostQueueAddress.High = 0;
1062265236Sken	init.ReplyDescriptorPostQueueAddress.Low =
1063265236Sken	    htole32((uint32_t)sc->post_busaddr);
1064265236Sken	init.ReplyFreeQueueAddress.High = 0;
1065265236Sken	init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
1066265236Sken	getmicrotime(&now);
1067265236Sken	time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
1068265236Sken	init.TimeStamp.High = htole32((time_in_msec >> 32) & 0xFFFFFFFF);
1069265236Sken	init.TimeStamp.Low = htole32(time_in_msec & 0xFFFFFFFF);
1070265236Sken
1071265236Sken	error = mpr_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
1072265236Sken	if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1073265236Sken		error = ENXIO;
1074265236Sken
1075265236Sken	mpr_dprint(sc, MPR_INIT, "IOCInit status= 0x%x\n", reply.IOCStatus);
1076265236Sken	return (error);
1077265236Sken}
1078265236Sken
1079265236Skenvoid
1080265236Skenmpr_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1081265236Sken{
1082265236Sken	bus_addr_t *addr;
1083265236Sken
1084265236Sken	addr = arg;
1085265236Sken	*addr = segs[0].ds_addr;
1086265236Sken}
1087265236Sken
1088265236Skenstatic int
1089265236Skenmpr_alloc_queues(struct mpr_softc *sc)
1090265236Sken{
1091265236Sken	bus_addr_t queues_busaddr;
1092265236Sken	uint8_t *queues;
1093265236Sken	int qsize, fqsize, pqsize;
1094265236Sken
1095265236Sken	/*
1096265236Sken	 * The reply free queue contains 4 byte entries in multiples of 16 and
1097265236Sken	 * aligned on a 16 byte boundary. There must always be an unused entry.
1098265236Sken	 * This queue supplies fresh reply frames for the firmware to use.
1099265236Sken	 *
1100265236Sken	 * The reply descriptor post queue contains 8 byte entries in
1101265236Sken	 * multiples of 16 and aligned on a 16 byte boundary.  This queue
1102265236Sken	 * contains filled-in reply frames sent from the firmware to the host.
1103265236Sken	 *
1104265236Sken	 * These two queues are allocated together for simplicity.
1105265236Sken	 */
1106265236Sken	sc->fqdepth = roundup2((sc->num_replies + 1), 16);
1107265236Sken	sc->pqdepth = roundup2((sc->num_replies + 1), 16);
1108265236Sken	fqsize= sc->fqdepth * 4;
1109265236Sken	pqsize = sc->pqdepth * 8;
1110265236Sken	qsize = fqsize + pqsize;
1111265236Sken
1112265236Sken        if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1113265236Sken				16, 0,			/* algnmnt, boundary */
1114265236Sken				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1115265236Sken				BUS_SPACE_MAXADDR,	/* highaddr */
1116265236Sken				NULL, NULL,		/* filter, filterarg */
1117265236Sken                                qsize,			/* maxsize */
1118265236Sken                                1,			/* nsegments */
1119265236Sken                                qsize,			/* maxsegsize */
1120265236Sken                                0,			/* flags */
1121265236Sken                                NULL, NULL,		/* lockfunc, lockarg */
1122265236Sken                                &sc->queues_dmat)) {
1123265236Sken		device_printf(sc->mpr_dev, "Cannot allocate queues DMA tag\n");
1124265236Sken		return (ENOMEM);
1125265236Sken        }
1126265236Sken        if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
1127265236Sken	    &sc->queues_map)) {
1128265236Sken		device_printf(sc->mpr_dev, "Cannot allocate queues memory\n");
1129265236Sken		return (ENOMEM);
1130265236Sken        }
1131265236Sken        bzero(queues, qsize);
1132265236Sken        bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
1133265236Sken	    mpr_memaddr_cb, &queues_busaddr, 0);
1134265236Sken
1135265236Sken	sc->free_queue = (uint32_t *)queues;
1136265236Sken	sc->free_busaddr = queues_busaddr;
1137265236Sken	sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
1138265236Sken	sc->post_busaddr = queues_busaddr + fqsize;
1139265236Sken
1140265236Sken	return (0);
1141265236Sken}
1142265236Sken
1143265236Skenstatic int
1144265236Skenmpr_alloc_replies(struct mpr_softc *sc)
1145265236Sken{
1146265236Sken	int rsize, num_replies;
1147265236Sken
1148265236Sken	/*
1149265236Sken	 * sc->num_replies should be one less than sc->fqdepth.  We need to
1150265236Sken	 * allocate space for sc->fqdepth replies, but only sc->num_replies
1151265236Sken	 * replies can be used at once.
1152265236Sken	 */
1153265236Sken	num_replies = max(sc->fqdepth, sc->num_replies);
1154265236Sken
1155265236Sken	rsize = sc->facts->ReplyFrameSize * num_replies * 4;
1156265236Sken        if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1157265236Sken				4, 0,			/* algnmnt, boundary */
1158265236Sken				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1159265236Sken				BUS_SPACE_MAXADDR,	/* highaddr */
1160265236Sken				NULL, NULL,		/* filter, filterarg */
1161265236Sken                                rsize,			/* maxsize */
1162265236Sken                                1,			/* nsegments */
1163265236Sken                                rsize,			/* maxsegsize */
1164265236Sken                                0,			/* flags */
1165265236Sken                                NULL, NULL,		/* lockfunc, lockarg */
1166265236Sken                                &sc->reply_dmat)) {
1167265236Sken		device_printf(sc->mpr_dev, "Cannot allocate replies DMA tag\n");
1168265236Sken		return (ENOMEM);
1169265236Sken        }
1170265236Sken        if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
1171265236Sken	    BUS_DMA_NOWAIT, &sc->reply_map)) {
1172265236Sken		device_printf(sc->mpr_dev, "Cannot allocate replies memory\n");
1173265236Sken		return (ENOMEM);
1174265236Sken        }
1175265236Sken        bzero(sc->reply_frames, rsize);
1176265236Sken        bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
1177265236Sken	    mpr_memaddr_cb, &sc->reply_busaddr, 0);
1178265236Sken
1179265236Sken	return (0);
1180265236Sken}
1181265236Sken
1182265236Skenstatic int
1183265236Skenmpr_alloc_requests(struct mpr_softc *sc)
1184265236Sken{
1185265236Sken	struct mpr_command *cm;
1186265236Sken	struct mpr_chain *chain;
1187265236Sken	int i, rsize, nsegs;
1188265236Sken
1189265236Sken	rsize = sc->facts->IOCRequestFrameSize * sc->num_reqs * 4;
1190265236Sken        if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1191265236Sken				16, 0,			/* algnmnt, boundary */
1192265236Sken				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1193265236Sken				BUS_SPACE_MAXADDR,	/* highaddr */
1194265236Sken				NULL, NULL,		/* filter, filterarg */
1195265236Sken                                rsize,			/* maxsize */
1196265236Sken                                1,			/* nsegments */
1197265236Sken                                rsize,			/* maxsegsize */
1198265236Sken                                0,			/* flags */
1199265236Sken                                NULL, NULL,		/* lockfunc, lockarg */
1200265236Sken                                &sc->req_dmat)) {
1201265236Sken		device_printf(sc->mpr_dev, "Cannot allocate request DMA tag\n");
1202265236Sken		return (ENOMEM);
1203265236Sken        }
1204265236Sken        if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
1205265236Sken	    BUS_DMA_NOWAIT, &sc->req_map)) {
1206265236Sken		device_printf(sc->mpr_dev, "Cannot allocate request memory\n");
1207265236Sken		return (ENOMEM);
1208265236Sken        }
1209265236Sken        bzero(sc->req_frames, rsize);
1210265236Sken        bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
1211265236Sken	    mpr_memaddr_cb, &sc->req_busaddr, 0);
1212265236Sken
1213265236Sken	rsize = sc->facts->IOCRequestFrameSize * sc->max_chains * 4;
1214265236Sken        if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1215265236Sken				16, 0,			/* algnmnt, boundary */
1216265236Sken				BUS_SPACE_MAXADDR,	/* lowaddr */
1217265236Sken				BUS_SPACE_MAXADDR,	/* highaddr */
1218265236Sken				NULL, NULL,		/* filter, filterarg */
1219265236Sken                                rsize,			/* maxsize */
1220265236Sken                                1,			/* nsegments */
1221265236Sken                                rsize,			/* maxsegsize */
1222265236Sken                                0,			/* flags */
1223265236Sken                                NULL, NULL,		/* lockfunc, lockarg */
1224265236Sken                                &sc->chain_dmat)) {
1225265236Sken		device_printf(sc->mpr_dev, "Cannot allocate chain DMA tag\n");
1226265236Sken		return (ENOMEM);
1227265236Sken        }
1228265236Sken        if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
1229265236Sken	    BUS_DMA_NOWAIT, &sc->chain_map)) {
1230265236Sken		device_printf(sc->mpr_dev, "Cannot allocate chain memory\n");
1231265236Sken		return (ENOMEM);
1232265236Sken        }
1233265236Sken        bzero(sc->chain_frames, rsize);
1234265236Sken        bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
1235265236Sken	    mpr_memaddr_cb, &sc->chain_busaddr, 0);
1236265236Sken
1237265236Sken	rsize = MPR_SENSE_LEN * sc->num_reqs;
1238265236Sken	if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1239265236Sken				1, 0,			/* algnmnt, boundary */
1240265236Sken				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1241265236Sken				BUS_SPACE_MAXADDR,	/* highaddr */
1242265236Sken				NULL, NULL,		/* filter, filterarg */
1243265236Sken                                rsize,			/* maxsize */
1244265236Sken                                1,			/* nsegments */
1245265236Sken                                rsize,			/* maxsegsize */
1246265236Sken                                0,			/* flags */
1247265236Sken                                NULL, NULL,		/* lockfunc, lockarg */
1248265236Sken                                &sc->sense_dmat)) {
1249265236Sken		device_printf(sc->mpr_dev, "Cannot allocate sense DMA tag\n");
1250265236Sken		return (ENOMEM);
1251265236Sken        }
1252265236Sken        if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
1253265236Sken	    BUS_DMA_NOWAIT, &sc->sense_map)) {
1254265236Sken		device_printf(sc->mpr_dev, "Cannot allocate sense memory\n");
1255265236Sken		return (ENOMEM);
1256265236Sken        }
1257265236Sken        bzero(sc->sense_frames, rsize);
1258265236Sken        bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
1259265236Sken	    mpr_memaddr_cb, &sc->sense_busaddr, 0);
1260265236Sken
1261265236Sken	sc->chains = malloc(sizeof(struct mpr_chain) * sc->max_chains, M_MPR,
1262265236Sken	    M_WAITOK | M_ZERO);
1263265236Sken	if (!sc->chains) {
1264265236Sken		device_printf(sc->mpr_dev, "Cannot allocate memory %s %d\n",
1265265236Sken		    __func__, __LINE__);
1266265236Sken		return (ENOMEM);
1267265236Sken	}
1268265236Sken	for (i = 0; i < sc->max_chains; i++) {
1269265236Sken		chain = &sc->chains[i];
1270265236Sken		chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
1271265236Sken		    i * sc->facts->IOCRequestFrameSize * 4);
1272265236Sken		chain->chain_busaddr = sc->chain_busaddr +
1273265236Sken		    i * sc->facts->IOCRequestFrameSize * 4;
1274265236Sken		mpr_free_chain(sc, chain);
1275265236Sken		sc->chain_free_lowwater++;
1276265236Sken	}
1277265236Sken
1278265236Sken	/* XXX Need to pick a more precise value */
1279265236Sken	nsegs = (MAXPHYS / PAGE_SIZE) + 1;
1280265236Sken        if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1281265236Sken				1, 0,			/* algnmnt, boundary */
1282265236Sken				BUS_SPACE_MAXADDR,	/* lowaddr */
1283265236Sken				BUS_SPACE_MAXADDR,	/* highaddr */
1284265236Sken				NULL, NULL,		/* filter, filterarg */
1285265236Sken                                BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1286265236Sken                                nsegs,			/* nsegments */
1287265236Sken                                BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1288265236Sken                                BUS_DMA_ALLOCNOW,	/* flags */
1289265236Sken                                busdma_lock_mutex,	/* lockfunc */
1290265236Sken				&sc->mpr_mtx,		/* lockarg */
1291265236Sken                                &sc->buffer_dmat)) {
1292265236Sken		device_printf(sc->mpr_dev, "Cannot allocate buffer DMA tag\n");
1293265236Sken		return (ENOMEM);
1294265236Sken        }
1295265236Sken
1296265236Sken	/*
1297265236Sken	 * SMID 0 cannot be used as a free command per the firmware spec.
1298265236Sken	 * Just drop that command instead of risking accounting bugs.
1299265236Sken	 */
1300265236Sken	sc->commands = malloc(sizeof(struct mpr_command) * sc->num_reqs,
1301265236Sken	    M_MPR, M_WAITOK | M_ZERO);
1302265236Sken	if (!sc->commands) {
1303265236Sken		device_printf(sc->mpr_dev, "Cannot allocate memory %s %d\n",
1304265236Sken		    __func__, __LINE__);
1305265236Sken		return (ENOMEM);
1306265236Sken	}
1307265236Sken	for (i = 1; i < sc->num_reqs; i++) {
1308265236Sken		cm = &sc->commands[i];
1309265236Sken		cm->cm_req = sc->req_frames +
1310265236Sken		    i * sc->facts->IOCRequestFrameSize * 4;
1311265236Sken		cm->cm_req_busaddr = sc->req_busaddr +
1312265236Sken		    i * sc->facts->IOCRequestFrameSize * 4;
1313265236Sken		cm->cm_sense = &sc->sense_frames[i];
1314265236Sken		cm->cm_sense_busaddr = sc->sense_busaddr + i * MPR_SENSE_LEN;
1315265236Sken		cm->cm_desc.Default.SMID = i;
1316265236Sken		cm->cm_sc = sc;
1317265236Sken		TAILQ_INIT(&cm->cm_chain_list);
1318265236Sken		callout_init_mtx(&cm->cm_callout, &sc->mpr_mtx, 0);
1319265236Sken
1320265236Sken		/* XXX Is a failure here a critical problem? */
1321265236Sken		if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap) == 0)
1322265236Sken			if (i <= sc->facts->HighPriorityCredit)
1323265236Sken				mpr_free_high_priority_command(sc, cm);
1324265236Sken			else
1325265236Sken				mpr_free_command(sc, cm);
1326265236Sken		else {
1327265236Sken			panic("failed to allocate command %d\n", i);
1328265236Sken			sc->num_reqs = i;
1329265236Sken			break;
1330265236Sken		}
1331265236Sken	}
1332265236Sken
1333265236Sken	return (0);
1334265236Sken}
1335265236Sken
1336265236Skenstatic int
1337265236Skenmpr_init_queues(struct mpr_softc *sc)
1338265236Sken{
1339265236Sken	int i;
1340265236Sken
1341265236Sken	memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
1342265236Sken
1343265236Sken	/*
1344265236Sken	 * According to the spec, we need to use one less reply than we
1345265236Sken	 * have space for on the queue.  So sc->num_replies (the number we
1346265236Sken	 * use) should be less than sc->fqdepth (allocated size).
1347265236Sken	 */
1348265236Sken	if (sc->num_replies >= sc->fqdepth)
1349265236Sken		return (EINVAL);
1350265236Sken
1351265236Sken	/*
1352265236Sken	 * Initialize all of the free queue entries.
1353265236Sken	 */
1354265236Sken	for (i = 0; i < sc->fqdepth; i++)
1355265236Sken		sc->free_queue[i] = sc->reply_busaddr + (i * sc->facts->ReplyFrameSize * 4);
1356265236Sken	sc->replyfreeindex = sc->num_replies;
1357265236Sken
1358265236Sken	return (0);
1359265236Sken}
1360265236Sken
1361265236Sken/* Get the driver parameter tunables.  Lowest priority are the driver defaults.
1362265236Sken * Next are the global settings, if they exist.  Highest are the per-unit
1363265236Sken * settings, if they exist.
1364265236Sken */
1365265236Skenstatic void
1366265236Skenmpr_get_tunables(struct mpr_softc *sc)
1367265236Sken{
1368265236Sken	char tmpstr[80];
1369265236Sken
1370265236Sken	/* XXX default to some debugging for now */
1371265236Sken	sc->mpr_debug = MPR_INFO | MPR_FAULT;
1372265236Sken	sc->disable_msix = 0;
1373265236Sken	sc->disable_msi = 0;
1374265236Sken	sc->max_chains = MPR_CHAIN_FRAMES;
1375265236Sken
1376265236Sken	/*
1377265236Sken	 * Grab the global variables.
1378265236Sken	 */
1379265236Sken	TUNABLE_INT_FETCH("hw.mpr.debug_level", &sc->mpr_debug);
1380265236Sken	TUNABLE_INT_FETCH("hw.mpr.disable_msix", &sc->disable_msix);
1381265236Sken	TUNABLE_INT_FETCH("hw.mpr.disable_msi", &sc->disable_msi);
1382265236Sken	TUNABLE_INT_FETCH("hw.mpr.max_chains", &sc->max_chains);
1383265236Sken
1384265236Sken	/* Grab the unit-instance variables */
1385265236Sken	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.debug_level",
1386265236Sken	    device_get_unit(sc->mpr_dev));
1387265236Sken	TUNABLE_INT_FETCH(tmpstr, &sc->mpr_debug);
1388265236Sken
1389265236Sken	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msix",
1390265236Sken	    device_get_unit(sc->mpr_dev));
1391265236Sken	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1392265236Sken
1393265236Sken	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msi",
1394265236Sken	    device_get_unit(sc->mpr_dev));
1395265236Sken	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1396265236Sken
1397265236Sken	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_chains",
1398265236Sken	    device_get_unit(sc->mpr_dev));
1399265236Sken	TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1400265236Sken
1401265236Sken	bzero(sc->exclude_ids, sizeof(sc->exclude_ids));
1402265236Sken	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.exclude_ids",
1403265236Sken	    device_get_unit(sc->mpr_dev));
1404265236Sken	TUNABLE_STR_FETCH(tmpstr, sc->exclude_ids, sizeof(sc->exclude_ids));
1405265236Sken}
1406265236Sken
1407265236Skenstatic void
1408265236Skenmpr_setup_sysctl(struct mpr_softc *sc)
1409265236Sken{
1410265236Sken	struct sysctl_ctx_list	*sysctl_ctx = NULL;
1411265236Sken	struct sysctl_oid	*sysctl_tree = NULL;
1412265236Sken	char tmpstr[80], tmpstr2[80];
1413265236Sken
1414265236Sken	/*
1415265236Sken	 * Setup the sysctl variable so the user can change the debug level
1416265236Sken	 * on the fly.
1417265236Sken	 */
1418265236Sken	snprintf(tmpstr, sizeof(tmpstr), "MPR controller %d",
1419265236Sken	    device_get_unit(sc->mpr_dev));
1420265236Sken	snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mpr_dev));
1421265236Sken
1422265236Sken	sysctl_ctx = device_get_sysctl_ctx(sc->mpr_dev);
1423265236Sken	if (sysctl_ctx != NULL)
1424265236Sken		sysctl_tree = device_get_sysctl_tree(sc->mpr_dev);
1425265236Sken
1426265236Sken	if (sysctl_tree == NULL) {
1427265236Sken		sysctl_ctx_init(&sc->sysctl_ctx);
1428265236Sken		sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1429265236Sken		    SYSCTL_STATIC_CHILDREN(_hw_mpr), OID_AUTO, tmpstr2,
1430265236Sken		    CTLFLAG_RD, 0, tmpstr);
1431265236Sken		if (sc->sysctl_tree == NULL)
1432265236Sken			return;
1433265236Sken		sysctl_ctx = &sc->sysctl_ctx;
1434265236Sken		sysctl_tree = sc->sysctl_tree;
1435265236Sken	}
1436265236Sken
1437265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1438265236Sken	    OID_AUTO, "debug_level", CTLFLAG_RW, &sc->mpr_debug, 0,
1439265236Sken	    "mpr debug level");
1440265236Sken
1441265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1442265236Sken	    OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1443265236Sken	    "Disable the use of MSI-X interrupts");
1444265236Sken
1445265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1446265236Sken	    OID_AUTO, "disable_msi", CTLFLAG_RD, &sc->disable_msi, 0,
1447265236Sken	    "Disable the use of MSI interrupts");
1448265236Sken
1449265236Sken	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1450265236Sken	    OID_AUTO, "firmware_version", CTLFLAG_RW, &sc->fw_version,
1451265236Sken	    strlen(sc->fw_version), "firmware version");
1452265236Sken
1453265236Sken	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1454265236Sken	    OID_AUTO, "driver_version", CTLFLAG_RW, MPR_DRIVER_VERSION,
1455265236Sken	    strlen(MPR_DRIVER_VERSION), "driver version");
1456265236Sken
1457265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1458265236Sken	    OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1459265236Sken	    &sc->io_cmds_active, 0, "number of currently active commands");
1460265236Sken
1461265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1462265236Sken	    OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1463265236Sken	    &sc->io_cmds_highwater, 0, "maximum active commands seen");
1464265236Sken
1465265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1466265236Sken	    OID_AUTO, "chain_free", CTLFLAG_RD,
1467265236Sken	    &sc->chain_free, 0, "number of free chain elements");
1468265236Sken
1469265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1470265236Sken	    OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1471265236Sken	    &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1472265236Sken
1473265236Sken	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1474265236Sken	    OID_AUTO, "max_chains", CTLFLAG_RD,
1475265236Sken	    &sc->max_chains, 0,"maximum chain frames that will be allocated");
1476265236Sken
1477265236Sken#if __FreeBSD_version >= 900030
1478265236Sken	SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1479265236Sken	    OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1480265236Sken	    &sc->chain_alloc_fail, "chain allocation failures");
1481265236Sken#endif //FreeBSD_version >= 900030
1482265236Sken}
1483265236Sken
1484265236Skenint
1485265236Skenmpr_attach(struct mpr_softc *sc)
1486265236Sken{
1487265236Sken	int error;
1488265236Sken
1489265236Sken	mpr_get_tunables(sc);
1490265236Sken
1491265236Sken	MPR_FUNCTRACE(sc);
1492265236Sken
1493265236Sken	mtx_init(&sc->mpr_mtx, "MPR lock", NULL, MTX_DEF);
1494265236Sken	callout_init_mtx(&sc->periodic, &sc->mpr_mtx, 0);
1495265236Sken	TAILQ_INIT(&sc->event_list);
1496265236Sken	timevalclear(&sc->lastfail);
1497265236Sken
1498265236Sken	if ((error = mpr_transition_ready(sc)) != 0) {
1499265236Sken		mpr_printf(sc, "%s failed to transition ready\n", __func__);
1500265236Sken		return (error);
1501265236Sken	}
1502265236Sken
1503265236Sken	sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPR,
1504265236Sken	    M_ZERO|M_NOWAIT);
1505265236Sken	if (!sc->facts) {
1506265236Sken		device_printf(sc->mpr_dev, "Cannot allocate memory %s %d\n",
1507265236Sken		    __func__, __LINE__);
1508265236Sken		return (ENOMEM);
1509265236Sken	}
1510265236Sken
1511265236Sken	/*
1512265236Sken	 * Get IOC Facts and allocate all structures based on this information.
1513265236Sken	 * A Diag Reset will also call mpr_iocfacts_allocate and re-read the IOC
1514265236Sken	 * Facts. If relevant values have changed in IOC Facts, this function
1515265236Sken	 * will free all of the memory based on IOC Facts and reallocate that
1516265236Sken	 * memory.  If this fails, any allocated memory should already be freed.
1517265236Sken	 */
1518265236Sken	if ((error = mpr_iocfacts_allocate(sc, TRUE)) != 0) {
1519265236Sken		mpr_dprint(sc, MPR_FAULT, "%s IOC Facts based allocation "
1520265236Sken		    "failed with error %d\n", __func__, error);
1521265236Sken		return (error);
1522265236Sken	}
1523265236Sken
1524265236Sken	/* Start the periodic watchdog check on the IOC Doorbell */
1525265236Sken	mpr_periodic(sc);
1526265236Sken
1527265236Sken	/*
1528265236Sken	 * The portenable will kick off discovery events that will drive the
1529265236Sken	 * rest of the initialization process.  The CAM/SAS module will
1530265236Sken	 * hold up the boot sequence until discovery is complete.
1531265236Sken	 */
1532265236Sken	sc->mpr_ich.ich_func = mpr_startup;
1533265236Sken	sc->mpr_ich.ich_arg = sc;
1534265236Sken	if (config_intrhook_establish(&sc->mpr_ich) != 0) {
1535265236Sken		mpr_dprint(sc, MPR_ERROR, "Cannot establish MPR config hook\n");
1536265236Sken		error = EINVAL;
1537265236Sken	}
1538265236Sken
1539265236Sken	/*
1540265236Sken	 * Allow IR to shutdown gracefully when shutdown occurs.
1541265236Sken	 */
1542265236Sken	sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
1543265236Sken	    mprsas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
1544265236Sken
1545265236Sken	if (sc->shutdown_eh == NULL)
1546265236Sken		mpr_dprint(sc, MPR_ERROR, "shutdown event registration "
1547265236Sken		    "failed\n");
1548265236Sken
1549265236Sken	mpr_setup_sysctl(sc);
1550265236Sken
1551265236Sken	sc->mpr_flags |= MPR_FLAGS_ATTACH_DONE;
1552265236Sken
1553265236Sken	return (error);
1554265236Sken}
1555265236Sken
1556265236Sken/* Run through any late-start handlers. */
1557265236Skenstatic void
1558265236Skenmpr_startup(void *arg)
1559265236Sken{
1560265236Sken	struct mpr_softc *sc;
1561265236Sken
1562265236Sken	sc = (struct mpr_softc *)arg;
1563265236Sken
1564265236Sken	mpr_lock(sc);
1565265236Sken	mpr_unmask_intr(sc);
1566265236Sken
1567265236Sken	/* initialize device mapping tables */
1568265236Sken	mpr_base_static_config_pages(sc);
1569265236Sken	mpr_mapping_initialize(sc);
1570265236Sken	mprsas_startup(sc);
1571265236Sken	mpr_unlock(sc);
1572265236Sken}
1573265236Sken
1574265236Sken/* Periodic watchdog.  Is called with the driver lock already held. */
1575265236Skenstatic void
1576265236Skenmpr_periodic(void *arg)
1577265236Sken{
1578265236Sken	struct mpr_softc *sc;
1579265236Sken	uint32_t db;
1580265236Sken
1581265236Sken	sc = (struct mpr_softc *)arg;
1582265236Sken	if (sc->mpr_flags & MPR_FLAGS_SHUTDOWN)
1583265236Sken		return;
1584265236Sken
1585265236Sken	db = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
1586265236Sken	if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
1587265236Sken		if ((db & MPI2_DOORBELL_FAULT_CODE_MASK) ==
1588265236Sken		    IFAULT_IOP_OVER_TEMP_THRESHOLD_EXCEEDED) {
1589265236Sken			panic("TEMPERATURE FAULT: STOPPING.");
1590265236Sken		}
1591265236Sken		mpr_dprint(sc, MPR_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
1592265236Sken		mpr_reinit(sc);
1593265236Sken	}
1594265236Sken
1595265236Sken	callout_reset(&sc->periodic, MPR_PERIODIC_DELAY * hz, mpr_periodic, sc);
1596265236Sken}
1597265236Sken
1598265236Skenstatic void
1599265236Skenmpr_log_evt_handler(struct mpr_softc *sc, uintptr_t data,
1600265236Sken    MPI2_EVENT_NOTIFICATION_REPLY *event)
1601265236Sken{
1602265236Sken	MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
1603265236Sken
1604265236Sken	mpr_print_event(sc, event);
1605265236Sken
1606265236Sken	switch (event->Event) {
1607265236Sken	case MPI2_EVENT_LOG_DATA:
1608265236Sken		mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_DATA:\n");
1609265236Sken		if (sc->mpr_debug & MPR_EVENT)
1610265236Sken			hexdump(event->EventData, event->EventDataLength, NULL,
1611265236Sken			    0);
1612265236Sken		break;
1613265236Sken	case MPI2_EVENT_LOG_ENTRY_ADDED:
1614265236Sken		entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
1615265236Sken		mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
1616265236Sken		    "0x%x Sequence %d:\n", entry->LogEntryQualifier,
1617265236Sken		     entry->LogSequence);
1618265236Sken		break;
1619265236Sken	default:
1620265236Sken		break;
1621265236Sken	}
1622265236Sken	return;
1623265236Sken}
1624265236Sken
1625265236Skenstatic int
1626265236Skenmpr_attach_log(struct mpr_softc *sc)
1627265236Sken{
1628265236Sken	uint8_t events[16];
1629265236Sken
1630265236Sken	bzero(events, 16);
1631265236Sken	setbit(events, MPI2_EVENT_LOG_DATA);
1632265236Sken	setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
1633265236Sken
1634265236Sken	mpr_register_events(sc, events, mpr_log_evt_handler, NULL,
1635265236Sken	    &sc->mpr_log_eh);
1636265236Sken
1637265236Sken	return (0);
1638265236Sken}
1639265236Sken
1640265236Skenstatic int
1641265236Skenmpr_detach_log(struct mpr_softc *sc)
1642265236Sken{
1643265236Sken
1644265236Sken	if (sc->mpr_log_eh != NULL)
1645265236Sken		mpr_deregister_events(sc, sc->mpr_log_eh);
1646265236Sken	return (0);
1647265236Sken}
1648265236Sken
1649265236Sken/*
1650265236Sken * Free all of the driver resources and detach submodules.  Should be called
1651265236Sken * without the lock held.
1652265236Sken */
1653265236Skenint
1654265236Skenmpr_free(struct mpr_softc *sc)
1655265236Sken{
1656265236Sken	int error;
1657265236Sken
1658265236Sken	/* Turn off the watchdog */
1659265236Sken	mpr_lock(sc);
1660265236Sken	sc->mpr_flags |= MPR_FLAGS_SHUTDOWN;
1661265236Sken	mpr_unlock(sc);
1662265236Sken	/* Lock must not be held for this */
1663265236Sken	callout_drain(&sc->periodic);
1664265236Sken
1665265236Sken	if (((error = mpr_detach_log(sc)) != 0) ||
1666265236Sken	    ((error = mpr_detach_sas(sc)) != 0))
1667265236Sken		return (error);
1668265236Sken
1669265236Sken	mpr_detach_user(sc);
1670265236Sken
1671265236Sken	/* Put the IOC back in the READY state. */
1672265236Sken	mpr_lock(sc);
1673265236Sken	if ((error = mpr_transition_ready(sc)) != 0) {
1674265236Sken		mpr_unlock(sc);
1675265236Sken		return (error);
1676265236Sken	}
1677265236Sken	mpr_unlock(sc);
1678265236Sken
1679265236Sken	if (sc->facts != NULL)
1680265236Sken		free(sc->facts, M_MPR);
1681265236Sken
1682265236Sken	/*
1683265236Sken	 * Free all buffers that are based on IOC Facts.  A Diag Reset may need
1684265236Sken	 * to free these buffers too.
1685265236Sken	 */
1686265236Sken	mpr_iocfacts_free(sc);
1687265236Sken
1688265236Sken	if (sc->sysctl_tree != NULL)
1689265236Sken		sysctl_ctx_free(&sc->sysctl_ctx);
1690265236Sken
1691265236Sken	/* Deregister the shutdown function */
1692265236Sken	if (sc->shutdown_eh != NULL)
1693265236Sken		EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
1694265236Sken
1695265236Sken	mtx_destroy(&sc->mpr_mtx);
1696265236Sken
1697265236Sken	return (0);
1698265236Sken}
1699265236Sken
1700265236Skenstatic __inline void
1701265236Skenmpr_complete_command(struct mpr_softc *sc, struct mpr_command *cm)
1702265236Sken{
1703265236Sken	MPR_FUNCTRACE(sc);
1704265236Sken
1705265236Sken	if (cm == NULL) {
1706265236Sken		mpr_dprint(sc, MPR_ERROR, "Completing NULL command\n");
1707265236Sken		return;
1708265236Sken	}
1709265236Sken
1710265236Sken	if (cm->cm_flags & MPR_CM_FLAGS_POLLED)
1711265236Sken		cm->cm_flags |= MPR_CM_FLAGS_COMPLETE;
1712265236Sken
1713265236Sken	if (cm->cm_complete != NULL) {
1714265236Sken		mpr_dprint(sc, MPR_TRACE,
1715265236Sken			   "%s cm %p calling cm_complete %p data %p reply %p\n",
1716265236Sken			   __func__, cm, cm->cm_complete, cm->cm_complete_data,
1717265236Sken			   cm->cm_reply);
1718265236Sken		cm->cm_complete(sc, cm);
1719265236Sken	}
1720265236Sken
1721265236Sken	if (cm->cm_flags & MPR_CM_FLAGS_WAKEUP) {
1722265236Sken		mpr_dprint(sc, MPR_TRACE, "waking up %p\n", cm);
1723265236Sken		wakeup(cm);
1724265236Sken	}
1725265236Sken
1726265236Sken	if (sc->io_cmds_active != 0) {
1727265236Sken		sc->io_cmds_active--;
1728265236Sken	} else {
1729265236Sken		mpr_dprint(sc, MPR_ERROR, "Warning: io_cmds_active is "
1730265236Sken		    "out of sync - resynching to 0\n");
1731265236Sken	}
1732265236Sken}
1733265236Sken
1734265236Skenstatic void
1735265236Skenmpr_sas_log_info(struct mpr_softc *sc , u32 log_info)
1736265236Sken{
1737265236Sken	union loginfo_type {
1738265236Sken		u32	loginfo;
1739265236Sken		struct {
1740265236Sken			u32	subcode:16;
1741265236Sken			u32	code:8;
1742265236Sken			u32	originator:4;
1743265236Sken			u32	bus_type:4;
1744265236Sken		} dw;
1745265236Sken	};
1746265236Sken	union loginfo_type sas_loginfo;
1747265236Sken	char *originator_str = NULL;
1748265236Sken
1749265236Sken	sas_loginfo.loginfo = log_info;
1750265236Sken	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
1751265236Sken		return;
1752265236Sken
1753265236Sken	/* each nexus loss loginfo */
1754265236Sken	if (log_info == 0x31170000)
1755265236Sken		return;
1756265236Sken
1757265236Sken	/* eat the loginfos associated with task aborts */
1758265236Sken	if ((log_info == 30050000) || (log_info == 0x31140000) ||
1759265236Sken	    (log_info == 0x31130000))
1760265236Sken		return;
1761265236Sken
1762265236Sken	switch (sas_loginfo.dw.originator) {
1763265236Sken	case 0:
1764265236Sken		originator_str = "IOP";
1765265236Sken		break;
1766265236Sken	case 1:
1767265236Sken		originator_str = "PL";
1768265236Sken		break;
1769265236Sken	case 2:
1770265236Sken		originator_str = "IR";
1771265236Sken		break;
1772265236Sken	}
1773265236Sken
1774265236Sken	mpr_dprint(sc, MPR_INFO, "log_info(0x%08x): originator(%s), "
1775265236Sken	    "code(0x%02x), sub_code(0x%04x)\n", log_info,
1776265236Sken	    originator_str, sas_loginfo.dw.code,
1777265236Sken	    sas_loginfo.dw.subcode);
1778265236Sken}
1779265236Sken
1780265236Skenstatic void
1781265236Skenmpr_display_reply_info(struct mpr_softc *sc, uint8_t *reply)
1782265236Sken{
1783265236Sken	MPI2DefaultReply_t *mpi_reply;
1784265236Sken	u16 sc_status;
1785265236Sken
1786265236Sken	mpi_reply = (MPI2DefaultReply_t*)reply;
1787265236Sken	sc_status = le16toh(mpi_reply->IOCStatus);
1788265236Sken	if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
1789265236Sken		mpr_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
1790265236Sken}
1791265236Sken
1792265236Skenvoid
1793265236Skenmpr_intr(void *data)
1794265236Sken{
1795265236Sken	struct mpr_softc *sc;
1796265236Sken	uint32_t status;
1797265236Sken
1798265236Sken	sc = (struct mpr_softc *)data;
1799265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
1800265236Sken
1801265236Sken	/*
1802265236Sken	 * Check interrupt status register to flush the bus.  This is
1803265236Sken	 * needed for both INTx interrupts and driver-driven polling
1804265236Sken	 */
1805265236Sken	status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
1806265236Sken	if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
1807265236Sken		return;
1808265236Sken
1809265236Sken	mpr_lock(sc);
1810265236Sken	mpr_intr_locked(data);
1811265236Sken	mpr_unlock(sc);
1812265236Sken	return;
1813265236Sken}
1814265236Sken
1815265236Sken/*
1816265236Sken * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
1817265236Sken * chip.  Hopefully this theory is correct.
1818265236Sken */
1819265236Skenvoid
1820265236Skenmpr_intr_msi(void *data)
1821265236Sken{
1822265236Sken	struct mpr_softc *sc;
1823265236Sken
1824265236Sken	sc = (struct mpr_softc *)data;
1825265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
1826265236Sken	mpr_lock(sc);
1827265236Sken	mpr_intr_locked(data);
1828265236Sken	mpr_unlock(sc);
1829265236Sken	return;
1830265236Sken}
1831265236Sken
1832265236Sken/*
1833265236Sken * The locking is overly broad and simplistic, but easy to deal with for now.
1834265236Sken */
1835265236Skenvoid
1836265236Skenmpr_intr_locked(void *data)
1837265236Sken{
1838265236Sken	MPI2_REPLY_DESCRIPTORS_UNION *desc;
1839265236Sken	struct mpr_softc *sc;
1840265236Sken	struct mpr_command *cm = NULL;
1841265236Sken	uint8_t flags;
1842265236Sken	u_int pq;
1843265236Sken	MPI2_DIAG_RELEASE_REPLY *rel_rep;
1844265236Sken	mpr_fw_diagnostic_buffer_t *pBuffer;
1845265236Sken
1846265236Sken	sc = (struct mpr_softc *)data;
1847265236Sken
1848265236Sken	pq = sc->replypostindex;
1849265236Sken	mpr_dprint(sc, MPR_TRACE,
1850265236Sken	    "%s sc %p starting with replypostindex %u\n",
1851265236Sken	    __func__, sc, sc->replypostindex);
1852265236Sken
1853265236Sken	for ( ;; ) {
1854265236Sken		cm = NULL;
1855265236Sken		desc = &sc->post_queue[sc->replypostindex];
1856265236Sken		flags = desc->Default.ReplyFlags &
1857265236Sken		    MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1858265236Sken		if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) ||
1859265236Sken		    (le32toh(desc->Words.High) == 0xffffffff))
1860265236Sken			break;
1861265236Sken
1862265236Sken		/* increment the replypostindex now, so that event handlers
1863265236Sken		 * and cm completion handlers which decide to do a diag
1864265236Sken		 * reset can zero it without it getting incremented again
1865265236Sken		 * afterwards, and we break out of this loop on the next
1866265236Sken		 * iteration since the reply post queue has been cleared to
1867265236Sken		 * 0xFF and all descriptors look unused (which they are).
1868265236Sken		 */
1869265236Sken		if (++sc->replypostindex >= sc->pqdepth)
1870265236Sken			sc->replypostindex = 0;
1871265236Sken
1872265236Sken		switch (flags) {
1873265236Sken		case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
1874265236Sken		case MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS:
1875265236Sken			cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
1876265236Sken			cm->cm_reply = NULL;
1877265236Sken			break;
1878265236Sken		case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
1879265236Sken		{
1880265236Sken			uint32_t baddr;
1881265236Sken			uint8_t *reply;
1882265236Sken
1883265236Sken			/*
1884265236Sken			 * Re-compose the reply address from the address
1885265236Sken			 * sent back from the chip.  The ReplyFrameAddress
1886265236Sken			 * is the lower 32 bits of the physical address of
1887265236Sken			 * particular reply frame.  Convert that address to
1888265236Sken			 * host format, and then use that to provide the
1889265236Sken			 * offset against the virtual address base
1890265236Sken			 * (sc->reply_frames).
1891265236Sken			 */
1892265236Sken			baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
1893265236Sken			reply = sc->reply_frames +
1894265236Sken				(baddr - ((uint32_t)sc->reply_busaddr));
1895265236Sken			/*
1896265236Sken			 * Make sure the reply we got back is in a valid
1897265236Sken			 * range.  If not, go ahead and panic here, since
1898265236Sken			 * we'll probably panic as soon as we deference the
1899265236Sken			 * reply pointer anyway.
1900265236Sken			 */
1901265236Sken			if ((reply < sc->reply_frames)
1902265236Sken			 || (reply > (sc->reply_frames +
1903265236Sken			     (sc->fqdepth * sc->facts->ReplyFrameSize * 4)))) {
1904265236Sken				printf("%s: WARNING: reply %p out of range!\n",
1905265236Sken				       __func__, reply);
1906265236Sken				printf("%s: reply_frames %p, fqdepth %d, "
1907265236Sken				       "frame size %d\n", __func__,
1908265236Sken				       sc->reply_frames, sc->fqdepth,
1909265236Sken				       sc->facts->ReplyFrameSize * 4);
1910265236Sken				printf("%s: baddr %#x,\n", __func__, baddr);
1911265236Sken				/* LSI-TODO. See Linux Code for Graceful exit */
1912265236Sken				panic("Reply address out of range");
1913265236Sken			}
1914265236Sken			if (le16toh(desc->AddressReply.SMID) == 0) {
1915265236Sken				if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
1916265236Sken				    MPI2_FUNCTION_DIAG_BUFFER_POST) {
1917265236Sken					/*
1918265236Sken					 * If SMID is 0 for Diag Buffer Post,
1919265236Sken					 * this implies that the reply is due to
1920265236Sken					 * a release function with a status that
1921265236Sken					 * the buffer has been released.  Set
1922265236Sken					 * the buffer flags accordingly.
1923265236Sken					 */
1924265236Sken					rel_rep =
1925265236Sken					    (MPI2_DIAG_RELEASE_REPLY *)reply;
1926265236Sken					if (le16toh(rel_rep->IOCStatus) ==
1927265236Sken					    MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
1928265236Sken					    {
1929265236Sken						pBuffer =
1930265236Sken						    &sc->fw_diag_buffer_list[
1931265236Sken						    rel_rep->BufferType];
1932265236Sken						pBuffer->valid_data = TRUE;
1933265236Sken						pBuffer->owned_by_firmware =
1934265236Sken						    FALSE;
1935265236Sken						pBuffer->immediate = FALSE;
1936265236Sken					}
1937265236Sken				} else
1938265236Sken					mpr_dispatch_event(sc, baddr,
1939265236Sken					    (MPI2_EVENT_NOTIFICATION_REPLY *)
1940265236Sken					    reply);
1941265236Sken			} else {
1942265236Sken				cm = &sc->commands[
1943265236Sken				    le16toh(desc->AddressReply.SMID)];
1944265236Sken				cm->cm_reply = reply;
1945265236Sken				cm->cm_reply_data =
1946265236Sken				    le32toh(desc->AddressReply.
1947265236Sken				    ReplyFrameAddress);
1948265236Sken			}
1949265236Sken			break;
1950265236Sken		}
1951265236Sken		case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
1952265236Sken		case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
1953265236Sken		case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
1954265236Sken		default:
1955265236Sken			/* Unhandled */
1956265236Sken			mpr_dprint(sc, MPR_ERROR, "Unhandled reply 0x%x\n",
1957265236Sken			    desc->Default.ReplyFlags);
1958265236Sken			cm = NULL;
1959265236Sken			break;
1960265236Sken		}
1961265236Sken
1962265236Sken		if (cm != NULL) {
1963265236Sken			// Print Error reply frame
1964265236Sken			if (cm->cm_reply)
1965265236Sken				mpr_display_reply_info(sc,cm->cm_reply);
1966265236Sken			mpr_complete_command(sc, cm);
1967265236Sken		}
1968265236Sken
1969265236Sken		desc->Words.Low = 0xffffffff;
1970265236Sken		desc->Words.High = 0xffffffff;
1971265236Sken	}
1972265236Sken
1973265236Sken	if (pq != sc->replypostindex) {
1974265236Sken		mpr_dprint(sc, MPR_TRACE,
1975265236Sken		    "%s sc %p writing postindex %d\n",
1976265236Sken		    __func__, sc, sc->replypostindex);
1977265236Sken		mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET,
1978265236Sken		    sc->replypostindex);
1979265236Sken	}
1980265236Sken
1981265236Sken	return;
1982265236Sken}
1983265236Sken
1984265236Skenstatic void
1985265236Skenmpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
1986265236Sken    MPI2_EVENT_NOTIFICATION_REPLY *reply)
1987265236Sken{
1988265236Sken	struct mpr_event_handle *eh;
1989265236Sken	int event, handled = 0;
1990265236Sken
1991265236Sken	event = le16toh(reply->Event);
1992265236Sken	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
1993265236Sken		if (isset(eh->mask, event)) {
1994265236Sken			eh->callback(sc, data, reply);
1995265236Sken			handled++;
1996265236Sken		}
1997265236Sken	}
1998265236Sken
1999265236Sken	if (handled == 0)
2000265236Sken		mpr_dprint(sc, MPR_EVENT, "Unhandled event 0x%x\n",
2001265236Sken		    le16toh(event));
2002265236Sken
2003265236Sken	/*
2004265236Sken	 * This is the only place that the event/reply should be freed.
2005265236Sken	 * Anything wanting to hold onto the event data should have
2006265236Sken	 * already copied it into their own storage.
2007265236Sken	 */
2008265236Sken	mpr_free_reply(sc, data);
2009265236Sken}
2010265236Sken
2011265236Skenstatic void
2012265236Skenmpr_reregister_events_complete(struct mpr_softc *sc, struct mpr_command *cm)
2013265236Sken{
2014265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2015265236Sken
2016265236Sken	if (cm->cm_reply)
2017265236Sken		mpr_print_event(sc,
2018265236Sken			(MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
2019265236Sken
2020265236Sken	mpr_free_command(sc, cm);
2021265236Sken
2022265236Sken	/* next, send a port enable */
2023265236Sken	mprsas_startup(sc);
2024265236Sken}
2025265236Sken
2026265236Sken/*
2027265236Sken * For both register_events and update_events, the caller supplies a bitmap
2028265236Sken * of events that it _wants_.  These functions then turn that into a bitmask
2029265236Sken * suitable for the controller.
2030265236Sken */
2031265236Skenint
2032265236Skenmpr_register_events(struct mpr_softc *sc, uint8_t *mask,
2033265236Sken    mpr_evt_callback_t *cb, void *data, struct mpr_event_handle **handle)
2034265236Sken{
2035265236Sken	struct mpr_event_handle *eh;
2036265236Sken	int error = 0;
2037265236Sken
2038265236Sken	eh = malloc(sizeof(struct mpr_event_handle), M_MPR, M_WAITOK|M_ZERO);
2039265236Sken	if (!eh) {
2040265236Sken		device_printf(sc->mpr_dev, "Cannot allocate memory %s %d\n",
2041265236Sken		    __func__, __LINE__);
2042265236Sken		return (ENOMEM);
2043265236Sken	}
2044265236Sken	eh->callback = cb;
2045265236Sken	eh->data = data;
2046265236Sken	TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
2047265236Sken	if (mask != NULL)
2048265236Sken		error = mpr_update_events(sc, eh, mask);
2049265236Sken	*handle = eh;
2050265236Sken
2051265236Sken	return (error);
2052265236Sken}
2053265236Sken
2054265236Skenint
2055265236Skenmpr_update_events(struct mpr_softc *sc, struct mpr_event_handle *handle,
2056265236Sken    uint8_t *mask)
2057265236Sken{
2058265236Sken	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2059265236Sken	MPI2_EVENT_NOTIFICATION_REPLY *reply;
2060265236Sken	struct mpr_command *cm;
2061265236Sken	struct mpr_event_handle *eh;
2062265236Sken	int error, i;
2063265236Sken
2064265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2065265236Sken
2066265236Sken	if ((mask != NULL) && (handle != NULL))
2067265236Sken		bcopy(mask, &handle->mask[0], 16);
2068265236Sken	memset(sc->event_mask, 0xff, 16);
2069265236Sken
2070265236Sken	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2071265236Sken		for (i = 0; i < 16; i++)
2072265236Sken			sc->event_mask[i] &= ~eh->mask[i];
2073265236Sken	}
2074265236Sken
2075265236Sken	if ((cm = mpr_alloc_command(sc)) == NULL)
2076265236Sken		return (EBUSY);
2077265236Sken	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2078265236Sken	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2079265236Sken	evtreq->MsgFlags = 0;
2080265236Sken	evtreq->SASBroadcastPrimitiveMasks = 0;
2081265236Sken#ifdef MPR_DEBUG_ALL_EVENTS
2082265236Sken	{
2083265236Sken		u_char fullmask[16];
2084265236Sken		memset(fullmask, 0x00, 16);
2085265236Sken		bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2086265236Sken	}
2087265236Sken#else
2088265236Sken		bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2089265236Sken#endif
2090265236Sken	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2091265236Sken	cm->cm_data = NULL;
2092265236Sken
2093265236Sken	error = mpr_request_polled(sc, cm);
2094265236Sken	reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
2095265236Sken	if ((reply == NULL) ||
2096265236Sken	    (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
2097265236Sken		error = ENXIO;
2098265236Sken
2099265236Sken	if(reply)
2100265236Sken		mpr_print_event(sc, reply);
2101265236Sken
2102265236Sken	mpr_dprint(sc, MPR_TRACE, "%s finished error %d\n", __func__, error);
2103265236Sken
2104265236Sken	mpr_free_command(sc, cm);
2105265236Sken	return (error);
2106265236Sken}
2107265236Sken
2108265236Skenstatic int
2109265236Skenmpr_reregister_events(struct mpr_softc *sc)
2110265236Sken{
2111265236Sken	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2112265236Sken	struct mpr_command *cm;
2113265236Sken	struct mpr_event_handle *eh;
2114265236Sken	int error, i;
2115265236Sken
2116265236Sken	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2117265236Sken
2118265236Sken	/* first, reregister events */
2119265236Sken
2120265236Sken	memset(sc->event_mask, 0xff, 16);
2121265236Sken
2122265236Sken	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2123265236Sken		for (i = 0; i < 16; i++)
2124265236Sken			sc->event_mask[i] &= ~eh->mask[i];
2125265236Sken	}
2126265236Sken
2127265236Sken	if ((cm = mpr_alloc_command(sc)) == NULL)
2128265236Sken		return (EBUSY);
2129265236Sken	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2130265236Sken	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2131265236Sken	evtreq->MsgFlags = 0;
2132265236Sken	evtreq->SASBroadcastPrimitiveMasks = 0;
2133265236Sken#ifdef MPR_DEBUG_ALL_EVENTS
2134265236Sken	{
2135265236Sken		u_char fullmask[16];
2136265236Sken		memset(fullmask, 0x00, 16);
2137265236Sken		bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2138265236Sken	}
2139265236Sken#else
2140265236Sken		bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2141265236Sken#endif
2142265236Sken	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2143265236Sken	cm->cm_data = NULL;
2144265236Sken	cm->cm_complete = mpr_reregister_events_complete;
2145265236Sken
2146265236Sken	error = mpr_map_command(sc, cm);
2147265236Sken
2148265236Sken	mpr_dprint(sc, MPR_TRACE, "%s finished with error %d\n", __func__,
2149265236Sken	    error);
2150265236Sken	return (error);
2151265236Sken}
2152265236Sken
2153265236Skenint
2154265236Skenmpr_deregister_events(struct mpr_softc *sc, struct mpr_event_handle *handle)
2155265236Sken{
2156265236Sken
2157265236Sken	TAILQ_REMOVE(&sc->event_list, handle, eh_list);
2158265236Sken	free(handle, M_MPR);
2159265236Sken	return (mpr_update_events(sc, NULL, NULL));
2160265236Sken}
2161265236Sken
2162265236Sken/*
2163265236Sken * Add a chain element as the next SGE for the specified command.
2164265236Sken * Reset cm_sge and cm_sgesize to indicate all the available space. Chains are
2165265236Sken * only required for IEEE commands.  Therefore there is no code for commands
2166265236Sken * that have the MPR_CM_FLAGS_SGE_SIMPLE flag set (and those commands shouldn't
2167265236Sken * be requesting chains).
2168265236Sken */
2169265236Skenstatic int
2170265236Skenmpr_add_chain(struct mpr_command *cm, int segsleft)
2171265236Sken{
2172265236Sken	struct mpr_softc *sc = cm->cm_sc;
2173265236Sken	MPI2_REQUEST_HEADER *req;
2174265236Sken	MPI25_IEEE_SGE_CHAIN64 *ieee_sgc;
2175265236Sken	struct mpr_chain *chain;
2176265236Sken	int space, sgc_size, current_segs, rem_segs, segs_per_frame;
2177265236Sken	uint8_t next_chain_offset = 0;
2178265236Sken
2179265236Sken	/*
2180265236Sken	 * Fail if a command is requesting a chain for SIMPLE SGE's.  For SAS3
2181265236Sken	 * only IEEE commands should be requesting chains.  Return some error
2182265236Sken	 * code other than 0.
2183265236Sken	 */
2184265236Sken	if (cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE) {
2185265236Sken		mpr_dprint(sc, MPR_ERROR, "A chain element cannot be added to "
2186265236Sken		    "an MPI SGL.\n");
2187265236Sken		return(ENOBUFS);
2188265236Sken	}
2189265236Sken
2190265236Sken	sgc_size = sizeof(MPI25_IEEE_SGE_CHAIN64);
2191265236Sken	if (cm->cm_sglsize < sgc_size)
2192265236Sken		panic("MPR: Need SGE Error Code\n");
2193265236Sken
2194265236Sken	chain = mpr_alloc_chain(cm->cm_sc);
2195265236Sken	if (chain == NULL)
2196265236Sken		return (ENOBUFS);
2197265236Sken
2198265236Sken	space = (int)cm->cm_sc->facts->IOCRequestFrameSize * 4;
2199265236Sken
2200265236Sken	/*
2201265236Sken	 * Note: a double-linked list is used to make it easier to walk for
2202265236Sken	 * debugging.
2203265236Sken	 */
2204265236Sken	TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
2205265236Sken
2206265236Sken	/*
2207265236Sken	 * Need to know if the number of frames left is more than 1 or not.  If
2208265236Sken	 * more than 1 frame is required, NextChainOffset will need to be set,
2209265236Sken	 * which will just be the last segment of the frame.
2210265236Sken	 */
2211265236Sken	rem_segs = 0;
2212265236Sken	if (cm->cm_sglsize < (sgc_size * segsleft)) {
2213265236Sken		/*
2214265236Sken		 * rem_segs is the number of segements remaining after the
2215265236Sken		 * segments that will go into the current frame.  Since it is
2216265236Sken		 * known that at least one more frame is required, account for
2217265236Sken		 * the chain element.  To know if more than one more frame is
2218265236Sken		 * required, just check if there will be a remainder after using
2219265236Sken		 * the current frame (with this chain) and the next frame.  If
2220265236Sken		 * so the NextChainOffset must be the last element of the next
2221265236Sken		 * frame.
2222265236Sken		 */
2223265236Sken		current_segs = (cm->cm_sglsize / sgc_size) - 1;
2224265236Sken		rem_segs = segsleft - current_segs;
2225265236Sken		segs_per_frame = space / sgc_size;
2226265236Sken		if (rem_segs > segs_per_frame) {
2227265236Sken			next_chain_offset = segs_per_frame - 1;
2228265236Sken		}
2229265236Sken	}
2230265236Sken	ieee_sgc = &((MPI25_SGE_IO_UNION *)cm->cm_sge)->IeeeChain;
2231265236Sken	ieee_sgc->Length = next_chain_offset ? htole32((uint32_t)space) :
2232265236Sken	    htole32((uint32_t)rem_segs * (uint32_t)sgc_size);
2233265236Sken	ieee_sgc->NextChainOffset = next_chain_offset;
2234265236Sken	ieee_sgc->Flags = (MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2235265236Sken	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
2236265236Sken	ieee_sgc->Address.Low = htole32(chain->chain_busaddr);
2237265236Sken	ieee_sgc->Address.High = htole32(chain->chain_busaddr >> 32);
2238265236Sken	cm->cm_sge = &((MPI25_SGE_IO_UNION *)chain->chain)->IeeeSimple;
2239265236Sken	req = (MPI2_REQUEST_HEADER *)cm->cm_req;
2240265236Sken	req->ChainOffset = ((sc->facts->IOCRequestFrameSize * 4) -
2241265236Sken	    sgc_size) >> 4;
2242265236Sken
2243265236Sken	cm->cm_sglsize = space;
2244265236Sken	return (0);
2245265236Sken}
2246265236Sken
2247265236Sken/*
2248265236Sken * Add one scatter-gather element to the scatter-gather list for a command.
2249265236Sken * Maintain cm_sglsize and cm_sge as the remaining size and pointer to the next
2250265236Sken * SGE to fill in, respectively.  In Gen3, the MPI SGL does not have a chain,
2251265236Sken * so don't consider any chain additions.
2252265236Sken */
2253265236Skenint
2254265236Skenmpr_push_sge(struct mpr_command *cm, MPI2_SGE_SIMPLE64 *sge, size_t len,
2255265236Sken    int segsleft)
2256265236Sken{
2257265236Sken	uint32_t saved_buf_len, saved_address_low, saved_address_high;
2258265236Sken	u32 sge_flags;
2259265236Sken
2260265236Sken	/*
2261265236Sken	 * case 1: >=1 more segment, no room for anything (error)
2262265236Sken	 * case 2: 1 more segment and enough room for it
2263265236Sken         */
2264265236Sken
2265265236Sken	if (cm->cm_sglsize < (segsleft * sizeof(MPI2_SGE_SIMPLE64))) {
2266265236Sken		mpr_dprint(cm->cm_sc, MPR_ERROR,
2267265236Sken		    "%s: warning: Not enough room for MPI SGL in frame.\n",
2268265236Sken		    __func__);
2269265236Sken		return(ENOBUFS);
2270265236Sken	}
2271265236Sken
2272265236Sken	KASSERT(segsleft == 1,
2273265236Sken	    ("segsleft cannot be more than 1 for an MPI SGL; segsleft = %d\n",
2274265236Sken	    segsleft));
2275265236Sken
2276265236Sken	/*
2277265236Sken	 * There is one more segment left to add for the MPI SGL and there is
2278265236Sken	 * enough room in the frame to add it.  This is the normal case because
2279265236Sken	 * MPI SGL's don't have chains, otherwise something is wrong.
2280265236Sken	 *
2281265236Sken	 * If this is a bi-directional request, need to account for that
2282265236Sken	 * here.  Save the pre-filled sge values.  These will be used
2283265236Sken	 * either for the 2nd SGL or for a single direction SGL.  If
2284265236Sken	 * cm_out_len is non-zero, this is a bi-directional request, so
2285265236Sken	 * fill in the OUT SGL first, then the IN SGL, otherwise just
2286265236Sken	 * fill in the IN SGL.  Note that at this time, when filling in
2287265236Sken	 * 2 SGL's for a bi-directional request, they both use the same
2288265236Sken	 * DMA buffer (same cm command).
2289265236Sken	 */
2290265236Sken	saved_buf_len = sge->FlagsLength & 0x00FFFFFF;
2291265236Sken	saved_address_low = sge->Address.Low;
2292265236Sken	saved_address_high = sge->Address.High;
2293265236Sken	if (cm->cm_out_len) {
2294265236Sken		sge->FlagsLength = cm->cm_out_len |
2295265236Sken		    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2296265236Sken		    MPI2_SGE_FLAGS_END_OF_BUFFER |
2297265236Sken		    MPI2_SGE_FLAGS_HOST_TO_IOC |
2298265236Sken		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2299265236Sken		    MPI2_SGE_FLAGS_SHIFT);
2300265236Sken		cm->cm_sglsize -= len;
2301265236Sken		/* Endian Safe code */
2302265236Sken		sge_flags = sge->FlagsLength;
2303265236Sken		sge->FlagsLength = htole32(sge_flags);
2304265236Sken		sge->Address.High = htole32(sge->Address.High);
2305265236Sken		sge->Address.Low = htole32(sge->Address.Low);
2306265236Sken		bcopy(sge, cm->cm_sge, len);
2307265236Sken		cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2308265236Sken	}
2309265236Sken	sge->FlagsLength = saved_buf_len |
2310265236Sken	    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2311265236Sken	    MPI2_SGE_FLAGS_END_OF_BUFFER |
2312265236Sken	    MPI2_SGE_FLAGS_LAST_ELEMENT |
2313265236Sken	    MPI2_SGE_FLAGS_END_OF_LIST |
2314265236Sken	    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2315265236Sken	    MPI2_SGE_FLAGS_SHIFT);
2316265236Sken	if (cm->cm_flags & MPR_CM_FLAGS_DATAIN) {
2317265236Sken		sge->FlagsLength |=
2318265236Sken		    ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
2319265236Sken		    MPI2_SGE_FLAGS_SHIFT);
2320265236Sken	} else {
2321265236Sken		sge->FlagsLength |=
2322265236Sken		    ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
2323265236Sken		    MPI2_SGE_FLAGS_SHIFT);
2324265236Sken	}
2325265236Sken	sge->Address.Low = saved_address_low;
2326265236Sken	sge->Address.High = saved_address_high;
2327265236Sken
2328265236Sken	cm->cm_sglsize -= len;
2329265236Sken	/* Endian Safe code */
2330265236Sken	sge_flags = sge->FlagsLength;
2331265236Sken	sge->FlagsLength = htole32(sge_flags);
2332265236Sken	sge->Address.High = htole32(sge->Address.High);
2333265236Sken	sge->Address.Low = htole32(sge->Address.Low);
2334265236Sken	bcopy(sge, cm->cm_sge, len);
2335265236Sken	cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2336265236Sken	return (0);
2337265236Sken}
2338265236Sken
2339265236Sken/*
2340265236Sken * Add one IEEE scatter-gather element (chain or simple) to the IEEE scatter-
2341265236Sken * gather list for a command.  Maintain cm_sglsize and cm_sge as the
2342265236Sken * remaining size and pointer to the next SGE to fill in, respectively.
2343265236Sken */
2344265236Skenint
2345265236Skenmpr_push_ieee_sge(struct mpr_command *cm, void *sgep, int segsleft)
2346265236Sken{
2347265236Sken	MPI2_IEEE_SGE_SIMPLE64 *sge = sgep;
2348265236Sken	int error, ieee_sge_size = sizeof(MPI25_SGE_IO_UNION);
2349265236Sken	uint32_t saved_buf_len, saved_address_low, saved_address_high;
2350265236Sken	uint32_t sge_length;
2351265236Sken
2352265236Sken	/*
2353265236Sken	 * case 1: No room for chain or segment (error).
2354265236Sken	 * case 2: Two or more segments left but only room for chain.
2355265236Sken	 * case 3: Last segment and room for it, so set flags.
2356265236Sken	 */
2357265236Sken
2358265236Sken	/*
2359265236Sken	 * There should be room for at least one element, or there is a big
2360265236Sken	 * problem.
2361265236Sken	 */
2362265236Sken	if (cm->cm_sglsize < ieee_sge_size)
2363265236Sken		panic("MPR: Need SGE Error Code\n");
2364265236Sken
2365265236Sken	if ((segsleft >= 2) && (cm->cm_sglsize < (ieee_sge_size * 2))) {
2366265236Sken		if ((error = mpr_add_chain(cm, segsleft)) != 0)
2367265236Sken			return (error);
2368265236Sken	}
2369265236Sken
2370265236Sken	if (segsleft == 1) {
2371265236Sken		/*
2372265236Sken		 * If this is a bi-directional request, need to account for that
2373265236Sken		 * here.  Save the pre-filled sge values.  These will be used
2374265236Sken		 * either for the 2nd SGL or for a single direction SGL.  If
2375265236Sken		 * cm_out_len is non-zero, this is a bi-directional request, so
2376265236Sken		 * fill in the OUT SGL first, then the IN SGL, otherwise just
2377265236Sken		 * fill in the IN SGL.  Note that at this time, when filling in
2378265236Sken		 * 2 SGL's for a bi-directional request, they both use the same
2379265236Sken		 * DMA buffer (same cm command).
2380265236Sken		 */
2381265236Sken		saved_buf_len = sge->Length;
2382265236Sken		saved_address_low = sge->Address.Low;
2383265236Sken		saved_address_high = sge->Address.High;
2384265236Sken		if (cm->cm_out_len) {
2385265236Sken			sge->Length = cm->cm_out_len;
2386265236Sken			sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2387265236Sken			    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
2388265236Sken			cm->cm_sglsize -= ieee_sge_size;
2389265236Sken			/* Endian Safe code */
2390265236Sken			sge_length = sge->Length;
2391265236Sken			sge->Length = htole32(sge_length);
2392265236Sken			sge->Address.High = htole32(sge->Address.High);
2393265236Sken			sge->Address.Low = htole32(sge->Address.Low);
2394265236Sken			bcopy(sgep, cm->cm_sge, ieee_sge_size);
2395265236Sken			cm->cm_sge =
2396265236Sken			    (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
2397265236Sken			    ieee_sge_size);
2398265236Sken		}
2399265236Sken		sge->Length = saved_buf_len;
2400265236Sken		sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2401265236Sken		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2402265236Sken		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
2403265236Sken		sge->Address.Low = saved_address_low;
2404265236Sken		sge->Address.High = saved_address_high;
2405265236Sken	}
2406265236Sken
2407265236Sken	cm->cm_sglsize -= ieee_sge_size;
2408265236Sken	/* Endian Safe code */
2409265236Sken	sge_length = sge->Length;
2410265236Sken	sge->Length = htole32(sge_length);
2411265236Sken	sge->Address.High = htole32(sge->Address.High);
2412265236Sken	sge->Address.Low = htole32(sge->Address.Low);
2413265236Sken	bcopy(sgep, cm->cm_sge, ieee_sge_size);
2414265236Sken	cm->cm_sge = (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
2415265236Sken	    ieee_sge_size);
2416265236Sken	return (0);
2417265236Sken}
2418265236Sken
2419265236Sken/*
2420265236Sken * Add one dma segment to the scatter-gather list for a command.
2421265236Sken */
2422265236Skenint
2423265236Skenmpr_add_dmaseg(struct mpr_command *cm, vm_paddr_t pa, size_t len, u_int flags,
2424265236Sken    int segsleft)
2425265236Sken{
2426265236Sken	MPI2_SGE_SIMPLE64 sge;
2427265236Sken	MPI2_IEEE_SGE_SIMPLE64 ieee_sge;
2428265236Sken
2429265236Sken	if (!(cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE)) {
2430265236Sken		ieee_sge.Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2431265236Sken		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
2432265236Sken		ieee_sge.Length = len;
2433265236Sken		mpr_from_u64(pa, &ieee_sge.Address);
2434265236Sken
2435265236Sken		return (mpr_push_ieee_sge(cm, &ieee_sge, segsleft));
2436265236Sken	} else {
2437265236Sken		/*
2438265236Sken		 * This driver always uses 64-bit address elements for
2439265236Sken		 * simplicity.
2440265236Sken		 */
2441265236Sken		flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2442265236Sken		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
2443265236Sken		/* Set Endian safe macro in mpr_push_sge */
2444265236Sken		sge.FlagsLength = len | (flags << MPI2_SGE_FLAGS_SHIFT);
2445265236Sken		mpr_from_u64(pa, &sge.Address);
2446265236Sken
2447265236Sken		return (mpr_push_sge(cm, &sge, sizeof sge, segsleft));
2448265236Sken	}
2449265236Sken}
2450265236Sken
2451265236Skenstatic void
2452265236Skenmpr_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2453265236Sken{
2454265236Sken	struct mpr_softc *sc;
2455265236Sken	struct mpr_command *cm;
2456265236Sken	u_int i, dir, sflags;
2457265236Sken
2458265236Sken	cm = (struct mpr_command *)arg;
2459265236Sken	sc = cm->cm_sc;
2460265236Sken
2461265236Sken	/*
2462265236Sken	 * In this case, just print out a warning and let the chip tell the
2463265236Sken	 * user they did the wrong thing.
2464265236Sken	 */
2465265236Sken	if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
2466265236Sken		mpr_dprint(sc, MPR_ERROR,
2467265236Sken			   "%s: warning: busdma returned %d segments, "
2468265236Sken			   "more than the %d allowed\n", __func__, nsegs,
2469265236Sken			   cm->cm_max_segs);
2470265236Sken	}
2471265236Sken
2472265236Sken	/*
2473265236Sken	 * Set up DMA direction flags.  Bi-directional requests are also handled
2474265236Sken	 * here.  In that case, both direction flags will be set.
2475265236Sken	 */
2476265236Sken	sflags = 0;
2477265236Sken	if (cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) {
2478265236Sken		/*
2479265236Sken		 * We have to add a special case for SMP passthrough, there
2480265236Sken		 * is no easy way to generically handle it.  The first
2481265236Sken		 * S/G element is used for the command (therefore the
2482265236Sken		 * direction bit needs to be set).  The second one is used
2483265236Sken		 * for the reply.  We'll leave it to the caller to make
2484265236Sken		 * sure we only have two buffers.
2485265236Sken		 */
2486265236Sken		/*
2487265236Sken		 * Even though the busdma man page says it doesn't make
2488265236Sken		 * sense to have both direction flags, it does in this case.
2489265236Sken		 * We have one s/g element being accessed in each direction.
2490265236Sken		 */
2491265236Sken		dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
2492265236Sken
2493265236Sken		/*
2494265236Sken		 * Set the direction flag on the first buffer in the SMP
2495265236Sken		 * passthrough request.  We'll clear it for the second one.
2496265236Sken		 */
2497265236Sken		sflags |= MPI2_SGE_FLAGS_DIRECTION |
2498265236Sken			  MPI2_SGE_FLAGS_END_OF_BUFFER;
2499265236Sken	} else if (cm->cm_flags & MPR_CM_FLAGS_DATAOUT) {
2500265236Sken		sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2501265236Sken		dir = BUS_DMASYNC_PREWRITE;
2502265236Sken	} else
2503265236Sken		dir = BUS_DMASYNC_PREREAD;
2504265236Sken
2505265236Sken	for (i = 0; i < nsegs; i++) {
2506265236Sken		if ((cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) && (i != 0)) {
2507265236Sken			sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
2508265236Sken		}
2509265236Sken		error = mpr_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
2510265236Sken		    sflags, nsegs - i);
2511265236Sken		if (error != 0) {
2512265236Sken			/* Resource shortage, roll back! */
2513265236Sken			if (ratecheck(&sc->lastfail, &mpr_chainfail_interval))
2514265236Sken				mpr_dprint(sc, MPR_INFO, "Out of chain frames, "
2515265236Sken				    "consider increasing hw.mpr.max_chains.\n");
2516265236Sken			cm->cm_flags |= MPR_CM_FLAGS_CHAIN_FAILED;
2517265236Sken			mpr_complete_command(sc, cm);
2518265236Sken			return;
2519265236Sken		}
2520265236Sken	}
2521265236Sken
2522265236Sken	bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
2523265236Sken	mpr_enqueue_request(sc, cm);
2524265236Sken
2525265236Sken	return;
2526265236Sken}
2527265236Sken
2528265236Skenstatic void
2529265236Skenmpr_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
2530265236Sken	     int error)
2531265236Sken{
2532265236Sken	mpr_data_cb(arg, segs, nsegs, error);
2533265236Sken}
2534265236Sken
2535265236Sken/*
2536265236Sken * This is the routine to enqueue commands ansynchronously.
2537265236Sken * Note that the only error path here is from bus_dmamap_load(), which can
2538265236Sken * return EINPROGRESS if it is waiting for resources.  Other than this, it's
2539265236Sken * assumed that if you have a command in-hand, then you have enough credits
2540265236Sken * to use it.
2541265236Sken */
2542265236Skenint
2543265236Skenmpr_map_command(struct mpr_softc *sc, struct mpr_command *cm)
2544265236Sken{
2545265236Sken	int error = 0;
2546265236Sken
2547265236Sken	if (cm->cm_flags & MPR_CM_FLAGS_USE_UIO) {
2548265236Sken		error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
2549265236Sken		    &cm->cm_uio, mpr_data_cb2, cm, 0);
2550265236Sken	} else if (cm->cm_flags & MPR_CM_FLAGS_USE_CCB) {
2551265236Sken		error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
2552265236Sken		    cm->cm_data, mpr_data_cb, cm, 0);
2553265236Sken	} else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
2554265236Sken		error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
2555265236Sken		    cm->cm_data, cm->cm_length, mpr_data_cb, cm, 0);
2556265236Sken	} else {
2557265236Sken		/* Add a zero-length element as needed */
2558265236Sken		if (cm->cm_sge != NULL)
2559265236Sken			mpr_add_dmaseg(cm, 0, 0, 0, 1);
2560265236Sken		mpr_enqueue_request(sc, cm);
2561265236Sken	}
2562265236Sken
2563265236Sken	return (error);
2564265236Sken}
2565265236Sken
2566265236Sken/*
2567265236Sken * This is the routine to enqueue commands synchronously.  An error of
2568265236Sken * EINPROGRESS from mpr_map_command() is ignored since the command will
2569265236Sken * be executed and enqueued automatically.  Other errors come from msleep().
2570265236Sken */
2571265236Skenint
2572265236Skenmpr_wait_command(struct mpr_softc *sc, struct mpr_command *cm, int timeout,
2573265236Sken    int sleep_flag)
2574265236Sken{
2575265236Sken	int error, rc;
2576265236Sken	struct timeval cur_time, start_time;
2577265236Sken
2578265236Sken	if (sc->mpr_flags & MPR_FLAGS_DIAGRESET)
2579265236Sken		return  EBUSY;
2580265236Sken
2581265236Sken	cm->cm_complete = NULL;
2582265236Sken	cm->cm_flags |= (MPR_CM_FLAGS_WAKEUP + MPR_CM_FLAGS_POLLED);
2583265236Sken	error = mpr_map_command(sc, cm);
2584265236Sken	if ((error != 0) && (error != EINPROGRESS))
2585265236Sken		return (error);
2586265236Sken
2587265236Sken	// Check for context and wait for 50 mSec at a time until time has
2588265236Sken	// expired or the command has finished.  If msleep can't be used, need
2589265236Sken	// to poll.
2590265236Sken#if __FreeBSD_version >= 1000029
2591265236Sken	if (curthread->td_no_sleeping)
2592265236Sken#else //__FreeBSD_version < 1000029
2593265236Sken	if (curthread->td_pflags & TDP_NOSLEEPING)
2594265236Sken#endif //__FreeBSD_version >= 1000029
2595265236Sken		sleep_flag = NO_SLEEP;
2596265236Sken	getmicrotime(&start_time);
2597265236Sken	if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP) {
2598265236Sken		error = msleep(cm, &sc->mpr_mtx, 0, "mprwait", timeout*hz);
2599265236Sken	} else {
2600265236Sken		while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
2601265236Sken			mpr_intr_locked(sc);
2602265236Sken			if (sleep_flag == CAN_SLEEP)
2603265236Sken				pause("mprwait", hz/20);
2604265236Sken			else
2605265236Sken				DELAY(50000);
2606265236Sken
2607265236Sken			getmicrotime(&cur_time);
2608265236Sken			if ((cur_time.tv_sec - start_time.tv_sec) > timeout) {
2609265236Sken				error = EWOULDBLOCK;
2610265236Sken				break;
2611265236Sken			}
2612265236Sken		}
2613265236Sken	}
2614265236Sken
2615265236Sken	if (error == EWOULDBLOCK) {
2616265236Sken		mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s\n", __func__);
2617265236Sken		rc = mpr_reinit(sc);
2618265236Sken		mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
2619265236Sken		    "failed");
2620265236Sken		error = ETIMEDOUT;
2621265236Sken	}
2622265236Sken	return (error);
2623265236Sken}
2624265236Sken
2625265236Sken/*
2626265236Sken * This is the routine to enqueue a command synchonously and poll for
2627265236Sken * completion.  Its use should be rare.
2628265236Sken */
2629265236Skenint
2630265236Skenmpr_request_polled(struct mpr_softc *sc, struct mpr_command *cm)
2631265236Sken{
2632265236Sken	int error, timeout = 0, rc;
2633265236Sken	struct timeval cur_time, start_time;
2634265236Sken
2635265236Sken	error = 0;
2636265236Sken
2637265236Sken	cm->cm_flags |= MPR_CM_FLAGS_POLLED;
2638265236Sken	cm->cm_complete = NULL;
2639265236Sken	mpr_map_command(sc, cm);
2640265236Sken
2641265236Sken	getmicrotime(&start_time);
2642265236Sken	while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
2643265236Sken		mpr_intr_locked(sc);
2644265236Sken
2645265236Sken		if (mtx_owned(&sc->mpr_mtx))
2646265236Sken			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
2647265236Sken			    "mprpoll", hz/20);
2648265236Sken		else
2649265236Sken			pause("mprpoll", hz/20);
2650265236Sken
2651265236Sken		/*
2652265236Sken		 * Check for real-time timeout and fail if more than 60 seconds.
2653265236Sken		 */
2654265236Sken		getmicrotime(&cur_time);
2655265236Sken		timeout = cur_time.tv_sec - start_time.tv_sec;
2656265236Sken		if (timeout > 60) {
2657265236Sken			mpr_dprint(sc, MPR_FAULT, "polling failed\n");
2658265236Sken			error = ETIMEDOUT;
2659265236Sken			break;
2660265236Sken		}
2661265236Sken	}
2662265236Sken
2663265236Sken	if(error) {
2664265236Sken		mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s\n", __func__);
2665265236Sken		rc = mpr_reinit(sc);
2666265236Sken		mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ?
2667265236Sken		    "success" : "failed");
2668265236Sken	}
2669265236Sken	return (error);
2670265236Sken}
2671265236Sken
2672265236Sken/*
2673265236Sken * The MPT driver had a verbose interface for config pages.  In this driver,
2674265236Sken * reduce it to much simplier terms, similar to the Linux driver.
2675265236Sken */
2676265236Skenint
2677265236Skenmpr_read_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
2678265236Sken{
2679265236Sken	MPI2_CONFIG_REQUEST *req;
2680265236Sken	struct mpr_command *cm;
2681265236Sken	int error;
2682265236Sken
2683265236Sken	if (sc->mpr_flags & MPR_FLAGS_BUSY) {
2684265236Sken		return (EBUSY);
2685265236Sken	}
2686265236Sken
2687265236Sken	cm = mpr_alloc_command(sc);
2688265236Sken	if (cm == NULL) {
2689265236Sken		return (EBUSY);
2690265236Sken	}
2691265236Sken
2692265236Sken	req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
2693265236Sken	req->Function = MPI2_FUNCTION_CONFIG;
2694265236Sken	req->Action = params->action;
2695265236Sken	req->SGLFlags = 0;
2696265236Sken	req->ChainOffset = 0;
2697265236Sken	req->PageAddress = params->page_address;
2698265236Sken	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
2699265236Sken		MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
2700265236Sken
2701265236Sken		hdr = &params->hdr.Ext;
2702265236Sken		req->ExtPageType = hdr->ExtPageType;
2703265236Sken		req->ExtPageLength = hdr->ExtPageLength;
2704265236Sken		req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
2705265236Sken		req->Header.PageLength = 0; /* Must be set to zero */
2706265236Sken		req->Header.PageNumber = hdr->PageNumber;
2707265236Sken		req->Header.PageVersion = hdr->PageVersion;
2708265236Sken	} else {
2709265236Sken		MPI2_CONFIG_PAGE_HEADER *hdr;
2710265236Sken
2711265236Sken		hdr = &params->hdr.Struct;
2712265236Sken		req->Header.PageType = hdr->PageType;
2713265236Sken		req->Header.PageNumber = hdr->PageNumber;
2714265236Sken		req->Header.PageLength = hdr->PageLength;
2715265236Sken		req->Header.PageVersion = hdr->PageVersion;
2716265236Sken	}
2717265236Sken
2718265236Sken	cm->cm_data = params->buffer;
2719265236Sken	cm->cm_length = params->length;
2720265236Sken	cm->cm_sge = &req->PageBufferSGE;
2721265236Sken	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
2722265236Sken	cm->cm_flags = MPR_CM_FLAGS_SGE_SIMPLE | MPR_CM_FLAGS_DATAIN;
2723265236Sken	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2724265236Sken
2725265236Sken	cm->cm_complete_data = params;
2726265236Sken	if (params->callback != NULL) {
2727265236Sken		cm->cm_complete = mpr_config_complete;
2728265236Sken		return (mpr_map_command(sc, cm));
2729265236Sken	} else {
2730265236Sken		error = mpr_wait_command(sc, cm, 0, CAN_SLEEP);
2731265236Sken		if (error) {
2732265236Sken			mpr_dprint(sc, MPR_FAULT,
2733265236Sken			    "Error %d reading config page\n", error);
2734265236Sken			mpr_free_command(sc, cm);
2735265236Sken			return (error);
2736265236Sken		}
2737265236Sken		mpr_config_complete(sc, cm);
2738265236Sken	}
2739265236Sken
2740265236Sken	return (0);
2741265236Sken}
2742265236Sken
2743265236Skenint
2744265236Skenmpr_write_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
2745265236Sken{
2746265236Sken	return (EINVAL);
2747265236Sken}
2748265236Sken
2749265236Skenstatic void
2750265236Skenmpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm)
2751265236Sken{
2752265236Sken	MPI2_CONFIG_REPLY *reply;
2753265236Sken	struct mpr_config_params *params;
2754265236Sken
2755265236Sken	MPR_FUNCTRACE(sc);
2756265236Sken	params = cm->cm_complete_data;
2757265236Sken
2758265236Sken	if (cm->cm_data != NULL) {
2759265236Sken		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
2760265236Sken		    BUS_DMASYNC_POSTREAD);
2761265236Sken		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
2762265236Sken	}
2763265236Sken
2764265236Sken	/*
2765265236Sken	 * XXX KDM need to do more error recovery?  This results in the
2766265236Sken	 * device in question not getting probed.
2767265236Sken	 */
2768265236Sken	if ((cm->cm_flags & MPR_CM_FLAGS_ERROR_MASK) != 0) {
2769265236Sken		params->status = MPI2_IOCSTATUS_BUSY;
2770265236Sken		goto done;
2771265236Sken	}
2772265236Sken
2773265236Sken	reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
2774265236Sken	if (reply == NULL) {
2775265236Sken		params->status = MPI2_IOCSTATUS_BUSY;
2776265236Sken		goto done;
2777265236Sken	}
2778265236Sken	params->status = reply->IOCStatus;
2779265236Sken	if (params->hdr.Ext.ExtPageType != 0) {
2780265236Sken		params->hdr.Ext.ExtPageType = reply->ExtPageType;
2781265236Sken		params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
2782265236Sken	} else {
2783265236Sken		params->hdr.Struct.PageType = reply->Header.PageType;
2784265236Sken		params->hdr.Struct.PageNumber = reply->Header.PageNumber;
2785265236Sken		params->hdr.Struct.PageLength = reply->Header.PageLength;
2786265236Sken		params->hdr.Struct.PageVersion = reply->Header.PageVersion;
2787265236Sken	}
2788265236Sken
2789265236Skendone:
2790265236Sken	mpr_free_command(sc, cm);
2791265236Sken	if (params->callback != NULL)
2792265236Sken		params->callback(sc, params);
2793265236Sken
2794265236Sken	return;
2795265236Sken}
2796