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