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