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