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