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