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