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