xref: /freebsd/sys/dev/mpr/mpr.c (revision 40427cca7a9ae77b095936fb1954417c290cfb17)
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/smp.h>
53 #include <sys/queue.h>
54 #include <sys/kthread.h>
55 #include <sys/taskqueue.h>
56 #include <sys/endian.h>
57 #include <sys/eventhandler.h>
58 
59 #include <machine/bus.h>
60 #include <machine/resource.h>
61 #include <sys/rman.h>
62 #include <sys/proc.h>
63 
64 #include <dev/pci/pcivar.h>
65 
66 #include <cam/cam.h>
67 #include <cam/cam_ccb.h>
68 #include <cam/scsi/scsi_all.h>
69 
70 #include <dev/mpr/mpi/mpi2_type.h>
71 #include <dev/mpr/mpi/mpi2.h>
72 #include <dev/mpr/mpi/mpi2_ioc.h>
73 #include <dev/mpr/mpi/mpi2_sas.h>
74 #include <dev/mpr/mpi/mpi2_pci.h>
75 #include <dev/mpr/mpi/mpi2_cnfg.h>
76 #include <dev/mpr/mpi/mpi2_init.h>
77 #include <dev/mpr/mpi/mpi2_tool.h>
78 #include <dev/mpr/mpr_ioctl.h>
79 #include <dev/mpr/mprvar.h>
80 #include <dev/mpr/mpr_table.h>
81 #include <dev/mpr/mpr_sas.h>
82 
83 static int mpr_diag_reset(struct mpr_softc *sc, int sleep_flag);
84 static int mpr_init_queues(struct mpr_softc *sc);
85 static void mpr_resize_queues(struct mpr_softc *sc);
86 static int mpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag);
87 static int mpr_transition_operational(struct mpr_softc *sc);
88 static int mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching);
89 static void mpr_iocfacts_free(struct mpr_softc *sc);
90 static void mpr_startup(void *arg);
91 static int mpr_send_iocinit(struct mpr_softc *sc);
92 static int mpr_alloc_queues(struct mpr_softc *sc);
93 static int mpr_alloc_hw_queues(struct mpr_softc *sc);
94 static int mpr_alloc_replies(struct mpr_softc *sc);
95 static int mpr_alloc_requests(struct mpr_softc *sc);
96 static int mpr_alloc_nvme_prp_pages(struct mpr_softc *sc);
97 static int mpr_attach_log(struct mpr_softc *sc);
98 static __inline void mpr_complete_command(struct mpr_softc *sc,
99     struct mpr_command *cm);
100 static void mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
101     MPI2_EVENT_NOTIFICATION_REPLY *reply);
102 static void mpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm);
103 static void mpr_periodic(void *);
104 static int mpr_reregister_events(struct mpr_softc *sc);
105 static void mpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm);
106 static int mpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts);
107 static int mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag);
108 SYSCTL_NODE(_hw, OID_AUTO, mpr, CTLFLAG_RD, 0, "MPR Driver Parameters");
109 
110 MALLOC_DEFINE(M_MPR, "mpr", "mpr driver memory");
111 
112 /*
113  * Do a "Diagnostic Reset" aka a hard reset.  This should get the chip out of
114  * any state and back to its initialization state machine.
115  */
116 static char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
117 
118 /*
119  * Added this union to smoothly convert le64toh cm->cm_desc.Words.
120  * Compiler only supports uint64_t to be passed as an argument.
121  * Otherwise it will throw this error:
122  * "aggregate value used where an integer was expected"
123  */
124 typedef union _reply_descriptor {
125         u64 word;
126         struct {
127                 u32 low;
128                 u32 high;
129         } u;
130 } reply_descriptor, request_descriptor;
131 
132 /* Rate limit chain-fail messages to 1 per minute */
133 static struct timeval mpr_chainfail_interval = { 60, 0 };
134 
135 /*
136  * sleep_flag can be either CAN_SLEEP or NO_SLEEP.
137  * If this function is called from process context, it can sleep
138  * and there is no harm to sleep, in case if this fuction is called
139  * from Interrupt handler, we can not sleep and need NO_SLEEP flag set.
140  * based on sleep flags driver will call either msleep, pause or DELAY.
141  * msleep and pause are of same variant, but pause is used when mpr_mtx
142  * is not hold by driver.
143  */
144 static int
145 mpr_diag_reset(struct mpr_softc *sc,int sleep_flag)
146 {
147 	uint32_t reg;
148 	int i, error, tries = 0;
149 	uint8_t first_wait_done = FALSE;
150 
151 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
152 
153 	/* Clear any pending interrupts */
154 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
155 
156 	/*
157 	 * Force NO_SLEEP for threads prohibited to sleep
158  	 * e.a Thread from interrupt handler are prohibited to sleep.
159  	 */
160 #if __FreeBSD_version >= 1000029
161 	if (curthread->td_no_sleeping)
162 #else //__FreeBSD_version < 1000029
163 	if (curthread->td_pflags & TDP_NOSLEEPING)
164 #endif //__FreeBSD_version >= 1000029
165 		sleep_flag = NO_SLEEP;
166 
167 	mpr_dprint(sc, MPR_INIT, "sequence start, sleep_flag=%d\n", sleep_flag);
168 	/* Push the magic sequence */
169 	error = ETIMEDOUT;
170 	while (tries++ < 20) {
171 		for (i = 0; i < sizeof(mpt2_reset_magic); i++)
172 			mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
173 			    mpt2_reset_magic[i]);
174 
175 		/* wait 100 msec */
176 		if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
177 			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
178 			    "mprdiag", hz/10);
179 		else if (sleep_flag == CAN_SLEEP)
180 			pause("mprdiag", hz/10);
181 		else
182 			DELAY(100 * 1000);
183 
184 		reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
185 		if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
186 			error = 0;
187 			break;
188 		}
189 	}
190 	if (error) {
191 		mpr_dprint(sc, MPR_INIT, "sequence failed, error=%d, exit\n",
192 		    error);
193 		return (error);
194 	}
195 
196 	/* Send the actual reset.  XXX need to refresh the reg? */
197 	reg |= MPI2_DIAG_RESET_ADAPTER;
198 	mpr_dprint(sc, MPR_INIT, "sequence success, sending reset, reg= 0x%x\n",
199 	    reg);
200 	mpr_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET, reg);
201 
202 	/* Wait up to 300 seconds in 50ms intervals */
203 	error = ETIMEDOUT;
204 	for (i = 0; i < 6000; i++) {
205 		/*
206 		 * Wait 50 msec. If this is the first time through, wait 256
207 		 * msec to satisfy Diag Reset timing requirements.
208 		 */
209 		if (first_wait_done) {
210 			if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
211 				msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
212 				    "mprdiag", hz/20);
213 			else if (sleep_flag == CAN_SLEEP)
214 				pause("mprdiag", hz/20);
215 			else
216 				DELAY(50 * 1000);
217 		} else {
218 			DELAY(256 * 1000);
219 			first_wait_done = TRUE;
220 		}
221 		/*
222 		 * Check for the RESET_ADAPTER bit to be cleared first, then
223 		 * wait for the RESET state to be cleared, which takes a little
224 		 * longer.
225 		 */
226 		reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
227 		if (reg & MPI2_DIAG_RESET_ADAPTER) {
228 			continue;
229 		}
230 		reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
231 		if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
232 			error = 0;
233 			break;
234 		}
235 	}
236 	if (error) {
237 		mpr_dprint(sc, MPR_INIT, "reset failed, error= %d, exit\n",
238 		    error);
239 		return (error);
240 	}
241 
242 	mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
243 	mpr_dprint(sc, MPR_INIT, "diag reset success, exit\n");
244 
245 	return (0);
246 }
247 
248 static int
249 mpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag)
250 {
251 	int error;
252 
253 	MPR_FUNCTRACE(sc);
254 
255 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
256 
257 	error = 0;
258 	mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
259 	    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
260 	    MPI2_DOORBELL_FUNCTION_SHIFT);
261 
262 	if (mpr_wait_db_ack(sc, 5, sleep_flag) != 0) {
263 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
264 		    "Doorbell handshake failed\n");
265 		error = ETIMEDOUT;
266 	}
267 
268 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
269 	return (error);
270 }
271 
272 static int
273 mpr_transition_ready(struct mpr_softc *sc)
274 {
275 	uint32_t reg, state;
276 	int error, tries = 0;
277 	int sleep_flags;
278 
279 	MPR_FUNCTRACE(sc);
280 	/* If we are in attach call, do not sleep */
281 	sleep_flags = (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE)
282 	    ? CAN_SLEEP : NO_SLEEP;
283 
284 	error = 0;
285 
286 	mpr_dprint(sc, MPR_INIT, "%s entered, sleep_flags= %d\n",
287 	    __func__, sleep_flags);
288 
289 	while (tries++ < 1200) {
290 		reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
291 		mpr_dprint(sc, MPR_INIT, "  Doorbell= 0x%x\n", reg);
292 
293 		/*
294 		 * Ensure the IOC is ready to talk.  If it's not, try
295 		 * resetting it.
296 		 */
297 		if (reg & MPI2_DOORBELL_USED) {
298 			mpr_dprint(sc, MPR_INIT, "  Not ready, sending diag "
299 			    "reset\n");
300 			mpr_diag_reset(sc, sleep_flags);
301 			DELAY(50000);
302 			continue;
303 		}
304 
305 		/* Is the adapter owned by another peer? */
306 		if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
307 		    (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
308 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC is under the "
309 			    "control of another peer host, aborting "
310 			    "initialization.\n");
311 			error = ENXIO;
312 			break;
313 		}
314 
315 		state = reg & MPI2_IOC_STATE_MASK;
316 		if (state == MPI2_IOC_STATE_READY) {
317 			/* Ready to go! */
318 			error = 0;
319 			break;
320 		} else if (state == MPI2_IOC_STATE_FAULT) {
321 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC in fault "
322 			    "state 0x%x, resetting\n",
323 			    state & MPI2_DOORBELL_FAULT_CODE_MASK);
324 			mpr_diag_reset(sc, sleep_flags);
325 		} else if (state == MPI2_IOC_STATE_OPERATIONAL) {
326 			/* Need to take ownership */
327 			mpr_message_unit_reset(sc, sleep_flags);
328 		} else if (state == MPI2_IOC_STATE_RESET) {
329 			/* Wait a bit, IOC might be in transition */
330 			mpr_dprint(sc, MPR_INIT|MPR_FAULT,
331 			    "IOC in unexpected reset state\n");
332 		} else {
333 			mpr_dprint(sc, MPR_INIT|MPR_FAULT,
334 			    "IOC in unknown state 0x%x\n", state);
335 			error = EINVAL;
336 			break;
337 		}
338 
339 		/* Wait 50ms for things to settle down. */
340 		DELAY(50000);
341 	}
342 
343 	if (error)
344 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
345 		    "Cannot transition IOC to ready\n");
346 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
347 	return (error);
348 }
349 
350 static int
351 mpr_transition_operational(struct mpr_softc *sc)
352 {
353 	uint32_t reg, state;
354 	int error;
355 
356 	MPR_FUNCTRACE(sc);
357 
358 	error = 0;
359 	reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
360 	mpr_dprint(sc, MPR_INIT, "%s entered, Doorbell= 0x%x\n", __func__, reg);
361 
362 	state = reg & MPI2_IOC_STATE_MASK;
363 	if (state != MPI2_IOC_STATE_READY) {
364 		mpr_dprint(sc, MPR_INIT, "IOC not ready\n");
365 		if ((error = mpr_transition_ready(sc)) != 0) {
366 			mpr_dprint(sc, MPR_INIT|MPR_FAULT,
367 			    "failed to transition ready, exit\n");
368 			return (error);
369 		}
370 	}
371 
372 	error = mpr_send_iocinit(sc);
373 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
374 
375 	return (error);
376 }
377 
378 static void
379 mpr_resize_queues(struct mpr_softc *sc)
380 {
381 	int reqcr, prireqcr;
382 
383 	/*
384 	 * Size the queues. Since the reply queues always need one free
385 	 * entry, we'll deduct one reply message here.  The LSI documents
386 	 * suggest instead to add a count to the request queue, but I think
387 	 * that it's better to deduct from reply queue.
388 	 */
389 	prireqcr = MAX(1, sc->max_prireqframes);
390 	prireqcr = MIN(prireqcr, sc->facts->HighPriorityCredit);
391 
392 	reqcr = MAX(2, sc->max_reqframes);
393 	reqcr = MIN(reqcr, sc->facts->RequestCredit);
394 
395 	sc->num_reqs = prireqcr + reqcr;
396 	sc->num_replies = MIN(sc->max_replyframes + sc->max_evtframes,
397 	    sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
398 
399 	/*
400 	 * Figure out the number of MSIx-based queues.  If the firmware or
401 	 * user has done something crazy and not allowed enough credit for
402 	 * the queues to be useful then don't enable multi-queue.
403 	 */
404 	if (sc->facts->MaxMSIxVectors < 2)
405 		sc->msi_msgs = 1;
406 
407 	if (sc->msi_msgs > 1) {
408 		sc->msi_msgs = MIN(sc->msi_msgs, mp_ncpus);
409 		sc->msi_msgs = MIN(sc->msi_msgs, sc->facts->MaxMSIxVectors);
410 		if (sc->num_reqs / sc->msi_msgs < 2)
411 			sc->msi_msgs = 1;
412 	}
413 
414 	mpr_dprint(sc, MPR_INIT, "Sized queues to q=%d reqs=%d replies=%d\n",
415 	    sc->msi_msgs, sc->num_reqs, sc->num_replies);
416 }
417 
418 /*
419  * This is called during attach and when re-initializing due to a Diag Reset.
420  * IOC Facts is used to allocate many of the structures needed by the driver.
421  * If called from attach, de-allocation is not required because the driver has
422  * not allocated any structures yet, but if called from a Diag Reset, previously
423  * allocated structures based on IOC Facts will need to be freed and re-
424  * allocated bases on the latest IOC Facts.
425  */
426 static int
427 mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching)
428 {
429 	int error;
430 	Mpi2IOCFactsReply_t saved_facts;
431 	uint8_t saved_mode, reallocating;
432 
433 	mpr_dprint(sc, MPR_INIT|MPR_TRACE, "%s entered\n", __func__);
434 
435 	/* Save old IOC Facts and then only reallocate if Facts have changed */
436 	if (!attaching) {
437 		bcopy(sc->facts, &saved_facts, sizeof(MPI2_IOC_FACTS_REPLY));
438 	}
439 
440 	/*
441 	 * Get IOC Facts.  In all cases throughout this function, panic if doing
442 	 * a re-initialization and only return the error if attaching so the OS
443 	 * can handle it.
444 	 */
445 	if ((error = mpr_get_iocfacts(sc, sc->facts)) != 0) {
446 		if (attaching) {
447 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to get "
448 			    "IOC Facts with error %d, exit\n", error);
449 			return (error);
450 		} else {
451 			panic("%s failed to get IOC Facts with error %d\n",
452 			    __func__, error);
453 		}
454 	}
455 
456 	MPR_DPRINT_PAGE(sc, MPR_XINFO, iocfacts, sc->facts);
457 
458 	snprintf(sc->fw_version, sizeof(sc->fw_version),
459 	    "%02d.%02d.%02d.%02d",
460 	    sc->facts->FWVersion.Struct.Major,
461 	    sc->facts->FWVersion.Struct.Minor,
462 	    sc->facts->FWVersion.Struct.Unit,
463 	    sc->facts->FWVersion.Struct.Dev);
464 
465 	mpr_dprint(sc, MPR_INFO, "Firmware: %s, Driver: %s\n", sc->fw_version,
466 	    MPR_DRIVER_VERSION);
467 	mpr_dprint(sc, MPR_INFO,
468 	    "IOCCapabilities: %b\n", sc->facts->IOCCapabilities,
469 	    "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
470 	    "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
471 	    "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc"
472 	    "\22FastPath" "\23RDPQArray" "\24AtomicReqDesc" "\25PCIeSRIOV");
473 
474 	/*
475 	 * If the chip doesn't support event replay then a hard reset will be
476 	 * required to trigger a full discovery.  Do the reset here then
477 	 * retransition to Ready.  A hard reset might have already been done,
478 	 * but it doesn't hurt to do it again.  Only do this if attaching, not
479 	 * for a Diag Reset.
480 	 */
481 	if (attaching && ((sc->facts->IOCCapabilities &
482 	    MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0)) {
483 		mpr_dprint(sc, MPR_INIT, "No event replay, resetting\n");
484 		mpr_diag_reset(sc, NO_SLEEP);
485 		if ((error = mpr_transition_ready(sc)) != 0) {
486 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
487 			    "transition to ready with error %d, exit\n",
488 			    error);
489 			return (error);
490 		}
491 	}
492 
493 	/*
494 	 * Set flag if IR Firmware is loaded.  If the RAID Capability has
495 	 * changed from the previous IOC Facts, log a warning, but only if
496 	 * checking this after a Diag Reset and not during attach.
497 	 */
498 	saved_mode = sc->ir_firmware;
499 	if (sc->facts->IOCCapabilities &
500 	    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
501 		sc->ir_firmware = 1;
502 	if (!attaching) {
503 		if (sc->ir_firmware != saved_mode) {
504 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "new IR/IT mode "
505 			    "in IOC Facts does not match previous mode\n");
506 		}
507 	}
508 
509 	/* Only deallocate and reallocate if relevant IOC Facts have changed */
510 	reallocating = FALSE;
511 	sc->mpr_flags &= ~MPR_FLAGS_REALLOCATED;
512 
513 	if ((!attaching) &&
514 	    ((saved_facts.MsgVersion != sc->facts->MsgVersion) ||
515 	    (saved_facts.HeaderVersion != sc->facts->HeaderVersion) ||
516 	    (saved_facts.MaxChainDepth != sc->facts->MaxChainDepth) ||
517 	    (saved_facts.RequestCredit != sc->facts->RequestCredit) ||
518 	    (saved_facts.ProductID != sc->facts->ProductID) ||
519 	    (saved_facts.IOCCapabilities != sc->facts->IOCCapabilities) ||
520 	    (saved_facts.IOCRequestFrameSize !=
521 	    sc->facts->IOCRequestFrameSize) ||
522 	    (saved_facts.IOCMaxChainSegmentSize !=
523 	    sc->facts->IOCMaxChainSegmentSize) ||
524 	    (saved_facts.MaxTargets != sc->facts->MaxTargets) ||
525 	    (saved_facts.MaxSasExpanders != sc->facts->MaxSasExpanders) ||
526 	    (saved_facts.MaxEnclosures != sc->facts->MaxEnclosures) ||
527 	    (saved_facts.HighPriorityCredit != sc->facts->HighPriorityCredit) ||
528 	    (saved_facts.MaxReplyDescriptorPostQueueDepth !=
529 	    sc->facts->MaxReplyDescriptorPostQueueDepth) ||
530 	    (saved_facts.ReplyFrameSize != sc->facts->ReplyFrameSize) ||
531 	    (saved_facts.MaxVolumes != sc->facts->MaxVolumes) ||
532 	    (saved_facts.MaxPersistentEntries !=
533 	    sc->facts->MaxPersistentEntries))) {
534 		reallocating = TRUE;
535 
536 		/* Record that we reallocated everything */
537 		sc->mpr_flags |= MPR_FLAGS_REALLOCATED;
538 	}
539 
540 	/*
541 	 * Some things should be done if attaching or re-allocating after a Diag
542 	 * Reset, but are not needed after a Diag Reset if the FW has not
543 	 * changed.
544 	 */
545 	if (attaching || reallocating) {
546 		/*
547 		 * Check if controller supports FW diag buffers and set flag to
548 		 * enable each type.
549 		 */
550 		if (sc->facts->IOCCapabilities &
551 		    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
552 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].
553 			    enabled = TRUE;
554 		if (sc->facts->IOCCapabilities &
555 		    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
556 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].
557 			    enabled = TRUE;
558 		if (sc->facts->IOCCapabilities &
559 		    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
560 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].
561 			    enabled = TRUE;
562 
563 		/*
564 		 * Set flags for some supported items.
565 		 */
566 		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
567 			sc->eedp_enabled = TRUE;
568 		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
569 			sc->control_TLR = TRUE;
570 		if (sc->facts->IOCCapabilities &
571 		    MPI26_IOCFACTS_CAPABILITY_ATOMIC_REQ)
572 			sc->atomic_desc_capable = TRUE;
573 
574 		mpr_resize_queues(sc);
575 
576 		/*
577 		 * Initialize all Tail Queues
578 		 */
579 		TAILQ_INIT(&sc->req_list);
580 		TAILQ_INIT(&sc->high_priority_req_list);
581 		TAILQ_INIT(&sc->chain_list);
582 		TAILQ_INIT(&sc->prp_page_list);
583 		TAILQ_INIT(&sc->tm_list);
584 	}
585 
586 	/*
587 	 * If doing a Diag Reset and the FW is significantly different
588 	 * (reallocating will be set above in IOC Facts comparison), then all
589 	 * buffers based on the IOC Facts will need to be freed before they are
590 	 * reallocated.
591 	 */
592 	if (reallocating) {
593 		mpr_iocfacts_free(sc);
594 		mprsas_realloc_targets(sc, saved_facts.MaxTargets +
595 		    saved_facts.MaxVolumes);
596 	}
597 
598 	/*
599 	 * Any deallocation has been completed.  Now start reallocating
600 	 * if needed.  Will only need to reallocate if attaching or if the new
601 	 * IOC Facts are different from the previous IOC Facts after a Diag
602 	 * Reset. Targets have already been allocated above if needed.
603 	 */
604 	error = 0;
605 	while (attaching || reallocating) {
606 		if ((error = mpr_alloc_hw_queues(sc)) != 0)
607 			break;
608 		if ((error = mpr_alloc_replies(sc)) != 0)
609 			break;
610 		if ((error = mpr_alloc_requests(sc)) != 0)
611 			break;
612 		if ((error = mpr_alloc_queues(sc)) != 0)
613 			break;
614 		break;
615 	}
616 	if (error) {
617 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
618 		    "Failed to alloc queues with error %d\n", error);
619 		mpr_free(sc);
620 		return (error);
621 	}
622 
623 	/* Always initialize the queues */
624 	bzero(sc->free_queue, sc->fqdepth * 4);
625 	mpr_init_queues(sc);
626 
627 	/*
628 	 * Always get the chip out of the reset state, but only panic if not
629 	 * attaching.  If attaching and there is an error, that is handled by
630 	 * the OS.
631 	 */
632 	error = mpr_transition_operational(sc);
633 	if (error != 0) {
634 		mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
635 		    "transition to operational with error %d\n", error);
636 		mpr_free(sc);
637 		return (error);
638 	}
639 
640 	/*
641 	 * Finish the queue initialization.
642 	 * These are set here instead of in mpr_init_queues() because the
643 	 * IOC resets these values during the state transition in
644 	 * mpr_transition_operational().  The free index is set to 1
645 	 * because the corresponding index in the IOC is set to 0, and the
646 	 * IOC treats the queues as full if both are set to the same value.
647 	 * Hence the reason that the queue can't hold all of the possible
648 	 * replies.
649 	 */
650 	sc->replypostindex = 0;
651 	mpr_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
652 	mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
653 
654 	/*
655 	 * Attach the subsystems so they can prepare their event masks.
656 	 * XXX Should be dynamic so that IM/IR and user modules can attach
657 	 */
658 	error = 0;
659 	while (attaching) {
660 		mpr_dprint(sc, MPR_INIT, "Attaching subsystems\n");
661 		if ((error = mpr_attach_log(sc)) != 0)
662 			break;
663 		if ((error = mpr_attach_sas(sc)) != 0)
664 			break;
665 		if ((error = mpr_attach_user(sc)) != 0)
666 			break;
667 		break;
668 	}
669 	if (error) {
670 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
671 		    "Failed to attach all subsystems: error %d\n", error);
672 		mpr_free(sc);
673 		return (error);
674 	}
675 
676 	if ((error = mpr_pci_setup_interrupts(sc)) != 0) {
677 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
678 		    "Failed to setup interrupts\n");
679 		mpr_free(sc);
680 		return (error);
681 	}
682 
683 	return (error);
684 }
685 
686 /*
687  * This is called if memory is being free (during detach for example) and when
688  * buffers need to be reallocated due to a Diag Reset.
689  */
690 static void
691 mpr_iocfacts_free(struct mpr_softc *sc)
692 {
693 	struct mpr_command *cm;
694 	int i;
695 
696 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
697 
698 	if (sc->free_busaddr != 0)
699 		bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
700 	if (sc->free_queue != NULL)
701 		bus_dmamem_free(sc->queues_dmat, sc->free_queue,
702 		    sc->queues_map);
703 	if (sc->queues_dmat != NULL)
704 		bus_dma_tag_destroy(sc->queues_dmat);
705 
706 	if (sc->chain_busaddr != 0)
707 		bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
708 	if (sc->chain_frames != NULL)
709 		bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
710 		    sc->chain_map);
711 	if (sc->chain_dmat != NULL)
712 		bus_dma_tag_destroy(sc->chain_dmat);
713 
714 	if (sc->sense_busaddr != 0)
715 		bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
716 	if (sc->sense_frames != NULL)
717 		bus_dmamem_free(sc->sense_dmat, sc->sense_frames,
718 		    sc->sense_map);
719 	if (sc->sense_dmat != NULL)
720 		bus_dma_tag_destroy(sc->sense_dmat);
721 
722 	if (sc->prp_page_busaddr != 0)
723 		bus_dmamap_unload(sc->prp_page_dmat, sc->prp_page_map);
724 	if (sc->prp_pages != NULL)
725 		bus_dmamem_free(sc->prp_page_dmat, sc->prp_pages,
726 		    sc->prp_page_map);
727 	if (sc->prp_page_dmat != NULL)
728 		bus_dma_tag_destroy(sc->prp_page_dmat);
729 
730 	if (sc->reply_busaddr != 0)
731 		bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
732 	if (sc->reply_frames != NULL)
733 		bus_dmamem_free(sc->reply_dmat, sc->reply_frames,
734 		    sc->reply_map);
735 	if (sc->reply_dmat != NULL)
736 		bus_dma_tag_destroy(sc->reply_dmat);
737 
738 	if (sc->req_busaddr != 0)
739 		bus_dmamap_unload(sc->req_dmat, sc->req_map);
740 	if (sc->req_frames != NULL)
741 		bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
742 	if (sc->req_dmat != NULL)
743 		bus_dma_tag_destroy(sc->req_dmat);
744 
745 	if (sc->chains != NULL)
746 		free(sc->chains, M_MPR);
747 	if (sc->prps != NULL)
748 		free(sc->prps, M_MPR);
749 	if (sc->commands != NULL) {
750 		for (i = 1; i < sc->num_reqs; i++) {
751 			cm = &sc->commands[i];
752 			bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
753 		}
754 		free(sc->commands, M_MPR);
755 	}
756 	if (sc->buffer_dmat != NULL)
757 		bus_dma_tag_destroy(sc->buffer_dmat);
758 
759 	mpr_pci_free_interrupts(sc);
760 	free(sc->queues, M_MPR);
761 	sc->queues = NULL;
762 }
763 
764 /*
765  * The terms diag reset and hard reset are used interchangeably in the MPI
766  * docs to mean resetting the controller chip.  In this code diag reset
767  * cleans everything up, and the hard reset function just sends the reset
768  * sequence to the chip.  This should probably be refactored so that every
769  * subsystem gets a reset notification of some sort, and can clean up
770  * appropriately.
771  */
772 int
773 mpr_reinit(struct mpr_softc *sc)
774 {
775 	int error;
776 	struct mprsas_softc *sassc;
777 
778 	sassc = sc->sassc;
779 
780 	MPR_FUNCTRACE(sc);
781 
782 	mtx_assert(&sc->mpr_mtx, MA_OWNED);
783 
784 	mpr_dprint(sc, MPR_INIT|MPR_INFO, "Reinitializing controller\n");
785 	if (sc->mpr_flags & MPR_FLAGS_DIAGRESET) {
786 		mpr_dprint(sc, MPR_INIT, "Reset already in progress\n");
787 		return 0;
788 	}
789 
790 	/*
791 	 * Make sure the completion callbacks can recognize they're getting
792 	 * a NULL cm_reply due to a reset.
793 	 */
794 	sc->mpr_flags |= MPR_FLAGS_DIAGRESET;
795 
796 	/*
797 	 * Mask interrupts here.
798 	 */
799 	mpr_dprint(sc, MPR_INIT, "Masking interrupts and resetting\n");
800 	mpr_mask_intr(sc);
801 
802 	error = mpr_diag_reset(sc, CAN_SLEEP);
803 	if (error != 0) {
804 		panic("%s hard reset failed with error %d\n", __func__, error);
805 	}
806 
807 	/* Restore the PCI state, including the MSI-X registers */
808 	mpr_pci_restore(sc);
809 
810 	/* Give the I/O subsystem special priority to get itself prepared */
811 	mprsas_handle_reinit(sc);
812 
813 	/*
814 	 * Get IOC Facts and allocate all structures based on this information.
815 	 * The attach function will also call mpr_iocfacts_allocate at startup.
816 	 * If relevant values have changed in IOC Facts, this function will free
817 	 * all of the memory based on IOC Facts and reallocate that memory.
818 	 */
819 	if ((error = mpr_iocfacts_allocate(sc, FALSE)) != 0) {
820 		panic("%s IOC Facts based allocation failed with error %d\n",
821 		    __func__, error);
822 	}
823 
824 	/*
825 	 * Mapping structures will be re-allocated after getting IOC Page8, so
826 	 * free these structures here.
827 	 */
828 	mpr_mapping_exit(sc);
829 
830 	/*
831 	 * The static page function currently read is IOC Page8.  Others can be
832 	 * added in future.  It's possible that the values in IOC Page8 have
833 	 * changed after a Diag Reset due to user modification, so always read
834 	 * these.  Interrupts are masked, so unmask them before getting config
835 	 * pages.
836 	 */
837 	mpr_unmask_intr(sc);
838 	sc->mpr_flags &= ~MPR_FLAGS_DIAGRESET;
839 	mpr_base_static_config_pages(sc);
840 
841 	/*
842 	 * Some mapping info is based in IOC Page8 data, so re-initialize the
843 	 * mapping tables.
844 	 */
845 	mpr_mapping_initialize(sc);
846 
847 	/*
848 	 * Restart will reload the event masks clobbered by the reset, and
849 	 * then enable the port.
850 	 */
851 	mpr_reregister_events(sc);
852 
853 	/* the end of discovery will release the simq, so we're done. */
854 	mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Finished sc %p post %u free %u\n",
855 	    sc, sc->replypostindex, sc->replyfreeindex);
856 	mprsas_release_simq_reinit(sassc);
857 	mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
858 
859 	return 0;
860 }
861 
862 /* Wait for the chip to ACK a word that we've put into its FIFO
863  * Wait for <timeout> seconds. In single loop wait for busy loop
864  * for 500 microseconds.
865  * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
866  * */
867 static int
868 mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag)
869 {
870 	u32 cntdn, count;
871 	u32 int_status;
872 	u32 doorbell;
873 
874 	count = 0;
875 	cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
876 	do {
877 		int_status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
878 		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
879 			mpr_dprint(sc, MPR_TRACE, "%s: successful count(%d), "
880 			    "timeout(%d)\n", __func__, count, timeout);
881 			return 0;
882 		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
883 			doorbell = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
884 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
885 			    MPI2_IOC_STATE_FAULT) {
886 				mpr_dprint(sc, MPR_FAULT,
887 				    "fault_state(0x%04x)!\n", doorbell);
888 				return (EFAULT);
889 			}
890 		} else if (int_status == 0xFFFFFFFF)
891 			goto out;
892 
893 		/*
894 		 * If it can sleep, sleep for 1 milisecond, else busy loop for
895  		 * 0.5 milisecond
896 		 */
897 		if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
898 			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0, "mprdba",
899 			    hz/1000);
900 		else if (sleep_flag == CAN_SLEEP)
901 			pause("mprdba", hz/1000);
902 		else
903 			DELAY(500);
904 		count++;
905 	} while (--cntdn);
906 
907 out:
908 	mpr_dprint(sc, MPR_FAULT, "%s: failed due to timeout count(%d), "
909 		"int_status(%x)!\n", __func__, count, int_status);
910 	return (ETIMEDOUT);
911 }
912 
913 /* Wait for the chip to signal that the next word in its FIFO can be fetched */
914 static int
915 mpr_wait_db_int(struct mpr_softc *sc)
916 {
917 	int retry;
918 
919 	for (retry = 0; retry < MPR_DB_MAX_WAIT; retry++) {
920 		if ((mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
921 		    MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
922 			return (0);
923 		DELAY(2000);
924 	}
925 	return (ETIMEDOUT);
926 }
927 
928 /* Step through the synchronous command state machine, i.e. "Doorbell mode" */
929 static int
930 mpr_request_sync(struct mpr_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
931     int req_sz, int reply_sz, int timeout)
932 {
933 	uint32_t *data32;
934 	uint16_t *data16;
935 	int i, count, ioc_sz, residual;
936 	int sleep_flags = CAN_SLEEP;
937 
938 #if __FreeBSD_version >= 1000029
939 	if (curthread->td_no_sleeping)
940 #else //__FreeBSD_version < 1000029
941 	if (curthread->td_pflags & TDP_NOSLEEPING)
942 #endif //__FreeBSD_version >= 1000029
943 		sleep_flags = NO_SLEEP;
944 
945 	/* Step 1 */
946 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
947 
948 	/* Step 2 */
949 	if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
950 		return (EBUSY);
951 
952 	/* Step 3
953 	 * Announce that a message is coming through the doorbell.  Messages
954 	 * are pushed at 32bit words, so round up if needed.
955 	 */
956 	count = (req_sz + 3) / 4;
957 	mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
958 	    (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
959 	    (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
960 
961 	/* Step 4 */
962 	if (mpr_wait_db_int(sc) ||
963 	    (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
964 		mpr_dprint(sc, MPR_FAULT, "Doorbell failed to activate\n");
965 		return (ENXIO);
966 	}
967 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
968 	if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
969 		mpr_dprint(sc, MPR_FAULT, "Doorbell handshake failed\n");
970 		return (ENXIO);
971 	}
972 
973 	/* Step 5 */
974 	/* Clock out the message data synchronously in 32-bit dwords*/
975 	data32 = (uint32_t *)req;
976 	for (i = 0; i < count; i++) {
977 		mpr_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
978 		if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
979 			mpr_dprint(sc, MPR_FAULT,
980 			    "Timeout while writing doorbell\n");
981 			return (ENXIO);
982 		}
983 	}
984 
985 	/* Step 6 */
986 	/* Clock in the reply in 16-bit words.  The total length of the
987 	 * message is always in the 4th byte, so clock out the first 2 words
988 	 * manually, then loop the rest.
989 	 */
990 	data16 = (uint16_t *)reply;
991 	if (mpr_wait_db_int(sc) != 0) {
992 		mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 0\n");
993 		return (ENXIO);
994 	}
995 	data16[0] =
996 	    mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
997 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
998 	if (mpr_wait_db_int(sc) != 0) {
999 		mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 1\n");
1000 		return (ENXIO);
1001 	}
1002 	data16[1] =
1003 	    mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
1004 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1005 
1006 	/* Number of 32bit words in the message */
1007 	ioc_sz = reply->MsgLength;
1008 
1009 	/*
1010 	 * Figure out how many 16bit words to clock in without overrunning.
1011 	 * The precision loss with dividing reply_sz can safely be
1012 	 * ignored because the messages can only be multiples of 32bits.
1013 	 */
1014 	residual = 0;
1015 	count = MIN((reply_sz / 4), ioc_sz) * 2;
1016 	if (count < ioc_sz * 2) {
1017 		residual = ioc_sz * 2 - count;
1018 		mpr_dprint(sc, MPR_ERROR, "Driver error, throwing away %d "
1019 		    "residual message words\n", residual);
1020 	}
1021 
1022 	for (i = 2; i < count; i++) {
1023 		if (mpr_wait_db_int(sc) != 0) {
1024 			mpr_dprint(sc, MPR_FAULT,
1025 			    "Timeout reading doorbell %d\n", i);
1026 			return (ENXIO);
1027 		}
1028 		data16[i] = mpr_regread(sc, MPI2_DOORBELL_OFFSET) &
1029 		    MPI2_DOORBELL_DATA_MASK;
1030 		mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1031 	}
1032 
1033 	/*
1034 	 * Pull out residual words that won't fit into the provided buffer.
1035 	 * This keeps the chip from hanging due to a driver programming
1036 	 * error.
1037 	 */
1038 	while (residual--) {
1039 		if (mpr_wait_db_int(sc) != 0) {
1040 			mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell\n");
1041 			return (ENXIO);
1042 		}
1043 		(void)mpr_regread(sc, MPI2_DOORBELL_OFFSET);
1044 		mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1045 	}
1046 
1047 	/* Step 7 */
1048 	if (mpr_wait_db_int(sc) != 0) {
1049 		mpr_dprint(sc, MPR_FAULT, "Timeout waiting to exit doorbell\n");
1050 		return (ENXIO);
1051 	}
1052 	if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
1053 		mpr_dprint(sc, MPR_FAULT, "Warning, doorbell still active\n");
1054 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1055 
1056 	return (0);
1057 }
1058 
1059 static void
1060 mpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm)
1061 {
1062 	request_descriptor rd;
1063 
1064 	MPR_FUNCTRACE(sc);
1065 	mpr_dprint(sc, MPR_TRACE, "SMID %u cm %p ccb %p\n",
1066 	    cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
1067 
1068 	if (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE && !(sc->mpr_flags &
1069 	    MPR_FLAGS_SHUTDOWN))
1070 		mtx_assert(&sc->mpr_mtx, MA_OWNED);
1071 
1072 	if (++sc->io_cmds_active > sc->io_cmds_highwater)
1073 		sc->io_cmds_highwater++;
1074 
1075 	if (sc->atomic_desc_capable) {
1076 		rd.u.low = cm->cm_desc.Words.Low;
1077 		mpr_regwrite(sc, MPI26_ATOMIC_REQUEST_DESCRIPTOR_POST_OFFSET,
1078 		    rd.u.low);
1079 	} else {
1080 		rd.u.low = cm->cm_desc.Words.Low;
1081 		rd.u.high = cm->cm_desc.Words.High;
1082 		rd.word = htole64(rd.word);
1083 		mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
1084 		    rd.u.low);
1085 		mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
1086 		    rd.u.high);
1087 	}
1088 }
1089 
1090 /*
1091  * Just the FACTS, ma'am.
1092  */
1093 static int
1094 mpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
1095 {
1096 	MPI2_DEFAULT_REPLY *reply;
1097 	MPI2_IOC_FACTS_REQUEST request;
1098 	int error, req_sz, reply_sz;
1099 
1100 	MPR_FUNCTRACE(sc);
1101 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1102 
1103 	req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
1104 	reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
1105 	reply = (MPI2_DEFAULT_REPLY *)facts;
1106 
1107 	bzero(&request, req_sz);
1108 	request.Function = MPI2_FUNCTION_IOC_FACTS;
1109 	error = mpr_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
1110 
1111 	mpr_dprint(sc, MPR_INIT, "%s exit, error= %d\n", __func__, error);
1112 	return (error);
1113 }
1114 
1115 static int
1116 mpr_send_iocinit(struct mpr_softc *sc)
1117 {
1118 	MPI2_IOC_INIT_REQUEST	init;
1119 	MPI2_DEFAULT_REPLY	reply;
1120 	int req_sz, reply_sz, error;
1121 	struct timeval now;
1122 	uint64_t time_in_msec;
1123 
1124 	MPR_FUNCTRACE(sc);
1125 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1126 
1127 	req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
1128 	reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
1129 	bzero(&init, req_sz);
1130 	bzero(&reply, reply_sz);
1131 
1132 	/*
1133 	 * Fill in the init block.  Note that most addresses are
1134 	 * deliberately in the lower 32bits of memory.  This is a micro-
1135 	 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
1136 	 */
1137 	init.Function = MPI2_FUNCTION_IOC_INIT;
1138 	init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
1139 	init.MsgVersion = htole16(MPI2_VERSION);
1140 	init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
1141 	init.SystemRequestFrameSize = htole16(sc->facts->IOCRequestFrameSize);
1142 	init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
1143 	init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
1144 	init.SenseBufferAddressHigh = 0;
1145 	init.SystemReplyAddressHigh = 0;
1146 	init.SystemRequestFrameBaseAddress.High = 0;
1147 	init.SystemRequestFrameBaseAddress.Low =
1148 	    htole32((uint32_t)sc->req_busaddr);
1149 	init.ReplyDescriptorPostQueueAddress.High = 0;
1150 	init.ReplyDescriptorPostQueueAddress.Low =
1151 	    htole32((uint32_t)sc->post_busaddr);
1152 	init.ReplyFreeQueueAddress.High = 0;
1153 	init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
1154 	getmicrotime(&now);
1155 	time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
1156 	init.TimeStamp.High = htole32((time_in_msec >> 32) & 0xFFFFFFFF);
1157 	init.TimeStamp.Low = htole32(time_in_msec & 0xFFFFFFFF);
1158 	init.HostPageSize = HOST_PAGE_SIZE_4K;
1159 
1160 	error = mpr_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
1161 	if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1162 		error = ENXIO;
1163 
1164 	mpr_dprint(sc, MPR_INIT, "IOCInit status= 0x%x\n", reply.IOCStatus);
1165 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
1166 	return (error);
1167 }
1168 
1169 void
1170 mpr_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1171 {
1172 	bus_addr_t *addr;
1173 
1174 	addr = arg;
1175 	*addr = segs[0].ds_addr;
1176 }
1177 
1178 static int
1179 mpr_alloc_queues(struct mpr_softc *sc)
1180 {
1181 	struct mpr_queue *q;
1182 	int nq, i;
1183 
1184 	nq = sc->msi_msgs;
1185 	mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Allocating %d I/O queues\n", nq);
1186 
1187 	sc->queues = malloc(sizeof(struct mpr_queue) * nq, M_MPR,
1188 	     M_NOWAIT|M_ZERO);
1189 	if (sc->queues == NULL)
1190 		return (ENOMEM);
1191 
1192 	for (i = 0; i < nq; i++) {
1193 		q = &sc->queues[i];
1194 		mpr_dprint(sc, MPR_INIT, "Configuring queue %d %p\n", i, q);
1195 		q->sc = sc;
1196 		q->qnum = i;
1197 	}
1198 	return (0);
1199 }
1200 
1201 static int
1202 mpr_alloc_hw_queues(struct mpr_softc *sc)
1203 {
1204 	bus_addr_t queues_busaddr;
1205 	uint8_t *queues;
1206 	int qsize, fqsize, pqsize;
1207 
1208 	/*
1209 	 * The reply free queue contains 4 byte entries in multiples of 16 and
1210 	 * aligned on a 16 byte boundary. There must always be an unused entry.
1211 	 * This queue supplies fresh reply frames for the firmware to use.
1212 	 *
1213 	 * The reply descriptor post queue contains 8 byte entries in
1214 	 * multiples of 16 and aligned on a 16 byte boundary.  This queue
1215 	 * contains filled-in reply frames sent from the firmware to the host.
1216 	 *
1217 	 * These two queues are allocated together for simplicity.
1218 	 */
1219 	sc->fqdepth = roundup2(sc->num_replies + 1, 16);
1220 	sc->pqdepth = roundup2(sc->num_replies + 1, 16);
1221 	fqsize= sc->fqdepth * 4;
1222 	pqsize = sc->pqdepth * 8;
1223 	qsize = fqsize + pqsize;
1224 
1225         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1226 				16, 0,			/* algnmnt, boundary */
1227 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1228 				BUS_SPACE_MAXADDR,	/* highaddr */
1229 				NULL, NULL,		/* filter, filterarg */
1230                                 qsize,			/* maxsize */
1231                                 1,			/* nsegments */
1232                                 qsize,			/* maxsegsize */
1233                                 0,			/* flags */
1234                                 NULL, NULL,		/* lockfunc, lockarg */
1235                                 &sc->queues_dmat)) {
1236 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues DMA tag\n");
1237 		return (ENOMEM);
1238         }
1239         if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
1240 	    &sc->queues_map)) {
1241 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues memory\n");
1242 		return (ENOMEM);
1243         }
1244         bzero(queues, qsize);
1245         bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
1246 	    mpr_memaddr_cb, &queues_busaddr, 0);
1247 
1248 	sc->free_queue = (uint32_t *)queues;
1249 	sc->free_busaddr = queues_busaddr;
1250 	sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
1251 	sc->post_busaddr = queues_busaddr + fqsize;
1252 
1253 	return (0);
1254 }
1255 
1256 static int
1257 mpr_alloc_replies(struct mpr_softc *sc)
1258 {
1259 	int rsize, num_replies;
1260 
1261 	/*
1262 	 * sc->num_replies should be one less than sc->fqdepth.  We need to
1263 	 * allocate space for sc->fqdepth replies, but only sc->num_replies
1264 	 * replies can be used at once.
1265 	 */
1266 	num_replies = max(sc->fqdepth, sc->num_replies);
1267 
1268 	rsize = sc->facts->ReplyFrameSize * num_replies * 4;
1269         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1270 				4, 0,			/* algnmnt, boundary */
1271 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1272 				BUS_SPACE_MAXADDR,	/* highaddr */
1273 				NULL, NULL,		/* filter, filterarg */
1274                                 rsize,			/* maxsize */
1275                                 1,			/* nsegments */
1276                                 rsize,			/* maxsegsize */
1277                                 0,			/* flags */
1278                                 NULL, NULL,		/* lockfunc, lockarg */
1279                                 &sc->reply_dmat)) {
1280 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies DMA tag\n");
1281 		return (ENOMEM);
1282         }
1283         if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
1284 	    BUS_DMA_NOWAIT, &sc->reply_map)) {
1285 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies memory\n");
1286 		return (ENOMEM);
1287         }
1288         bzero(sc->reply_frames, rsize);
1289         bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
1290 	    mpr_memaddr_cb, &sc->reply_busaddr, 0);
1291 
1292 	return (0);
1293 }
1294 
1295 static int
1296 mpr_alloc_requests(struct mpr_softc *sc)
1297 {
1298 	struct mpr_command *cm;
1299 	struct mpr_chain *chain;
1300 	int i, rsize, nsegs;
1301 
1302 	rsize = sc->facts->IOCRequestFrameSize * sc->num_reqs * 4;
1303         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1304 				16, 0,			/* algnmnt, boundary */
1305 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1306 				BUS_SPACE_MAXADDR,	/* highaddr */
1307 				NULL, NULL,		/* filter, filterarg */
1308                                 rsize,			/* maxsize */
1309                                 1,			/* nsegments */
1310                                 rsize,			/* maxsegsize */
1311                                 0,			/* flags */
1312                                 NULL, NULL,		/* lockfunc, lockarg */
1313                                 &sc->req_dmat)) {
1314 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate request DMA tag\n");
1315 		return (ENOMEM);
1316         }
1317         if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
1318 	    BUS_DMA_NOWAIT, &sc->req_map)) {
1319 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate request memory\n");
1320 		return (ENOMEM);
1321         }
1322         bzero(sc->req_frames, rsize);
1323         bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
1324 	    mpr_memaddr_cb, &sc->req_busaddr, 0);
1325 
1326 	/*
1327 	 * Gen3 and beyond uses the IOCMaxChainSegmentSize from IOC Facts to
1328 	 * get the size of a Chain Frame.  Previous versions use the size as a
1329 	 * Request Frame for the Chain Frame size.  If IOCMaxChainSegmentSize
1330 	 * is 0, use the default value.  The IOCMaxChainSegmentSize is the
1331 	 * number of 16-byte elelements that can fit in a Chain Frame, which is
1332 	 * the size of an IEEE Simple SGE.
1333 	 */
1334 	if (sc->facts->MsgVersion >= MPI2_VERSION_02_05) {
1335 		sc->chain_seg_size =
1336 		    htole16(sc->facts->IOCMaxChainSegmentSize);
1337 		if (sc->chain_seg_size == 0) {
1338 			sc->chain_frame_size = MPR_DEFAULT_CHAIN_SEG_SIZE *
1339 			    MPR_MAX_CHAIN_ELEMENT_SIZE;
1340 		} else {
1341 			sc->chain_frame_size = sc->chain_seg_size *
1342 			    MPR_MAX_CHAIN_ELEMENT_SIZE;
1343 		}
1344 	} else {
1345 		sc->chain_frame_size = sc->facts->IOCRequestFrameSize * 4;
1346 	}
1347 	rsize = sc->chain_frame_size * sc->max_chains;
1348         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1349 				16, 0,			/* algnmnt, boundary */
1350 				BUS_SPACE_MAXADDR,	/* lowaddr */
1351 				BUS_SPACE_MAXADDR,	/* highaddr */
1352 				NULL, NULL,		/* filter, filterarg */
1353                                 rsize,			/* maxsize */
1354                                 1,			/* nsegments */
1355                                 rsize,			/* maxsegsize */
1356                                 0,			/* flags */
1357                                 NULL, NULL,		/* lockfunc, lockarg */
1358                                 &sc->chain_dmat)) {
1359 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain DMA tag\n");
1360 		return (ENOMEM);
1361         }
1362         if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
1363 	    BUS_DMA_NOWAIT, &sc->chain_map)) {
1364 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1365 		return (ENOMEM);
1366         }
1367         bzero(sc->chain_frames, rsize);
1368         bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
1369 	    mpr_memaddr_cb, &sc->chain_busaddr, 0);
1370 
1371 	rsize = MPR_SENSE_LEN * sc->num_reqs;
1372 	if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1373 				1, 0,			/* algnmnt, boundary */
1374 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1375 				BUS_SPACE_MAXADDR,	/* highaddr */
1376 				NULL, NULL,		/* filter, filterarg */
1377                                 rsize,			/* maxsize */
1378                                 1,			/* nsegments */
1379                                 rsize,			/* maxsegsize */
1380                                 0,			/* flags */
1381                                 NULL, NULL,		/* lockfunc, lockarg */
1382                                 &sc->sense_dmat)) {
1383 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense DMA tag\n");
1384 		return (ENOMEM);
1385         }
1386         if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
1387 	    BUS_DMA_NOWAIT, &sc->sense_map)) {
1388 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense memory\n");
1389 		return (ENOMEM);
1390         }
1391         bzero(sc->sense_frames, rsize);
1392         bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
1393 	    mpr_memaddr_cb, &sc->sense_busaddr, 0);
1394 
1395 	sc->chains = malloc(sizeof(struct mpr_chain) * sc->max_chains, M_MPR,
1396 	    M_WAITOK | M_ZERO);
1397 	if (!sc->chains) {
1398 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1399 		return (ENOMEM);
1400 	}
1401 	for (i = 0; i < sc->max_chains; i++) {
1402 		chain = &sc->chains[i];
1403 		chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
1404 		    i * sc->chain_frame_size);
1405 		chain->chain_busaddr = sc->chain_busaddr +
1406 		    i * sc->chain_frame_size;
1407 		mpr_free_chain(sc, chain);
1408 		sc->chain_free_lowwater++;
1409 	}
1410 
1411 	/*
1412 	 * Allocate NVMe PRP Pages for NVMe SGL support only if the FW supports
1413 	 * these devices.
1414 	 */
1415 	if ((sc->facts->MsgVersion >= MPI2_VERSION_02_06) &&
1416 	    (sc->facts->ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES)) {
1417 		if (mpr_alloc_nvme_prp_pages(sc) == ENOMEM)
1418 			return (ENOMEM);
1419 	}
1420 
1421 	/* XXX Need to pick a more precise value */
1422 	nsegs = (MAXPHYS / PAGE_SIZE) + 1;
1423         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1424 				1, 0,			/* algnmnt, boundary */
1425 				BUS_SPACE_MAXADDR,	/* lowaddr */
1426 				BUS_SPACE_MAXADDR,	/* highaddr */
1427 				NULL, NULL,		/* filter, filterarg */
1428                                 BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1429                                 nsegs,			/* nsegments */
1430                                 BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1431                                 BUS_DMA_ALLOCNOW,	/* flags */
1432                                 busdma_lock_mutex,	/* lockfunc */
1433 				&sc->mpr_mtx,		/* lockarg */
1434                                 &sc->buffer_dmat)) {
1435 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate buffer DMA tag\n");
1436 		return (ENOMEM);
1437         }
1438 
1439 	/*
1440 	 * SMID 0 cannot be used as a free command per the firmware spec.
1441 	 * Just drop that command instead of risking accounting bugs.
1442 	 */
1443 	sc->commands = malloc(sizeof(struct mpr_command) * sc->num_reqs,
1444 	    M_MPR, M_WAITOK | M_ZERO);
1445 	if (!sc->commands) {
1446 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate command memory\n");
1447 		return (ENOMEM);
1448 	}
1449 	for (i = 1; i < sc->num_reqs; i++) {
1450 		cm = &sc->commands[i];
1451 		cm->cm_req = sc->req_frames +
1452 		    i * sc->facts->IOCRequestFrameSize * 4;
1453 		cm->cm_req_busaddr = sc->req_busaddr +
1454 		    i * sc->facts->IOCRequestFrameSize * 4;
1455 		cm->cm_sense = &sc->sense_frames[i];
1456 		cm->cm_sense_busaddr = sc->sense_busaddr + i * MPR_SENSE_LEN;
1457 		cm->cm_desc.Default.SMID = i;
1458 		cm->cm_sc = sc;
1459 		TAILQ_INIT(&cm->cm_chain_list);
1460 		TAILQ_INIT(&cm->cm_prp_page_list);
1461 		callout_init_mtx(&cm->cm_callout, &sc->mpr_mtx, 0);
1462 
1463 		/* XXX Is a failure here a critical problem? */
1464 		if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap)
1465 		    == 0) {
1466 			if (i <= sc->facts->HighPriorityCredit)
1467 				mpr_free_high_priority_command(sc, cm);
1468 			else
1469 				mpr_free_command(sc, cm);
1470 		} else {
1471 			panic("failed to allocate command %d\n", i);
1472 			sc->num_reqs = i;
1473 			break;
1474 		}
1475 	}
1476 
1477 	return (0);
1478 }
1479 
1480 /*
1481  * Allocate contiguous buffers for PCIe NVMe devices for building native PRPs,
1482  * which are scatter/gather lists for NVMe devices.
1483  *
1484  * This buffer must be contiguous due to the nature of how NVMe PRPs are built
1485  * and translated by FW.
1486  *
1487  * returns ENOMEM if memory could not be allocated, otherwise returns 0.
1488  */
1489 static int
1490 mpr_alloc_nvme_prp_pages(struct mpr_softc *sc)
1491 {
1492 	int PRPs_per_page, PRPs_required, pages_required;
1493 	int rsize, i;
1494 	struct mpr_prp_page *prp_page;
1495 
1496 	/*
1497 	 * Assuming a MAX_IO_SIZE of 1MB and a PAGE_SIZE of 4k, the max number
1498 	 * of PRPs (NVMe's Scatter/Gather Element) needed per I/O is:
1499 	 * MAX_IO_SIZE / PAGE_SIZE = 256
1500 	 *
1501 	 * 1 PRP entry in main frame for PRP list pointer still leaves 255 PRPs
1502 	 * required for the remainder of the 1MB I/O. 512 PRPs can fit into one
1503 	 * page (4096 / 8 = 512), so only one page is required for each I/O.
1504 	 *
1505 	 * Each of these buffers will need to be contiguous. For simplicity,
1506 	 * only one buffer is allocated here, which has all of the space
1507 	 * required for the NVMe Queue Depth. If there are problems allocating
1508 	 * this one buffer, this function will need to change to allocate
1509 	 * individual, contiguous NVME_QDEPTH buffers.
1510 	 *
1511 	 * The real calculation will use the real max io size. Above is just an
1512 	 * example.
1513 	 *
1514 	 */
1515 	PRPs_required = sc->maxio / PAGE_SIZE;
1516 	PRPs_per_page = (PAGE_SIZE / PRP_ENTRY_SIZE) - 1;
1517 	pages_required = (PRPs_required / PRPs_per_page) + 1;
1518 
1519 	sc->prp_buffer_size = PAGE_SIZE * pages_required;
1520 	rsize = sc->prp_buffer_size * NVME_QDEPTH;
1521 	if (bus_dma_tag_create( sc->mpr_parent_dmat,	/* parent */
1522 				4, 0,			/* algnmnt, boundary */
1523 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1524 				BUS_SPACE_MAXADDR,	/* highaddr */
1525 				NULL, NULL,		/* filter, filterarg */
1526 				rsize,			/* maxsize */
1527 				1,			/* nsegments */
1528 				rsize,			/* maxsegsize */
1529 				0,			/* flags */
1530 				NULL, NULL,		/* lockfunc, lockarg */
1531 				&sc->prp_page_dmat)) {
1532 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP DMA "
1533 		    "tag\n");
1534 		return (ENOMEM);
1535 	}
1536 	if (bus_dmamem_alloc(sc->prp_page_dmat, (void **)&sc->prp_pages,
1537 	    BUS_DMA_NOWAIT, &sc->prp_page_map)) {
1538 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP memory\n");
1539 		return (ENOMEM);
1540 	}
1541 	bzero(sc->prp_pages, rsize);
1542 	bus_dmamap_load(sc->prp_page_dmat, sc->prp_page_map, sc->prp_pages,
1543 	    rsize, mpr_memaddr_cb, &sc->prp_page_busaddr, 0);
1544 
1545 	sc->prps = malloc(sizeof(struct mpr_prp_page) * NVME_QDEPTH, M_MPR,
1546 	    M_WAITOK | M_ZERO);
1547 	for (i = 0; i < NVME_QDEPTH; i++) {
1548 		prp_page = &sc->prps[i];
1549 		prp_page->prp_page = (uint64_t *)(sc->prp_pages +
1550 		    i * sc->prp_buffer_size);
1551 		prp_page->prp_page_busaddr = (uint64_t)(sc->prp_page_busaddr +
1552 		    i * sc->prp_buffer_size);
1553 		mpr_free_prp_page(sc, prp_page);
1554 		sc->prp_pages_free_lowwater++;
1555 	}
1556 
1557 	return (0);
1558 }
1559 
1560 static int
1561 mpr_init_queues(struct mpr_softc *sc)
1562 {
1563 	int i;
1564 
1565 	memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
1566 
1567 	/*
1568 	 * According to the spec, we need to use one less reply than we
1569 	 * have space for on the queue.  So sc->num_replies (the number we
1570 	 * use) should be less than sc->fqdepth (allocated size).
1571 	 */
1572 	if (sc->num_replies >= sc->fqdepth)
1573 		return (EINVAL);
1574 
1575 	/*
1576 	 * Initialize all of the free queue entries.
1577 	 */
1578 	for (i = 0; i < sc->fqdepth; i++) {
1579 		sc->free_queue[i] = sc->reply_busaddr +
1580 		    (i * sc->facts->ReplyFrameSize * 4);
1581 	}
1582 	sc->replyfreeindex = sc->num_replies;
1583 
1584 	return (0);
1585 }
1586 
1587 /* Get the driver parameter tunables.  Lowest priority are the driver defaults.
1588  * Next are the global settings, if they exist.  Highest are the per-unit
1589  * settings, if they exist.
1590  */
1591 void
1592 mpr_get_tunables(struct mpr_softc *sc)
1593 {
1594 	char tmpstr[80];
1595 
1596 	/* XXX default to some debugging for now */
1597 	sc->mpr_debug = MPR_INFO | MPR_FAULT;
1598 	sc->disable_msix = 0;
1599 	sc->disable_msi = 0;
1600 	sc->max_msix = MPR_MSIX_MAX;
1601 	sc->max_chains = MPR_CHAIN_FRAMES;
1602 	sc->max_io_pages = MPR_MAXIO_PAGES;
1603 	sc->enable_ssu = MPR_SSU_ENABLE_SSD_DISABLE_HDD;
1604 	sc->spinup_wait_time = DEFAULT_SPINUP_WAIT;
1605 	sc->use_phynum = 1;
1606 	sc->max_reqframes = MPR_REQ_FRAMES;
1607 	sc->max_prireqframes = MPR_PRI_REQ_FRAMES;
1608 	sc->max_replyframes = MPR_REPLY_FRAMES;
1609 	sc->max_evtframes = MPR_EVT_REPLY_FRAMES;
1610 
1611 	/*
1612 	 * Grab the global variables.
1613 	 */
1614 	TUNABLE_INT_FETCH("hw.mpr.debug_level", &sc->mpr_debug);
1615 	TUNABLE_INT_FETCH("hw.mpr.disable_msix", &sc->disable_msix);
1616 	TUNABLE_INT_FETCH("hw.mpr.disable_msi", &sc->disable_msi);
1617 	TUNABLE_INT_FETCH("hw.mpr.max_msix", &sc->max_msix);
1618 	TUNABLE_INT_FETCH("hw.mpr.max_chains", &sc->max_chains);
1619 	TUNABLE_INT_FETCH("hw.mpr.max_io_pages", &sc->max_io_pages);
1620 	TUNABLE_INT_FETCH("hw.mpr.enable_ssu", &sc->enable_ssu);
1621 	TUNABLE_INT_FETCH("hw.mpr.spinup_wait_time", &sc->spinup_wait_time);
1622 	TUNABLE_INT_FETCH("hw.mpr.use_phy_num", &sc->use_phynum);
1623 	TUNABLE_INT_FETCH("hw.mpr.max_reqframes", &sc->max_reqframes);
1624 	TUNABLE_INT_FETCH("hw.mpr.max_prireqframes", &sc->max_prireqframes);
1625 	TUNABLE_INT_FETCH("hw.mpr.max_replyframes", &sc->max_replyframes);
1626 	TUNABLE_INT_FETCH("hw.mpr.max_evtframes", &sc->max_evtframes);
1627 
1628 	/* Grab the unit-instance variables */
1629 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.debug_level",
1630 	    device_get_unit(sc->mpr_dev));
1631 	TUNABLE_INT_FETCH(tmpstr, &sc->mpr_debug);
1632 
1633 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msix",
1634 	    device_get_unit(sc->mpr_dev));
1635 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1636 
1637 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msi",
1638 	    device_get_unit(sc->mpr_dev));
1639 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1640 
1641 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_msix",
1642 	    device_get_unit(sc->mpr_dev));
1643 	TUNABLE_INT_FETCH(tmpstr, &sc->max_msix);
1644 
1645 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_chains",
1646 	    device_get_unit(sc->mpr_dev));
1647 	TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1648 
1649 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_io_pages",
1650 	    device_get_unit(sc->mpr_dev));
1651 	TUNABLE_INT_FETCH(tmpstr, &sc->max_io_pages);
1652 
1653 	bzero(sc->exclude_ids, sizeof(sc->exclude_ids));
1654 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.exclude_ids",
1655 	    device_get_unit(sc->mpr_dev));
1656 	TUNABLE_STR_FETCH(tmpstr, sc->exclude_ids, sizeof(sc->exclude_ids));
1657 
1658 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.enable_ssu",
1659 	    device_get_unit(sc->mpr_dev));
1660 	TUNABLE_INT_FETCH(tmpstr, &sc->enable_ssu);
1661 
1662 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.spinup_wait_time",
1663 	    device_get_unit(sc->mpr_dev));
1664 	TUNABLE_INT_FETCH(tmpstr, &sc->spinup_wait_time);
1665 
1666 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.use_phy_num",
1667 	    device_get_unit(sc->mpr_dev));
1668 	TUNABLE_INT_FETCH(tmpstr, &sc->use_phynum);
1669 
1670 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_reqframes",
1671 	    device_get_unit(sc->mpr_dev));
1672 	TUNABLE_INT_FETCH(tmpstr, &sc->max_reqframes);
1673 
1674 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_prireqframes",
1675 	    device_get_unit(sc->mpr_dev));
1676 	TUNABLE_INT_FETCH(tmpstr, &sc->max_prireqframes);
1677 
1678 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_replyframes",
1679 	    device_get_unit(sc->mpr_dev));
1680 	TUNABLE_INT_FETCH(tmpstr, &sc->max_replyframes);
1681 
1682 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_evtframes",
1683 	    device_get_unit(sc->mpr_dev));
1684 	TUNABLE_INT_FETCH(tmpstr, &sc->max_evtframes);
1685 }
1686 
1687 static void
1688 mpr_setup_sysctl(struct mpr_softc *sc)
1689 {
1690 	struct sysctl_ctx_list	*sysctl_ctx = NULL;
1691 	struct sysctl_oid	*sysctl_tree = NULL;
1692 	char tmpstr[80], tmpstr2[80];
1693 
1694 	/*
1695 	 * Setup the sysctl variable so the user can change the debug level
1696 	 * on the fly.
1697 	 */
1698 	snprintf(tmpstr, sizeof(tmpstr), "MPR controller %d",
1699 	    device_get_unit(sc->mpr_dev));
1700 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mpr_dev));
1701 
1702 	sysctl_ctx = device_get_sysctl_ctx(sc->mpr_dev);
1703 	if (sysctl_ctx != NULL)
1704 		sysctl_tree = device_get_sysctl_tree(sc->mpr_dev);
1705 
1706 	if (sysctl_tree == NULL) {
1707 		sysctl_ctx_init(&sc->sysctl_ctx);
1708 		sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1709 		    SYSCTL_STATIC_CHILDREN(_hw_mpr), OID_AUTO, tmpstr2,
1710 		    CTLFLAG_RD, 0, tmpstr);
1711 		if (sc->sysctl_tree == NULL)
1712 			return;
1713 		sysctl_ctx = &sc->sysctl_ctx;
1714 		sysctl_tree = sc->sysctl_tree;
1715 	}
1716 
1717 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1718 	    OID_AUTO, "debug_level", CTLFLAG_RW, &sc->mpr_debug, 0,
1719 	    "mpr debug level");
1720 
1721 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1722 	    OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1723 	    "Disable the use of MSI-X interrupts");
1724 
1725 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1726 	    OID_AUTO, "max_msix", CTLFLAG_RD, &sc->max_msix, 0,
1727 	    "User-defined maximum number of MSIX queues");
1728 
1729 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1730 	    OID_AUTO, "msix_msgs", CTLFLAG_RD, &sc->msi_msgs, 0,
1731 	    "Negotiated number of MSIX queues");
1732 
1733 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1734 	    OID_AUTO, "max_reqframes", CTLFLAG_RD, &sc->max_reqframes, 0,
1735 	    "Total number of allocated request frames");
1736 
1737 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1738 	    OID_AUTO, "max_prireqframes", CTLFLAG_RD, &sc->max_prireqframes, 0,
1739 	    "Total number of allocated high priority request frames");
1740 
1741 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1742 	    OID_AUTO, "max_replyframes", CTLFLAG_RD, &sc->max_replyframes, 0,
1743 	    "Total number of allocated reply frames");
1744 
1745 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1746 	    OID_AUTO, "max_evtframes", CTLFLAG_RD, &sc->max_evtframes, 0,
1747 	    "Total number of event frames allocated");
1748 
1749 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1750 	    OID_AUTO, "firmware_version", CTLFLAG_RW, sc->fw_version,
1751 	    strlen(sc->fw_version), "firmware version");
1752 
1753 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1754 	    OID_AUTO, "driver_version", CTLFLAG_RW, MPR_DRIVER_VERSION,
1755 	    strlen(MPR_DRIVER_VERSION), "driver version");
1756 
1757 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1758 	    OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1759 	    &sc->io_cmds_active, 0, "number of currently active commands");
1760 
1761 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1762 	    OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1763 	    &sc->io_cmds_highwater, 0, "maximum active commands seen");
1764 
1765 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1766 	    OID_AUTO, "chain_free", CTLFLAG_RD,
1767 	    &sc->chain_free, 0, "number of free chain elements");
1768 
1769 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1770 	    OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1771 	    &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1772 
1773 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1774 	    OID_AUTO, "max_chains", CTLFLAG_RD,
1775 	    &sc->max_chains, 0,"maximum chain frames that will be allocated");
1776 
1777 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1778 	    OID_AUTO, "max_io_pages", CTLFLAG_RD,
1779 	    &sc->max_io_pages, 0,"maximum pages to allow per I/O (if <1 use "
1780 	    "IOCFacts)");
1781 
1782 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1783 	    OID_AUTO, "enable_ssu", CTLFLAG_RW, &sc->enable_ssu, 0,
1784 	    "enable SSU to SATA SSD/HDD at shutdown");
1785 
1786 	SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1787 	    OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1788 	    &sc->chain_alloc_fail, "chain allocation failures");
1789 
1790 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1791 	    OID_AUTO, "spinup_wait_time", CTLFLAG_RD,
1792 	    &sc->spinup_wait_time, DEFAULT_SPINUP_WAIT, "seconds to wait for "
1793 	    "spinup after SATA ID error");
1794 
1795 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1796 	    OID_AUTO, "use_phy_num", CTLFLAG_RD, &sc->use_phynum, 0,
1797 	    "Use the phy number for enumeration");
1798 
1799 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1800 	    OID_AUTO, "prp_pages_free", CTLFLAG_RD,
1801 	    &sc->prp_pages_free, 0, "number of free PRP pages");
1802 
1803 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1804 	    OID_AUTO, "prp_pages_free_lowwater", CTLFLAG_RD,
1805 	    &sc->prp_pages_free_lowwater, 0,"lowest number of free PRP pages");
1806 
1807 	SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1808 	    OID_AUTO, "prp_page_alloc_fail", CTLFLAG_RD,
1809 	    &sc->prp_page_alloc_fail, "PRP page allocation failures");
1810 }
1811 
1812 int
1813 mpr_attach(struct mpr_softc *sc)
1814 {
1815 	int error;
1816 
1817 	MPR_FUNCTRACE(sc);
1818 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1819 
1820 	mtx_init(&sc->mpr_mtx, "MPR lock", NULL, MTX_DEF);
1821 	callout_init_mtx(&sc->periodic, &sc->mpr_mtx, 0);
1822 	callout_init_mtx(&sc->device_check_callout, &sc->mpr_mtx, 0);
1823 	TAILQ_INIT(&sc->event_list);
1824 	timevalclear(&sc->lastfail);
1825 
1826 	if ((error = mpr_transition_ready(sc)) != 0) {
1827 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
1828 		    "Failed to transition ready\n");
1829 		return (error);
1830 	}
1831 
1832 	sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPR,
1833 	    M_ZERO|M_NOWAIT);
1834 	if (!sc->facts) {
1835 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
1836 		    "Cannot allocate memory, exit\n");
1837 		return (ENOMEM);
1838 	}
1839 
1840 	/*
1841 	 * Get IOC Facts and allocate all structures based on this information.
1842 	 * A Diag Reset will also call mpr_iocfacts_allocate and re-read the IOC
1843 	 * Facts. If relevant values have changed in IOC Facts, this function
1844 	 * will free all of the memory based on IOC Facts and reallocate that
1845 	 * memory.  If this fails, any allocated memory should already be freed.
1846 	 */
1847 	if ((error = mpr_iocfacts_allocate(sc, TRUE)) != 0) {
1848 		mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC Facts allocation "
1849 		    "failed with error %d\n", error);
1850 		return (error);
1851 	}
1852 
1853 	/* Start the periodic watchdog check on the IOC Doorbell */
1854 	mpr_periodic(sc);
1855 
1856 	/*
1857 	 * The portenable will kick off discovery events that will drive the
1858 	 * rest of the initialization process.  The CAM/SAS module will
1859 	 * hold up the boot sequence until discovery is complete.
1860 	 */
1861 	sc->mpr_ich.ich_func = mpr_startup;
1862 	sc->mpr_ich.ich_arg = sc;
1863 	if (config_intrhook_establish(&sc->mpr_ich) != 0) {
1864 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
1865 		    "Cannot establish MPR config hook\n");
1866 		error = EINVAL;
1867 	}
1868 
1869 	/*
1870 	 * Allow IR to shutdown gracefully when shutdown occurs.
1871 	 */
1872 	sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
1873 	    mprsas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
1874 
1875 	if (sc->shutdown_eh == NULL)
1876 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
1877 		    "shutdown event registration failed\n");
1878 
1879 	mpr_setup_sysctl(sc);
1880 
1881 	sc->mpr_flags |= MPR_FLAGS_ATTACH_DONE;
1882 	mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
1883 
1884 	return (error);
1885 }
1886 
1887 /* Run through any late-start handlers. */
1888 static void
1889 mpr_startup(void *arg)
1890 {
1891 	struct mpr_softc *sc;
1892 
1893 	sc = (struct mpr_softc *)arg;
1894 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1895 
1896 	mpr_lock(sc);
1897 	mpr_unmask_intr(sc);
1898 
1899 	/* initialize device mapping tables */
1900 	mpr_base_static_config_pages(sc);
1901 	mpr_mapping_initialize(sc);
1902 	mprsas_startup(sc);
1903 	mpr_unlock(sc);
1904 
1905 	mpr_dprint(sc, MPR_INIT, "disestablish config intrhook\n");
1906 	config_intrhook_disestablish(&sc->mpr_ich);
1907 	sc->mpr_ich.ich_arg = NULL;
1908 
1909 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
1910 }
1911 
1912 /* Periodic watchdog.  Is called with the driver lock already held. */
1913 static void
1914 mpr_periodic(void *arg)
1915 {
1916 	struct mpr_softc *sc;
1917 	uint32_t db;
1918 
1919 	sc = (struct mpr_softc *)arg;
1920 	if (sc->mpr_flags & MPR_FLAGS_SHUTDOWN)
1921 		return;
1922 
1923 	db = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
1924 	if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
1925 		if ((db & MPI2_DOORBELL_FAULT_CODE_MASK) ==
1926 		    IFAULT_IOP_OVER_TEMP_THRESHOLD_EXCEEDED) {
1927 			panic("TEMPERATURE FAULT: STOPPING.");
1928 		}
1929 		mpr_dprint(sc, MPR_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
1930 		mpr_reinit(sc);
1931 	}
1932 
1933 	callout_reset(&sc->periodic, MPR_PERIODIC_DELAY * hz, mpr_periodic, sc);
1934 }
1935 
1936 static void
1937 mpr_log_evt_handler(struct mpr_softc *sc, uintptr_t data,
1938     MPI2_EVENT_NOTIFICATION_REPLY *event)
1939 {
1940 	MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
1941 
1942 	MPR_DPRINT_EVENT(sc, generic, event);
1943 
1944 	switch (event->Event) {
1945 	case MPI2_EVENT_LOG_DATA:
1946 		mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_DATA:\n");
1947 		if (sc->mpr_debug & MPR_EVENT)
1948 			hexdump(event->EventData, event->EventDataLength, NULL,
1949 			    0);
1950 		break;
1951 	case MPI2_EVENT_LOG_ENTRY_ADDED:
1952 		entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
1953 		mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
1954 		    "0x%x Sequence %d:\n", entry->LogEntryQualifier,
1955 		     entry->LogSequence);
1956 		break;
1957 	default:
1958 		break;
1959 	}
1960 	return;
1961 }
1962 
1963 static int
1964 mpr_attach_log(struct mpr_softc *sc)
1965 {
1966 	uint8_t events[16];
1967 
1968 	bzero(events, 16);
1969 	setbit(events, MPI2_EVENT_LOG_DATA);
1970 	setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
1971 
1972 	mpr_register_events(sc, events, mpr_log_evt_handler, NULL,
1973 	    &sc->mpr_log_eh);
1974 
1975 	return (0);
1976 }
1977 
1978 static int
1979 mpr_detach_log(struct mpr_softc *sc)
1980 {
1981 
1982 	if (sc->mpr_log_eh != NULL)
1983 		mpr_deregister_events(sc, sc->mpr_log_eh);
1984 	return (0);
1985 }
1986 
1987 /*
1988  * Free all of the driver resources and detach submodules.  Should be called
1989  * without the lock held.
1990  */
1991 int
1992 mpr_free(struct mpr_softc *sc)
1993 {
1994 	int error;
1995 
1996 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1997 	/* Turn off the watchdog */
1998 	mpr_lock(sc);
1999 	sc->mpr_flags |= MPR_FLAGS_SHUTDOWN;
2000 	mpr_unlock(sc);
2001 	/* Lock must not be held for this */
2002 	callout_drain(&sc->periodic);
2003 	callout_drain(&sc->device_check_callout);
2004 
2005 	if (((error = mpr_detach_log(sc)) != 0) ||
2006 	    ((error = mpr_detach_sas(sc)) != 0)) {
2007 		mpr_dprint(sc, MPR_INIT|MPR_FAULT, "failed to detach "
2008 		    "subsystems, error= %d, exit\n", error);
2009 		return (error);
2010 	}
2011 
2012 	mpr_detach_user(sc);
2013 
2014 	/* Put the IOC back in the READY state. */
2015 	mpr_lock(sc);
2016 	if ((error = mpr_transition_ready(sc)) != 0) {
2017 		mpr_unlock(sc);
2018 		return (error);
2019 	}
2020 	mpr_unlock(sc);
2021 
2022 	if (sc->facts != NULL)
2023 		free(sc->facts, M_MPR);
2024 
2025 	/*
2026 	 * Free all buffers that are based on IOC Facts.  A Diag Reset may need
2027 	 * to free these buffers too.
2028 	 */
2029 	mpr_iocfacts_free(sc);
2030 
2031 	if (sc->sysctl_tree != NULL)
2032 		sysctl_ctx_free(&sc->sysctl_ctx);
2033 
2034 	/* Deregister the shutdown function */
2035 	if (sc->shutdown_eh != NULL)
2036 		EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
2037 
2038 	mtx_destroy(&sc->mpr_mtx);
2039 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
2040 
2041 	return (0);
2042 }
2043 
2044 static __inline void
2045 mpr_complete_command(struct mpr_softc *sc, struct mpr_command *cm)
2046 {
2047 	MPR_FUNCTRACE(sc);
2048 
2049 	if (cm == NULL) {
2050 		mpr_dprint(sc, MPR_ERROR, "Completing NULL command\n");
2051 		return;
2052 	}
2053 
2054 	if (cm->cm_flags & MPR_CM_FLAGS_POLLED)
2055 		cm->cm_flags |= MPR_CM_FLAGS_COMPLETE;
2056 
2057 	if (cm->cm_complete != NULL) {
2058 		mpr_dprint(sc, MPR_TRACE,
2059 		    "%s cm %p calling cm_complete %p data %p reply %p\n",
2060 		    __func__, cm, cm->cm_complete, cm->cm_complete_data,
2061 		    cm->cm_reply);
2062 		cm->cm_complete(sc, cm);
2063 	}
2064 
2065 	if (cm->cm_flags & MPR_CM_FLAGS_WAKEUP) {
2066 		mpr_dprint(sc, MPR_TRACE, "waking up %p\n", cm);
2067 		wakeup(cm);
2068 	}
2069 
2070 	if (sc->io_cmds_active != 0) {
2071 		sc->io_cmds_active--;
2072 	} else {
2073 		mpr_dprint(sc, MPR_ERROR, "Warning: io_cmds_active is "
2074 		    "out of sync - resynching to 0\n");
2075 	}
2076 }
2077 
2078 static void
2079 mpr_sas_log_info(struct mpr_softc *sc , u32 log_info)
2080 {
2081 	union loginfo_type {
2082 		u32	loginfo;
2083 		struct {
2084 			u32	subcode:16;
2085 			u32	code:8;
2086 			u32	originator:4;
2087 			u32	bus_type:4;
2088 		} dw;
2089 	};
2090 	union loginfo_type sas_loginfo;
2091 	char *originator_str = NULL;
2092 
2093 	sas_loginfo.loginfo = log_info;
2094 	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
2095 		return;
2096 
2097 	/* each nexus loss loginfo */
2098 	if (log_info == 0x31170000)
2099 		return;
2100 
2101 	/* eat the loginfos associated with task aborts */
2102 	if ((log_info == 30050000) || (log_info == 0x31140000) ||
2103 	    (log_info == 0x31130000))
2104 		return;
2105 
2106 	switch (sas_loginfo.dw.originator) {
2107 	case 0:
2108 		originator_str = "IOP";
2109 		break;
2110 	case 1:
2111 		originator_str = "PL";
2112 		break;
2113 	case 2:
2114 		originator_str = "IR";
2115 		break;
2116 	}
2117 
2118 	mpr_dprint(sc, MPR_LOG, "log_info(0x%08x): originator(%s), "
2119 	    "code(0x%02x), sub_code(0x%04x)\n", log_info, originator_str,
2120 	    sas_loginfo.dw.code, sas_loginfo.dw.subcode);
2121 }
2122 
2123 static void
2124 mpr_display_reply_info(struct mpr_softc *sc, uint8_t *reply)
2125 {
2126 	MPI2DefaultReply_t *mpi_reply;
2127 	u16 sc_status;
2128 
2129 	mpi_reply = (MPI2DefaultReply_t*)reply;
2130 	sc_status = le16toh(mpi_reply->IOCStatus);
2131 	if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
2132 		mpr_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
2133 }
2134 
2135 void
2136 mpr_intr(void *data)
2137 {
2138 	struct mpr_softc *sc;
2139 	uint32_t status;
2140 
2141 	sc = (struct mpr_softc *)data;
2142 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2143 
2144 	/*
2145 	 * Check interrupt status register to flush the bus.  This is
2146 	 * needed for both INTx interrupts and driver-driven polling
2147 	 */
2148 	status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
2149 	if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
2150 		return;
2151 
2152 	mpr_lock(sc);
2153 	mpr_intr_locked(data);
2154 	mpr_unlock(sc);
2155 	return;
2156 }
2157 
2158 /*
2159  * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
2160  * chip.  Hopefully this theory is correct.
2161  */
2162 void
2163 mpr_intr_msi(void *data)
2164 {
2165 	struct mpr_softc *sc;
2166 
2167 	sc = (struct mpr_softc *)data;
2168 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2169 	mpr_lock(sc);
2170 	mpr_intr_locked(data);
2171 	mpr_unlock(sc);
2172 	return;
2173 }
2174 
2175 /*
2176  * The locking is overly broad and simplistic, but easy to deal with for now.
2177  */
2178 void
2179 mpr_intr_locked(void *data)
2180 {
2181 	MPI2_REPLY_DESCRIPTORS_UNION *desc;
2182 	struct mpr_softc *sc;
2183 	struct mpr_command *cm = NULL;
2184 	uint8_t flags;
2185 	u_int pq;
2186 	MPI2_DIAG_RELEASE_REPLY *rel_rep;
2187 	mpr_fw_diagnostic_buffer_t *pBuffer;
2188 
2189 	sc = (struct mpr_softc *)data;
2190 
2191 	pq = sc->replypostindex;
2192 	mpr_dprint(sc, MPR_TRACE,
2193 	    "%s sc %p starting with replypostindex %u\n",
2194 	    __func__, sc, sc->replypostindex);
2195 
2196 	for ( ;; ) {
2197 		cm = NULL;
2198 		desc = &sc->post_queue[sc->replypostindex];
2199 		flags = desc->Default.ReplyFlags &
2200 		    MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
2201 		if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) ||
2202 		    (le32toh(desc->Words.High) == 0xffffffff))
2203 			break;
2204 
2205 		/* increment the replypostindex now, so that event handlers
2206 		 * and cm completion handlers which decide to do a diag
2207 		 * reset can zero it without it getting incremented again
2208 		 * afterwards, and we break out of this loop on the next
2209 		 * iteration since the reply post queue has been cleared to
2210 		 * 0xFF and all descriptors look unused (which they are).
2211 		 */
2212 		if (++sc->replypostindex >= sc->pqdepth)
2213 			sc->replypostindex = 0;
2214 
2215 		switch (flags) {
2216 		case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
2217 		case MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS:
2218 		case MPI26_RPY_DESCRIPT_FLAGS_PCIE_ENCAPSULATED_SUCCESS:
2219 			cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
2220 			cm->cm_reply = NULL;
2221 			break;
2222 		case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
2223 		{
2224 			uint32_t baddr;
2225 			uint8_t *reply;
2226 
2227 			/*
2228 			 * Re-compose the reply address from the address
2229 			 * sent back from the chip.  The ReplyFrameAddress
2230 			 * is the lower 32 bits of the physical address of
2231 			 * particular reply frame.  Convert that address to
2232 			 * host format, and then use that to provide the
2233 			 * offset against the virtual address base
2234 			 * (sc->reply_frames).
2235 			 */
2236 			baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
2237 			reply = sc->reply_frames +
2238 				(baddr - ((uint32_t)sc->reply_busaddr));
2239 			/*
2240 			 * Make sure the reply we got back is in a valid
2241 			 * range.  If not, go ahead and panic here, since
2242 			 * we'll probably panic as soon as we deference the
2243 			 * reply pointer anyway.
2244 			 */
2245 			if ((reply < sc->reply_frames)
2246 			 || (reply > (sc->reply_frames +
2247 			     (sc->fqdepth * sc->facts->ReplyFrameSize * 4)))) {
2248 				printf("%s: WARNING: reply %p out of range!\n",
2249 				       __func__, reply);
2250 				printf("%s: reply_frames %p, fqdepth %d, "
2251 				       "frame size %d\n", __func__,
2252 				       sc->reply_frames, sc->fqdepth,
2253 				       sc->facts->ReplyFrameSize * 4);
2254 				printf("%s: baddr %#x,\n", __func__, baddr);
2255 				/* LSI-TODO. See Linux Code for Graceful exit */
2256 				panic("Reply address out of range");
2257 			}
2258 			if (le16toh(desc->AddressReply.SMID) == 0) {
2259 				if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
2260 				    MPI2_FUNCTION_DIAG_BUFFER_POST) {
2261 					/*
2262 					 * If SMID is 0 for Diag Buffer Post,
2263 					 * this implies that the reply is due to
2264 					 * a release function with a status that
2265 					 * the buffer has been released.  Set
2266 					 * the buffer flags accordingly.
2267 					 */
2268 					rel_rep =
2269 					    (MPI2_DIAG_RELEASE_REPLY *)reply;
2270 					if ((le16toh(rel_rep->IOCStatus) &
2271 					    MPI2_IOCSTATUS_MASK) ==
2272 					    MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
2273 					{
2274 						pBuffer =
2275 						    &sc->fw_diag_buffer_list[
2276 						    rel_rep->BufferType];
2277 						pBuffer->valid_data = TRUE;
2278 						pBuffer->owned_by_firmware =
2279 						    FALSE;
2280 						pBuffer->immediate = FALSE;
2281 					}
2282 				} else
2283 					mpr_dispatch_event(sc, baddr,
2284 					    (MPI2_EVENT_NOTIFICATION_REPLY *)
2285 					    reply);
2286 			} else {
2287 				cm = &sc->commands[
2288 				    le16toh(desc->AddressReply.SMID)];
2289 				cm->cm_reply = reply;
2290 				cm->cm_reply_data =
2291 				    le32toh(desc->AddressReply.
2292 				    ReplyFrameAddress);
2293 			}
2294 			break;
2295 		}
2296 		case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
2297 		case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
2298 		case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
2299 		default:
2300 			/* Unhandled */
2301 			mpr_dprint(sc, MPR_ERROR, "Unhandled reply 0x%x\n",
2302 			    desc->Default.ReplyFlags);
2303 			cm = NULL;
2304 			break;
2305 		}
2306 
2307 		if (cm != NULL) {
2308 			// Print Error reply frame
2309 			if (cm->cm_reply)
2310 				mpr_display_reply_info(sc,cm->cm_reply);
2311 			mpr_complete_command(sc, cm);
2312 		}
2313 
2314 		desc->Words.Low = 0xffffffff;
2315 		desc->Words.High = 0xffffffff;
2316 	}
2317 
2318 	if (pq != sc->replypostindex) {
2319 		mpr_dprint(sc, MPR_TRACE,
2320 		    "%s sc %p writing postindex %d\n",
2321 		    __func__, sc, sc->replypostindex);
2322 		mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET,
2323 		    sc->replypostindex);
2324 	}
2325 
2326 	return;
2327 }
2328 
2329 static void
2330 mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
2331     MPI2_EVENT_NOTIFICATION_REPLY *reply)
2332 {
2333 	struct mpr_event_handle *eh;
2334 	int event, handled = 0;
2335 
2336 	event = le16toh(reply->Event);
2337 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2338 		if (isset(eh->mask, event)) {
2339 			eh->callback(sc, data, reply);
2340 			handled++;
2341 		}
2342 	}
2343 
2344 	if (handled == 0)
2345 		mpr_dprint(sc, MPR_EVENT, "Unhandled event 0x%x\n",
2346 		    le16toh(event));
2347 
2348 	/*
2349 	 * This is the only place that the event/reply should be freed.
2350 	 * Anything wanting to hold onto the event data should have
2351 	 * already copied it into their own storage.
2352 	 */
2353 	mpr_free_reply(sc, data);
2354 }
2355 
2356 static void
2357 mpr_reregister_events_complete(struct mpr_softc *sc, struct mpr_command *cm)
2358 {
2359 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2360 
2361 	if (cm->cm_reply)
2362 		MPR_DPRINT_EVENT(sc, generic,
2363 			(MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
2364 
2365 	mpr_free_command(sc, cm);
2366 
2367 	/* next, send a port enable */
2368 	mprsas_startup(sc);
2369 }
2370 
2371 /*
2372  * For both register_events and update_events, the caller supplies a bitmap
2373  * of events that it _wants_.  These functions then turn that into a bitmask
2374  * suitable for the controller.
2375  */
2376 int
2377 mpr_register_events(struct mpr_softc *sc, uint8_t *mask,
2378     mpr_evt_callback_t *cb, void *data, struct mpr_event_handle **handle)
2379 {
2380 	struct mpr_event_handle *eh;
2381 	int error = 0;
2382 
2383 	eh = malloc(sizeof(struct mpr_event_handle), M_MPR, M_WAITOK|M_ZERO);
2384 	if (!eh) {
2385 		mpr_dprint(sc, MPR_EVENT|MPR_ERROR,
2386 		    "Cannot allocate event memory\n");
2387 		return (ENOMEM);
2388 	}
2389 	eh->callback = cb;
2390 	eh->data = data;
2391 	TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
2392 	if (mask != NULL)
2393 		error = mpr_update_events(sc, eh, mask);
2394 	*handle = eh;
2395 
2396 	return (error);
2397 }
2398 
2399 int
2400 mpr_update_events(struct mpr_softc *sc, struct mpr_event_handle *handle,
2401     uint8_t *mask)
2402 {
2403 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2404 	MPI2_EVENT_NOTIFICATION_REPLY *reply = NULL;
2405 	struct mpr_command *cm = NULL;
2406 	struct mpr_event_handle *eh;
2407 	int error, i;
2408 
2409 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2410 
2411 	if ((mask != NULL) && (handle != NULL))
2412 		bcopy(mask, &handle->mask[0], 16);
2413 	memset(sc->event_mask, 0xff, 16);
2414 
2415 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2416 		for (i = 0; i < 16; i++)
2417 			sc->event_mask[i] &= ~eh->mask[i];
2418 	}
2419 
2420 	if ((cm = mpr_alloc_command(sc)) == NULL)
2421 		return (EBUSY);
2422 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2423 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2424 	evtreq->MsgFlags = 0;
2425 	evtreq->SASBroadcastPrimitiveMasks = 0;
2426 #ifdef MPR_DEBUG_ALL_EVENTS
2427 	{
2428 		u_char fullmask[16];
2429 		memset(fullmask, 0x00, 16);
2430 		bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2431 	}
2432 #else
2433 		bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2434 #endif
2435 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2436 	cm->cm_data = NULL;
2437 
2438 	error = mpr_request_polled(sc, &cm);
2439 	if (cm != NULL)
2440 		reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
2441 	if ((reply == NULL) ||
2442 	    (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
2443 		error = ENXIO;
2444 
2445 	if (reply)
2446 		MPR_DPRINT_EVENT(sc, generic, reply);
2447 
2448 	mpr_dprint(sc, MPR_TRACE, "%s finished error %d\n", __func__, error);
2449 
2450 	if (cm != NULL)
2451 		mpr_free_command(sc, cm);
2452 	return (error);
2453 }
2454 
2455 static int
2456 mpr_reregister_events(struct mpr_softc *sc)
2457 {
2458 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2459 	struct mpr_command *cm;
2460 	struct mpr_event_handle *eh;
2461 	int error, i;
2462 
2463 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2464 
2465 	/* first, reregister events */
2466 
2467 	memset(sc->event_mask, 0xff, 16);
2468 
2469 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2470 		for (i = 0; i < 16; i++)
2471 			sc->event_mask[i] &= ~eh->mask[i];
2472 	}
2473 
2474 	if ((cm = mpr_alloc_command(sc)) == NULL)
2475 		return (EBUSY);
2476 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2477 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2478 	evtreq->MsgFlags = 0;
2479 	evtreq->SASBroadcastPrimitiveMasks = 0;
2480 #ifdef MPR_DEBUG_ALL_EVENTS
2481 	{
2482 		u_char fullmask[16];
2483 		memset(fullmask, 0x00, 16);
2484 		bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2485 	}
2486 #else
2487 		bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2488 #endif
2489 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2490 	cm->cm_data = NULL;
2491 	cm->cm_complete = mpr_reregister_events_complete;
2492 
2493 	error = mpr_map_command(sc, cm);
2494 
2495 	mpr_dprint(sc, MPR_TRACE, "%s finished with error %d\n", __func__,
2496 	    error);
2497 	return (error);
2498 }
2499 
2500 int
2501 mpr_deregister_events(struct mpr_softc *sc, struct mpr_event_handle *handle)
2502 {
2503 
2504 	TAILQ_REMOVE(&sc->event_list, handle, eh_list);
2505 	free(handle, M_MPR);
2506 	return (mpr_update_events(sc, NULL, NULL));
2507 }
2508 
2509 /**
2510 * mpr_build_nvme_prp - This function is called for NVMe end devices to build a
2511 * native SGL (NVMe PRP). The native SGL is built starting in the first PRP entry
2512 * of the NVMe message (PRP1). If the data buffer is small enough to be described
2513 * entirely using PRP1, then PRP2 is not used. If needed, PRP2 is used to
2514 * describe a larger data buffer. If the data buffer is too large to describe
2515 * using the two PRP entriess inside the NVMe message, then PRP1 describes the
2516 * first data memory segment, and PRP2 contains a pointer to a PRP list located
2517 * elsewhere in memory to describe the remaining data memory segments. The PRP
2518 * list will be contiguous.
2519 
2520 * The native SGL for NVMe devices is a Physical Region Page (PRP). A PRP
2521 * consists of a list of PRP entries to describe a number of noncontigous
2522 * physical memory segments as a single memory buffer, just as a SGL does. Note
2523 * however, that this function is only used by the IOCTL call, so the memory
2524 * given will be guaranteed to be contiguous. There is no need to translate
2525 * non-contiguous SGL into a PRP in this case. All PRPs will describe contiguous
2526 * space that is one page size each.
2527 *
2528 * Each NVMe message contains two PRP entries. The first (PRP1) either contains
2529 * a PRP list pointer or a PRP element, depending upon the command. PRP2 contains
2530 * the second PRP element if the memory being described fits within 2 PRP
2531 * entries, or a PRP list pointer if the PRP spans more than two entries.
2532 *
2533 * A PRP list pointer contains the address of a PRP list, structured as a linear
2534 * array of PRP entries. Each PRP entry in this list describes a segment of
2535 * physical memory.
2536 *
2537 * Each 64-bit PRP entry comprises an address and an offset field. The address
2538 * always points to the beginning of a PAGE_SIZE physical memory page, and the
2539 * offset describes where within that page the memory segment begins. Only the
2540 * first element in a PRP list may contain a non-zero offest, implying that all
2541 * memory segments following the first begin at the start of a PAGE_SIZE page.
2542 *
2543 * Each PRP element normally describes a chunck of PAGE_SIZE physical memory,
2544 * with exceptions for the first and last elements in the list. If the memory
2545 * being described by the list begins at a non-zero offset within the first page,
2546 * then the first PRP element will contain a non-zero offset indicating where the
2547 * region begins within the page. The last memory segment may end before the end
2548 * of the PAGE_SIZE segment, depending upon the overall size of the memory being
2549 * described by the PRP list.
2550 *
2551 * Since PRP entries lack any indication of size, the overall data buffer length
2552 * is used to determine where the end of the data memory buffer is located, and
2553 * how many PRP entries are required to describe it.
2554 *
2555 * Returns nothing.
2556 */
2557 void
2558 mpr_build_nvme_prp(struct mpr_softc *sc, struct mpr_command *cm,
2559     Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request, void *data,
2560     uint32_t data_in_sz, uint32_t data_out_sz)
2561 {
2562 	int			prp_size = PRP_ENTRY_SIZE;
2563 	uint64_t		*prp_entry, *prp1_entry, *prp2_entry;
2564 	uint64_t		*prp_entry_phys, *prp_page, *prp_page_phys;
2565 	uint32_t		offset, entry_len, page_mask_result, page_mask;
2566 	bus_addr_t		paddr;
2567 	size_t			length;
2568 	struct mpr_prp_page	*prp_page_info = NULL;
2569 
2570 	/*
2571 	 * Not all commands require a data transfer. If no data, just return
2572 	 * without constructing any PRP.
2573 	 */
2574 	if (!data_in_sz && !data_out_sz)
2575 		return;
2576 
2577 	/*
2578 	 * Set pointers to PRP1 and PRP2, which are in the NVMe command. PRP1 is
2579 	 * located at a 24 byte offset from the start of the NVMe command. Then
2580 	 * set the current PRP entry pointer to PRP1.
2581 	 */
2582 	prp1_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2583 	    NVME_CMD_PRP1_OFFSET);
2584 	prp2_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2585 	    NVME_CMD_PRP2_OFFSET);
2586 	prp_entry = prp1_entry;
2587 
2588 	/*
2589 	 * For the PRP entries, use the specially allocated buffer of
2590 	 * contiguous memory. PRP Page allocation failures should not happen
2591 	 * because there should be enough PRP page buffers to account for the
2592 	 * possible NVMe QDepth.
2593 	 */
2594 	prp_page_info = mpr_alloc_prp_page(sc);
2595 	KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
2596 	    "used for building a native NVMe SGL.\n", __func__));
2597 	prp_page = (uint64_t *)prp_page_info->prp_page;
2598 	prp_page_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
2599 
2600 	/*
2601 	 * Insert the allocated PRP page into the command's PRP page list. This
2602 	 * will be freed when the command is freed.
2603 	 */
2604 	TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
2605 
2606 	/*
2607 	 * Check if we are within 1 entry of a page boundary we don't want our
2608 	 * first entry to be a PRP List entry.
2609 	 */
2610 	page_mask = PAGE_SIZE - 1;
2611 	page_mask_result = (uintptr_t)((uint8_t *)prp_page + prp_size) &
2612 	    page_mask;
2613 	if (!page_mask_result)
2614 	{
2615 		/* Bump up to next page boundary. */
2616 		prp_page = (uint64_t *)((uint8_t *)prp_page + prp_size);
2617 		prp_page_phys = (uint64_t *)((uint8_t *)prp_page_phys +
2618 		    prp_size);
2619 	}
2620 
2621 	/*
2622 	 * Set PRP physical pointer, which initially points to the current PRP
2623 	 * DMA memory page.
2624 	 */
2625 	prp_entry_phys = prp_page_phys;
2626 
2627 	/* Get physical address and length of the data buffer. */
2628 	paddr = (bus_addr_t)data;
2629 	if (data_in_sz)
2630 		length = data_in_sz;
2631 	else
2632 		length = data_out_sz;
2633 
2634 	/* Loop while the length is not zero. */
2635 	while (length)
2636 	{
2637 		/*
2638 		 * Check if we need to put a list pointer here if we are at page
2639 		 * boundary - prp_size (8 bytes).
2640 		 */
2641 		page_mask_result = (uintptr_t)((uint8_t *)prp_entry_phys +
2642 		    prp_size) & page_mask;
2643 		if (!page_mask_result)
2644 		{
2645 			/*
2646 			 * This is the last entry in a PRP List, so we need to
2647 			 * put a PRP list pointer here. What this does is:
2648 			 *   - bump the current memory pointer to the next
2649 			 *     address, which will be the next full page.
2650 			 *   - set the PRP Entry to point to that page. This is
2651 			 *     now the PRP List pointer.
2652 			 *   - bump the PRP Entry pointer the start of the next
2653 			 *     page. Since all of this PRP memory is contiguous,
2654 			 *     no need to get a new page - it's just the next
2655 			 *     address.
2656 			 */
2657 			prp_entry_phys++;
2658 			*prp_entry =
2659 			    htole64((uint64_t)(uintptr_t)prp_entry_phys);
2660 			prp_entry++;
2661 		}
2662 
2663 		/* Need to handle if entry will be part of a page. */
2664 		offset = (uint32_t)paddr & page_mask;
2665 		entry_len = PAGE_SIZE - offset;
2666 
2667 		if (prp_entry == prp1_entry)
2668 		{
2669 			/*
2670 			 * Must fill in the first PRP pointer (PRP1) before
2671 			 * moving on.
2672 			 */
2673 			*prp1_entry = htole64((uint64_t)paddr);
2674 
2675 			/*
2676 			 * Now point to the second PRP entry within the
2677 			 * command (PRP2).
2678 			 */
2679 			prp_entry = prp2_entry;
2680 		}
2681 		else if (prp_entry == prp2_entry)
2682 		{
2683 			/*
2684 			 * Should the PRP2 entry be a PRP List pointer or just a
2685 			 * regular PRP pointer? If there is more than one more
2686 			 * page of data, must use a PRP List pointer.
2687 			 */
2688 			if (length > PAGE_SIZE)
2689 			{
2690 				/*
2691 				 * PRP2 will contain a PRP List pointer because
2692 				 * more PRP's are needed with this command. The
2693 				 * list will start at the beginning of the
2694 				 * contiguous buffer.
2695 				 */
2696 				*prp2_entry =
2697 				    htole64(
2698 				    (uint64_t)(uintptr_t)prp_entry_phys);
2699 
2700 				/*
2701 				 * The next PRP Entry will be the start of the
2702 				 * first PRP List.
2703 				 */
2704 				prp_entry = prp_page;
2705 			}
2706 			else
2707 			{
2708 				/*
2709 				 * After this, the PRP Entries are complete.
2710 				 * This command uses 2 PRP's and no PRP list.
2711 				 */
2712 				*prp2_entry = htole64((uint64_t)paddr);
2713 			}
2714 		}
2715 		else
2716 		{
2717 			/*
2718 			 * Put entry in list and bump the addresses.
2719 			 *
2720 			 * After PRP1 and PRP2 are filled in, this will fill in
2721 			 * all remaining PRP entries in a PRP List, one per each
2722 			 * time through the loop.
2723 			 */
2724 			*prp_entry = htole64((uint64_t)paddr);
2725 			prp_entry++;
2726 			prp_entry_phys++;
2727 		}
2728 
2729 		/*
2730 		 * Bump the phys address of the command's data buffer by the
2731 		 * entry_len.
2732 		 */
2733 		paddr += entry_len;
2734 
2735 		/* Decrement length accounting for last partial page. */
2736 		if (entry_len > length)
2737 			length = 0;
2738 		else
2739 			length -= entry_len;
2740 	}
2741 }
2742 
2743 /*
2744  * mpr_check_pcie_native_sgl - This function is called for PCIe end devices to
2745  * determine if the driver needs to build a native SGL. If so, that native SGL
2746  * is built in the contiguous buffers allocated especially for PCIe SGL
2747  * creation. If the driver will not build a native SGL, return TRUE and a
2748  * normal IEEE SGL will be built. Currently this routine supports NVMe devices
2749  * only.
2750  *
2751  * Returns FALSE (0) if native SGL was built, TRUE (1) if no SGL was built.
2752  */
2753 static int
2754 mpr_check_pcie_native_sgl(struct mpr_softc *sc, struct mpr_command *cm,
2755     bus_dma_segment_t *segs, int segs_left)
2756 {
2757 	uint32_t		i, sge_dwords, length, offset, entry_len;
2758 	uint32_t		num_entries, buff_len = 0, sges_in_segment;
2759 	uint32_t		page_mask, page_mask_result, *curr_buff;
2760 	uint32_t		*ptr_sgl, *ptr_first_sgl, first_page_offset;
2761 	uint32_t		first_page_data_size, end_residual;
2762 	uint64_t		*msg_phys;
2763 	bus_addr_t		paddr;
2764 	int			build_native_sgl = 0, first_prp_entry;
2765 	int			prp_size = PRP_ENTRY_SIZE;
2766 	Mpi25IeeeSgeChain64_t	*main_chain_element = NULL;
2767 	struct mpr_prp_page	*prp_page_info = NULL;
2768 
2769 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2770 
2771 	/*
2772 	 * Add up the sizes of each segment length to get the total transfer
2773 	 * size, which will be checked against the Maximum Data Transfer Size.
2774 	 * If the data transfer length exceeds the MDTS for this device, just
2775 	 * return 1 so a normal IEEE SGL will be built. F/W will break the I/O
2776 	 * up into multiple I/O's. [nvme_mdts = 0 means unlimited]
2777 	 */
2778 	for (i = 0; i < segs_left; i++)
2779 		buff_len += htole32(segs[i].ds_len);
2780 	if ((cm->cm_targ->MDTS > 0) && (buff_len > cm->cm_targ->MDTS))
2781 		return 1;
2782 
2783 	/* Create page_mask (to get offset within page) */
2784 	page_mask = PAGE_SIZE - 1;
2785 
2786 	/*
2787 	 * Check if the number of elements exceeds the max number that can be
2788 	 * put in the main message frame (H/W can only translate an SGL that
2789 	 * is contained entirely in the main message frame).
2790 	 */
2791 	sges_in_segment = (sc->facts->IOCRequestFrameSize -
2792 	    offsetof(Mpi25SCSIIORequest_t, SGL)) / sizeof(MPI25_SGE_IO_UNION);
2793 	if (segs_left > sges_in_segment)
2794 		build_native_sgl = 1;
2795 	else
2796 	{
2797 		/*
2798 		 * NVMe uses one PRP for each physical page (or part of physical
2799 		 * page).
2800 		 *    if 4 pages or less then IEEE is OK
2801 		 *    if > 5 pages then we need to build a native SGL
2802 		 *    if > 4 and <= 5 pages, then check the physical address of
2803 		 *      the first SG entry, then if this first size in the page
2804 		 *      is >= the residual beyond 4 pages then use IEEE,
2805 		 *      otherwise use native SGL
2806 		 */
2807 		if (buff_len > (PAGE_SIZE * 5))
2808 			build_native_sgl = 1;
2809 		else if ((buff_len > (PAGE_SIZE * 4)) &&
2810 		    (buff_len <= (PAGE_SIZE * 5)) )
2811 		{
2812 			msg_phys = (uint64_t *)segs[0].ds_addr;
2813 			first_page_offset =
2814 			    ((uint32_t)(uint64_t)(uintptr_t)msg_phys &
2815 			    page_mask);
2816 			first_page_data_size = PAGE_SIZE - first_page_offset;
2817 			end_residual = buff_len % PAGE_SIZE;
2818 
2819 			/*
2820 			 * If offset into first page pushes the end of the data
2821 			 * beyond end of the 5th page, we need the extra PRP
2822 			 * list.
2823 			 */
2824 			if (first_page_data_size < end_residual)
2825 				build_native_sgl = 1;
2826 
2827 			/*
2828 			 * Check if first SG entry size is < residual beyond 4
2829 			 * pages.
2830 			 */
2831 			if (htole32(segs[0].ds_len) <
2832 			    (buff_len - (PAGE_SIZE * 4)))
2833 				build_native_sgl = 1;
2834 		}
2835 	}
2836 
2837 	/* check if native SGL is needed */
2838 	if (!build_native_sgl)
2839 		return 1;
2840 
2841 	/*
2842 	 * Native SGL is needed.
2843 	 * Put a chain element in main message frame that points to the first
2844 	 * chain buffer.
2845 	 *
2846 	 * NOTE:  The ChainOffset field must be 0 when using a chain pointer to
2847 	 *        a native SGL.
2848 	 */
2849 
2850 	/* Set main message chain element pointer */
2851 	main_chain_element = (pMpi25IeeeSgeChain64_t)cm->cm_sge;
2852 
2853 	/*
2854 	 * For NVMe the chain element needs to be the 2nd SGL entry in the main
2855 	 * message.
2856 	 */
2857 	main_chain_element = (Mpi25IeeeSgeChain64_t *)
2858 	    ((uint8_t *)main_chain_element + sizeof(MPI25_IEEE_SGE_CHAIN64));
2859 
2860 	/*
2861 	 * For the PRP entries, use the specially allocated buffer of
2862 	 * contiguous memory. PRP Page allocation failures should not happen
2863 	 * because there should be enough PRP page buffers to account for the
2864 	 * possible NVMe QDepth.
2865 	 */
2866 	prp_page_info = mpr_alloc_prp_page(sc);
2867 	KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
2868 	    "used for building a native NVMe SGL.\n", __func__));
2869 	curr_buff = (uint32_t *)prp_page_info->prp_page;
2870 	msg_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
2871 
2872 	/*
2873 	 * Insert the allocated PRP page into the command's PRP page list. This
2874 	 * will be freed when the command is freed.
2875 	 */
2876 	TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
2877 
2878 	/*
2879 	 * Check if we are within 1 entry of a page boundary we don't want our
2880 	 * first entry to be a PRP List entry.
2881 	 */
2882 	page_mask_result = (uintptr_t)((uint8_t *)curr_buff + prp_size) &
2883 	    page_mask;
2884 	if (!page_mask_result) {
2885 		/* Bump up to next page boundary. */
2886 		curr_buff = (uint32_t *)((uint8_t *)curr_buff + prp_size);
2887 		msg_phys = (uint64_t *)((uint8_t *)msg_phys + prp_size);
2888 	}
2889 
2890 	/* Fill in the chain element and make it an NVMe segment type. */
2891 	main_chain_element->Address.High =
2892 	    htole32((uint32_t)((uint64_t)(uintptr_t)msg_phys >> 32));
2893 	main_chain_element->Address.Low =
2894 	    htole32((uint32_t)(uintptr_t)msg_phys);
2895 	main_chain_element->NextChainOffset = 0;
2896 	main_chain_element->Flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2897 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2898 	    MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
2899 
2900 	/* Set SGL pointer to start of contiguous PCIe buffer. */
2901 	ptr_sgl = curr_buff;
2902 	sge_dwords = 2;
2903 	num_entries = 0;
2904 
2905 	/*
2906 	 * NVMe has a very convoluted PRP format. One PRP is required for each
2907 	 * page or partial page. We need to split up OS SG entries if they are
2908 	 * longer than one page or cross a page boundary. We also have to insert
2909 	 * a PRP list pointer entry as the last entry in each physical page of
2910 	 * the PRP list.
2911 	 *
2912 	 * NOTE: The first PRP "entry" is actually placed in the first SGL entry
2913 	 * in the main message in IEEE 64 format. The 2nd entry in the main
2914 	 * message is the chain element, and the rest of the PRP entries are
2915 	 * built in the contiguous PCIe buffer.
2916 	 */
2917 	first_prp_entry = 1;
2918 	ptr_first_sgl = (uint32_t *)cm->cm_sge;
2919 
2920 	for (i = 0; i < segs_left; i++) {
2921 		/* Get physical address and length of this SG entry. */
2922 		paddr = segs[i].ds_addr;
2923 		length = segs[i].ds_len;
2924 
2925 		/*
2926 		 * Check whether a given SGE buffer lies on a non-PAGED
2927 		 * boundary if this is not the first page. If so, this is not
2928 		 * expected so have FW build the SGL.
2929 		 */
2930 		if ((i != 0) && (((uint32_t)paddr & page_mask) != 0)) {
2931 			mpr_dprint(sc, MPR_ERROR, "Unaligned SGE while "
2932 			    "building NVMe PRPs, low address is 0x%x\n",
2933 			    (uint32_t)paddr);
2934 			return 1;
2935 		}
2936 
2937 		/* Apart from last SGE, if any other SGE boundary is not page
2938 		 * aligned then it means that hole exists. Existence of hole
2939 		 * leads to data corruption. So fallback to IEEE SGEs.
2940 		 */
2941 		if (i != (segs_left - 1)) {
2942 			if (((uint32_t)paddr + length) & page_mask) {
2943 				mpr_dprint(sc, MPR_ERROR, "Unaligned SGE "
2944 				    "boundary while building NVMe PRPs, low "
2945 				    "address: 0x%x and length: %u\n",
2946 				    (uint32_t)paddr, length);
2947 				return 1;
2948 			}
2949 		}
2950 
2951 		/* Loop while the length is not zero. */
2952 		while (length) {
2953 			/*
2954 			 * Check if we need to put a list pointer here if we are
2955 			 * at page boundary - prp_size.
2956 			 */
2957 			page_mask_result = (uintptr_t)((uint8_t *)ptr_sgl +
2958 			    prp_size) & page_mask;
2959 			if (!page_mask_result) {
2960 				/*
2961 				 * Need to put a PRP list pointer here.
2962 				 */
2963 				msg_phys = (uint64_t *)((uint8_t *)msg_phys +
2964 				    prp_size);
2965 				*ptr_sgl = htole32((uintptr_t)msg_phys);
2966 				*(ptr_sgl+1) = htole32((uint64_t)(uintptr_t)
2967 				    msg_phys >> 32);
2968 				ptr_sgl += sge_dwords;
2969 				num_entries++;
2970 			}
2971 
2972 			/* Need to handle if entry will be part of a page. */
2973 			offset = (uint32_t)paddr & page_mask;
2974 			entry_len = PAGE_SIZE - offset;
2975 			if (first_prp_entry) {
2976 				/*
2977 				 * Put IEEE entry in first SGE in main message.
2978 				 * (Simple element, System addr, not end of
2979 				 * list.)
2980 				 */
2981 				*ptr_first_sgl = htole32((uint32_t)paddr);
2982 				*(ptr_first_sgl + 1) =
2983 				    htole32((uint32_t)((uint64_t)paddr >> 32));
2984 				*(ptr_first_sgl + 2) = htole32(entry_len);
2985 				*(ptr_first_sgl + 3) = 0;
2986 
2987 				/* No longer the first PRP entry. */
2988 				first_prp_entry = 0;
2989 			} else {
2990 				/* Put entry in list. */
2991 				*ptr_sgl = htole32((uint32_t)paddr);
2992 				*(ptr_sgl + 1) =
2993 				    htole32((uint32_t)((uint64_t)paddr >> 32));
2994 
2995 				/* Bump ptr_sgl, msg_phys, and num_entries. */
2996 				ptr_sgl += sge_dwords;
2997 				msg_phys = (uint64_t *)((uint8_t *)msg_phys +
2998 				    prp_size);
2999 				num_entries++;
3000 			}
3001 
3002 			/* Bump the phys address by the entry_len. */
3003 			paddr += entry_len;
3004 
3005 			/* Decrement length accounting for last partial page. */
3006 			if (entry_len > length)
3007 				length = 0;
3008 			else
3009 				length -= entry_len;
3010 		}
3011 	}
3012 
3013 	/* Set chain element Length. */
3014 	main_chain_element->Length = htole32(num_entries * prp_size);
3015 
3016 	/* Return 0, indicating we built a native SGL. */
3017 	return 0;
3018 }
3019 
3020 /*
3021  * Add a chain element as the next SGE for the specified command.
3022  * Reset cm_sge and cm_sgesize to indicate all the available space. Chains are
3023  * only required for IEEE commands.  Therefore there is no code for commands
3024  * that have the MPR_CM_FLAGS_SGE_SIMPLE flag set (and those commands
3025  * shouldn't be requesting chains).
3026  */
3027 static int
3028 mpr_add_chain(struct mpr_command *cm, int segsleft)
3029 {
3030 	struct mpr_softc *sc = cm->cm_sc;
3031 	MPI2_REQUEST_HEADER *req;
3032 	MPI25_IEEE_SGE_CHAIN64 *ieee_sgc;
3033 	struct mpr_chain *chain;
3034 	int sgc_size, current_segs, rem_segs, segs_per_frame;
3035 	uint8_t next_chain_offset = 0;
3036 
3037 	/*
3038 	 * Fail if a command is requesting a chain for SIMPLE SGE's.  For SAS3
3039 	 * only IEEE commands should be requesting chains.  Return some error
3040 	 * code other than 0.
3041 	 */
3042 	if (cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE) {
3043 		mpr_dprint(sc, MPR_ERROR, "A chain element cannot be added to "
3044 		    "an MPI SGL.\n");
3045 		return(ENOBUFS);
3046 	}
3047 
3048 	sgc_size = sizeof(MPI25_IEEE_SGE_CHAIN64);
3049 	if (cm->cm_sglsize < sgc_size)
3050 		panic("MPR: Need SGE Error Code\n");
3051 
3052 	chain = mpr_alloc_chain(cm->cm_sc);
3053 	if (chain == NULL)
3054 		return (ENOBUFS);
3055 
3056 	/*
3057 	 * Note: a double-linked list is used to make it easier to walk for
3058 	 * debugging.
3059 	 */
3060 	TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
3061 
3062 	/*
3063 	 * Need to know if the number of frames left is more than 1 or not.  If
3064 	 * more than 1 frame is required, NextChainOffset will need to be set,
3065 	 * which will just be the last segment of the frame.
3066 	 */
3067 	rem_segs = 0;
3068 	if (cm->cm_sglsize < (sgc_size * segsleft)) {
3069 		/*
3070 		 * rem_segs is the number of segements remaining after the
3071 		 * segments that will go into the current frame.  Since it is
3072 		 * known that at least one more frame is required, account for
3073 		 * the chain element.  To know if more than one more frame is
3074 		 * required, just check if there will be a remainder after using
3075 		 * the current frame (with this chain) and the next frame.  If
3076 		 * so the NextChainOffset must be the last element of the next
3077 		 * frame.
3078 		 */
3079 		current_segs = (cm->cm_sglsize / sgc_size) - 1;
3080 		rem_segs = segsleft - current_segs;
3081 		segs_per_frame = sc->chain_frame_size / sgc_size;
3082 		if (rem_segs > segs_per_frame) {
3083 			next_chain_offset = segs_per_frame - 1;
3084 		}
3085 	}
3086 	ieee_sgc = &((MPI25_SGE_IO_UNION *)cm->cm_sge)->IeeeChain;
3087 	ieee_sgc->Length = next_chain_offset ?
3088 	    htole32((uint32_t)sc->chain_frame_size) :
3089 	    htole32((uint32_t)rem_segs * (uint32_t)sgc_size);
3090 	ieee_sgc->NextChainOffset = next_chain_offset;
3091 	ieee_sgc->Flags = (MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3092 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3093 	ieee_sgc->Address.Low = htole32(chain->chain_busaddr);
3094 	ieee_sgc->Address.High = htole32(chain->chain_busaddr >> 32);
3095 	cm->cm_sge = &((MPI25_SGE_IO_UNION *)chain->chain)->IeeeSimple;
3096 	req = (MPI2_REQUEST_HEADER *)cm->cm_req;
3097 	req->ChainOffset = (sc->chain_frame_size - sgc_size) >> 4;
3098 
3099 	cm->cm_sglsize = sc->chain_frame_size;
3100 	return (0);
3101 }
3102 
3103 /*
3104  * Add one scatter-gather element to the scatter-gather list for a command.
3105  * Maintain cm_sglsize and cm_sge as the remaining size and pointer to the
3106  * next SGE to fill in, respectively.  In Gen3, the MPI SGL does not have a
3107  * chain, so don't consider any chain additions.
3108  */
3109 int
3110 mpr_push_sge(struct mpr_command *cm, MPI2_SGE_SIMPLE64 *sge, size_t len,
3111     int segsleft)
3112 {
3113 	uint32_t saved_buf_len, saved_address_low, saved_address_high;
3114 	u32 sge_flags;
3115 
3116 	/*
3117 	 * case 1: >=1 more segment, no room for anything (error)
3118 	 * case 2: 1 more segment and enough room for it
3119          */
3120 
3121 	if (cm->cm_sglsize < (segsleft * sizeof(MPI2_SGE_SIMPLE64))) {
3122 		mpr_dprint(cm->cm_sc, MPR_ERROR,
3123 		    "%s: warning: Not enough room for MPI SGL in frame.\n",
3124 		    __func__);
3125 		return(ENOBUFS);
3126 	}
3127 
3128 	KASSERT(segsleft == 1,
3129 	    ("segsleft cannot be more than 1 for an MPI SGL; segsleft = %d\n",
3130 	    segsleft));
3131 
3132 	/*
3133 	 * There is one more segment left to add for the MPI SGL and there is
3134 	 * enough room in the frame to add it.  This is the normal case because
3135 	 * MPI SGL's don't have chains, otherwise something is wrong.
3136 	 *
3137 	 * If this is a bi-directional request, need to account for that
3138 	 * here.  Save the pre-filled sge values.  These will be used
3139 	 * either for the 2nd SGL or for a single direction SGL.  If
3140 	 * cm_out_len is non-zero, this is a bi-directional request, so
3141 	 * fill in the OUT SGL first, then the IN SGL, otherwise just
3142 	 * fill in the IN SGL.  Note that at this time, when filling in
3143 	 * 2 SGL's for a bi-directional request, they both use the same
3144 	 * DMA buffer (same cm command).
3145 	 */
3146 	saved_buf_len = sge->FlagsLength & 0x00FFFFFF;
3147 	saved_address_low = sge->Address.Low;
3148 	saved_address_high = sge->Address.High;
3149 	if (cm->cm_out_len) {
3150 		sge->FlagsLength = cm->cm_out_len |
3151 		    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3152 		    MPI2_SGE_FLAGS_END_OF_BUFFER |
3153 		    MPI2_SGE_FLAGS_HOST_TO_IOC |
3154 		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3155 		    MPI2_SGE_FLAGS_SHIFT);
3156 		cm->cm_sglsize -= len;
3157 		/* Endian Safe code */
3158 		sge_flags = sge->FlagsLength;
3159 		sge->FlagsLength = htole32(sge_flags);
3160 		sge->Address.High = htole32(sge->Address.High);
3161 		sge->Address.Low = htole32(sge->Address.Low);
3162 		bcopy(sge, cm->cm_sge, len);
3163 		cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3164 	}
3165 	sge->FlagsLength = saved_buf_len |
3166 	    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3167 	    MPI2_SGE_FLAGS_END_OF_BUFFER |
3168 	    MPI2_SGE_FLAGS_LAST_ELEMENT |
3169 	    MPI2_SGE_FLAGS_END_OF_LIST |
3170 	    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3171 	    MPI2_SGE_FLAGS_SHIFT);
3172 	if (cm->cm_flags & MPR_CM_FLAGS_DATAIN) {
3173 		sge->FlagsLength |=
3174 		    ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
3175 		    MPI2_SGE_FLAGS_SHIFT);
3176 	} else {
3177 		sge->FlagsLength |=
3178 		    ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
3179 		    MPI2_SGE_FLAGS_SHIFT);
3180 	}
3181 	sge->Address.Low = saved_address_low;
3182 	sge->Address.High = saved_address_high;
3183 
3184 	cm->cm_sglsize -= len;
3185 	/* Endian Safe code */
3186 	sge_flags = sge->FlagsLength;
3187 	sge->FlagsLength = htole32(sge_flags);
3188 	sge->Address.High = htole32(sge->Address.High);
3189 	sge->Address.Low = htole32(sge->Address.Low);
3190 	bcopy(sge, cm->cm_sge, len);
3191 	cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3192 	return (0);
3193 }
3194 
3195 /*
3196  * Add one IEEE scatter-gather element (chain or simple) to the IEEE scatter-
3197  * gather list for a command.  Maintain cm_sglsize and cm_sge as the
3198  * remaining size and pointer to the next SGE to fill in, respectively.
3199  */
3200 int
3201 mpr_push_ieee_sge(struct mpr_command *cm, void *sgep, int segsleft)
3202 {
3203 	MPI2_IEEE_SGE_SIMPLE64 *sge = sgep;
3204 	int error, ieee_sge_size = sizeof(MPI25_SGE_IO_UNION);
3205 	uint32_t saved_buf_len, saved_address_low, saved_address_high;
3206 	uint32_t sge_length;
3207 
3208 	/*
3209 	 * case 1: No room for chain or segment (error).
3210 	 * case 2: Two or more segments left but only room for chain.
3211 	 * case 3: Last segment and room for it, so set flags.
3212 	 */
3213 
3214 	/*
3215 	 * There should be room for at least one element, or there is a big
3216 	 * problem.
3217 	 */
3218 	if (cm->cm_sglsize < ieee_sge_size)
3219 		panic("MPR: Need SGE Error Code\n");
3220 
3221 	if ((segsleft >= 2) && (cm->cm_sglsize < (ieee_sge_size * 2))) {
3222 		if ((error = mpr_add_chain(cm, segsleft)) != 0)
3223 			return (error);
3224 	}
3225 
3226 	if (segsleft == 1) {
3227 		/*
3228 		 * If this is a bi-directional request, need to account for that
3229 		 * here.  Save the pre-filled sge values.  These will be used
3230 		 * either for the 2nd SGL or for a single direction SGL.  If
3231 		 * cm_out_len is non-zero, this is a bi-directional request, so
3232 		 * fill in the OUT SGL first, then the IN SGL, otherwise just
3233 		 * fill in the IN SGL.  Note that at this time, when filling in
3234 		 * 2 SGL's for a bi-directional request, they both use the same
3235 		 * DMA buffer (same cm command).
3236 		 */
3237 		saved_buf_len = sge->Length;
3238 		saved_address_low = sge->Address.Low;
3239 		saved_address_high = sge->Address.High;
3240 		if (cm->cm_out_len) {
3241 			sge->Length = cm->cm_out_len;
3242 			sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3243 			    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3244 			cm->cm_sglsize -= ieee_sge_size;
3245 			/* Endian Safe code */
3246 			sge_length = sge->Length;
3247 			sge->Length = htole32(sge_length);
3248 			sge->Address.High = htole32(sge->Address.High);
3249 			sge->Address.Low = htole32(sge->Address.Low);
3250 			bcopy(sgep, cm->cm_sge, ieee_sge_size);
3251 			cm->cm_sge =
3252 			    (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3253 			    ieee_sge_size);
3254 		}
3255 		sge->Length = saved_buf_len;
3256 		sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3257 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
3258 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
3259 		sge->Address.Low = saved_address_low;
3260 		sge->Address.High = saved_address_high;
3261 	}
3262 
3263 	cm->cm_sglsize -= ieee_sge_size;
3264 	/* Endian Safe code */
3265 	sge_length = sge->Length;
3266 	sge->Length = htole32(sge_length);
3267 	sge->Address.High = htole32(sge->Address.High);
3268 	sge->Address.Low = htole32(sge->Address.Low);
3269 	bcopy(sgep, cm->cm_sge, ieee_sge_size);
3270 	cm->cm_sge = (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3271 	    ieee_sge_size);
3272 	return (0);
3273 }
3274 
3275 /*
3276  * Add one dma segment to the scatter-gather list for a command.
3277  */
3278 int
3279 mpr_add_dmaseg(struct mpr_command *cm, vm_paddr_t pa, size_t len, u_int flags,
3280     int segsleft)
3281 {
3282 	MPI2_SGE_SIMPLE64 sge;
3283 	MPI2_IEEE_SGE_SIMPLE64 ieee_sge;
3284 
3285 	if (!(cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE)) {
3286 		ieee_sge.Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3287 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3288 		ieee_sge.Length = len;
3289 		mpr_from_u64(pa, &ieee_sge.Address);
3290 
3291 		return (mpr_push_ieee_sge(cm, &ieee_sge, segsleft));
3292 	} else {
3293 		/*
3294 		 * This driver always uses 64-bit address elements for
3295 		 * simplicity.
3296 		 */
3297 		flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3298 		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
3299 		/* Set Endian safe macro in mpr_push_sge */
3300 		sge.FlagsLength = len | (flags << MPI2_SGE_FLAGS_SHIFT);
3301 		mpr_from_u64(pa, &sge.Address);
3302 
3303 		return (mpr_push_sge(cm, &sge, sizeof sge, segsleft));
3304 	}
3305 }
3306 
3307 static void
3308 mpr_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3309 {
3310 	struct mpr_softc *sc;
3311 	struct mpr_command *cm;
3312 	u_int i, dir, sflags;
3313 
3314 	cm = (struct mpr_command *)arg;
3315 	sc = cm->cm_sc;
3316 
3317 	/*
3318 	 * In this case, just print out a warning and let the chip tell the
3319 	 * user they did the wrong thing.
3320 	 */
3321 	if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
3322 		mpr_dprint(sc, MPR_ERROR, "%s: warning: busdma returned %d "
3323 		    "segments, more than the %d allowed\n", __func__, nsegs,
3324 		    cm->cm_max_segs);
3325 	}
3326 
3327 	/*
3328 	 * Set up DMA direction flags.  Bi-directional requests are also handled
3329 	 * here.  In that case, both direction flags will be set.
3330 	 */
3331 	sflags = 0;
3332 	if (cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) {
3333 		/*
3334 		 * We have to add a special case for SMP passthrough, there
3335 		 * is no easy way to generically handle it.  The first
3336 		 * S/G element is used for the command (therefore the
3337 		 * direction bit needs to be set).  The second one is used
3338 		 * for the reply.  We'll leave it to the caller to make
3339 		 * sure we only have two buffers.
3340 		 */
3341 		/*
3342 		 * Even though the busdma man page says it doesn't make
3343 		 * sense to have both direction flags, it does in this case.
3344 		 * We have one s/g element being accessed in each direction.
3345 		 */
3346 		dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
3347 
3348 		/*
3349 		 * Set the direction flag on the first buffer in the SMP
3350 		 * passthrough request.  We'll clear it for the second one.
3351 		 */
3352 		sflags |= MPI2_SGE_FLAGS_DIRECTION |
3353 			  MPI2_SGE_FLAGS_END_OF_BUFFER;
3354 	} else if (cm->cm_flags & MPR_CM_FLAGS_DATAOUT) {
3355 		sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
3356 		dir = BUS_DMASYNC_PREWRITE;
3357 	} else
3358 		dir = BUS_DMASYNC_PREREAD;
3359 
3360 	/* Check if a native SG list is needed for an NVMe PCIe device. */
3361 	if (cm->cm_targ && cm->cm_targ->is_nvme &&
3362 	    mpr_check_pcie_native_sgl(sc, cm, segs, nsegs) == 0) {
3363 		/* A native SG list was built, skip to end. */
3364 		goto out;
3365 	}
3366 
3367 	for (i = 0; i < nsegs; i++) {
3368 		if ((cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) && (i != 0)) {
3369 			sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
3370 		}
3371 		error = mpr_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
3372 		    sflags, nsegs - i);
3373 		if (error != 0) {
3374 			/* Resource shortage, roll back! */
3375 			if (ratecheck(&sc->lastfail, &mpr_chainfail_interval))
3376 				mpr_dprint(sc, MPR_INFO, "Out of chain frames, "
3377 				    "consider increasing hw.mpr.max_chains.\n");
3378 			cm->cm_flags |= MPR_CM_FLAGS_CHAIN_FAILED;
3379 			mpr_complete_command(sc, cm);
3380 			return;
3381 		}
3382 	}
3383 
3384 out:
3385 	bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
3386 	mpr_enqueue_request(sc, cm);
3387 
3388 	return;
3389 }
3390 
3391 static void
3392 mpr_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
3393 	     int error)
3394 {
3395 	mpr_data_cb(arg, segs, nsegs, error);
3396 }
3397 
3398 /*
3399  * This is the routine to enqueue commands ansynchronously.
3400  * Note that the only error path here is from bus_dmamap_load(), which can
3401  * return EINPROGRESS if it is waiting for resources.  Other than this, it's
3402  * assumed that if you have a command in-hand, then you have enough credits
3403  * to use it.
3404  */
3405 int
3406 mpr_map_command(struct mpr_softc *sc, struct mpr_command *cm)
3407 {
3408 	int error = 0;
3409 
3410 	if (cm->cm_flags & MPR_CM_FLAGS_USE_UIO) {
3411 		error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
3412 		    &cm->cm_uio, mpr_data_cb2, cm, 0);
3413 	} else if (cm->cm_flags & MPR_CM_FLAGS_USE_CCB) {
3414 		error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
3415 		    cm->cm_data, mpr_data_cb, cm, 0);
3416 	} else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
3417 		error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
3418 		    cm->cm_data, cm->cm_length, mpr_data_cb, cm, 0);
3419 	} else {
3420 		/* Add a zero-length element as needed */
3421 		if (cm->cm_sge != NULL)
3422 			mpr_add_dmaseg(cm, 0, 0, 0, 1);
3423 		mpr_enqueue_request(sc, cm);
3424 	}
3425 
3426 	return (error);
3427 }
3428 
3429 /*
3430  * This is the routine to enqueue commands synchronously.  An error of
3431  * EINPROGRESS from mpr_map_command() is ignored since the command will
3432  * be executed and enqueued automatically.  Other errors come from msleep().
3433  */
3434 int
3435 mpr_wait_command(struct mpr_softc *sc, struct mpr_command **cmp, int timeout,
3436     int sleep_flag)
3437 {
3438 	int error, rc;
3439 	struct timeval cur_time, start_time;
3440 	struct mpr_command *cm = *cmp;
3441 
3442 	if (sc->mpr_flags & MPR_FLAGS_DIAGRESET)
3443 		return  EBUSY;
3444 
3445 	cm->cm_complete = NULL;
3446 	cm->cm_flags |= (MPR_CM_FLAGS_WAKEUP + MPR_CM_FLAGS_POLLED);
3447 	error = mpr_map_command(sc, cm);
3448 	if ((error != 0) && (error != EINPROGRESS))
3449 		return (error);
3450 
3451 	// Check for context and wait for 50 mSec at a time until time has
3452 	// expired or the command has finished.  If msleep can't be used, need
3453 	// to poll.
3454 #if __FreeBSD_version >= 1000029
3455 	if (curthread->td_no_sleeping)
3456 #else //__FreeBSD_version < 1000029
3457 	if (curthread->td_pflags & TDP_NOSLEEPING)
3458 #endif //__FreeBSD_version >= 1000029
3459 		sleep_flag = NO_SLEEP;
3460 	getmicrouptime(&start_time);
3461 	if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP) {
3462 		error = msleep(cm, &sc->mpr_mtx, 0, "mprwait", timeout*hz);
3463 		if (error == EWOULDBLOCK) {
3464 			/*
3465 			 * Record the actual elapsed time in the case of a
3466 			 * timeout for the message below.
3467 			 */
3468 			getmicrouptime(&cur_time);
3469 			timevalsub(&cur_time, &start_time);
3470 		}
3471 	} else {
3472 		while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3473 			mpr_intr_locked(sc);
3474 			if (sleep_flag == CAN_SLEEP)
3475 				pause("mprwait", hz/20);
3476 			else
3477 				DELAY(50000);
3478 
3479 			getmicrouptime(&cur_time);
3480 			timevalsub(&cur_time, &start_time);
3481 			if (cur_time.tv_sec > timeout) {
3482 				error = EWOULDBLOCK;
3483 				break;
3484 			}
3485 		}
3486 	}
3487 
3488 	if (error == EWOULDBLOCK) {
3489 		mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s, timeout=%d,"
3490 		    " elapsed=%jd\n", __func__, timeout,
3491 		    (intmax_t)cur_time.tv_sec);
3492 		rc = mpr_reinit(sc);
3493 		mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3494 		    "failed");
3495 		if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3496 			/*
3497 			 * Tell the caller that we freed the command in a
3498 			 * reinit.
3499 			 */
3500 			*cmp = NULL;
3501 		}
3502 		error = ETIMEDOUT;
3503 	}
3504 	return (error);
3505 }
3506 
3507 /*
3508  * This is the routine to enqueue a command synchonously and poll for
3509  * completion.  Its use should be rare.
3510  */
3511 int
3512 mpr_request_polled(struct mpr_softc *sc, struct mpr_command **cmp)
3513 {
3514 	int error, rc;
3515 	struct timeval cur_time, start_time;
3516 	struct mpr_command *cm = *cmp;
3517 
3518 	error = 0;
3519 
3520 	cm->cm_flags |= MPR_CM_FLAGS_POLLED;
3521 	cm->cm_complete = NULL;
3522 	mpr_map_command(sc, cm);
3523 
3524 	getmicrouptime(&start_time);
3525 	while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3526 		mpr_intr_locked(sc);
3527 
3528 		if (mtx_owned(&sc->mpr_mtx))
3529 			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
3530 			    "mprpoll", hz/20);
3531 		else
3532 			pause("mprpoll", hz/20);
3533 
3534 		/*
3535 		 * Check for real-time timeout and fail if more than 60 seconds.
3536 		 */
3537 		getmicrouptime(&cur_time);
3538 		timevalsub(&cur_time, &start_time);
3539 		if (cur_time.tv_sec > 60) {
3540 			mpr_dprint(sc, MPR_FAULT, "polling failed\n");
3541 			error = ETIMEDOUT;
3542 			break;
3543 		}
3544 	}
3545 
3546 	if (error) {
3547 		mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s\n", __func__);
3548 		rc = mpr_reinit(sc);
3549 		mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3550 		    "failed");
3551 
3552 		if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3553 			/*
3554 			 * Tell the caller that we freed the command in a
3555 			 * reinit.
3556 			 */
3557 			*cmp = NULL;
3558 		}
3559 	}
3560 	return (error);
3561 }
3562 
3563 /*
3564  * The MPT driver had a verbose interface for config pages.  In this driver,
3565  * reduce it to much simpler terms, similar to the Linux driver.
3566  */
3567 int
3568 mpr_read_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
3569 {
3570 	MPI2_CONFIG_REQUEST *req;
3571 	struct mpr_command *cm;
3572 	int error;
3573 
3574 	if (sc->mpr_flags & MPR_FLAGS_BUSY) {
3575 		return (EBUSY);
3576 	}
3577 
3578 	cm = mpr_alloc_command(sc);
3579 	if (cm == NULL) {
3580 		return (EBUSY);
3581 	}
3582 
3583 	req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
3584 	req->Function = MPI2_FUNCTION_CONFIG;
3585 	req->Action = params->action;
3586 	req->SGLFlags = 0;
3587 	req->ChainOffset = 0;
3588 	req->PageAddress = params->page_address;
3589 	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3590 		MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
3591 
3592 		hdr = &params->hdr.Ext;
3593 		req->ExtPageType = hdr->ExtPageType;
3594 		req->ExtPageLength = hdr->ExtPageLength;
3595 		req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
3596 		req->Header.PageLength = 0; /* Must be set to zero */
3597 		req->Header.PageNumber = hdr->PageNumber;
3598 		req->Header.PageVersion = hdr->PageVersion;
3599 	} else {
3600 		MPI2_CONFIG_PAGE_HEADER *hdr;
3601 
3602 		hdr = &params->hdr.Struct;
3603 		req->Header.PageType = hdr->PageType;
3604 		req->Header.PageNumber = hdr->PageNumber;
3605 		req->Header.PageLength = hdr->PageLength;
3606 		req->Header.PageVersion = hdr->PageVersion;
3607 	}
3608 
3609 	cm->cm_data = params->buffer;
3610 	cm->cm_length = params->length;
3611 	if (cm->cm_data != NULL) {
3612 		cm->cm_sge = &req->PageBufferSGE;
3613 		cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
3614 		cm->cm_flags = MPR_CM_FLAGS_SGE_SIMPLE | MPR_CM_FLAGS_DATAIN;
3615 	} else
3616 		cm->cm_sge = NULL;
3617 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3618 
3619 	cm->cm_complete_data = params;
3620 	if (params->callback != NULL) {
3621 		cm->cm_complete = mpr_config_complete;
3622 		return (mpr_map_command(sc, cm));
3623 	} else {
3624 		error = mpr_wait_command(sc, &cm, 0, CAN_SLEEP);
3625 		if (error) {
3626 			mpr_dprint(sc, MPR_FAULT,
3627 			    "Error %d reading config page\n", error);
3628 			if (cm != NULL)
3629 				mpr_free_command(sc, cm);
3630 			return (error);
3631 		}
3632 		mpr_config_complete(sc, cm);
3633 	}
3634 
3635 	return (0);
3636 }
3637 
3638 int
3639 mpr_write_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
3640 {
3641 	return (EINVAL);
3642 }
3643 
3644 static void
3645 mpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm)
3646 {
3647 	MPI2_CONFIG_REPLY *reply;
3648 	struct mpr_config_params *params;
3649 
3650 	MPR_FUNCTRACE(sc);
3651 	params = cm->cm_complete_data;
3652 
3653 	if (cm->cm_data != NULL) {
3654 		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
3655 		    BUS_DMASYNC_POSTREAD);
3656 		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
3657 	}
3658 
3659 	/*
3660 	 * XXX KDM need to do more error recovery?  This results in the
3661 	 * device in question not getting probed.
3662 	 */
3663 	if ((cm->cm_flags & MPR_CM_FLAGS_ERROR_MASK) != 0) {
3664 		params->status = MPI2_IOCSTATUS_BUSY;
3665 		goto done;
3666 	}
3667 
3668 	reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
3669 	if (reply == NULL) {
3670 		params->status = MPI2_IOCSTATUS_BUSY;
3671 		goto done;
3672 	}
3673 	params->status = reply->IOCStatus;
3674 	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3675 		params->hdr.Ext.ExtPageType = reply->ExtPageType;
3676 		params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
3677 		params->hdr.Ext.PageType = reply->Header.PageType;
3678 		params->hdr.Ext.PageNumber = reply->Header.PageNumber;
3679 		params->hdr.Ext.PageVersion = reply->Header.PageVersion;
3680 	} else {
3681 		params->hdr.Struct.PageType = reply->Header.PageType;
3682 		params->hdr.Struct.PageNumber = reply->Header.PageNumber;
3683 		params->hdr.Struct.PageLength = reply->Header.PageLength;
3684 		params->hdr.Struct.PageVersion = reply->Header.PageVersion;
3685 	}
3686 
3687 done:
3688 	mpr_free_command(sc, cm);
3689 	if (params->callback != NULL)
3690 		params->callback(sc, params);
3691 
3692 	return;
3693 }
3694