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