xref: /freebsd/sys/dev/mps/mps.c (revision 46902503bc85c7b5fcdfb06e027ad756e083b3a4)
1 /*-
2  * Copyright (c) 2009 Yahoo! Inc.
3  * Copyright (c) 2012 LSI Corp.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * LSI MPT-Fusion Host Adapter FreeBSD
28  *
29  * $FreeBSD$
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 /* Communications core for LSI MPT2 */
36 
37 /* TODO Move headers to mpsvar */
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/selinfo.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/module.h>
46 #include <sys/bus.h>
47 #include <sys/conf.h>
48 #include <sys/bio.h>
49 #include <sys/malloc.h>
50 #include <sys/uio.h>
51 #include <sys/sysctl.h>
52 #include <sys/queue.h>
53 #include <sys/kthread.h>
54 #include <sys/endian.h>
55 #include <sys/eventhandler.h>
56 
57 #include <machine/bus.h>
58 #include <machine/resource.h>
59 #include <sys/rman.h>
60 #include <sys/proc.h>
61 
62 #include <dev/pci/pcivar.h>
63 
64 #include <cam/scsi/scsi_all.h>
65 
66 #include <dev/mps/mpi/mpi2_type.h>
67 #include <dev/mps/mpi/mpi2.h>
68 #include <dev/mps/mpi/mpi2_ioc.h>
69 #include <dev/mps/mpi/mpi2_sas.h>
70 #include <dev/mps/mpi/mpi2_cnfg.h>
71 #include <dev/mps/mpi/mpi2_init.h>
72 #include <dev/mps/mpi/mpi2_tool.h>
73 #include <dev/mps/mps_ioctl.h>
74 #include <dev/mps/mpsvar.h>
75 #include <dev/mps/mps_table.h>
76 
77 static int mps_diag_reset(struct mps_softc *sc, int sleep_flag);
78 static int mps_init_queues(struct mps_softc *sc);
79 static int mps_message_unit_reset(struct mps_softc *sc, int sleep_flag);
80 static int mps_transition_operational(struct mps_softc *sc);
81 static void mps_startup(void *arg);
82 static int mps_send_iocinit(struct mps_softc *sc);
83 static int mps_attach_log(struct mps_softc *sc);
84 static __inline void mps_complete_command(struct mps_softc *sc,
85     struct mps_command *cm);
86 static void mps_dispatch_event(struct mps_softc *sc, uintptr_t data,
87     MPI2_EVENT_NOTIFICATION_REPLY *reply);
88 static void mps_config_complete(struct mps_softc *sc, struct mps_command *cm);
89 static void mps_periodic(void *);
90 static int mps_reregister_events(struct mps_softc *sc);
91 static void mps_enqueue_request(struct mps_softc *sc, struct mps_command *cm);
92 static int mps_wait_db_ack(struct mps_softc *sc, int timeout, int sleep_flag);
93 SYSCTL_NODE(_hw, OID_AUTO, mps, CTLFLAG_RD, 0, "MPS Driver Parameters");
94 
95 MALLOC_DEFINE(M_MPT2, "mps", "mpt2 driver memory");
96 
97 /*
98  * Do a "Diagnostic Reset" aka a hard reset.  This should get the chip out of
99  * any state and back to its initialization state machine.
100  */
101 static char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
102 
103 /* Added this union to smoothly convert le64toh cm->cm_desc.Words.
104  * Compiler only support unint64_t to be passed as argument.
105  * Otherwise it will through below error
106  * "aggregate value used where an integer was expected"
107  */
108 
109 typedef union _reply_descriptor {
110         u64 word;
111         struct {
112                 u32 low;
113                 u32 high;
114         } u;
115 }reply_descriptor,address_descriptor;
116 
117 /*
118  * sleep_flag can be either CAN_SLEEP or NO_SLEEP.
119  * If this function is called from process context, it can sleep
120  * and there is no harm to sleep, in case if this fuction is called
121  * from Interrupt handler, we can not sleep and need NO_SLEEP flag set.
122  * based on sleep flags driver will call either msleep, pause or DELAY.
123  * msleep and pause are of same variant, but pause is used when mps_mtx
124  * is not hold by driver.
125  *
126  */
127 static int
128 mps_diag_reset(struct mps_softc *sc,int sleep_flag)
129 {
130 	uint32_t reg;
131 	int i, error, tries = 0;
132 
133 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
134 
135 	/* Clear any pending interrupts */
136 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
137 
138 	/*Force NO_SLEEP for threads prohibited to sleep
139  	* e.a Thread from interrupt handler are prohibited to sleep.
140  	*/
141 	if (curthread->td_no_sleeping != 0)
142 		sleep_flag = NO_SLEEP;
143 
144 	/* Push the magic sequence */
145 	error = ETIMEDOUT;
146 	while (tries++ < 20) {
147 		for (i = 0; i < sizeof(mpt2_reset_magic); i++)
148 			mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
149 			    mpt2_reset_magic[i]);
150 		/* wait 100 msec */
151 		if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
152 			msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0, "mpsdiag", hz/10);
153 		else if (sleep_flag == CAN_SLEEP)
154 			pause("mpsdiag", hz/10);
155 		else
156 			DELAY(100 * 1000);
157 
158 		reg = mps_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
159 		if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
160 			error = 0;
161 			break;
162 		}
163 	}
164 	if (error)
165 		return (error);
166 
167 	/* Send the actual reset.  XXX need to refresh the reg? */
168 	mps_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET,
169 	    reg | MPI2_DIAG_RESET_ADAPTER);
170 
171 	/* Wait up to 300 seconds in 50ms intervals */
172 	error = ETIMEDOUT;
173 	for (i = 0; i < 60000; i++) {
174 		/* wait 50 msec */
175 		if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
176 			msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0, "mpsdiag", hz/20);
177 		else if (sleep_flag == CAN_SLEEP)
178 			pause("mpsdiag", hz/20);
179 		else
180 			DELAY(50 * 1000);
181 		reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
182 		if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
183 			error = 0;
184 			break;
185 		}
186 	}
187 	if (error)
188 		return (error);
189 
190 	mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
191 
192 	return (0);
193 }
194 
195 static int
196 mps_message_unit_reset(struct mps_softc *sc, int sleep_flag)
197 {
198 
199 	MPS_FUNCTRACE(sc);
200 
201 	mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
202 	    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
203 	    MPI2_DOORBELL_FUNCTION_SHIFT);
204 
205 	if (mps_wait_db_ack(sc, 5, sleep_flag) != 0) {
206 		mps_dprint(sc, MPS_FAULT, "Doorbell handshake failed : <%s>\n",
207 				__func__);
208 		return (ETIMEDOUT);
209 	}
210 
211 	return (0);
212 }
213 
214 static int
215 mps_transition_ready(struct mps_softc *sc)
216 {
217 	uint32_t reg, state;
218 	int error, tries = 0;
219 	int sleep_flags;
220 
221 	MPS_FUNCTRACE(sc);
222 	/* If we are in attach call, do not sleep */
223 	sleep_flags = (sc->mps_flags & MPS_FLAGS_ATTACH_DONE)
224 					? CAN_SLEEP:NO_SLEEP;
225 	error = 0;
226 	while (tries++ < 5) {
227 		reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
228 		mps_dprint(sc, MPS_INIT, "Doorbell= 0x%x\n", reg);
229 
230 		/*
231 		 * Ensure the IOC is ready to talk.  If it's not, try
232 		 * resetting it.
233 		 */
234 		if (reg & MPI2_DOORBELL_USED) {
235 			mps_diag_reset(sc, sleep_flags);
236 			DELAY(50000);
237 			continue;
238 		}
239 
240 		/* Is the adapter owned by another peer? */
241 		if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
242 		    (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
243 			device_printf(sc->mps_dev, "IOC is under the control "
244 			    "of another peer host, aborting initialization.\n");
245 			return (ENXIO);
246 		}
247 
248 		state = reg & MPI2_IOC_STATE_MASK;
249 		if (state == MPI2_IOC_STATE_READY) {
250 			/* Ready to go! */
251 			error = 0;
252 			break;
253 		} else if (state == MPI2_IOC_STATE_FAULT) {
254 			mps_dprint(sc, MPS_FAULT, "IOC in fault state 0x%x, resetting\n",
255 			    state & MPI2_DOORBELL_FAULT_CODE_MASK);
256 			mps_diag_reset(sc, sleep_flags);
257 		} else if (state == MPI2_IOC_STATE_OPERATIONAL) {
258 			/* Need to take ownership */
259 			mps_message_unit_reset(sc, sleep_flags);
260 		} else if (state == MPI2_IOC_STATE_RESET) {
261 			/* Wait a bit, IOC might be in transition */
262 			mps_dprint(sc, MPS_FAULT,
263 			    "IOC in unexpected reset state\n");
264 		} else {
265 			mps_dprint(sc, MPS_FAULT,
266 			    "IOC in unknown state 0x%x\n", state);
267 			error = EINVAL;
268 			break;
269 		}
270 
271 		/* Wait 50ms for things to settle down. */
272 		DELAY(50000);
273 	}
274 
275 	if (error)
276 		device_printf(sc->mps_dev, "Cannot transition IOC to ready\n");
277 
278 	return (error);
279 }
280 
281 static int
282 mps_transition_operational(struct mps_softc *sc)
283 {
284 	uint32_t reg, state;
285 	int error;
286 
287 	MPS_FUNCTRACE(sc);
288 
289 	error = 0;
290 	reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
291 	mps_dprint(sc, MPS_INIT, "Doorbell= 0x%x\n", reg);
292 
293 	state = reg & MPI2_IOC_STATE_MASK;
294 	if (state != MPI2_IOC_STATE_READY) {
295 		if ((error = mps_transition_ready(sc)) != 0) {
296 			mps_dprint(sc, MPS_FAULT,
297 			    "%s failed to transition ready\n", __func__);
298 			return (error);
299 		}
300 	}
301 
302 	error = mps_send_iocinit(sc);
303 	return (error);
304 }
305 
306 /*
307  * XXX Some of this should probably move to mps.c
308  *
309  * The terms diag reset and hard reset are used interchangeably in the MPI
310  * docs to mean resetting the controller chip.  In this code diag reset
311  * cleans everything up, and the hard reset function just sends the reset
312  * sequence to the chip.  This should probably be refactored so that every
313  * subsystem gets a reset notification of some sort, and can clean up
314  * appropriately.
315  */
316 int
317 mps_reinit(struct mps_softc *sc)
318 {
319 	int error;
320 	uint32_t db;
321 
322 	MPS_FUNCTRACE(sc);
323 
324 	mtx_assert(&sc->mps_mtx, MA_OWNED);
325 
326 	if (sc->mps_flags & MPS_FLAGS_DIAGRESET) {
327 		mps_dprint(sc, MPS_INIT, "%s reset already in progress\n",
328 			   __func__);
329 		return 0;
330 	}
331 
332 	mps_dprint(sc, MPS_INFO, "Reinitializing controller,\n");
333 	/* make sure the completion callbacks can recognize they're getting
334 	 * a NULL cm_reply due to a reset.
335 	 */
336 	sc->mps_flags |= MPS_FLAGS_DIAGRESET;
337 
338 	mps_dprint(sc, MPS_INIT, "%s mask interrupts\n", __func__);
339 	mps_mask_intr(sc);
340 
341 	error = mps_diag_reset(sc, CAN_SLEEP);
342 	if (error != 0) {
343 		/* XXXSL No need to panic here */
344 		panic("%s hard reset failed with error %d\n",
345 		    __func__, error);
346 	}
347 
348 	/* Restore the PCI state, including the MSI-X registers */
349 	mps_pci_restore(sc);
350 
351 	/* Give the I/O subsystem special priority to get itself prepared */
352 	mpssas_handle_reinit(sc);
353 
354 	/* reinitialize queues after the reset */
355 	bzero(sc->free_queue, sc->fqdepth * 4);
356 	mps_init_queues(sc);
357 
358 	/* get the chip out of the reset state */
359 	error = mps_transition_operational(sc);
360 	if (error != 0)
361 		/* XXXSL No need to panic here */
362 		panic("%s transition operational failed with error %d\n",
363 		    __func__, error);
364 
365 	/* Reinitialize the reply queue. This is delicate because this
366 	 * function is typically invoked by task mgmt completion callbacks,
367 	 * which are called by the interrupt thread.  We need to make sure
368 	 * the interrupt handler loop will exit when we return to it, and
369 	 * that it will recognize the indexes we've changed.
370 	 */
371 	sc->replypostindex = 0;
372 	mps_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
373 	mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, sc->replypostindex);
374 
375 	db = mps_regread(sc, MPI2_DOORBELL_OFFSET);
376 	mps_dprint(sc, MPS_INIT, "%s doorbell 0x%08x\n", __func__, db);
377 
378 	mps_dprint(sc, MPS_INIT, "%s unmask interrupts post %u free %u\n",
379 		   __func__, sc->replypostindex, sc->replyfreeindex);
380 
381 	mps_unmask_intr(sc);
382 
383 	mps_dprint(sc, MPS_INIT, "%s restarting post %u free %u\n", __func__,
384 	    sc->replypostindex, sc->replyfreeindex);
385 
386 	/* restart will reload the event masks clobbered by the reset, and
387 	 * then enable the port.
388 	 */
389 	mps_reregister_events(sc);
390 
391 	/* the end of discovery will release the simq, so we're done. */
392 	mps_dprint(sc, MPS_INFO, "%s finished sc %p post %u free %u\n",
393 	    __func__, sc, sc->replypostindex, sc->replyfreeindex);
394 
395 	sc->mps_flags &= ~MPS_FLAGS_DIAGRESET;
396 
397 	return 0;
398 }
399 
400 /* Wait for the chip to ACK a word that we've put into its FIFO
401  * Wait for <timeout> seconds. In single loop wait for busy loop
402  * for 500 microseconds.
403  * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
404  * */
405 static int
406 mps_wait_db_ack(struct mps_softc *sc, int timeout, int sleep_flag)
407 {
408 
409 	u32 cntdn, count;
410 	u32 int_status;
411 	u32 doorbell;
412 
413 	count = 0;
414 	cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
415 	do {
416 		int_status = mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
417 		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
418 			mps_dprint(sc, MPS_INIT,
419 			"%s: successfull count(%d), timeout(%d)\n",
420 			__func__, count, timeout);
421 		return 0;
422 		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
423 			doorbell = mps_regread(sc, MPI2_DOORBELL_OFFSET);
424 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
425 				MPI2_IOC_STATE_FAULT) {
426 				mps_dprint(sc, MPS_FAULT,
427 					"fault_state(0x%04x)!\n", doorbell);
428 				return (EFAULT);
429 			}
430 		} else if (int_status == 0xFFFFFFFF)
431 			goto out;
432 
433 		/* If it can sleep, sleep for 1 milisecond, else busy loop for
434 		* 0.5 milisecond */
435 		if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
436 			msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
437 			"mpsdba", hz/1000);
438 		else if (sleep_flag == CAN_SLEEP)
439 			pause("mpsdba", hz/1000);
440 		else
441 			DELAY(500);
442 		count++;
443 	} while (--cntdn);
444 
445 	out:
446 	mps_dprint(sc, MPS_FAULT, "%s: failed due to timeout count(%d), "
447 		"int_status(%x)!\n", __func__, count, int_status);
448 	return (ETIMEDOUT);
449 
450 }
451 
452 /* Wait for the chip to signal that the next word in its FIFO can be fetched */
453 static int
454 mps_wait_db_int(struct mps_softc *sc)
455 {
456 	int retry;
457 
458 	for (retry = 0; retry < MPS_DB_MAX_WAIT; retry++) {
459 		if ((mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
460 		    MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
461 			return (0);
462 		DELAY(2000);
463 	}
464 	return (ETIMEDOUT);
465 }
466 
467 /* Step through the synchronous command state machine, i.e. "Doorbell mode" */
468 static int
469 mps_request_sync(struct mps_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
470     int req_sz, int reply_sz, int timeout)
471 {
472 	uint32_t *data32;
473 	uint16_t *data16;
474 	int i, count, ioc_sz, residual;
475 	int sleep_flags = CAN_SLEEP;
476 
477 	if (curthread->td_no_sleeping != 0)
478 		sleep_flags = NO_SLEEP;
479 
480 	/* Step 1 */
481 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
482 
483 	/* Step 2 */
484 	if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
485 		return (EBUSY);
486 
487 	/* Step 3
488 	 * Announce that a message is coming through the doorbell.  Messages
489 	 * are pushed at 32bit words, so round up if needed.
490 	 */
491 	count = (req_sz + 3) / 4;
492 	mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
493 	    (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
494 	    (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
495 
496 	/* Step 4 */
497 	if (mps_wait_db_int(sc) ||
498 	    (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
499 		mps_dprint(sc, MPS_FAULT, "Doorbell failed to activate\n");
500 		return (ENXIO);
501 	}
502 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
503 	if (mps_wait_db_ack(sc, 5, sleep_flags) != 0) {
504 		mps_dprint(sc, MPS_FAULT, "Doorbell handshake failed\n");
505 		return (ENXIO);
506 	}
507 
508 	/* Step 5 */
509 	/* Clock out the message data synchronously in 32-bit dwords*/
510 	data32 = (uint32_t *)req;
511 	for (i = 0; i < count; i++) {
512 		mps_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
513 		if (mps_wait_db_ack(sc, 5, sleep_flags) != 0) {
514 			mps_dprint(sc, MPS_FAULT,
515 			    "Timeout while writing doorbell\n");
516 			return (ENXIO);
517 		}
518 	}
519 
520 	/* Step 6 */
521 	/* Clock in the reply in 16-bit words.  The total length of the
522 	 * message is always in the 4th byte, so clock out the first 2 words
523 	 * manually, then loop the rest.
524 	 */
525 	data16 = (uint16_t *)reply;
526 	if (mps_wait_db_int(sc) != 0) {
527 		mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 0\n");
528 		return (ENXIO);
529 	}
530 	data16[0] =
531 	    mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
532 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
533 	if (mps_wait_db_int(sc) != 0) {
534 		mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 1\n");
535 		return (ENXIO);
536 	}
537 	data16[1] =
538 	    mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
539 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
540 
541 	/* Number of 32bit words in the message */
542 	ioc_sz = reply->MsgLength;
543 
544 	/*
545 	 * Figure out how many 16bit words to clock in without overrunning.
546 	 * The precision loss with dividing reply_sz can safely be
547 	 * ignored because the messages can only be multiples of 32bits.
548 	 */
549 	residual = 0;
550 	count = MIN((reply_sz / 4), ioc_sz) * 2;
551 	if (count < ioc_sz * 2) {
552 		residual = ioc_sz * 2 - count;
553 		mps_dprint(sc, MPS_ERROR, "Driver error, throwing away %d "
554 		    "residual message words\n", residual);
555 	}
556 
557 	for (i = 2; i < count; i++) {
558 		if (mps_wait_db_int(sc) != 0) {
559 			mps_dprint(sc, MPS_FAULT,
560 			    "Timeout reading doorbell %d\n", i);
561 			return (ENXIO);
562 		}
563 		data16[i] = mps_regread(sc, MPI2_DOORBELL_OFFSET) &
564 		    MPI2_DOORBELL_DATA_MASK;
565 		mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
566 	}
567 
568 	/*
569 	 * Pull out residual words that won't fit into the provided buffer.
570 	 * This keeps the chip from hanging due to a driver programming
571 	 * error.
572 	 */
573 	while (residual--) {
574 		if (mps_wait_db_int(sc) != 0) {
575 			mps_dprint(sc, MPS_FAULT,
576 			    "Timeout reading doorbell\n");
577 			return (ENXIO);
578 		}
579 		(void)mps_regread(sc, MPI2_DOORBELL_OFFSET);
580 		mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
581 	}
582 
583 	/* Step 7 */
584 	if (mps_wait_db_int(sc) != 0) {
585 		mps_dprint(sc, MPS_FAULT, "Timeout waiting to exit doorbell\n");
586 		return (ENXIO);
587 	}
588 	if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
589 		mps_dprint(sc, MPS_FAULT, "Warning, doorbell still active\n");
590 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
591 
592 	return (0);
593 }
594 
595 static void
596 mps_enqueue_request(struct mps_softc *sc, struct mps_command *cm)
597 {
598 	reply_descriptor rd;
599 	MPS_FUNCTRACE(sc);
600 	mps_dprint(sc, MPS_TRACE, "SMID %u cm %p ccb %p\n",
601 	    cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
602 
603 	if (sc->mps_flags & MPS_FLAGS_ATTACH_DONE && !(sc->mps_flags & MPS_FLAGS_SHUTDOWN))
604 		mtx_assert(&sc->mps_mtx, MA_OWNED);
605 
606 	if (++sc->io_cmds_active > sc->io_cmds_highwater)
607 		sc->io_cmds_highwater++;
608 	rd.u.low = cm->cm_desc.Words.Low;
609 	rd.u.high = cm->cm_desc.Words.High;
610 	rd.word = htole64(rd.word);
611 	/* TODO-We may need to make below regwrite atomic */
612 	mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
613 	    rd.u.low);
614 	mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
615 	    rd.u.high);
616 }
617 
618 /*
619  * Just the FACTS, ma'am.
620  */
621 static int
622 mps_get_iocfacts(struct mps_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
623 {
624 	MPI2_DEFAULT_REPLY *reply;
625 	MPI2_IOC_FACTS_REQUEST request;
626 	int error, req_sz, reply_sz;
627 
628 	MPS_FUNCTRACE(sc);
629 
630 	req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
631 	reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
632 	reply = (MPI2_DEFAULT_REPLY *)facts;
633 
634 	bzero(&request, req_sz);
635 	request.Function = MPI2_FUNCTION_IOC_FACTS;
636 	error = mps_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
637 
638 	return (error);
639 }
640 
641 static int
642 mps_get_portfacts(struct mps_softc *sc, MPI2_PORT_FACTS_REPLY *facts, int port)
643 {
644 	MPI2_PORT_FACTS_REQUEST *request;
645 	MPI2_PORT_FACTS_REPLY *reply;
646 	struct mps_command *cm;
647 	int error;
648 
649 	MPS_FUNCTRACE(sc);
650 
651 	if ((cm = mps_alloc_command(sc)) == NULL)
652 		return (EBUSY);
653 	request = (MPI2_PORT_FACTS_REQUEST *)cm->cm_req;
654 	request->Function = MPI2_FUNCTION_PORT_FACTS;
655 	request->PortNumber = port;
656 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
657 	cm->cm_data = NULL;
658 	error = mps_request_polled(sc, cm);
659 	reply = (MPI2_PORT_FACTS_REPLY *)cm->cm_reply;
660 	if (reply == NULL) {
661 		mps_printf(sc, "%s NULL reply\n", __func__);
662 		goto done;
663 	}
664 	if ((reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS) {
665 		mps_printf(sc,
666 		    "%s error %d iocstatus 0x%x iocloginfo 0x%x type 0x%x\n",
667 		    __func__, error, reply->IOCStatus, reply->IOCLogInfo,
668 		    reply->PortType);
669 		error = ENXIO;
670 	}
671 	bcopy(reply, facts, sizeof(MPI2_PORT_FACTS_REPLY));
672 done:
673 	mps_free_command(sc, cm);
674 
675 	return (error);
676 }
677 
678 static int
679 mps_send_iocinit(struct mps_softc *sc)
680 {
681 	MPI2_IOC_INIT_REQUEST	init;
682 	MPI2_DEFAULT_REPLY	reply;
683 	int req_sz, reply_sz, error;
684 
685 	MPS_FUNCTRACE(sc);
686 
687 	req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
688 	reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
689 	bzero(&init, req_sz);
690 	bzero(&reply, reply_sz);
691 
692 	/*
693 	 * Fill in the init block.  Note that most addresses are
694 	 * deliberately in the lower 32bits of memory.  This is a micro-
695 	 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
696 	 */
697 	init.Function = MPI2_FUNCTION_IOC_INIT;
698 	init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
699 	init.MsgVersion = htole16(MPI2_VERSION);
700 	init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
701 	init.SystemRequestFrameSize = htole16(sc->facts->IOCRequestFrameSize);
702 	init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
703 	init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
704 	init.SenseBufferAddressHigh = 0;
705 	init.SystemReplyAddressHigh = 0;
706 	init.SystemRequestFrameBaseAddress.High = 0;
707 	init.SystemRequestFrameBaseAddress.Low = htole32((uint32_t)sc->req_busaddr);
708 	init.ReplyDescriptorPostQueueAddress.High = 0;
709 	init.ReplyDescriptorPostQueueAddress.Low = htole32((uint32_t)sc->post_busaddr);
710 	init.ReplyFreeQueueAddress.High = 0;
711 	init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
712 	init.TimeStamp.High = 0;
713 	init.TimeStamp.Low = htole32((uint32_t)time_uptime);
714 
715 	error = mps_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
716 	if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
717 		error = ENXIO;
718 
719 	mps_dprint(sc, MPS_INIT, "IOCInit status= 0x%x\n", reply.IOCStatus);
720 	return (error);
721 }
722 
723 void
724 mps_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
725 {
726 	bus_addr_t *addr;
727 
728 	addr = arg;
729 	*addr = segs[0].ds_addr;
730 }
731 
732 static int
733 mps_alloc_queues(struct mps_softc *sc)
734 {
735 	bus_addr_t queues_busaddr;
736 	uint8_t *queues;
737 	int qsize, fqsize, pqsize;
738 
739 	/*
740 	 * The reply free queue contains 4 byte entries in multiples of 16 and
741 	 * aligned on a 16 byte boundary. There must always be an unused entry.
742 	 * This queue supplies fresh reply frames for the firmware to use.
743 	 *
744 	 * The reply descriptor post queue contains 8 byte entries in
745 	 * multiples of 16 and aligned on a 16 byte boundary.  This queue
746 	 * contains filled-in reply frames sent from the firmware to the host.
747 	 *
748 	 * These two queues are allocated together for simplicity.
749 	 */
750 	sc->fqdepth = roundup2((sc->num_replies + 1), 16);
751 	sc->pqdepth = roundup2((sc->num_replies + 1), 16);
752 	fqsize= sc->fqdepth * 4;
753 	pqsize = sc->pqdepth * 8;
754 	qsize = fqsize + pqsize;
755 
756         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
757 				16, 0,			/* algnmnt, boundary */
758 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
759 				BUS_SPACE_MAXADDR,	/* highaddr */
760 				NULL, NULL,		/* filter, filterarg */
761                                 qsize,			/* maxsize */
762                                 1,			/* nsegments */
763                                 qsize,			/* maxsegsize */
764                                 0,			/* flags */
765                                 NULL, NULL,		/* lockfunc, lockarg */
766                                 &sc->queues_dmat)) {
767 		device_printf(sc->mps_dev, "Cannot allocate queues DMA tag\n");
768 		return (ENOMEM);
769         }
770         if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
771 	    &sc->queues_map)) {
772 		device_printf(sc->mps_dev, "Cannot allocate queues memory\n");
773 		return (ENOMEM);
774         }
775         bzero(queues, qsize);
776         bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
777 	    mps_memaddr_cb, &queues_busaddr, 0);
778 
779 	sc->free_queue = (uint32_t *)queues;
780 	sc->free_busaddr = queues_busaddr;
781 	sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
782 	sc->post_busaddr = queues_busaddr + fqsize;
783 
784 	return (0);
785 }
786 
787 static int
788 mps_alloc_replies(struct mps_softc *sc)
789 {
790 	int rsize, num_replies;
791 
792 	/*
793 	 * sc->num_replies should be one less than sc->fqdepth.  We need to
794 	 * allocate space for sc->fqdepth replies, but only sc->num_replies
795 	 * replies can be used at once.
796 	 */
797 	num_replies = max(sc->fqdepth, sc->num_replies);
798 
799 	rsize = sc->facts->ReplyFrameSize * num_replies * 4;
800         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
801 				4, 0,			/* algnmnt, boundary */
802 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
803 				BUS_SPACE_MAXADDR,	/* highaddr */
804 				NULL, NULL,		/* filter, filterarg */
805                                 rsize,			/* maxsize */
806                                 1,			/* nsegments */
807                                 rsize,			/* maxsegsize */
808                                 0,			/* flags */
809                                 NULL, NULL,		/* lockfunc, lockarg */
810                                 &sc->reply_dmat)) {
811 		device_printf(sc->mps_dev, "Cannot allocate replies DMA tag\n");
812 		return (ENOMEM);
813         }
814         if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
815 	    BUS_DMA_NOWAIT, &sc->reply_map)) {
816 		device_printf(sc->mps_dev, "Cannot allocate replies memory\n");
817 		return (ENOMEM);
818         }
819         bzero(sc->reply_frames, rsize);
820         bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
821 	    mps_memaddr_cb, &sc->reply_busaddr, 0);
822 
823 	return (0);
824 }
825 
826 static int
827 mps_alloc_requests(struct mps_softc *sc)
828 {
829 	struct mps_command *cm;
830 	struct mps_chain *chain;
831 	int i, rsize, nsegs;
832 
833 	rsize = sc->facts->IOCRequestFrameSize * sc->num_reqs * 4;
834         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
835 				16, 0,			/* algnmnt, boundary */
836 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
837 				BUS_SPACE_MAXADDR,	/* highaddr */
838 				NULL, NULL,		/* filter, filterarg */
839                                 rsize,			/* maxsize */
840                                 1,			/* nsegments */
841                                 rsize,			/* maxsegsize */
842                                 0,			/* flags */
843                                 NULL, NULL,		/* lockfunc, lockarg */
844                                 &sc->req_dmat)) {
845 		device_printf(sc->mps_dev, "Cannot allocate request DMA tag\n");
846 		return (ENOMEM);
847         }
848         if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
849 	    BUS_DMA_NOWAIT, &sc->req_map)) {
850 		device_printf(sc->mps_dev, "Cannot allocate request memory\n");
851 		return (ENOMEM);
852         }
853         bzero(sc->req_frames, rsize);
854         bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
855 	    mps_memaddr_cb, &sc->req_busaddr, 0);
856 
857 	rsize = sc->facts->IOCRequestFrameSize * sc->max_chains * 4;
858         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
859 				16, 0,			/* algnmnt, boundary */
860 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
861 				BUS_SPACE_MAXADDR,	/* highaddr */
862 				NULL, NULL,		/* filter, filterarg */
863                                 rsize,			/* maxsize */
864                                 1,			/* nsegments */
865                                 rsize,			/* maxsegsize */
866                                 0,			/* flags */
867                                 NULL, NULL,		/* lockfunc, lockarg */
868                                 &sc->chain_dmat)) {
869 		device_printf(sc->mps_dev, "Cannot allocate chain DMA tag\n");
870 		return (ENOMEM);
871         }
872         if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
873 	    BUS_DMA_NOWAIT, &sc->chain_map)) {
874 		device_printf(sc->mps_dev, "Cannot allocate chain memory\n");
875 		return (ENOMEM);
876         }
877         bzero(sc->chain_frames, rsize);
878         bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
879 	    mps_memaddr_cb, &sc->chain_busaddr, 0);
880 
881 	rsize = MPS_SENSE_LEN * sc->num_reqs;
882         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
883 				1, 0,			/* algnmnt, boundary */
884 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
885 				BUS_SPACE_MAXADDR,	/* highaddr */
886 				NULL, NULL,		/* filter, filterarg */
887                                 rsize,			/* maxsize */
888                                 1,			/* nsegments */
889                                 rsize,			/* maxsegsize */
890                                 0,			/* flags */
891                                 NULL, NULL,		/* lockfunc, lockarg */
892                                 &sc->sense_dmat)) {
893 		device_printf(sc->mps_dev, "Cannot allocate sense DMA tag\n");
894 		return (ENOMEM);
895         }
896         if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
897 	    BUS_DMA_NOWAIT, &sc->sense_map)) {
898 		device_printf(sc->mps_dev, "Cannot allocate sense memory\n");
899 		return (ENOMEM);
900         }
901         bzero(sc->sense_frames, rsize);
902         bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
903 	    mps_memaddr_cb, &sc->sense_busaddr, 0);
904 
905 	sc->chains = malloc(sizeof(struct mps_chain) * sc->max_chains, M_MPT2,
906 	    M_WAITOK | M_ZERO);
907 	if(!sc->chains) {
908 		device_printf(sc->mps_dev,
909 		"Cannot allocate chains memory %s %d\n",
910 		 __func__, __LINE__);
911 		return (ENOMEM);
912 	}
913 	for (i = 0; i < sc->max_chains; i++) {
914 		chain = &sc->chains[i];
915 		chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
916 		    i * sc->facts->IOCRequestFrameSize * 4);
917 		chain->chain_busaddr = sc->chain_busaddr +
918 		    i * sc->facts->IOCRequestFrameSize * 4;
919 		mps_free_chain(sc, chain);
920 		sc->chain_free_lowwater++;
921 	}
922 
923 	/* XXX Need to pick a more precise value */
924 	nsegs = (MAXPHYS / PAGE_SIZE) + 1;
925         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
926 				1, 0,			/* algnmnt, boundary */
927 				BUS_SPACE_MAXADDR,	/* lowaddr */
928 				BUS_SPACE_MAXADDR,	/* highaddr */
929 				NULL, NULL,		/* filter, filterarg */
930                                 BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
931                                 nsegs,			/* nsegments */
932                                 BUS_SPACE_MAXSIZE_24BIT,/* maxsegsize */
933                                 BUS_DMA_ALLOCNOW,	/* flags */
934                                 busdma_lock_mutex,	/* lockfunc */
935 				&sc->mps_mtx,		/* lockarg */
936                                 &sc->buffer_dmat)) {
937 		device_printf(sc->mps_dev, "Cannot allocate buffer DMA tag\n");
938 		return (ENOMEM);
939         }
940 
941 	/*
942 	 * SMID 0 cannot be used as a free command per the firmware spec.
943 	 * Just drop that command instead of risking accounting bugs.
944 	 */
945 	sc->commands = malloc(sizeof(struct mps_command) * sc->num_reqs,
946 	    M_MPT2, M_WAITOK | M_ZERO);
947 	if(!sc->commands) {
948 		device_printf(sc->mps_dev, "Cannot allocate memory %s %d\n",
949 		 __func__, __LINE__);
950 		return (ENOMEM);
951 	}
952 	for (i = 1; i < sc->num_reqs; i++) {
953 		cm = &sc->commands[i];
954 		cm->cm_req = sc->req_frames +
955 		    i * sc->facts->IOCRequestFrameSize * 4;
956 		cm->cm_req_busaddr = sc->req_busaddr +
957 		    i * sc->facts->IOCRequestFrameSize * 4;
958 		cm->cm_sense = &sc->sense_frames[i];
959 		cm->cm_sense_busaddr = sc->sense_busaddr + i * MPS_SENSE_LEN;
960 		cm->cm_desc.Default.SMID = i;
961 		cm->cm_sc = sc;
962 		TAILQ_INIT(&cm->cm_chain_list);
963 		callout_init_mtx(&cm->cm_callout, &sc->mps_mtx, 0);
964 
965 		/* XXX Is a failure here a critical problem? */
966 		if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap) == 0)
967 			if (i <= sc->facts->HighPriorityCredit)
968 				mps_free_high_priority_command(sc, cm);
969 			else
970 				mps_free_command(sc, cm);
971 		else {
972 			panic("failed to allocate command %d\n", i);
973 			sc->num_reqs = i;
974 			break;
975 		}
976 	}
977 
978 	return (0);
979 }
980 
981 static int
982 mps_init_queues(struct mps_softc *sc)
983 {
984 	int i;
985 
986 	memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
987 
988 	/*
989 	 * According to the spec, we need to use one less reply than we
990 	 * have space for on the queue.  So sc->num_replies (the number we
991 	 * use) should be less than sc->fqdepth (allocated size).
992 	 */
993 	if (sc->num_replies >= sc->fqdepth)
994 		return (EINVAL);
995 
996 	/*
997 	 * Initialize all of the free queue entries.
998 	 */
999 	for (i = 0; i < sc->fqdepth; i++)
1000 		sc->free_queue[i] = sc->reply_busaddr + (i * sc->facts->ReplyFrameSize * 4);
1001 	sc->replyfreeindex = sc->num_replies;
1002 
1003 	return (0);
1004 }
1005 
1006 /* Get the driver parameter tunables.  Lowest priority are the driver defaults.
1007  * Next are the global settings, if they exist.  Highest are the per-unit
1008  * settings, if they exist.
1009  */
1010 static void
1011 mps_get_tunables(struct mps_softc *sc)
1012 {
1013 	char tmpstr[80];
1014 
1015 	/* XXX default to some debugging for now */
1016 	sc->mps_debug = MPS_INFO|MPS_FAULT;
1017 	sc->disable_msix = 0;
1018 	sc->disable_msi = 0;
1019 	sc->max_chains = MPS_CHAIN_FRAMES;
1020 
1021 	/*
1022 	 * Grab the global variables.
1023 	 */
1024 	TUNABLE_INT_FETCH("hw.mps.debug_level", &sc->mps_debug);
1025 	TUNABLE_INT_FETCH("hw.mps.disable_msix", &sc->disable_msix);
1026 	TUNABLE_INT_FETCH("hw.mps.disable_msi", &sc->disable_msi);
1027 	TUNABLE_INT_FETCH("hw.mps.max_chains", &sc->max_chains);
1028 
1029 	/* Grab the unit-instance variables */
1030 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.debug_level",
1031 	    device_get_unit(sc->mps_dev));
1032 	TUNABLE_INT_FETCH(tmpstr, &sc->mps_debug);
1033 
1034 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.disable_msix",
1035 	    device_get_unit(sc->mps_dev));
1036 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1037 
1038 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.disable_msi",
1039 	    device_get_unit(sc->mps_dev));
1040 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1041 
1042 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_chains",
1043 	    device_get_unit(sc->mps_dev));
1044 	TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1045 }
1046 
1047 static void
1048 mps_setup_sysctl(struct mps_softc *sc)
1049 {
1050 	struct sysctl_ctx_list	*sysctl_ctx = NULL;
1051 	struct sysctl_oid	*sysctl_tree = NULL;
1052 	char tmpstr[80], tmpstr2[80];
1053 
1054 	/*
1055 	 * Setup the sysctl variable so the user can change the debug level
1056 	 * on the fly.
1057 	 */
1058 	snprintf(tmpstr, sizeof(tmpstr), "MPS controller %d",
1059 	    device_get_unit(sc->mps_dev));
1060 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mps_dev));
1061 
1062 	sysctl_ctx = device_get_sysctl_ctx(sc->mps_dev);
1063 	if (sysctl_ctx != NULL)
1064 		sysctl_tree = device_get_sysctl_tree(sc->mps_dev);
1065 
1066 	if (sysctl_tree == NULL) {
1067 		sysctl_ctx_init(&sc->sysctl_ctx);
1068 		sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1069 		    SYSCTL_STATIC_CHILDREN(_hw_mps), OID_AUTO, tmpstr2,
1070 		    CTLFLAG_RD, 0, tmpstr);
1071 		if (sc->sysctl_tree == NULL)
1072 			return;
1073 		sysctl_ctx = &sc->sysctl_ctx;
1074 		sysctl_tree = sc->sysctl_tree;
1075 	}
1076 
1077 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1078 	    OID_AUTO, "debug_level", CTLFLAG_RW, &sc->mps_debug, 0,
1079 	    "mps debug level");
1080 
1081 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1082 	    OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1083 	    "Disable the use of MSI-X interrupts");
1084 
1085 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1086 	    OID_AUTO, "disable_msi", CTLFLAG_RD, &sc->disable_msi, 0,
1087 	    "Disable the use of MSI interrupts");
1088 
1089 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1090 	    OID_AUTO, "firmware_version", CTLFLAG_RW, &sc->fw_version,
1091 	    strlen(sc->fw_version), "firmware version");
1092 
1093 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1094 	    OID_AUTO, "driver_version", CTLFLAG_RW, MPS_DRIVER_VERSION,
1095 	    strlen(MPS_DRIVER_VERSION), "driver version");
1096 
1097 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1098 	    OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1099 	    &sc->io_cmds_active, 0, "number of currently active commands");
1100 
1101 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1102 	    OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1103 	    &sc->io_cmds_highwater, 0, "maximum active commands seen");
1104 
1105 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1106 	    OID_AUTO, "chain_free", CTLFLAG_RD,
1107 	    &sc->chain_free, 0, "number of free chain elements");
1108 
1109 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1110 	    OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1111 	    &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1112 
1113 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1114 	    OID_AUTO, "max_chains", CTLFLAG_RD,
1115 	    &sc->max_chains, 0,"maximum chain frames that will be allocated");
1116 
1117 #if __FreeBSD_version >= 900030
1118 	SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1119 	    OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1120 	    &sc->chain_alloc_fail, "chain allocation failures");
1121 #endif //FreeBSD_version >= 900030
1122 }
1123 
1124 int
1125 mps_attach(struct mps_softc *sc)
1126 {
1127 	int i, error;
1128 
1129 	mps_get_tunables(sc);
1130 
1131 	MPS_FUNCTRACE(sc);
1132 
1133 	mtx_init(&sc->mps_mtx, "MPT2SAS lock", NULL, MTX_DEF);
1134 	callout_init_mtx(&sc->periodic, &sc->mps_mtx, 0);
1135 	TAILQ_INIT(&sc->event_list);
1136 
1137 	if ((error = mps_transition_ready(sc)) != 0) {
1138 		mps_printf(sc, "%s failed to transition ready\n", __func__);
1139 		return (error);
1140 	}
1141 
1142 	sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPT2,
1143 	    M_ZERO|M_NOWAIT);
1144 	if(!sc->facts) {
1145 		device_printf(sc->mps_dev, "Cannot allocate memory %s %d\n",
1146 		 __func__, __LINE__);
1147 		return (ENOMEM);
1148 	}
1149 	if ((error = mps_get_iocfacts(sc, sc->facts)) != 0)
1150 		return (error);
1151 
1152 	mps_print_iocfacts(sc, sc->facts);
1153 
1154 	snprintf(sc->fw_version, sizeof(sc->fw_version),
1155 	    "%02d.%02d.%02d.%02d",
1156 	    sc->facts->FWVersion.Struct.Major,
1157 	    sc->facts->FWVersion.Struct.Minor,
1158 	    sc->facts->FWVersion.Struct.Unit,
1159 	    sc->facts->FWVersion.Struct.Dev);
1160 
1161 	mps_printf(sc, "Firmware: %s, Driver: %s\n", sc->fw_version,
1162 	    MPS_DRIVER_VERSION);
1163 	mps_printf(sc, "IOCCapabilities: %b\n", sc->facts->IOCCapabilities,
1164 	    "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
1165 	    "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
1166 	    "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc");
1167 
1168 	/*
1169 	 * If the chip doesn't support event replay then a hard reset will be
1170 	 * required to trigger a full discovery.  Do the reset here then
1171 	 * retransition to Ready.  A hard reset might have already been done,
1172 	 * but it doesn't hurt to do it again.
1173 	 */
1174 	if ((sc->facts->IOCCapabilities &
1175 	    MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0) {
1176 		mps_diag_reset(sc, NO_SLEEP);
1177 		if ((error = mps_transition_ready(sc)) != 0)
1178 			return (error);
1179 	}
1180 
1181 	/*
1182 	 * Set flag if IR Firmware is loaded.
1183 	 */
1184 	if (sc->facts->IOCCapabilities &
1185 	    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
1186 		sc->ir_firmware = 1;
1187 
1188 	/*
1189 	 * Check if controller supports FW diag buffers and set flag to enable
1190 	 * each type.
1191 	 */
1192 	if (sc->facts->IOCCapabilities &
1193 	    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
1194 		sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].enabled =
1195 		    TRUE;
1196 	if (sc->facts->IOCCapabilities &
1197 	    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
1198 		sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].enabled =
1199 		    TRUE;
1200 	if (sc->facts->IOCCapabilities &
1201 	    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
1202 		sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].enabled =
1203 		    TRUE;
1204 
1205 	/*
1206 	 * Set flag if EEDP is supported and if TLR is supported.
1207 	 */
1208 	if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
1209 		sc->eedp_enabled = TRUE;
1210 	if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
1211 		sc->control_TLR = TRUE;
1212 
1213 	/*
1214 	 * Size the queues. Since the reply queues always need one free entry,
1215 	 * we'll just deduct one reply message here.
1216 	 */
1217 	sc->num_reqs = MIN(MPS_REQ_FRAMES, sc->facts->RequestCredit);
1218 	sc->num_replies = MIN(MPS_REPLY_FRAMES + MPS_EVT_REPLY_FRAMES,
1219 	    sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
1220 	TAILQ_INIT(&sc->req_list);
1221 	TAILQ_INIT(&sc->high_priority_req_list);
1222 	TAILQ_INIT(&sc->chain_list);
1223 	TAILQ_INIT(&sc->tm_list);
1224 
1225 	if (((error = mps_alloc_queues(sc)) != 0) ||
1226 	    ((error = mps_alloc_replies(sc)) != 0) ||
1227 	    ((error = mps_alloc_requests(sc)) != 0)) {
1228 		mps_printf(sc, "%s failed to alloc\n", __func__);
1229 		mps_free(sc);
1230 		return (error);
1231 	}
1232 
1233 	if (((error = mps_init_queues(sc)) != 0) ||
1234 	    ((error = mps_transition_operational(sc)) != 0)) {
1235 		mps_printf(sc, "%s failed to transition operational\n", __func__);
1236 		mps_free(sc);
1237 		return (error);
1238 	}
1239 
1240 	/*
1241 	 * Finish the queue initialization.
1242 	 * These are set here instead of in mps_init_queues() because the
1243 	 * IOC resets these values during the state transition in
1244 	 * mps_transition_operational().  The free index is set to 1
1245 	 * because the corresponding index in the IOC is set to 0, and the
1246 	 * IOC treats the queues as full if both are set to the same value.
1247 	 * Hence the reason that the queue can't hold all of the possible
1248 	 * replies.
1249 	 */
1250 	sc->replypostindex = 0;
1251 	mps_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
1252 	mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
1253 
1254 	sc->pfacts = malloc(sizeof(MPI2_PORT_FACTS_REPLY) *
1255 	    sc->facts->NumberOfPorts, M_MPT2, M_ZERO|M_WAITOK);
1256 	if(!sc->pfacts) {
1257 		device_printf(sc->mps_dev, "Cannot allocate memory %s %d\n",
1258 		 __func__, __LINE__);
1259 		return (ENOMEM);
1260 	}
1261 	for (i = 0; i < sc->facts->NumberOfPorts; i++) {
1262 		if ((error = mps_get_portfacts(sc, &sc->pfacts[i], i)) != 0) {
1263 			mps_printf(sc, "%s failed to get portfacts for port %d\n",
1264 			    __func__, i);
1265 			mps_free(sc);
1266 			return (error);
1267 		}
1268 		mps_print_portfacts(sc, &sc->pfacts[i]);
1269 	}
1270 
1271 	/* Attach the subsystems so they can prepare their event masks. */
1272 	/* XXX Should be dynamic so that IM/IR and user modules can attach */
1273 	if (((error = mps_attach_log(sc)) != 0) ||
1274 	    ((error = mps_attach_sas(sc)) != 0) ||
1275 	    ((error = mps_attach_user(sc)) != 0)) {
1276 		mps_printf(sc, "%s failed to attach all subsystems: error %d\n",
1277 		    __func__, error);
1278 		mps_free(sc);
1279 		return (error);
1280 	}
1281 
1282 	if ((error = mps_pci_setup_interrupts(sc)) != 0) {
1283 		mps_printf(sc, "%s failed to setup interrupts\n", __func__);
1284 		mps_free(sc);
1285 		return (error);
1286 	}
1287 
1288 	/*
1289 	 * The static page function currently read is ioc page8.  Others can be
1290 	 * added in future.
1291 	 */
1292 	mps_base_static_config_pages(sc);
1293 
1294 	/* Start the periodic watchdog check on the IOC Doorbell */
1295 	mps_periodic(sc);
1296 
1297 	/*
1298 	 * The portenable will kick off discovery events that will drive the
1299 	 * rest of the initialization process.  The CAM/SAS module will
1300 	 * hold up the boot sequence until discovery is complete.
1301 	 */
1302 	sc->mps_ich.ich_func = mps_startup;
1303 	sc->mps_ich.ich_arg = sc;
1304 	if (config_intrhook_establish(&sc->mps_ich) != 0) {
1305 		mps_dprint(sc, MPS_ERROR, "Cannot establish MPS config hook\n");
1306 		error = EINVAL;
1307 	}
1308 
1309 	/*
1310 	 * Allow IR to shutdown gracefully when shutdown occurs.
1311 	 */
1312 	sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
1313 	    mpssas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
1314 
1315 	if (sc->shutdown_eh == NULL)
1316 		mps_dprint(sc, MPS_ERROR, "shutdown event registration "
1317 		    "failed\n");
1318 
1319 	mps_setup_sysctl(sc);
1320 
1321 	sc->mps_flags |= MPS_FLAGS_ATTACH_DONE;
1322 
1323 	return (error);
1324 }
1325 
1326 /* Run through any late-start handlers. */
1327 static void
1328 mps_startup(void *arg)
1329 {
1330 	struct mps_softc *sc;
1331 
1332 	sc = (struct mps_softc *)arg;
1333 
1334 	mps_lock(sc);
1335 	mps_unmask_intr(sc);
1336 	/* initialize device mapping tables */
1337 	mps_mapping_initialize(sc);
1338 	mpssas_startup(sc);
1339 	mps_unlock(sc);
1340 }
1341 
1342 /* Periodic watchdog.  Is called with the driver lock already held. */
1343 static void
1344 mps_periodic(void *arg)
1345 {
1346 	struct mps_softc *sc;
1347 	uint32_t db;
1348 
1349 	sc = (struct mps_softc *)arg;
1350 	if (sc->mps_flags & MPS_FLAGS_SHUTDOWN)
1351 		return;
1352 
1353 	db = mps_regread(sc, MPI2_DOORBELL_OFFSET);
1354 	if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
1355 		mps_dprint(sc, MPS_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
1356 		mps_reinit(sc);
1357 	}
1358 
1359 	callout_reset(&sc->periodic, MPS_PERIODIC_DELAY * hz, mps_periodic, sc);
1360 }
1361 
1362 static void
1363 mps_log_evt_handler(struct mps_softc *sc, uintptr_t data,
1364     MPI2_EVENT_NOTIFICATION_REPLY *event)
1365 {
1366 	MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
1367 
1368 	mps_print_event(sc, event);
1369 
1370 	switch (event->Event) {
1371 	case MPI2_EVENT_LOG_DATA:
1372 		mps_dprint(sc, MPS_EVENT, "MPI2_EVENT_LOG_DATA:\n");
1373 		if (sc->mps_debug & MPS_EVENT)
1374 			hexdump(event->EventData, event->EventDataLength, NULL, 0);
1375 		break;
1376 	case MPI2_EVENT_LOG_ENTRY_ADDED:
1377 		entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
1378 		mps_dprint(sc, MPS_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
1379 		    "0x%x Sequence %d:\n", entry->LogEntryQualifier,
1380 		     entry->LogSequence);
1381 		break;
1382 	default:
1383 		break;
1384 	}
1385 	return;
1386 }
1387 
1388 static int
1389 mps_attach_log(struct mps_softc *sc)
1390 {
1391 	u32 events[MPI2_EVENT_NOTIFY_EVENTMASK_WORDS];
1392 
1393 	bzero(events, 16);
1394 	setbit(events, MPI2_EVENT_LOG_DATA);
1395 	setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
1396 
1397 	mps_register_events(sc, events, mps_log_evt_handler, NULL,
1398 	    &sc->mps_log_eh);
1399 
1400 	return (0);
1401 }
1402 
1403 static int
1404 mps_detach_log(struct mps_softc *sc)
1405 {
1406 
1407 	if (sc->mps_log_eh != NULL)
1408 		mps_deregister_events(sc, sc->mps_log_eh);
1409 	return (0);
1410 }
1411 
1412 /*
1413  * Free all of the driver resources and detach submodules.  Should be called
1414  * without the lock held.
1415  */
1416 int
1417 mps_free(struct mps_softc *sc)
1418 {
1419 	struct mps_command *cm;
1420 	int i, error;
1421 
1422 	/* Turn off the watchdog */
1423 	mps_lock(sc);
1424 	sc->mps_flags |= MPS_FLAGS_SHUTDOWN;
1425 	mps_unlock(sc);
1426 	/* Lock must not be held for this */
1427 	callout_drain(&sc->periodic);
1428 
1429 	if (((error = mps_detach_log(sc)) != 0) ||
1430 	    ((error = mps_detach_sas(sc)) != 0))
1431 		return (error);
1432 
1433 	mps_detach_user(sc);
1434 
1435 	/* Put the IOC back in the READY state. */
1436 	mps_lock(sc);
1437 	if ((error = mps_transition_ready(sc)) != 0) {
1438 		mps_unlock(sc);
1439 		return (error);
1440 	}
1441 	mps_unlock(sc);
1442 
1443 	if (sc->facts != NULL)
1444 		free(sc->facts, M_MPT2);
1445 
1446 	if (sc->pfacts != NULL)
1447 		free(sc->pfacts, M_MPT2);
1448 
1449 	if (sc->post_busaddr != 0)
1450 		bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
1451 	if (sc->post_queue != NULL)
1452 		bus_dmamem_free(sc->queues_dmat, sc->post_queue,
1453 		    sc->queues_map);
1454 	if (sc->queues_dmat != NULL)
1455 		bus_dma_tag_destroy(sc->queues_dmat);
1456 
1457 	if (sc->chain_busaddr != 0)
1458 		bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
1459 	if (sc->chain_frames != NULL)
1460 		bus_dmamem_free(sc->chain_dmat, sc->chain_frames,sc->chain_map);
1461 	if (sc->chain_dmat != NULL)
1462 		bus_dma_tag_destroy(sc->chain_dmat);
1463 
1464 	if (sc->sense_busaddr != 0)
1465 		bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
1466 	if (sc->sense_frames != NULL)
1467 		bus_dmamem_free(sc->sense_dmat, sc->sense_frames,sc->sense_map);
1468 	if (sc->sense_dmat != NULL)
1469 		bus_dma_tag_destroy(sc->sense_dmat);
1470 
1471 	if (sc->reply_busaddr != 0)
1472 		bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
1473 	if (sc->reply_frames != NULL)
1474 		bus_dmamem_free(sc->reply_dmat, sc->reply_frames,sc->reply_map);
1475 	if (sc->reply_dmat != NULL)
1476 		bus_dma_tag_destroy(sc->reply_dmat);
1477 
1478 	if (sc->req_busaddr != 0)
1479 		bus_dmamap_unload(sc->req_dmat, sc->req_map);
1480 	if (sc->req_frames != NULL)
1481 		bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
1482 	if (sc->req_dmat != NULL)
1483 		bus_dma_tag_destroy(sc->req_dmat);
1484 
1485 	if (sc->chains != NULL)
1486 		free(sc->chains, M_MPT2);
1487 	if (sc->commands != NULL) {
1488 		for (i = 1; i < sc->num_reqs; i++) {
1489 			cm = &sc->commands[i];
1490 			bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
1491 		}
1492 		free(sc->commands, M_MPT2);
1493 	}
1494 	if (sc->buffer_dmat != NULL)
1495 		bus_dma_tag_destroy(sc->buffer_dmat);
1496 
1497 	if (sc->sysctl_tree != NULL)
1498 		sysctl_ctx_free(&sc->sysctl_ctx);
1499 
1500 	mps_mapping_free_memory(sc);
1501 
1502 	/* Deregister the shutdown function */
1503 	if (sc->shutdown_eh != NULL)
1504 		EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
1505 
1506 	mtx_destroy(&sc->mps_mtx);
1507 
1508 	return (0);
1509 }
1510 
1511 static __inline void
1512 mps_complete_command(struct mps_softc *sc, struct mps_command *cm)
1513 {
1514 	MPS_FUNCTRACE(sc);
1515 
1516 	if (cm == NULL) {
1517 		mps_dprint(sc, MPS_ERROR, "Completing NULL command\n");
1518 		return;
1519 	}
1520 
1521 	if (cm->cm_flags & MPS_CM_FLAGS_POLLED)
1522 		cm->cm_flags |= MPS_CM_FLAGS_COMPLETE;
1523 
1524 	if (cm->cm_complete != NULL) {
1525 		mps_dprint(sc, MPS_TRACE,
1526 			   "%s cm %p calling cm_complete %p data %p reply %p\n",
1527 			   __func__, cm, cm->cm_complete, cm->cm_complete_data,
1528 			   cm->cm_reply);
1529 		cm->cm_complete(sc, cm);
1530 	}
1531 
1532 	if (cm->cm_flags & MPS_CM_FLAGS_WAKEUP) {
1533 		mps_dprint(sc, MPS_TRACE, "waking up %p\n", cm);
1534 		wakeup(cm);
1535 	}
1536 
1537 	if (cm->cm_sc->io_cmds_active != 0) {
1538 		cm->cm_sc->io_cmds_active--;
1539 	} else {
1540 		mps_dprint(sc, MPS_ERROR, "Warning: io_cmds_active is "
1541 		    "out of sync - resynching to 0\n");
1542 	}
1543 }
1544 
1545 
1546 static void
1547 mps_sas_log_info(struct mps_softc *sc , u32 log_info)
1548 {
1549 	union loginfo_type {
1550 		u32     loginfo;
1551 		struct {
1552 			u32     subcode:16;
1553 			u32     code:8;
1554 			u32     originator:4;
1555 			u32     bus_type:4;
1556 		} dw;
1557 	};
1558 	union loginfo_type sas_loginfo;
1559 	char *originator_str = NULL;
1560 
1561 	sas_loginfo.loginfo = log_info;
1562 	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
1563 		return;
1564 
1565 	/* each nexus loss loginfo */
1566 	if (log_info == 0x31170000)
1567 		return;
1568 
1569 	/* eat the loginfos associated with task aborts */
1570 	if ((log_info == 30050000 || log_info ==
1571 	    0x31140000 || log_info == 0x31130000))
1572 		return;
1573 
1574 	switch (sas_loginfo.dw.originator) {
1575 	case 0:
1576 		originator_str = "IOP";
1577 		break;
1578 	case 1:
1579 		originator_str = "PL";
1580 		break;
1581 	case 2:
1582 		originator_str = "IR";
1583 		break;
1584 }
1585 
1586 	mps_dprint(sc, MPS_LOG, "log_info(0x%08x): originator(%s), "
1587 	"code(0x%02x), sub_code(0x%04x)\n", log_info,
1588 	originator_str, sas_loginfo.dw.code,
1589 	sas_loginfo.dw.subcode);
1590 }
1591 
1592 static void
1593 mps_display_reply_info(struct mps_softc *sc, uint8_t *reply)
1594 {
1595 	MPI2DefaultReply_t *mpi_reply;
1596 	u16 sc_status;
1597 
1598 	mpi_reply = (MPI2DefaultReply_t*)reply;
1599 	sc_status = le16toh(mpi_reply->IOCStatus);
1600 	if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
1601 		mps_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
1602 }
1603 void
1604 mps_intr(void *data)
1605 {
1606 	struct mps_softc *sc;
1607 	uint32_t status;
1608 
1609 	sc = (struct mps_softc *)data;
1610 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1611 
1612 	/*
1613 	 * Check interrupt status register to flush the bus.  This is
1614 	 * needed for both INTx interrupts and driver-driven polling
1615 	 */
1616 	status = mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
1617 	if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
1618 		return;
1619 
1620 	mps_lock(sc);
1621 	mps_intr_locked(data);
1622 	mps_unlock(sc);
1623 	return;
1624 }
1625 
1626 /*
1627  * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
1628  * chip.  Hopefully this theory is correct.
1629  */
1630 void
1631 mps_intr_msi(void *data)
1632 {
1633 	struct mps_softc *sc;
1634 
1635 	sc = (struct mps_softc *)data;
1636 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1637 	mps_lock(sc);
1638 	mps_intr_locked(data);
1639 	mps_unlock(sc);
1640 	return;
1641 }
1642 
1643 /*
1644  * The locking is overly broad and simplistic, but easy to deal with for now.
1645  */
1646 void
1647 mps_intr_locked(void *data)
1648 {
1649 	MPI2_REPLY_DESCRIPTORS_UNION *desc;
1650 	struct mps_softc *sc;
1651 	struct mps_command *cm = NULL;
1652 	uint8_t flags;
1653 	u_int pq;
1654 	MPI2_DIAG_RELEASE_REPLY *rel_rep;
1655 	mps_fw_diagnostic_buffer_t *pBuffer;
1656 
1657 	sc = (struct mps_softc *)data;
1658 
1659 	pq = sc->replypostindex;
1660 	mps_dprint(sc, MPS_TRACE,
1661 	    "%s sc %p starting with replypostindex %u\n",
1662 	    __func__, sc, sc->replypostindex);
1663 
1664 	for ( ;; ) {
1665 		cm = NULL;
1666 		desc = &sc->post_queue[sc->replypostindex];
1667 		flags = desc->Default.ReplyFlags &
1668 		    MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1669 		if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1670 		 || (le32toh(desc->Words.High) == 0xffffffff))
1671 			break;
1672 
1673 		/* increment the replypostindex now, so that event handlers
1674 		 * and cm completion handlers which decide to do a diag
1675 		 * reset can zero it without it getting incremented again
1676 		 * afterwards, and we break out of this loop on the next
1677 		 * iteration since the reply post queue has been cleared to
1678 		 * 0xFF and all descriptors look unused (which they are).
1679 		 */
1680 		if (++sc->replypostindex >= sc->pqdepth)
1681 			sc->replypostindex = 0;
1682 
1683 		switch (flags) {
1684 		case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
1685 			cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
1686 			cm->cm_reply = NULL;
1687 			break;
1688 		case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
1689 		{
1690 			uint32_t baddr;
1691 			uint8_t *reply;
1692 
1693 			/*
1694 			 * Re-compose the reply address from the address
1695 			 * sent back from the chip.  The ReplyFrameAddress
1696 			 * is the lower 32 bits of the physical address of
1697 			 * particular reply frame.  Convert that address to
1698 			 * host format, and then use that to provide the
1699 			 * offset against the virtual address base
1700 			 * (sc->reply_frames).
1701 			 */
1702 			baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
1703 			reply = sc->reply_frames +
1704 				(baddr - ((uint32_t)sc->reply_busaddr));
1705 			/*
1706 			 * Make sure the reply we got back is in a valid
1707 			 * range.  If not, go ahead and panic here, since
1708 			 * we'll probably panic as soon as we deference the
1709 			 * reply pointer anyway.
1710 			 */
1711 			if ((reply < sc->reply_frames)
1712 			 || (reply > (sc->reply_frames +
1713 			     (sc->fqdepth * sc->facts->ReplyFrameSize * 4)))) {
1714 				printf("%s: WARNING: reply %p out of range!\n",
1715 				       __func__, reply);
1716 				printf("%s: reply_frames %p, fqdepth %d, "
1717 				       "frame size %d\n", __func__,
1718 				       sc->reply_frames, sc->fqdepth,
1719 				       sc->facts->ReplyFrameSize * 4);
1720 				printf("%s: baddr %#x,\n", __func__, baddr);
1721 				/* LSI-TODO. See Linux Code. Need Gracefull exit*/
1722 				panic("Reply address out of range");
1723 			}
1724 			if (le16toh(desc->AddressReply.SMID) == 0) {
1725 				if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
1726 				    MPI2_FUNCTION_DIAG_BUFFER_POST) {
1727 					/*
1728 					 * If SMID is 0 for Diag Buffer Post,
1729 					 * this implies that the reply is due to
1730 					 * a release function with a status that
1731 					 * the buffer has been released.  Set
1732 					 * the buffer flags accordingly.
1733 					 */
1734 					rel_rep =
1735 					    (MPI2_DIAG_RELEASE_REPLY *)reply;
1736 					if (le16toh(rel_rep->IOCStatus) ==
1737 					    MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
1738 					    {
1739 						pBuffer =
1740 						    &sc->fw_diag_buffer_list[
1741 						    rel_rep->BufferType];
1742 						pBuffer->valid_data = TRUE;
1743 						pBuffer->owned_by_firmware =
1744 						    FALSE;
1745 						pBuffer->immediate = FALSE;
1746 					}
1747 				} else
1748 					mps_dispatch_event(sc, baddr,
1749 					    (MPI2_EVENT_NOTIFICATION_REPLY *)
1750 					    reply);
1751 			} else {
1752 				cm = &sc->commands[le16toh(desc->AddressReply.SMID)];
1753 				cm->cm_reply = reply;
1754 				cm->cm_reply_data =
1755 				    le32toh(desc->AddressReply.ReplyFrameAddress);
1756 			}
1757 			break;
1758 		}
1759 		case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
1760 		case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
1761 		case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
1762 		default:
1763 			/* Unhandled */
1764 			mps_dprint(sc, MPS_ERROR, "Unhandled reply 0x%x\n",
1765 			    desc->Default.ReplyFlags);
1766 			cm = NULL;
1767 			break;
1768 		}
1769 
1770 
1771 		if (cm != NULL) {
1772 			// Print Error reply frame
1773 			if (cm->cm_reply)
1774 				mps_display_reply_info(sc,cm->cm_reply);
1775 			mps_complete_command(sc, cm);
1776 		}
1777 
1778 		desc->Words.Low = 0xffffffff;
1779 		desc->Words.High = 0xffffffff;
1780 	}
1781 
1782 	if (pq != sc->replypostindex) {
1783 		mps_dprint(sc, MPS_TRACE,
1784 		    "%s sc %p writing postindex %d\n",
1785 		    __func__, sc, sc->replypostindex);
1786 		mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, sc->replypostindex);
1787 	}
1788 
1789 	return;
1790 }
1791 
1792 static void
1793 mps_dispatch_event(struct mps_softc *sc, uintptr_t data,
1794     MPI2_EVENT_NOTIFICATION_REPLY *reply)
1795 {
1796 	struct mps_event_handle *eh;
1797 	int event, handled = 0;
1798 
1799 	event = le16toh(reply->Event);
1800 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
1801 		if (isset(eh->mask, event)) {
1802 			eh->callback(sc, data, reply);
1803 			handled++;
1804 		}
1805 	}
1806 
1807 	if (handled == 0)
1808 		mps_dprint(sc, MPS_EVENT, "Unhandled event 0x%x\n", le16toh(event));
1809 
1810 	/*
1811 	 * This is the only place that the event/reply should be freed.
1812 	 * Anything wanting to hold onto the event data should have
1813 	 * already copied it into their own storage.
1814 	 */
1815 	mps_free_reply(sc, data);
1816 }
1817 
1818 static void
1819 mps_reregister_events_complete(struct mps_softc *sc, struct mps_command *cm)
1820 {
1821 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1822 
1823 	if (cm->cm_reply)
1824 		mps_print_event(sc,
1825 			(MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
1826 
1827 	mps_free_command(sc, cm);
1828 
1829 	/* next, send a port enable */
1830 	mpssas_startup(sc);
1831 }
1832 
1833 /*
1834  * For both register_events and update_events, the caller supplies a bitmap
1835  * of events that it _wants_.  These functions then turn that into a bitmask
1836  * suitable for the controller.
1837  */
1838 int
1839 mps_register_events(struct mps_softc *sc, u32 *mask,
1840     mps_evt_callback_t *cb, void *data, struct mps_event_handle **handle)
1841 {
1842 	struct mps_event_handle *eh;
1843 	int error = 0;
1844 
1845 	eh = malloc(sizeof(struct mps_event_handle), M_MPT2, M_WAITOK|M_ZERO);
1846 	if(!eh) {
1847 		device_printf(sc->mps_dev, "Cannot allocate memory %s %d\n",
1848 		 __func__, __LINE__);
1849 		return (ENOMEM);
1850 	}
1851 	eh->callback = cb;
1852 	eh->data = data;
1853 	TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
1854 	if (mask != NULL)
1855 		error = mps_update_events(sc, eh, mask);
1856 	*handle = eh;
1857 
1858 	return (error);
1859 }
1860 
1861 int
1862 mps_update_events(struct mps_softc *sc, struct mps_event_handle *handle,
1863     u32 *mask)
1864 {
1865 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
1866 	MPI2_EVENT_NOTIFICATION_REPLY *reply;
1867 	struct mps_command *cm;
1868 	int error, i;
1869 
1870 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1871 
1872 	if ((mask != NULL) && (handle != NULL))
1873 		bcopy(mask, &handle->mask[0], sizeof(u32) *
1874 				MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
1875 
1876 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
1877 		sc->event_mask[i] = -1;
1878 
1879 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
1880 		sc->event_mask[i] &= ~handle->mask[i];
1881 
1882 
1883 	if ((cm = mps_alloc_command(sc)) == NULL)
1884 		return (EBUSY);
1885 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
1886 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
1887 	evtreq->MsgFlags = 0;
1888 	evtreq->SASBroadcastPrimitiveMasks = 0;
1889 #ifdef MPS_DEBUG_ALL_EVENTS
1890 	{
1891 		u_char fullmask[16];
1892 		memset(fullmask, 0x00, 16);
1893 		bcopy(fullmask, &evtreq->EventMasks[0], sizeof(u32) *
1894 				MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
1895 	}
1896 #else
1897         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
1898                 evtreq->EventMasks[i] =
1899                     htole32(sc->event_mask[i]);
1900 #endif
1901 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1902 	cm->cm_data = NULL;
1903 
1904 	error = mps_request_polled(sc, cm);
1905 	reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
1906 	if ((reply == NULL) ||
1907 	    (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1908 		error = ENXIO;
1909 	mps_print_event(sc, reply);
1910 	mps_dprint(sc, MPS_TRACE, "%s finished error %d\n", __func__, error);
1911 
1912 	mps_free_command(sc, cm);
1913 	return (error);
1914 }
1915 
1916 static int
1917 mps_reregister_events(struct mps_softc *sc)
1918 {
1919 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
1920 	struct mps_command *cm;
1921 	struct mps_event_handle *eh;
1922 	int error, i;
1923 
1924 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1925 
1926 	/* first, reregister events */
1927 
1928     for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
1929 		sc->event_mask[i] = -1;
1930 
1931 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
1932 		for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
1933 			sc->event_mask[i] &= ~eh->mask[i];
1934 	}
1935 
1936 	if ((cm = mps_alloc_command(sc)) == NULL)
1937 		return (EBUSY);
1938 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
1939 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
1940 	evtreq->MsgFlags = 0;
1941 	evtreq->SASBroadcastPrimitiveMasks = 0;
1942 #ifdef MPS_DEBUG_ALL_EVENTS
1943 	{
1944 		u_char fullmask[16];
1945 		memset(fullmask, 0x00, 16);
1946 		bcopy(fullmask, &evtreq->EventMasks[0], sizeof(u32) *
1947 			MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
1948 	}
1949 #else
1950         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
1951                 evtreq->EventMasks[i] =
1952                     htole32(sc->event_mask[i]);
1953 #endif
1954 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1955 	cm->cm_data = NULL;
1956 	cm->cm_complete = mps_reregister_events_complete;
1957 
1958 	error = mps_map_command(sc, cm);
1959 
1960 	mps_dprint(sc, MPS_TRACE, "%s finished with error %d\n", __func__, error);
1961 	return (error);
1962 }
1963 
1964 void
1965 mps_deregister_events(struct mps_softc *sc, struct mps_event_handle *handle)
1966 {
1967 
1968 	TAILQ_REMOVE(&sc->event_list, handle, eh_list);
1969 	free(handle, M_MPT2);
1970 }
1971 
1972 /*
1973  * Add a chain element as the next SGE for the specified command.
1974  * Reset cm_sge and cm_sgesize to indicate all the available space.
1975  */
1976 static int
1977 mps_add_chain(struct mps_command *cm)
1978 {
1979 	MPI2_SGE_CHAIN32 *sgc;
1980 	struct mps_chain *chain;
1981 	int space;
1982 
1983 	if (cm->cm_sglsize < MPS_SGC_SIZE)
1984 		panic("MPS: Need SGE Error Code\n");
1985 
1986 	chain = mps_alloc_chain(cm->cm_sc);
1987 	if (chain == NULL)
1988 		return (ENOBUFS);
1989 
1990 	space = (int)cm->cm_sc->facts->IOCRequestFrameSize * 4;
1991 
1992 	/*
1993 	 * Note: a double-linked list is used to make it easier to
1994 	 * walk for debugging.
1995 	 */
1996 	TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
1997 
1998 	sgc = (MPI2_SGE_CHAIN32 *)&cm->cm_sge->MpiChain;
1999 	sgc->Length = htole16(space);
2000 	sgc->NextChainOffset = 0;
2001 	/* TODO Looks like bug in Setting sgc->Flags.
2002 	 *	sgc->Flags = ( MPI2_SGE_FLAGS_CHAIN_ELEMENT | MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
2003 	 *	            MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT
2004 	 *	This is fine.. because we are not using simple element. In case of
2005 	 *	MPI2_SGE_CHAIN32, we have seperate Length and Flags feild.
2006  	 */
2007 	sgc->Flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT;
2008 	sgc->Address = htole32(chain->chain_busaddr);
2009 
2010 	cm->cm_sge = (MPI2_SGE_IO_UNION *)&chain->chain->MpiSimple;
2011 	cm->cm_sglsize = space;
2012 	return (0);
2013 }
2014 
2015 /*
2016  * Add one scatter-gather element (chain, simple, transaction context)
2017  * to the scatter-gather list for a command.  Maintain cm_sglsize and
2018  * cm_sge as the remaining size and pointer to the next SGE to fill
2019  * in, respectively.
2020  */
2021 int
2022 mps_push_sge(struct mps_command *cm, void *sgep, size_t len, int segsleft)
2023 {
2024 	MPI2_SGE_TRANSACTION_UNION *tc = sgep;
2025 	MPI2_SGE_SIMPLE64 *sge = sgep;
2026 	int error, type;
2027 	uint32_t saved_buf_len, saved_address_low, saved_address_high;
2028 
2029 	type = (tc->Flags & MPI2_SGE_FLAGS_ELEMENT_MASK);
2030 
2031 #ifdef INVARIANTS
2032 	switch (type) {
2033 	case MPI2_SGE_FLAGS_TRANSACTION_ELEMENT: {
2034 		if (len != tc->DetailsLength + 4)
2035 			panic("TC %p length %u or %zu?", tc,
2036 			    tc->DetailsLength + 4, len);
2037 		}
2038 		break;
2039 	case MPI2_SGE_FLAGS_CHAIN_ELEMENT:
2040 		/* Driver only uses 32-bit chain elements */
2041 		if (len != MPS_SGC_SIZE)
2042 			panic("CHAIN %p length %u or %zu?", sgep,
2043 			    MPS_SGC_SIZE, len);
2044 		break;
2045 	case MPI2_SGE_FLAGS_SIMPLE_ELEMENT:
2046 		/* Driver only uses 64-bit SGE simple elements */
2047 		if (len != MPS_SGE64_SIZE)
2048 			panic("SGE simple %p length %u or %zu?", sge,
2049 			    MPS_SGE64_SIZE, len);
2050 		if (((le32toh(sge->FlagsLength) >> MPI2_SGE_FLAGS_SHIFT) &
2051 		    MPI2_SGE_FLAGS_ADDRESS_SIZE) == 0)
2052 			panic("SGE simple %p not marked 64-bit?", sge);
2053 
2054 		break;
2055 	default:
2056 		panic("Unexpected SGE %p, flags %02x", tc, tc->Flags);
2057 	}
2058 #endif
2059 
2060 	/*
2061 	 * case 1: 1 more segment, enough room for it
2062 	 * case 2: 2 more segments, enough room for both
2063 	 * case 3: >=2 more segments, only enough room for 1 and a chain
2064 	 * case 4: >=1 more segment, enough room for only a chain
2065 	 * case 5: >=1 more segment, no room for anything (error)
2066          */
2067 
2068 	/*
2069 	 * There should be room for at least a chain element, or this
2070 	 * code is buggy.  Case (5).
2071 	 */
2072 	if (cm->cm_sglsize < MPS_SGC_SIZE)
2073 		panic("MPS: Need SGE Error Code\n");
2074 
2075 	if (segsleft >= 2 &&
2076 	    cm->cm_sglsize < len + MPS_SGC_SIZE + MPS_SGE64_SIZE) {
2077 		/*
2078 		 * There are 2 or more segments left to add, and only
2079 		 * enough room for 1 and a chain.  Case (3).
2080 		 *
2081 		 * Mark as last element in this chain if necessary.
2082 		 */
2083 		if (type == MPI2_SGE_FLAGS_SIMPLE_ELEMENT) {
2084 			sge->FlagsLength |= htole32(
2085 			    MPI2_SGE_FLAGS_LAST_ELEMENT << MPI2_SGE_FLAGS_SHIFT);
2086 		}
2087 
2088 		/*
2089 		 * Add the item then a chain.  Do the chain now,
2090 		 * rather than on the next iteration, to simplify
2091 		 * understanding the code.
2092 		 */
2093 		cm->cm_sglsize -= len;
2094 		bcopy(sgep, cm->cm_sge, len);
2095 		cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2096 		return (mps_add_chain(cm));
2097 	}
2098 
2099 	if (segsleft >= 1 && cm->cm_sglsize < len + MPS_SGC_SIZE) {
2100 		/*
2101 		 * 1 or more segment, enough room for only a chain.
2102 		 * Hope the previous element wasn't a Simple entry
2103 		 * that needed to be marked with
2104 		 * MPI2_SGE_FLAGS_LAST_ELEMENT.  Case (4).
2105 		 */
2106 		if ((error = mps_add_chain(cm)) != 0)
2107 			return (error);
2108 	}
2109 
2110 #ifdef INVARIANTS
2111 	/* Case 1: 1 more segment, enough room for it. */
2112 	if (segsleft == 1 && cm->cm_sglsize < len)
2113 		panic("1 seg left and no room? %u versus %zu",
2114 		    cm->cm_sglsize, len);
2115 
2116 	/* Case 2: 2 more segments, enough room for both */
2117 	if (segsleft == 2 && cm->cm_sglsize < len + MPS_SGE64_SIZE)
2118 		panic("2 segs left and no room? %u versus %zu",
2119 		    cm->cm_sglsize, len);
2120 #endif
2121 
2122 	if (segsleft == 1 && type == MPI2_SGE_FLAGS_SIMPLE_ELEMENT) {
2123 		/*
2124 		 * If this is a bi-directional request, need to account for that
2125 		 * here.  Save the pre-filled sge values.  These will be used
2126 		 * either for the 2nd SGL or for a single direction SGL.  If
2127 		 * cm_out_len is non-zero, this is a bi-directional request, so
2128 		 * fill in the OUT SGL first, then the IN SGL, otherwise just
2129 		 * fill in the IN SGL.  Note that at this time, when filling in
2130 		 * 2 SGL's for a bi-directional request, they both use the same
2131 		 * DMA buffer (same cm command).
2132 		 */
2133 		saved_buf_len = le32toh(sge->FlagsLength) & 0x00FFFFFF;
2134 		saved_address_low = sge->Address.Low;
2135 		saved_address_high = sge->Address.High;
2136 		if (cm->cm_out_len) {
2137 			sge->FlagsLength = htole32(cm->cm_out_len |
2138 			    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2139 			    MPI2_SGE_FLAGS_END_OF_BUFFER |
2140 			    MPI2_SGE_FLAGS_HOST_TO_IOC |
2141 			    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2142 			    MPI2_SGE_FLAGS_SHIFT));
2143 			cm->cm_sglsize -= len;
2144 			bcopy(sgep, cm->cm_sge, len);
2145 			cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge
2146 			    + len);
2147 		}
2148 		saved_buf_len |=
2149 		    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2150 		    MPI2_SGE_FLAGS_END_OF_BUFFER |
2151 		    MPI2_SGE_FLAGS_LAST_ELEMENT |
2152 		    MPI2_SGE_FLAGS_END_OF_LIST |
2153 		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2154 		    MPI2_SGE_FLAGS_SHIFT);
2155 		if (cm->cm_flags & MPS_CM_FLAGS_DATAIN) {
2156 			saved_buf_len |=
2157 			    ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
2158 			    MPI2_SGE_FLAGS_SHIFT);
2159 		} else {
2160 			saved_buf_len |=
2161 			    ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
2162 			    MPI2_SGE_FLAGS_SHIFT);
2163 		}
2164 		sge->FlagsLength = htole32(saved_buf_len);
2165 		sge->Address.Low = saved_address_low;
2166 		sge->Address.High = saved_address_high;
2167 	}
2168 
2169 	cm->cm_sglsize -= len;
2170 	bcopy(sgep, cm->cm_sge, len);
2171 	cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2172 	return (0);
2173 }
2174 
2175 /*
2176  * Add one dma segment to the scatter-gather list for a command.
2177  */
2178 int
2179 mps_add_dmaseg(struct mps_command *cm, vm_paddr_t pa, size_t len, u_int flags,
2180     int segsleft)
2181 {
2182 	MPI2_SGE_SIMPLE64 sge;
2183 
2184 	/*
2185 	 * This driver always uses 64-bit address elements for simplicity.
2186 	 */
2187 	bzero(&sge, sizeof(sge));
2188 	flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2189 	    MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
2190 	sge.FlagsLength = htole32(len | (flags << MPI2_SGE_FLAGS_SHIFT));
2191 	mps_from_u64(pa, &sge.Address);
2192 
2193 	return (mps_push_sge(cm, &sge, sizeof sge, segsleft));
2194 }
2195 
2196 static void
2197 mps_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2198 {
2199 	struct mps_softc *sc;
2200 	struct mps_command *cm;
2201 	u_int i, dir, sflags;
2202 
2203 	cm = (struct mps_command *)arg;
2204 	sc = cm->cm_sc;
2205 
2206 	/*
2207 	 * In this case, just print out a warning and let the chip tell the
2208 	 * user they did the wrong thing.
2209 	 */
2210 	if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
2211 		mps_dprint(sc, MPS_ERROR,
2212 			   "%s: warning: busdma returned %d segments, "
2213 			   "more than the %d allowed\n", __func__, nsegs,
2214 			   cm->cm_max_segs);
2215 	}
2216 
2217 	/*
2218 	 * Set up DMA direction flags.  Bi-directional requests are also handled
2219 	 * here.  In that case, both direction flags will be set.
2220 	 */
2221 	sflags = 0;
2222 	if (cm->cm_flags & MPS_CM_FLAGS_SMP_PASS) {
2223 		/*
2224 		 * We have to add a special case for SMP passthrough, there
2225 		 * is no easy way to generically handle it.  The first
2226 		 * S/G element is used for the command (therefore the
2227 		 * direction bit needs to be set).  The second one is used
2228 		 * for the reply.  We'll leave it to the caller to make
2229 		 * sure we only have two buffers.
2230 		 */
2231 		/*
2232 		 * Even though the busdma man page says it doesn't make
2233 		 * sense to have both direction flags, it does in this case.
2234 		 * We have one s/g element being accessed in each direction.
2235 		 */
2236 		dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
2237 
2238 		/*
2239 		 * Set the direction flag on the first buffer in the SMP
2240 		 * passthrough request.  We'll clear it for the second one.
2241 		 */
2242 		sflags |= MPI2_SGE_FLAGS_DIRECTION |
2243 			  MPI2_SGE_FLAGS_END_OF_BUFFER;
2244 	} else if (cm->cm_flags & MPS_CM_FLAGS_DATAOUT) {
2245 		sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2246 		dir = BUS_DMASYNC_PREWRITE;
2247 	} else
2248 		dir = BUS_DMASYNC_PREREAD;
2249 
2250 	for (i = 0; i < nsegs; i++) {
2251 		if ((cm->cm_flags & MPS_CM_FLAGS_SMP_PASS) && (i != 0)) {
2252 			sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
2253 		}
2254 		error = mps_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
2255 		    sflags, nsegs - i);
2256 		if (error != 0) {
2257 			/* Resource shortage, roll back! */
2258 			mps_dprint(sc, MPS_INFO, "Out of chain frames, "
2259 			    "consider increasing hw.mps.max_chains.\n");
2260 			cm->cm_flags |= MPS_CM_FLAGS_CHAIN_FAILED;
2261 			mps_complete_command(sc, cm);
2262 			return;
2263 		}
2264 	}
2265 
2266 	bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
2267 	mps_enqueue_request(sc, cm);
2268 
2269 	return;
2270 }
2271 
2272 static void
2273 mps_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
2274 	     int error)
2275 {
2276 	mps_data_cb(arg, segs, nsegs, error);
2277 }
2278 
2279 /*
2280  * This is the routine to enqueue commands ansynchronously.
2281  * Note that the only error path here is from bus_dmamap_load(), which can
2282  * return EINPROGRESS if it is waiting for resources.  Other than this, it's
2283  * assumed that if you have a command in-hand, then you have enough credits
2284  * to use it.
2285  */
2286 int
2287 mps_map_command(struct mps_softc *sc, struct mps_command *cm)
2288 {
2289 	int error = 0;
2290 
2291 	if (cm->cm_flags & MPS_CM_FLAGS_USE_UIO) {
2292 		error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
2293 		    &cm->cm_uio, mps_data_cb2, cm, 0);
2294 	} else if (cm->cm_flags & MPS_CM_FLAGS_USE_CCB) {
2295 		error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
2296 		    cm->cm_data, mps_data_cb, cm, 0);
2297 	} else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
2298 		error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
2299 		    cm->cm_data, cm->cm_length, mps_data_cb, cm, 0);
2300 	} else {
2301 		/* Add a zero-length element as needed */
2302 		if (cm->cm_sge != NULL)
2303 			mps_add_dmaseg(cm, 0, 0, 0, 1);
2304 		mps_enqueue_request(sc, cm);
2305 	}
2306 
2307 	return (error);
2308 }
2309 
2310 /*
2311  * This is the routine to enqueue commands synchronously.  An error of
2312  * EINPROGRESS from mps_map_command() is ignored since the command will
2313  * be executed and enqueued automatically.  Other errors come from msleep().
2314  */
2315 int
2316 mps_wait_command(struct mps_softc *sc, struct mps_command *cm, int timeout)
2317 {
2318 	int error, rc;
2319 
2320 	mtx_assert(&sc->mps_mtx, MA_OWNED);
2321 
2322 	if(sc->mps_flags & MPS_FLAGS_DIAGRESET)
2323 		return  EBUSY;
2324 
2325 	cm->cm_complete = NULL;
2326 	cm->cm_flags |= MPS_CM_FLAGS_WAKEUP;
2327 	error = mps_map_command(sc, cm);
2328 	if ((error != 0) && (error != EINPROGRESS))
2329 		return (error);
2330 	error = msleep(cm, &sc->mps_mtx, 0, "mpswait", timeout*hz);
2331 	if (error == EWOULDBLOCK) {
2332 		mps_dprint(sc, MPS_FAULT, "Calling Reinit from %s\n", __func__);
2333 		rc = mps_reinit(sc);
2334 		mps_dprint(sc, MPS_FAULT, "Reinit %s\n",
2335 				(rc == 0) ? "success" : "failed");
2336 		error = ETIMEDOUT;
2337 	}
2338 	return (error);
2339 }
2340 
2341 /*
2342  * This is the routine to enqueue a command synchonously and poll for
2343  * completion.  Its use should be rare.
2344  */
2345 int
2346 mps_request_polled(struct mps_softc *sc, struct mps_command *cm)
2347 {
2348 	int error, timeout = 0, rc;
2349 
2350 	error = 0;
2351 
2352 	cm->cm_flags |= MPS_CM_FLAGS_POLLED;
2353 	cm->cm_complete = NULL;
2354 	mps_map_command(sc, cm);
2355 
2356 	while ((cm->cm_flags & MPS_CM_FLAGS_COMPLETE) == 0) {
2357 		mps_intr_locked(sc);
2358 
2359 		DELAY(50 * 1000);
2360 		if (timeout++ > 1000) {
2361 			mps_dprint(sc, MPS_FAULT, "polling failed\n");
2362 			error = ETIMEDOUT;
2363 			break;
2364 		}
2365 	}
2366 
2367 	if (error) {
2368 		mps_dprint(sc, MPS_FAULT, "Calling Reinit from %s\n", __func__);
2369 		rc = mps_reinit(sc);
2370 		mps_dprint(sc, MPS_FAULT, "Reinit %s\n",
2371 				(rc == 0) ? "success" : "failed");
2372 	}
2373 
2374 	return (error);
2375 }
2376 
2377 /*
2378  * The MPT driver had a verbose interface for config pages.  In this driver,
2379  * reduce it to much simplier terms, similar to the Linux driver.
2380  */
2381 int
2382 mps_read_config_page(struct mps_softc *sc, struct mps_config_params *params)
2383 {
2384 	MPI2_CONFIG_REQUEST *req;
2385 	struct mps_command *cm;
2386 	int error;
2387 
2388 	if (sc->mps_flags & MPS_FLAGS_BUSY) {
2389 		return (EBUSY);
2390 	}
2391 
2392 	cm = mps_alloc_command(sc);
2393 	if (cm == NULL) {
2394 		return (EBUSY);
2395 	}
2396 
2397 	req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
2398 	req->Function = MPI2_FUNCTION_CONFIG;
2399 	req->Action = params->action;
2400 	req->SGLFlags = 0;
2401 	req->ChainOffset = 0;
2402 	req->PageAddress = params->page_address;
2403 	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
2404 		MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
2405 
2406 		hdr = &params->hdr.Ext;
2407 		req->ExtPageType = hdr->ExtPageType;
2408 		req->ExtPageLength = hdr->ExtPageLength;
2409 		req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
2410 		req->Header.PageLength = 0; /* Must be set to zero */
2411 		req->Header.PageNumber = hdr->PageNumber;
2412 		req->Header.PageVersion = hdr->PageVersion;
2413 	} else {
2414 		MPI2_CONFIG_PAGE_HEADER *hdr;
2415 
2416 		hdr = &params->hdr.Struct;
2417 		req->Header.PageType = hdr->PageType;
2418 		req->Header.PageNumber = hdr->PageNumber;
2419 		req->Header.PageLength = hdr->PageLength;
2420 		req->Header.PageVersion = hdr->PageVersion;
2421 	}
2422 
2423 	cm->cm_data = params->buffer;
2424 	cm->cm_length = params->length;
2425 	cm->cm_sge = &req->PageBufferSGE;
2426 	cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
2427 	cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_DATAIN;
2428 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2429 
2430 	cm->cm_complete_data = params;
2431 	if (params->callback != NULL) {
2432 		cm->cm_complete = mps_config_complete;
2433 		return (mps_map_command(sc, cm));
2434 	} else {
2435 		error = mps_wait_command(sc, cm, 0);
2436 		if (error) {
2437 			mps_dprint(sc, MPS_FAULT,
2438 			    "Error %d reading config page\n", error);
2439 			mps_free_command(sc, cm);
2440 			return (error);
2441 		}
2442 		mps_config_complete(sc, cm);
2443 	}
2444 
2445 	return (0);
2446 }
2447 
2448 int
2449 mps_write_config_page(struct mps_softc *sc, struct mps_config_params *params)
2450 {
2451 	return (EINVAL);
2452 }
2453 
2454 static void
2455 mps_config_complete(struct mps_softc *sc, struct mps_command *cm)
2456 {
2457 	MPI2_CONFIG_REPLY *reply;
2458 	struct mps_config_params *params;
2459 
2460 	MPS_FUNCTRACE(sc);
2461 	params = cm->cm_complete_data;
2462 
2463 	if (cm->cm_data != NULL) {
2464 		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
2465 		    BUS_DMASYNC_POSTREAD);
2466 		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
2467 	}
2468 
2469 	/*
2470 	 * XXX KDM need to do more error recovery?  This results in the
2471 	 * device in question not getting probed.
2472 	 */
2473 	if ((cm->cm_flags & MPS_CM_FLAGS_ERROR_MASK) != 0) {
2474 		params->status = MPI2_IOCSTATUS_BUSY;
2475 		goto done;
2476 	}
2477 
2478 	reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
2479 	if (reply == NULL) {
2480 		params->status = MPI2_IOCSTATUS_BUSY;
2481 		goto done;
2482 	}
2483 	params->status = reply->IOCStatus;
2484 	if (params->hdr.Ext.ExtPageType != 0) {
2485 		params->hdr.Ext.ExtPageType = reply->ExtPageType;
2486 		params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
2487 	} else {
2488 		params->hdr.Struct.PageType = reply->Header.PageType;
2489 		params->hdr.Struct.PageNumber = reply->Header.PageNumber;
2490 		params->hdr.Struct.PageLength = reply->Header.PageLength;
2491 		params->hdr.Struct.PageVersion = reply->Header.PageVersion;
2492 	}
2493 
2494 done:
2495 	mps_free_command(sc, cm);
2496 	if (params->callback != NULL)
2497 		params->callback(sc, params);
2498 
2499 	return;
2500 }
2501