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