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