xref: /freebsd/sys/dev/mps/mps.c (revision 07c17b2b00d8c1c8a2d58d4d8f99e64ec1182476)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2009 Yahoo! Inc.
5  * Copyright (c) 2011-2015 LSI Corp.
6  * Copyright (c) 2013-2015 Avago Technologies
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * Avago Technologies (LSI) MPT-Fusion Host Adapter FreeBSD
31  *
32  * $FreeBSD$
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 /* Communications core for Avago Technologies (LSI) MPT2 */
39 
40 /* TODO Move headers to mpsvar */
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/selinfo.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/module.h>
49 #include <sys/bus.h>
50 #include <sys/conf.h>
51 #include <sys/bio.h>
52 #include <sys/malloc.h>
53 #include <sys/uio.h>
54 #include <sys/sysctl.h>
55 #include <sys/smp.h>
56 #include <sys/queue.h>
57 #include <sys/kthread.h>
58 #include <sys/taskqueue.h>
59 #include <sys/endian.h>
60 #include <sys/eventhandler.h>
61 #include <sys/sbuf.h>
62 
63 #include <machine/bus.h>
64 #include <machine/resource.h>
65 #include <sys/rman.h>
66 #include <sys/proc.h>
67 
68 #include <dev/pci/pcivar.h>
69 
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 
73 #include <dev/mps/mpi/mpi2_type.h>
74 #include <dev/mps/mpi/mpi2.h>
75 #include <dev/mps/mpi/mpi2_ioc.h>
76 #include <dev/mps/mpi/mpi2_sas.h>
77 #include <dev/mps/mpi/mpi2_cnfg.h>
78 #include <dev/mps/mpi/mpi2_init.h>
79 #include <dev/mps/mpi/mpi2_tool.h>
80 #include <dev/mps/mps_ioctl.h>
81 #include <dev/mps/mpsvar.h>
82 #include <dev/mps/mps_table.h>
83 
84 static int mps_diag_reset(struct mps_softc *sc, int sleep_flag);
85 static int mps_init_queues(struct mps_softc *sc);
86 static void mps_resize_queues(struct mps_softc *sc);
87 static int mps_message_unit_reset(struct mps_softc *sc, int sleep_flag);
88 static int mps_transition_operational(struct mps_softc *sc);
89 static int mps_iocfacts_allocate(struct mps_softc *sc, uint8_t attaching);
90 static void mps_iocfacts_free(struct mps_softc *sc);
91 static void mps_startup(void *arg);
92 static int mps_send_iocinit(struct mps_softc *sc);
93 static int mps_alloc_queues(struct mps_softc *sc);
94 static int mps_alloc_hw_queues(struct mps_softc *sc);
95 static int mps_alloc_replies(struct mps_softc *sc);
96 static int mps_alloc_requests(struct mps_softc *sc);
97 static int mps_attach_log(struct mps_softc *sc);
98 static __inline void mps_complete_command(struct mps_softc *sc,
99     struct mps_command *cm);
100 static void mps_dispatch_event(struct mps_softc *sc, uintptr_t data,
101     MPI2_EVENT_NOTIFICATION_REPLY *reply);
102 static void mps_config_complete(struct mps_softc *sc, struct mps_command *cm);
103 static void mps_periodic(void *);
104 static int mps_reregister_events(struct mps_softc *sc);
105 static void mps_enqueue_request(struct mps_softc *sc, struct mps_command *cm);
106 static int mps_get_iocfacts(struct mps_softc *sc, MPI2_IOC_FACTS_REPLY *facts);
107 static int mps_wait_db_ack(struct mps_softc *sc, int timeout, int sleep_flag);
108 static int mps_debug_sysctl(SYSCTL_HANDLER_ARGS);
109 static void mps_parse_debug(struct mps_softc *sc, char *list);
110 
111 SYSCTL_NODE(_hw, OID_AUTO, mps, CTLFLAG_RD, 0, "MPS Driver Parameters");
112 
113 MALLOC_DEFINE(M_MPT2, "mps", "mpt2 driver memory");
114 MALLOC_DECLARE(M_MPSUSER);
115 
116 /*
117  * Do a "Diagnostic Reset" aka a hard reset.  This should get the chip out of
118  * any state and back to its initialization state machine.
119  */
120 static char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
121 
122 /* Added this union to smoothly convert le64toh cm->cm_desc.Words.
123  * Compiler only support unint64_t to be passed as argument.
124  * Otherwise it will throw below error
125  * "aggregate value used where an integer was expected"
126  */
127 
128 typedef union _reply_descriptor {
129         u64 word;
130         struct {
131                 u32 low;
132                 u32 high;
133         } u;
134 }reply_descriptor,address_descriptor;
135 
136 /* Rate limit chain-fail messages to 1 per minute */
137 static struct timeval mps_chainfail_interval = { 60, 0 };
138 
139 /*
140  * sleep_flag can be either CAN_SLEEP or NO_SLEEP.
141  * If this function is called from process context, it can sleep
142  * and there is no harm to sleep, in case if this fuction is called
143  * from Interrupt handler, we can not sleep and need NO_SLEEP flag set.
144  * based on sleep flags driver will call either msleep, pause or DELAY.
145  * msleep and pause are of same variant, but pause is used when mps_mtx
146  * is not hold by driver.
147  *
148  */
149 static int
150 mps_diag_reset(struct mps_softc *sc,int sleep_flag)
151 {
152 	uint32_t reg;
153 	int i, error, tries = 0;
154 	uint8_t first_wait_done = FALSE;
155 
156 	mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
157 
158 	/* Clear any pending interrupts */
159 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
160 
161 	/*
162 	 * Force NO_SLEEP for threads prohibited to sleep
163  	 * e.a Thread from interrupt handler are prohibited to sleep.
164  	 */
165 	if (curthread->td_no_sleeping != 0)
166 		sleep_flag = NO_SLEEP;
167 
168 	mps_dprint(sc, MPS_INIT, "sequence start, sleep_flag= %d\n", sleep_flag);
169 
170 	/* Push the magic sequence */
171 	error = ETIMEDOUT;
172 	while (tries++ < 20) {
173 		for (i = 0; i < sizeof(mpt2_reset_magic); i++)
174 			mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
175 			    mpt2_reset_magic[i]);
176 		/* wait 100 msec */
177 		if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
178 			msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
179 			    "mpsdiag", hz/10);
180 		else if (sleep_flag == CAN_SLEEP)
181 			pause("mpsdiag", hz/10);
182 		else
183 			DELAY(100 * 1000);
184 
185 		reg = mps_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
186 		if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
187 			error = 0;
188 			break;
189 		}
190 	}
191 	if (error) {
192 		mps_dprint(sc, MPS_INIT, "sequence failed, error=%d, exit\n",
193 		    error);
194 		return (error);
195 	}
196 
197 	/* Send the actual reset.  XXX need to refresh the reg? */
198 	reg |= MPI2_DIAG_RESET_ADAPTER;
199 	mps_dprint(sc, MPS_INIT, "sequence success, sending reset, reg= 0x%x\n",
200 		reg);
201 	mps_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET, reg);
202 
203 	/* Wait up to 300 seconds in 50ms intervals */
204 	error = ETIMEDOUT;
205 	for (i = 0; i < 6000; i++) {
206 		/*
207 		 * Wait 50 msec. If this is the first time through, wait 256
208 		 * msec to satisfy Diag Reset timing requirements.
209 		 */
210 		if (first_wait_done) {
211 			if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
212 				msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
213 				    "mpsdiag", hz/20);
214 			else if (sleep_flag == CAN_SLEEP)
215 				pause("mpsdiag", hz/20);
216 			else
217 				DELAY(50 * 1000);
218 		} else {
219 			DELAY(256 * 1000);
220 			first_wait_done = TRUE;
221 		}
222 		/*
223 		 * Check for the RESET_ADAPTER bit to be cleared first, then
224 		 * wait for the RESET state to be cleared, which takes a little
225 		 * longer.
226 		 */
227 		reg = mps_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
228 		if (reg & MPI2_DIAG_RESET_ADAPTER) {
229 			continue;
230 		}
231 		reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
232 		if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
233 			error = 0;
234 			break;
235 		}
236 	}
237 	if (error) {
238 		mps_dprint(sc, MPS_INIT, "reset failed, error= %d, exit\n",
239 		    error);
240 		return (error);
241 	}
242 
243 	mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
244 	mps_dprint(sc, MPS_INIT, "diag reset success, exit\n");
245 
246 	return (0);
247 }
248 
249 static int
250 mps_message_unit_reset(struct mps_softc *sc, int sleep_flag)
251 {
252 	int error;
253 
254 	MPS_FUNCTRACE(sc);
255 
256 	mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
257 
258 	error = 0;
259 	mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
260 	    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
261 	    MPI2_DOORBELL_FUNCTION_SHIFT);
262 
263 	if (mps_wait_db_ack(sc, 5, sleep_flag) != 0) {
264 		mps_dprint(sc, MPS_INIT|MPS_FAULT,
265 		    "Doorbell handshake failed\n");
266 		error = ETIMEDOUT;
267 	}
268 
269 	mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
270 	return (error);
271 }
272 
273 static int
274 mps_transition_ready(struct mps_softc *sc)
275 {
276 	uint32_t reg, state;
277 	int error, tries = 0;
278 	int sleep_flags;
279 
280 	MPS_FUNCTRACE(sc);
281 	/* If we are in attach call, do not sleep */
282 	sleep_flags = (sc->mps_flags & MPS_FLAGS_ATTACH_DONE)
283 					? CAN_SLEEP:NO_SLEEP;
284 	error = 0;
285 
286 	mps_dprint(sc, MPS_INIT, "%s entered, sleep_flags= %d\n",
287 	   __func__, sleep_flags);
288 
289 	while (tries++ < 1200) {
290 		reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
291 		mps_dprint(sc, MPS_INIT, "  Doorbell= 0x%x\n", reg);
292 
293 		/*
294 		 * Ensure the IOC is ready to talk.  If it's not, try
295 		 * resetting it.
296 		 */
297 		if (reg & MPI2_DOORBELL_USED) {
298 			mps_dprint(sc, MPS_INIT, "  Not ready, sending diag "
299 			    "reset\n");
300 			mps_diag_reset(sc, sleep_flags);
301 			DELAY(50000);
302 			continue;
303 		}
304 
305 		/* Is the adapter owned by another peer? */
306 		if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
307 		    (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
308 			mps_dprint(sc, MPS_INIT|MPS_FAULT, "IOC is under the "
309 			    "control of another peer host, aborting "
310 			    "initialization.\n");
311 			error = ENXIO;
312 			break;
313 		}
314 
315 		state = reg & MPI2_IOC_STATE_MASK;
316 		if (state == MPI2_IOC_STATE_READY) {
317 			/* Ready to go! */
318 			error = 0;
319 			break;
320 		} else if (state == MPI2_IOC_STATE_FAULT) {
321 			mps_dprint(sc, MPS_INIT|MPS_FAULT, "IOC in fault "
322 			    "state 0x%x, resetting\n",
323 			    state & MPI2_DOORBELL_FAULT_CODE_MASK);
324 			mps_diag_reset(sc, sleep_flags);
325 		} else if (state == MPI2_IOC_STATE_OPERATIONAL) {
326 			/* Need to take ownership */
327 			mps_message_unit_reset(sc, sleep_flags);
328 		} else if (state == MPI2_IOC_STATE_RESET) {
329 			/* Wait a bit, IOC might be in transition */
330 			mps_dprint(sc, MPS_INIT|MPS_FAULT,
331 			    "IOC in unexpected reset state\n");
332 		} else {
333 			mps_dprint(sc, MPS_INIT|MPS_FAULT,
334 			    "IOC in unknown state 0x%x\n", state);
335 			error = EINVAL;
336 			break;
337 		}
338 
339 		/* Wait 50ms for things to settle down. */
340 		DELAY(50000);
341 	}
342 
343 	if (error)
344 		mps_dprint(sc, MPS_INIT|MPS_FAULT,
345 		    "Cannot transition IOC to ready\n");
346 	mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
347 
348 	return (error);
349 }
350 
351 static int
352 mps_transition_operational(struct mps_softc *sc)
353 {
354 	uint32_t reg, state;
355 	int error;
356 
357 	MPS_FUNCTRACE(sc);
358 
359 	error = 0;
360 	reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
361 	mps_dprint(sc, MPS_INIT, "%s entered, Doorbell= 0x%x\n", __func__, reg);
362 
363 	state = reg & MPI2_IOC_STATE_MASK;
364 	if (state != MPI2_IOC_STATE_READY) {
365 		mps_dprint(sc, MPS_INIT, "IOC not ready\n");
366 		if ((error = mps_transition_ready(sc)) != 0) {
367 			mps_dprint(sc, MPS_INIT|MPS_FAULT,
368 			    "failed to transition ready, exit\n");
369 			return (error);
370 		}
371 	}
372 
373 	error = mps_send_iocinit(sc);
374 	mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
375 
376 	return (error);
377 }
378 
379 static void
380 mps_resize_queues(struct mps_softc *sc)
381 {
382 	u_int reqcr, prireqcr, maxio, sges_per_frame;
383 
384 	/*
385 	 * Size the queues. Since the reply queues always need one free
386 	 * entry, we'll deduct one reply message here.  The LSI documents
387 	 * suggest instead to add a count to the request queue, but I think
388 	 * that it's better to deduct from reply queue.
389 	 */
390 	prireqcr = MAX(1, sc->max_prireqframes);
391 	prireqcr = MIN(prireqcr, sc->facts->HighPriorityCredit);
392 
393 	reqcr = MAX(2, sc->max_reqframes);
394 	reqcr = MIN(reqcr, sc->facts->RequestCredit);
395 
396 	sc->num_reqs = prireqcr + reqcr;
397 	sc->num_prireqs = prireqcr;
398 	sc->num_replies = MIN(sc->max_replyframes + sc->max_evtframes,
399 	    sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
400 
401 	/* Store the request frame size in bytes rather than as 32bit words */
402 	sc->reqframesz = sc->facts->IOCRequestFrameSize * 4;
403 
404 	/*
405 	 * Max IO Size is Page Size * the following:
406 	 * ((SGEs per frame - 1 for chain element) * Max Chain Depth)
407 	 * + 1 for no chain needed in last frame
408 	 *
409 	 * If user suggests a Max IO size to use, use the smaller of the
410 	 * user's value and the calculated value as long as the user's
411 	 * value is larger than 0. The user's value is in pages.
412 	 */
413 	sges_per_frame = sc->reqframesz / sizeof(MPI2_SGE_SIMPLE64) - 1;
414 	maxio = (sges_per_frame * sc->facts->MaxChainDepth + 1) * PAGE_SIZE;
415 
416 	/*
417 	 * If I/O size limitation requested, then use it and pass up to CAM.
418 	 * If not, use MAXPHYS as an optimization hint, but report HW limit.
419 	 */
420 	if (sc->max_io_pages > 0) {
421 		maxio = min(maxio, sc->max_io_pages * PAGE_SIZE);
422 		sc->maxio = maxio;
423 	} else {
424 		sc->maxio = maxio;
425 		maxio = min(maxio, MAXPHYS);
426 	}
427 
428 	sc->num_chains = (maxio / PAGE_SIZE + sges_per_frame - 2) /
429 	    sges_per_frame * reqcr;
430 	if (sc->max_chains > 0 && sc->max_chains < sc->num_chains)
431 		sc->num_chains = sc->max_chains;
432 
433 	/*
434 	 * Figure out the number of MSIx-based queues.  If the firmware or
435 	 * user has done something crazy and not allowed enough credit for
436 	 * the queues to be useful then don't enable multi-queue.
437 	 */
438 	if (sc->facts->MaxMSIxVectors < 2)
439 		sc->msi_msgs = 1;
440 
441 	if (sc->msi_msgs > 1) {
442 		sc->msi_msgs = MIN(sc->msi_msgs, mp_ncpus);
443 		sc->msi_msgs = MIN(sc->msi_msgs, sc->facts->MaxMSIxVectors);
444 		if (sc->num_reqs / sc->msi_msgs < 2)
445 			sc->msi_msgs = 1;
446 	}
447 
448 	mps_dprint(sc, MPS_INIT, "Sized queues to q=%d reqs=%d replies=%d\n",
449 	    sc->msi_msgs, sc->num_reqs, sc->num_replies);
450 }
451 
452 /*
453  * This is called during attach and when re-initializing due to a Diag Reset.
454  * IOC Facts is used to allocate many of the structures needed by the driver.
455  * If called from attach, de-allocation is not required because the driver has
456  * not allocated any structures yet, but if called from a Diag Reset, previously
457  * allocated structures based on IOC Facts will need to be freed and re-
458  * allocated bases on the latest IOC Facts.
459  */
460 static int
461 mps_iocfacts_allocate(struct mps_softc *sc, uint8_t attaching)
462 {
463 	int error;
464 	Mpi2IOCFactsReply_t saved_facts;
465 	uint8_t saved_mode, reallocating;
466 
467 	mps_dprint(sc, MPS_INIT|MPS_TRACE, "%s entered\n", __func__);
468 
469 	/* Save old IOC Facts and then only reallocate if Facts have changed */
470 	if (!attaching) {
471 		bcopy(sc->facts, &saved_facts, sizeof(MPI2_IOC_FACTS_REPLY));
472 	}
473 
474 	/*
475 	 * Get IOC Facts.  In all cases throughout this function, panic if doing
476 	 * a re-initialization and only return the error if attaching so the OS
477 	 * can handle it.
478 	 */
479 	if ((error = mps_get_iocfacts(sc, sc->facts)) != 0) {
480 		if (attaching) {
481 			mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to get "
482 			    "IOC Facts with error %d, exit\n", error);
483 			return (error);
484 		} else {
485 			panic("%s failed to get IOC Facts with error %d\n",
486 			    __func__, error);
487 		}
488 	}
489 
490 	MPS_DPRINT_PAGE(sc, MPS_XINFO, iocfacts, sc->facts);
491 
492 	snprintf(sc->fw_version, sizeof(sc->fw_version),
493 	    "%02d.%02d.%02d.%02d",
494 	    sc->facts->FWVersion.Struct.Major,
495 	    sc->facts->FWVersion.Struct.Minor,
496 	    sc->facts->FWVersion.Struct.Unit,
497 	    sc->facts->FWVersion.Struct.Dev);
498 
499 	mps_dprint(sc, MPS_INFO, "Firmware: %s, Driver: %s\n", sc->fw_version,
500 	    MPS_DRIVER_VERSION);
501 	mps_dprint(sc, MPS_INFO, "IOCCapabilities: %b\n",
502 	     sc->facts->IOCCapabilities,
503 	    "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
504 	    "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
505 	    "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc");
506 
507 	/*
508 	 * If the chip doesn't support event replay then a hard reset will be
509 	 * required to trigger a full discovery.  Do the reset here then
510 	 * retransition to Ready.  A hard reset might have already been done,
511 	 * but it doesn't hurt to do it again.  Only do this if attaching, not
512 	 * for a Diag Reset.
513 	 */
514 	if (attaching && ((sc->facts->IOCCapabilities &
515 	    MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0)) {
516 		mps_dprint(sc, MPS_INIT, "No event replay, reseting\n");
517 		mps_diag_reset(sc, NO_SLEEP);
518 		if ((error = mps_transition_ready(sc)) != 0) {
519 			mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to "
520 			    "transition to ready with error %d, exit\n",
521 			    error);
522 			return (error);
523 		}
524 	}
525 
526 	/*
527 	 * Set flag if IR Firmware is loaded.  If the RAID Capability has
528 	 * changed from the previous IOC Facts, log a warning, but only if
529 	 * checking this after a Diag Reset and not during attach.
530 	 */
531 	saved_mode = sc->ir_firmware;
532 	if (sc->facts->IOCCapabilities &
533 	    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
534 		sc->ir_firmware = 1;
535 	if (!attaching) {
536 		if (sc->ir_firmware != saved_mode) {
537 			mps_dprint(sc, MPS_INIT|MPS_FAULT, "new IR/IT mode "
538 			    "in IOC Facts does not match previous mode\n");
539 		}
540 	}
541 
542 	/* Only deallocate and reallocate if relevant IOC Facts have changed */
543 	reallocating = FALSE;
544 	sc->mps_flags &= ~MPS_FLAGS_REALLOCATED;
545 
546 	if ((!attaching) &&
547 	    ((saved_facts.MsgVersion != sc->facts->MsgVersion) ||
548 	    (saved_facts.HeaderVersion != sc->facts->HeaderVersion) ||
549 	    (saved_facts.MaxChainDepth != sc->facts->MaxChainDepth) ||
550 	    (saved_facts.RequestCredit != sc->facts->RequestCredit) ||
551 	    (saved_facts.ProductID != sc->facts->ProductID) ||
552 	    (saved_facts.IOCCapabilities != sc->facts->IOCCapabilities) ||
553 	    (saved_facts.IOCRequestFrameSize !=
554 	    sc->facts->IOCRequestFrameSize) ||
555 	    (saved_facts.MaxTargets != sc->facts->MaxTargets) ||
556 	    (saved_facts.MaxSasExpanders != sc->facts->MaxSasExpanders) ||
557 	    (saved_facts.MaxEnclosures != sc->facts->MaxEnclosures) ||
558 	    (saved_facts.HighPriorityCredit != sc->facts->HighPriorityCredit) ||
559 	    (saved_facts.MaxReplyDescriptorPostQueueDepth !=
560 	    sc->facts->MaxReplyDescriptorPostQueueDepth) ||
561 	    (saved_facts.ReplyFrameSize != sc->facts->ReplyFrameSize) ||
562 	    (saved_facts.MaxVolumes != sc->facts->MaxVolumes) ||
563 	    (saved_facts.MaxPersistentEntries !=
564 	    sc->facts->MaxPersistentEntries))) {
565 		reallocating = TRUE;
566 
567 		/* Record that we reallocated everything */
568 		sc->mps_flags |= MPS_FLAGS_REALLOCATED;
569 	}
570 
571 	/*
572 	 * Some things should be done if attaching or re-allocating after a Diag
573 	 * Reset, but are not needed after a Diag Reset if the FW has not
574 	 * changed.
575 	 */
576 	if (attaching || reallocating) {
577 		/*
578 		 * Check if controller supports FW diag buffers and set flag to
579 		 * enable each type.
580 		 */
581 		if (sc->facts->IOCCapabilities &
582 		    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
583 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].
584 			    enabled = TRUE;
585 		if (sc->facts->IOCCapabilities &
586 		    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
587 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].
588 			    enabled = TRUE;
589 		if (sc->facts->IOCCapabilities &
590 		    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
591 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].
592 			    enabled = TRUE;
593 
594 		/*
595 		 * Set flag if EEDP is supported and if TLR is supported.
596 		 */
597 		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
598 			sc->eedp_enabled = TRUE;
599 		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
600 			sc->control_TLR = TRUE;
601 
602 		mps_resize_queues(sc);
603 
604 		/*
605 		 * Initialize all Tail Queues
606 		 */
607 		TAILQ_INIT(&sc->req_list);
608 		TAILQ_INIT(&sc->high_priority_req_list);
609 		TAILQ_INIT(&sc->chain_list);
610 		TAILQ_INIT(&sc->tm_list);
611 	}
612 
613 	/*
614 	 * If doing a Diag Reset and the FW is significantly different
615 	 * (reallocating will be set above in IOC Facts comparison), then all
616 	 * buffers based on the IOC Facts will need to be freed before they are
617 	 * reallocated.
618 	 */
619 	if (reallocating) {
620 		mps_iocfacts_free(sc);
621 		mpssas_realloc_targets(sc, saved_facts.MaxTargets +
622 		    saved_facts.MaxVolumes);
623 	}
624 
625 	/*
626 	 * Any deallocation has been completed.  Now start reallocating
627 	 * if needed.  Will only need to reallocate if attaching or if the new
628 	 * IOC Facts are different from the previous IOC Facts after a Diag
629 	 * Reset. Targets have already been allocated above if needed.
630 	 */
631 	error = 0;
632 	while (attaching || reallocating) {
633 		if ((error = mps_alloc_hw_queues(sc)) != 0)
634 			break;
635 		if ((error = mps_alloc_replies(sc)) != 0)
636 			break;
637 		if ((error = mps_alloc_requests(sc)) != 0)
638 			break;
639 		if ((error = mps_alloc_queues(sc)) != 0)
640 			break;
641 
642 		break;
643 	}
644 	if (error) {
645 		mps_dprint(sc, MPS_INIT|MPS_FAULT,
646 		    "Failed to alloc queues with error %d\n", error);
647 		mps_free(sc);
648 		return (error);
649 	}
650 
651 	/* Always initialize the queues */
652 	bzero(sc->free_queue, sc->fqdepth * 4);
653 	mps_init_queues(sc);
654 
655 	/*
656 	 * Always get the chip out of the reset state, but only panic if not
657 	 * attaching.  If attaching and there is an error, that is handled by
658 	 * the OS.
659 	 */
660 	error = mps_transition_operational(sc);
661 	if (error != 0) {
662 		mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to "
663 		    "transition to operational with error %d\n", error);
664 		mps_free(sc);
665 		return (error);
666 	}
667 
668 	/*
669 	 * Finish the queue initialization.
670 	 * These are set here instead of in mps_init_queues() because the
671 	 * IOC resets these values during the state transition in
672 	 * mps_transition_operational().  The free index is set to 1
673 	 * because the corresponding index in the IOC is set to 0, and the
674 	 * IOC treats the queues as full if both are set to the same value.
675 	 * Hence the reason that the queue can't hold all of the possible
676 	 * replies.
677 	 */
678 	sc->replypostindex = 0;
679 	mps_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
680 	mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
681 
682 	/*
683 	 * Attach the subsystems so they can prepare their event masks.
684 	 * XXX Should be dynamic so that IM/IR and user modules can attach
685 	 */
686 	error = 0;
687 	while (attaching) {
688 		mps_dprint(sc, MPS_INIT, "Attaching subsystems\n");
689 		if ((error = mps_attach_log(sc)) != 0)
690 			break;
691 		if ((error = mps_attach_sas(sc)) != 0)
692 			break;
693 		if ((error = mps_attach_user(sc)) != 0)
694 			break;
695 		break;
696 	}
697 	if (error) {
698 		mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to attach all "
699 		    "subsystems: error %d\n", error);
700 		mps_free(sc);
701 		return (error);
702 	}
703 
704 	/*
705 	 * XXX If the number of MSI-X vectors changes during re-init, this
706 	 * won't see it and adjust.
707 	 */
708 	if (attaching && (error = mps_pci_setup_interrupts(sc)) != 0) {
709 		mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to setup "
710 		    "interrupts\n");
711 		mps_free(sc);
712 		return (error);
713 	}
714 
715 	/*
716 	 * Set flag if this is a WD controller.  This shouldn't ever change, but
717 	 * reset it after a Diag Reset, just in case.
718 	 */
719 	sc->WD_available = FALSE;
720 	if (pci_get_device(sc->mps_dev) == MPI2_MFGPAGE_DEVID_SSS6200)
721 		sc->WD_available = TRUE;
722 
723 	return (error);
724 }
725 
726 /*
727  * This is called if memory is being free (during detach for example) and when
728  * buffers need to be reallocated due to a Diag Reset.
729  */
730 static void
731 mps_iocfacts_free(struct mps_softc *sc)
732 {
733 	struct mps_command *cm;
734 	int i;
735 
736 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
737 
738 	if (sc->free_busaddr != 0)
739 		bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
740 	if (sc->free_queue != NULL)
741 		bus_dmamem_free(sc->queues_dmat, sc->free_queue,
742 		    sc->queues_map);
743 	if (sc->queues_dmat != NULL)
744 		bus_dma_tag_destroy(sc->queues_dmat);
745 
746 	if (sc->chain_busaddr != 0)
747 		bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
748 	if (sc->chain_frames != NULL)
749 		bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
750 		    sc->chain_map);
751 	if (sc->chain_dmat != NULL)
752 		bus_dma_tag_destroy(sc->chain_dmat);
753 
754 	if (sc->sense_busaddr != 0)
755 		bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
756 	if (sc->sense_frames != NULL)
757 		bus_dmamem_free(sc->sense_dmat, sc->sense_frames,
758 		    sc->sense_map);
759 	if (sc->sense_dmat != NULL)
760 		bus_dma_tag_destroy(sc->sense_dmat);
761 
762 	if (sc->reply_busaddr != 0)
763 		bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
764 	if (sc->reply_frames != NULL)
765 		bus_dmamem_free(sc->reply_dmat, sc->reply_frames,
766 		    sc->reply_map);
767 	if (sc->reply_dmat != NULL)
768 		bus_dma_tag_destroy(sc->reply_dmat);
769 
770 	if (sc->req_busaddr != 0)
771 		bus_dmamap_unload(sc->req_dmat, sc->req_map);
772 	if (sc->req_frames != NULL)
773 		bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
774 	if (sc->req_dmat != NULL)
775 		bus_dma_tag_destroy(sc->req_dmat);
776 
777 	if (sc->chains != NULL)
778 		free(sc->chains, M_MPT2);
779 	if (sc->commands != NULL) {
780 		for (i = 1; i < sc->num_reqs; i++) {
781 			cm = &sc->commands[i];
782 			bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
783 		}
784 		free(sc->commands, M_MPT2);
785 	}
786 	if (sc->buffer_dmat != NULL)
787 		bus_dma_tag_destroy(sc->buffer_dmat);
788 
789 	mps_pci_free_interrupts(sc);
790 	free(sc->queues, M_MPT2);
791 	sc->queues = NULL;
792 }
793 
794 /*
795  * The terms diag reset and hard reset are used interchangeably in the MPI
796  * docs to mean resetting the controller chip.  In this code diag reset
797  * cleans everything up, and the hard reset function just sends the reset
798  * sequence to the chip.  This should probably be refactored so that every
799  * subsystem gets a reset notification of some sort, and can clean up
800  * appropriately.
801  */
802 int
803 mps_reinit(struct mps_softc *sc)
804 {
805 	int error;
806 	struct mpssas_softc *sassc;
807 
808 	sassc = sc->sassc;
809 
810 	MPS_FUNCTRACE(sc);
811 
812 	mtx_assert(&sc->mps_mtx, MA_OWNED);
813 
814 	mps_dprint(sc, MPS_INIT|MPS_INFO, "Reinitializing controller\n");
815 	if (sc->mps_flags & MPS_FLAGS_DIAGRESET) {
816 		mps_dprint(sc, MPS_INIT, "Reset already in progress\n");
817 		return 0;
818 	}
819 
820 	/* make sure the completion callbacks can recognize they're getting
821 	 * a NULL cm_reply due to a reset.
822 	 */
823 	sc->mps_flags |= MPS_FLAGS_DIAGRESET;
824 
825 	/*
826 	 * Mask interrupts here.
827 	 */
828 	mps_dprint(sc, MPS_INIT, "masking interrupts and resetting\n");
829 	mps_mask_intr(sc);
830 
831 	error = mps_diag_reset(sc, CAN_SLEEP);
832 	if (error != 0) {
833 		/* XXXSL No need to panic here */
834 		panic("%s hard reset failed with error %d\n",
835 		    __func__, error);
836 	}
837 
838 	/* Restore the PCI state, including the MSI-X registers */
839 	mps_pci_restore(sc);
840 
841 	/* Give the I/O subsystem special priority to get itself prepared */
842 	mpssas_handle_reinit(sc);
843 
844 	/*
845 	 * Get IOC Facts and allocate all structures based on this information.
846 	 * The attach function will also call mps_iocfacts_allocate at startup.
847 	 * If relevant values have changed in IOC Facts, this function will free
848 	 * all of the memory based on IOC Facts and reallocate that memory.
849 	 */
850 	if ((error = mps_iocfacts_allocate(sc, FALSE)) != 0) {
851 		panic("%s IOC Facts based allocation failed with error %d\n",
852 		    __func__, error);
853 	}
854 
855 	/*
856 	 * Mapping structures will be re-allocated after getting IOC Page8, so
857 	 * free these structures here.
858 	 */
859 	mps_mapping_exit(sc);
860 
861 	/*
862 	 * The static page function currently read is IOC Page8.  Others can be
863 	 * added in future.  It's possible that the values in IOC Page8 have
864 	 * changed after a Diag Reset due to user modification, so always read
865 	 * these.  Interrupts are masked, so unmask them before getting config
866 	 * pages.
867 	 */
868 	mps_unmask_intr(sc);
869 	sc->mps_flags &= ~MPS_FLAGS_DIAGRESET;
870 	mps_base_static_config_pages(sc);
871 
872 	/*
873 	 * Some mapping info is based in IOC Page8 data, so re-initialize the
874 	 * mapping tables.
875 	 */
876 	mps_mapping_initialize(sc);
877 
878 	/*
879 	 * Restart will reload the event masks clobbered by the reset, and
880 	 * then enable the port.
881 	 */
882 	mps_reregister_events(sc);
883 
884 	/* the end of discovery will release the simq, so we're done. */
885 	mps_dprint(sc, MPS_INIT|MPS_XINFO, "Finished sc %p post %u free %u\n",
886 	    sc, sc->replypostindex, sc->replyfreeindex);
887 
888 	mpssas_release_simq_reinit(sassc);
889 	mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
890 
891 	return 0;
892 }
893 
894 /* Wait for the chip to ACK a word that we've put into its FIFO
895  * Wait for <timeout> seconds. In single loop wait for busy loop
896  * for 500 microseconds.
897  * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
898  * */
899 static int
900 mps_wait_db_ack(struct mps_softc *sc, int timeout, int sleep_flag)
901 {
902 
903 	u32 cntdn, count;
904 	u32 int_status;
905 	u32 doorbell;
906 
907 	count = 0;
908 	cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
909 	do {
910 		int_status = mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
911 		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
912 			mps_dprint(sc, MPS_TRACE,
913 			"%s: successful count(%d), timeout(%d)\n",
914 			__func__, count, timeout);
915 		return 0;
916 		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
917 			doorbell = mps_regread(sc, MPI2_DOORBELL_OFFSET);
918 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
919 				MPI2_IOC_STATE_FAULT) {
920 				mps_dprint(sc, MPS_FAULT,
921 					"fault_state(0x%04x)!\n", doorbell);
922 				return (EFAULT);
923 			}
924 		} else if (int_status == 0xFFFFFFFF)
925 			goto out;
926 
927 		/* If it can sleep, sleep for 1 milisecond, else busy loop for
928 		* 0.5 milisecond */
929 		if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
930 			msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
931 			"mpsdba", hz/1000);
932 		else if (sleep_flag == CAN_SLEEP)
933 			pause("mpsdba", hz/1000);
934 		else
935 			DELAY(500);
936 		count++;
937 	} while (--cntdn);
938 
939 	out:
940 	mps_dprint(sc, MPS_FAULT, "%s: failed due to timeout count(%d), "
941 		"int_status(%x)!\n", __func__, count, int_status);
942 	return (ETIMEDOUT);
943 
944 }
945 
946 /* Wait for the chip to signal that the next word in its FIFO can be fetched */
947 static int
948 mps_wait_db_int(struct mps_softc *sc)
949 {
950 	int retry;
951 
952 	for (retry = 0; retry < MPS_DB_MAX_WAIT; retry++) {
953 		if ((mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
954 		    MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
955 			return (0);
956 		DELAY(2000);
957 	}
958 	return (ETIMEDOUT);
959 }
960 
961 /* Step through the synchronous command state machine, i.e. "Doorbell mode" */
962 static int
963 mps_request_sync(struct mps_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
964     int req_sz, int reply_sz, int timeout)
965 {
966 	uint32_t *data32;
967 	uint16_t *data16;
968 	int i, count, ioc_sz, residual;
969 	int sleep_flags = CAN_SLEEP;
970 
971 	if (curthread->td_no_sleeping != 0)
972 		sleep_flags = NO_SLEEP;
973 
974 	/* Step 1 */
975 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
976 
977 	/* Step 2 */
978 	if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
979 		return (EBUSY);
980 
981 	/* Step 3
982 	 * Announce that a message is coming through the doorbell.  Messages
983 	 * are pushed at 32bit words, so round up if needed.
984 	 */
985 	count = (req_sz + 3) / 4;
986 	mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
987 	    (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
988 	    (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
989 
990 	/* Step 4 */
991 	if (mps_wait_db_int(sc) ||
992 	    (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
993 		mps_dprint(sc, MPS_FAULT, "Doorbell failed to activate\n");
994 		return (ENXIO);
995 	}
996 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
997 	if (mps_wait_db_ack(sc, 5, sleep_flags) != 0) {
998 		mps_dprint(sc, MPS_FAULT, "Doorbell handshake failed\n");
999 		return (ENXIO);
1000 	}
1001 
1002 	/* Step 5 */
1003 	/* Clock out the message data synchronously in 32-bit dwords*/
1004 	data32 = (uint32_t *)req;
1005 	for (i = 0; i < count; i++) {
1006 		mps_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
1007 		if (mps_wait_db_ack(sc, 5, sleep_flags) != 0) {
1008 			mps_dprint(sc, MPS_FAULT,
1009 			    "Timeout while writing doorbell\n");
1010 			return (ENXIO);
1011 		}
1012 	}
1013 
1014 	/* Step 6 */
1015 	/* Clock in the reply in 16-bit words.  The total length of the
1016 	 * message is always in the 4th byte, so clock out the first 2 words
1017 	 * manually, then loop the rest.
1018 	 */
1019 	data16 = (uint16_t *)reply;
1020 	if (mps_wait_db_int(sc) != 0) {
1021 		mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 0\n");
1022 		return (ENXIO);
1023 	}
1024 	data16[0] =
1025 	    mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
1026 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1027 	if (mps_wait_db_int(sc) != 0) {
1028 		mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 1\n");
1029 		return (ENXIO);
1030 	}
1031 	data16[1] =
1032 	    mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
1033 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1034 
1035 	/* Number of 32bit words in the message */
1036 	ioc_sz = reply->MsgLength;
1037 
1038 	/*
1039 	 * Figure out how many 16bit words to clock in without overrunning.
1040 	 * The precision loss with dividing reply_sz can safely be
1041 	 * ignored because the messages can only be multiples of 32bits.
1042 	 */
1043 	residual = 0;
1044 	count = MIN((reply_sz / 4), ioc_sz) * 2;
1045 	if (count < ioc_sz * 2) {
1046 		residual = ioc_sz * 2 - count;
1047 		mps_dprint(sc, MPS_ERROR, "Driver error, throwing away %d "
1048 		    "residual message words\n", residual);
1049 	}
1050 
1051 	for (i = 2; i < count; i++) {
1052 		if (mps_wait_db_int(sc) != 0) {
1053 			mps_dprint(sc, MPS_FAULT,
1054 			    "Timeout reading doorbell %d\n", i);
1055 			return (ENXIO);
1056 		}
1057 		data16[i] = mps_regread(sc, MPI2_DOORBELL_OFFSET) &
1058 		    MPI2_DOORBELL_DATA_MASK;
1059 		mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1060 	}
1061 
1062 	/*
1063 	 * Pull out residual words that won't fit into the provided buffer.
1064 	 * This keeps the chip from hanging due to a driver programming
1065 	 * error.
1066 	 */
1067 	while (residual--) {
1068 		if (mps_wait_db_int(sc) != 0) {
1069 			mps_dprint(sc, MPS_FAULT,
1070 			    "Timeout reading doorbell\n");
1071 			return (ENXIO);
1072 		}
1073 		(void)mps_regread(sc, MPI2_DOORBELL_OFFSET);
1074 		mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1075 	}
1076 
1077 	/* Step 7 */
1078 	if (mps_wait_db_int(sc) != 0) {
1079 		mps_dprint(sc, MPS_FAULT, "Timeout waiting to exit doorbell\n");
1080 		return (ENXIO);
1081 	}
1082 	if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
1083 		mps_dprint(sc, MPS_FAULT, "Warning, doorbell still active\n");
1084 	mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1085 
1086 	return (0);
1087 }
1088 
1089 static void
1090 mps_enqueue_request(struct mps_softc *sc, struct mps_command *cm)
1091 {
1092 	reply_descriptor rd;
1093 	MPS_FUNCTRACE(sc);
1094 	mps_dprint(sc, MPS_TRACE, "SMID %u cm %p ccb %p\n",
1095 	    cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
1096 
1097 	if (sc->mps_flags & MPS_FLAGS_ATTACH_DONE && !(sc->mps_flags & MPS_FLAGS_SHUTDOWN))
1098 		mtx_assert(&sc->mps_mtx, MA_OWNED);
1099 
1100 	if (++sc->io_cmds_active > sc->io_cmds_highwater)
1101 		sc->io_cmds_highwater++;
1102 	rd.u.low = cm->cm_desc.Words.Low;
1103 	rd.u.high = cm->cm_desc.Words.High;
1104 	rd.word = htole64(rd.word);
1105 
1106 	KASSERT(cm->cm_state == MPS_CM_STATE_BUSY, ("command not busy\n"));
1107 	cm->cm_state = MPS_CM_STATE_INQUEUE;
1108 
1109 	/* TODO-We may need to make below regwrite atomic */
1110 	mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
1111 	    rd.u.low);
1112 	mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
1113 	    rd.u.high);
1114 }
1115 
1116 /*
1117  * Just the FACTS, ma'am.
1118  */
1119 static int
1120 mps_get_iocfacts(struct mps_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
1121 {
1122 	MPI2_DEFAULT_REPLY *reply;
1123 	MPI2_IOC_FACTS_REQUEST request;
1124 	int error, req_sz, reply_sz;
1125 
1126 	MPS_FUNCTRACE(sc);
1127 	mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1128 
1129 	req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
1130 	reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
1131 	reply = (MPI2_DEFAULT_REPLY *)facts;
1132 
1133 	bzero(&request, req_sz);
1134 	request.Function = MPI2_FUNCTION_IOC_FACTS;
1135 	error = mps_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
1136 	mps_dprint(sc, MPS_INIT, "%s exit error= %d\n", __func__, error);
1137 
1138 	return (error);
1139 }
1140 
1141 static int
1142 mps_send_iocinit(struct mps_softc *sc)
1143 {
1144 	MPI2_IOC_INIT_REQUEST	init;
1145 	MPI2_DEFAULT_REPLY	reply;
1146 	int req_sz, reply_sz, error;
1147 	struct timeval now;
1148 	uint64_t time_in_msec;
1149 
1150 	MPS_FUNCTRACE(sc);
1151 	mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1152 
1153 	/* Do a quick sanity check on proper initialization */
1154 	if ((sc->pqdepth == 0) || (sc->fqdepth == 0) || (sc->reqframesz == 0)
1155 	    || (sc->replyframesz == 0)) {
1156 		mps_dprint(sc, MPS_INIT|MPS_ERROR,
1157 		    "Driver not fully initialized for IOCInit\n");
1158 		return (EINVAL);
1159 	}
1160 
1161 	req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
1162 	reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
1163 	bzero(&init, req_sz);
1164 	bzero(&reply, reply_sz);
1165 
1166 	/*
1167 	 * Fill in the init block.  Note that most addresses are
1168 	 * deliberately in the lower 32bits of memory.  This is a micro-
1169 	 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
1170 	 */
1171 	init.Function = MPI2_FUNCTION_IOC_INIT;
1172 	init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
1173 	init.MsgVersion = htole16(MPI2_VERSION);
1174 	init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
1175 	init.SystemRequestFrameSize = htole16((uint16_t)(sc->reqframesz / 4));
1176 	init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
1177 	init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
1178 	init.SenseBufferAddressHigh = 0;
1179 	init.SystemReplyAddressHigh = 0;
1180 	init.SystemRequestFrameBaseAddress.High = 0;
1181 	init.SystemRequestFrameBaseAddress.Low = htole32((uint32_t)sc->req_busaddr);
1182 	init.ReplyDescriptorPostQueueAddress.High = 0;
1183 	init.ReplyDescriptorPostQueueAddress.Low = htole32((uint32_t)sc->post_busaddr);
1184 	init.ReplyFreeQueueAddress.High = 0;
1185 	init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
1186 	getmicrotime(&now);
1187 	time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
1188 	init.TimeStamp.High = htole32((time_in_msec >> 32) & 0xFFFFFFFF);
1189 	init.TimeStamp.Low = htole32(time_in_msec & 0xFFFFFFFF);
1190 
1191 	error = mps_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
1192 	if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1193 		error = ENXIO;
1194 
1195 	mps_dprint(sc, MPS_INIT, "IOCInit status= 0x%x\n", reply.IOCStatus);
1196 	mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
1197 	return (error);
1198 }
1199 
1200 void
1201 mps_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1202 {
1203 	bus_addr_t *addr;
1204 
1205 	addr = arg;
1206 	*addr = segs[0].ds_addr;
1207 }
1208 
1209 void
1210 mps_memaddr_wait_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1211 {
1212 	struct mps_busdma_context *ctx;
1213 	int need_unload, need_free;
1214 
1215 	ctx = (struct mps_busdma_context *)arg;
1216 	need_unload = 0;
1217 	need_free = 0;
1218 
1219 	mps_lock(ctx->softc);
1220 	ctx->error = error;
1221 	ctx->completed = 1;
1222 	if ((error == 0) && (ctx->abandoned == 0)) {
1223 		*ctx->addr = segs[0].ds_addr;
1224 	} else {
1225 		if (nsegs != 0)
1226 			need_unload = 1;
1227 		if (ctx->abandoned != 0)
1228 			need_free = 1;
1229 	}
1230 	if (need_free == 0)
1231 		wakeup(ctx);
1232 
1233 	mps_unlock(ctx->softc);
1234 
1235 	if (need_unload != 0) {
1236 		bus_dmamap_unload(ctx->buffer_dmat,
1237 				  ctx->buffer_dmamap);
1238 		*ctx->addr = 0;
1239 	}
1240 
1241 	if (need_free != 0)
1242 		free(ctx, M_MPSUSER);
1243 }
1244 
1245 static int
1246 mps_alloc_queues(struct mps_softc *sc)
1247 {
1248 	struct mps_queue *q;
1249 	u_int nq, i;
1250 
1251 	nq = sc->msi_msgs;
1252 	mps_dprint(sc, MPS_INIT|MPS_XINFO, "Allocating %d I/O queues\n", nq);
1253 
1254 	sc->queues = malloc(sizeof(struct mps_queue) * nq, M_MPT2,
1255 	    M_NOWAIT|M_ZERO);
1256 	if (sc->queues == NULL)
1257 		return (ENOMEM);
1258 
1259 	for (i = 0; i < nq; i++) {
1260 		q = &sc->queues[i];
1261 		mps_dprint(sc, MPS_INIT, "Configuring queue %d %p\n", i, q);
1262 		q->sc = sc;
1263 		q->qnum = i;
1264 	}
1265 
1266 	return (0);
1267 }
1268 
1269 static int
1270 mps_alloc_hw_queues(struct mps_softc *sc)
1271 {
1272 	bus_addr_t queues_busaddr;
1273 	uint8_t *queues;
1274 	int qsize, fqsize, pqsize;
1275 
1276 	/*
1277 	 * The reply free queue contains 4 byte entries in multiples of 16 and
1278 	 * aligned on a 16 byte boundary. There must always be an unused entry.
1279 	 * This queue supplies fresh reply frames for the firmware to use.
1280 	 *
1281 	 * The reply descriptor post queue contains 8 byte entries in
1282 	 * multiples of 16 and aligned on a 16 byte boundary.  This queue
1283 	 * contains filled-in reply frames sent from the firmware to the host.
1284 	 *
1285 	 * These two queues are allocated together for simplicity.
1286 	 */
1287 	sc->fqdepth = roundup2(sc->num_replies + 1, 16);
1288 	sc->pqdepth = roundup2(sc->num_replies + 1, 16);
1289 	fqsize= sc->fqdepth * 4;
1290 	pqsize = sc->pqdepth * 8;
1291 	qsize = fqsize + pqsize;
1292 
1293         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1294 				16, 0,			/* algnmnt, boundary */
1295 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1296 				BUS_SPACE_MAXADDR,	/* highaddr */
1297 				NULL, NULL,		/* filter, filterarg */
1298                                 qsize,			/* maxsize */
1299                                 1,			/* nsegments */
1300                                 qsize,			/* maxsegsize */
1301                                 0,			/* flags */
1302                                 NULL, NULL,		/* lockfunc, lockarg */
1303                                 &sc->queues_dmat)) {
1304 		mps_dprint(sc, MPS_ERROR, "Cannot allocate queues DMA tag\n");
1305 		return (ENOMEM);
1306         }
1307         if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
1308 	    &sc->queues_map)) {
1309 		mps_dprint(sc, MPS_ERROR, "Cannot allocate queues memory\n");
1310 		return (ENOMEM);
1311         }
1312         bzero(queues, qsize);
1313         bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
1314 	    mps_memaddr_cb, &queues_busaddr, 0);
1315 
1316 	sc->free_queue = (uint32_t *)queues;
1317 	sc->free_busaddr = queues_busaddr;
1318 	sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
1319 	sc->post_busaddr = queues_busaddr + fqsize;
1320 	mps_dprint(sc, MPS_INIT, "free queue busaddr= %#016jx size= %d\n",
1321 	    (uintmax_t)sc->free_busaddr, fqsize);
1322 	mps_dprint(sc, MPS_INIT, "reply queue busaddr= %#016jx size= %d\n",
1323 	    (uintmax_t)sc->post_busaddr, pqsize);
1324 
1325 	return (0);
1326 }
1327 
1328 static int
1329 mps_alloc_replies(struct mps_softc *sc)
1330 {
1331 	int rsize, num_replies;
1332 
1333 	/* Store the reply frame size in bytes rather than as 32bit words */
1334 	sc->replyframesz = sc->facts->ReplyFrameSize * 4;
1335 
1336 	/*
1337 	 * sc->num_replies should be one less than sc->fqdepth.  We need to
1338 	 * allocate space for sc->fqdepth replies, but only sc->num_replies
1339 	 * replies can be used at once.
1340 	 */
1341 	num_replies = max(sc->fqdepth, sc->num_replies);
1342 
1343 	rsize = sc->replyframesz * num_replies;
1344         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1345 				4, 0,			/* algnmnt, boundary */
1346 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1347 				BUS_SPACE_MAXADDR,	/* highaddr */
1348 				NULL, NULL,		/* filter, filterarg */
1349                                 rsize,			/* maxsize */
1350                                 1,			/* nsegments */
1351                                 rsize,			/* maxsegsize */
1352                                 0,			/* flags */
1353                                 NULL, NULL,		/* lockfunc, lockarg */
1354                                 &sc->reply_dmat)) {
1355 		mps_dprint(sc, MPS_ERROR, "Cannot allocate replies DMA tag\n");
1356 		return (ENOMEM);
1357         }
1358         if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
1359 	    BUS_DMA_NOWAIT, &sc->reply_map)) {
1360 		mps_dprint(sc, MPS_ERROR, "Cannot allocate replies memory\n");
1361 		return (ENOMEM);
1362         }
1363         bzero(sc->reply_frames, rsize);
1364         bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
1365 	    mps_memaddr_cb, &sc->reply_busaddr, 0);
1366 
1367 	mps_dprint(sc, MPS_INIT, "reply frames busaddr= %#016jx size= %d\n",
1368 	    (uintmax_t)sc->reply_busaddr, rsize);
1369 
1370 	return (0);
1371 }
1372 
1373 static int
1374 mps_alloc_requests(struct mps_softc *sc)
1375 {
1376 	struct mps_command *cm;
1377 	struct mps_chain *chain;
1378 	int i, rsize, nsegs;
1379 
1380 	rsize = sc->reqframesz * sc->num_reqs;
1381         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1382 				16, 0,			/* algnmnt, boundary */
1383 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1384 				BUS_SPACE_MAXADDR,	/* highaddr */
1385 				NULL, NULL,		/* filter, filterarg */
1386                                 rsize,			/* maxsize */
1387                                 1,			/* nsegments */
1388                                 rsize,			/* maxsegsize */
1389                                 0,			/* flags */
1390                                 NULL, NULL,		/* lockfunc, lockarg */
1391                                 &sc->req_dmat)) {
1392 		mps_dprint(sc, MPS_ERROR, "Cannot allocate request DMA tag\n");
1393 		return (ENOMEM);
1394         }
1395         if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
1396 	    BUS_DMA_NOWAIT, &sc->req_map)) {
1397 		mps_dprint(sc, MPS_ERROR, "Cannot allocate request memory\n");
1398 		return (ENOMEM);
1399         }
1400         bzero(sc->req_frames, rsize);
1401         bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
1402 	    mps_memaddr_cb, &sc->req_busaddr, 0);
1403 	mps_dprint(sc, MPS_INIT, "request frames busaddr= %#016jx size= %d\n",
1404 	    (uintmax_t)sc->req_busaddr, rsize);
1405 
1406 	rsize = sc->reqframesz * sc->num_chains;
1407         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1408 				16, 0,			/* algnmnt, boundary */
1409 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1410 				BUS_SPACE_MAXADDR,	/* highaddr */
1411 				NULL, NULL,		/* filter, filterarg */
1412                                 rsize,			/* maxsize */
1413                                 1,			/* nsegments */
1414                                 rsize,			/* maxsegsize */
1415                                 0,			/* flags */
1416                                 NULL, NULL,		/* lockfunc, lockarg */
1417                                 &sc->chain_dmat)) {
1418 		mps_dprint(sc, MPS_ERROR, "Cannot allocate chain DMA tag\n");
1419 		return (ENOMEM);
1420         }
1421         if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
1422 	    BUS_DMA_NOWAIT, &sc->chain_map)) {
1423 		mps_dprint(sc, MPS_ERROR, "Cannot allocate chain memory\n");
1424 		return (ENOMEM);
1425         }
1426         bzero(sc->chain_frames, rsize);
1427         bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
1428 	    mps_memaddr_cb, &sc->chain_busaddr, 0);
1429 	mps_dprint(sc, MPS_INIT, "chain frames busaddr= %#016jx size= %d\n",
1430 	    (uintmax_t)sc->chain_busaddr, rsize);
1431 
1432 	rsize = MPS_SENSE_LEN * sc->num_reqs;
1433         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1434 				1, 0,			/* algnmnt, boundary */
1435 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1436 				BUS_SPACE_MAXADDR,	/* highaddr */
1437 				NULL, NULL,		/* filter, filterarg */
1438                                 rsize,			/* maxsize */
1439                                 1,			/* nsegments */
1440                                 rsize,			/* maxsegsize */
1441                                 0,			/* flags */
1442                                 NULL, NULL,		/* lockfunc, lockarg */
1443                                 &sc->sense_dmat)) {
1444 		mps_dprint(sc, MPS_ERROR, "Cannot allocate sense DMA tag\n");
1445 		return (ENOMEM);
1446         }
1447         if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
1448 	    BUS_DMA_NOWAIT, &sc->sense_map)) {
1449 		mps_dprint(sc, MPS_ERROR, "Cannot allocate sense memory\n");
1450 		return (ENOMEM);
1451         }
1452         bzero(sc->sense_frames, rsize);
1453         bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
1454 	    mps_memaddr_cb, &sc->sense_busaddr, 0);
1455 	mps_dprint(sc, MPS_INIT, "sense frames busaddr= %#016jx size= %d\n",
1456 	    (uintmax_t)sc->sense_busaddr, rsize);
1457 
1458 	sc->chains = malloc(sizeof(struct mps_chain) * sc->num_chains, M_MPT2,
1459 	    M_WAITOK | M_ZERO);
1460 	if(!sc->chains) {
1461 		mps_dprint(sc, MPS_ERROR, "Cannot allocate chains memory\n");
1462 		return (ENOMEM);
1463 	}
1464 	for (i = 0; i < sc->num_chains; i++) {
1465 		chain = &sc->chains[i];
1466 		chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
1467 		    i * sc->reqframesz);
1468 		chain->chain_busaddr = sc->chain_busaddr +
1469 		    i * sc->reqframesz;
1470 		mps_free_chain(sc, chain);
1471 		sc->chain_free_lowwater++;
1472 	}
1473 
1474 	nsegs = (sc->maxio / PAGE_SIZE) + 1;
1475         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1476 				1, 0,			/* algnmnt, boundary */
1477 				BUS_SPACE_MAXADDR,	/* lowaddr */
1478 				BUS_SPACE_MAXADDR,	/* highaddr */
1479 				NULL, NULL,		/* filter, filterarg */
1480                                 BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1481                                 nsegs,			/* nsegments */
1482                                 BUS_SPACE_MAXSIZE_24BIT,/* maxsegsize */
1483                                 BUS_DMA_ALLOCNOW,	/* flags */
1484                                 busdma_lock_mutex,	/* lockfunc */
1485 				&sc->mps_mtx,		/* lockarg */
1486                                 &sc->buffer_dmat)) {
1487 		mps_dprint(sc, MPS_ERROR, "Cannot allocate buffer DMA tag\n");
1488 		return (ENOMEM);
1489         }
1490 
1491 	/*
1492 	 * SMID 0 cannot be used as a free command per the firmware spec.
1493 	 * Just drop that command instead of risking accounting bugs.
1494 	 */
1495 	sc->commands = malloc(sizeof(struct mps_command) * sc->num_reqs,
1496 	    M_MPT2, M_WAITOK | M_ZERO);
1497 	if(!sc->commands) {
1498 		mps_dprint(sc, MPS_ERROR, "Cannot allocate command memory\n");
1499 		return (ENOMEM);
1500 	}
1501 	for (i = 1; i < sc->num_reqs; i++) {
1502 		cm = &sc->commands[i];
1503 		cm->cm_req = sc->req_frames + i * sc->reqframesz;
1504 		cm->cm_req_busaddr = sc->req_busaddr + i * sc->reqframesz;
1505 		cm->cm_sense = &sc->sense_frames[i];
1506 		cm->cm_sense_busaddr = sc->sense_busaddr + i * MPS_SENSE_LEN;
1507 		cm->cm_desc.Default.SMID = i;
1508 		cm->cm_sc = sc;
1509 		cm->cm_state = MPS_CM_STATE_BUSY;
1510 		TAILQ_INIT(&cm->cm_chain_list);
1511 		callout_init_mtx(&cm->cm_callout, &sc->mps_mtx, 0);
1512 
1513 		/* XXX Is a failure here a critical problem? */
1514 		if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap) == 0)
1515 			if (i <= sc->num_prireqs)
1516 				mps_free_high_priority_command(sc, cm);
1517 			else
1518 				mps_free_command(sc, cm);
1519 		else {
1520 			panic("failed to allocate command %d\n", i);
1521 			sc->num_reqs = i;
1522 			break;
1523 		}
1524 	}
1525 
1526 	return (0);
1527 }
1528 
1529 static int
1530 mps_init_queues(struct mps_softc *sc)
1531 {
1532 	int i;
1533 
1534 	memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
1535 
1536 	/*
1537 	 * According to the spec, we need to use one less reply than we
1538 	 * have space for on the queue.  So sc->num_replies (the number we
1539 	 * use) should be less than sc->fqdepth (allocated size).
1540 	 */
1541 	if (sc->num_replies >= sc->fqdepth)
1542 		return (EINVAL);
1543 
1544 	/*
1545 	 * Initialize all of the free queue entries.
1546 	 */
1547 	for (i = 0; i < sc->fqdepth; i++)
1548 		sc->free_queue[i] = sc->reply_busaddr + (i * sc->replyframesz);
1549 	sc->replyfreeindex = sc->num_replies;
1550 
1551 	return (0);
1552 }
1553 
1554 /* Get the driver parameter tunables.  Lowest priority are the driver defaults.
1555  * Next are the global settings, if they exist.  Highest are the per-unit
1556  * settings, if they exist.
1557  */
1558 void
1559 mps_get_tunables(struct mps_softc *sc)
1560 {
1561 	char tmpstr[80], mps_debug[80];
1562 
1563 	/* XXX default to some debugging for now */
1564 	sc->mps_debug = MPS_INFO|MPS_FAULT;
1565 	sc->disable_msix = 0;
1566 	sc->disable_msi = 0;
1567 	sc->max_msix = MPS_MSIX_MAX;
1568 	sc->max_chains = MPS_CHAIN_FRAMES;
1569 	sc->max_io_pages = MPS_MAXIO_PAGES;
1570 	sc->enable_ssu = MPS_SSU_ENABLE_SSD_DISABLE_HDD;
1571 	sc->spinup_wait_time = DEFAULT_SPINUP_WAIT;
1572 	sc->use_phynum = 1;
1573 	sc->max_reqframes = MPS_REQ_FRAMES;
1574 	sc->max_prireqframes = MPS_PRI_REQ_FRAMES;
1575 	sc->max_replyframes = MPS_REPLY_FRAMES;
1576 	sc->max_evtframes = MPS_EVT_REPLY_FRAMES;
1577 
1578 	/*
1579 	 * Grab the global variables.
1580 	 */
1581 	bzero(mps_debug, 80);
1582 	if (TUNABLE_STR_FETCH("hw.mps.debug_level", mps_debug, 80) != 0)
1583 		mps_parse_debug(sc, mps_debug);
1584 	TUNABLE_INT_FETCH("hw.mps.disable_msix", &sc->disable_msix);
1585 	TUNABLE_INT_FETCH("hw.mps.disable_msi", &sc->disable_msi);
1586 	TUNABLE_INT_FETCH("hw.mps.max_msix", &sc->max_msix);
1587 	TUNABLE_INT_FETCH("hw.mps.max_chains", &sc->max_chains);
1588 	TUNABLE_INT_FETCH("hw.mps.max_io_pages", &sc->max_io_pages);
1589 	TUNABLE_INT_FETCH("hw.mps.enable_ssu", &sc->enable_ssu);
1590 	TUNABLE_INT_FETCH("hw.mps.spinup_wait_time", &sc->spinup_wait_time);
1591 	TUNABLE_INT_FETCH("hw.mps.use_phy_num", &sc->use_phynum);
1592 	TUNABLE_INT_FETCH("hw.mps.max_reqframes", &sc->max_reqframes);
1593 	TUNABLE_INT_FETCH("hw.mps.max_prireqframes", &sc->max_prireqframes);
1594 	TUNABLE_INT_FETCH("hw.mps.max_replyframes", &sc->max_replyframes);
1595 	TUNABLE_INT_FETCH("hw.mps.max_evtframes", &sc->max_evtframes);
1596 
1597 	/* Grab the unit-instance variables */
1598 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.debug_level",
1599 	    device_get_unit(sc->mps_dev));
1600 	bzero(mps_debug, 80);
1601 	if (TUNABLE_STR_FETCH(tmpstr, mps_debug, 80) != 0)
1602 		mps_parse_debug(sc, mps_debug);
1603 
1604 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.disable_msix",
1605 	    device_get_unit(sc->mps_dev));
1606 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1607 
1608 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.disable_msi",
1609 	    device_get_unit(sc->mps_dev));
1610 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1611 
1612 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_msix",
1613 	    device_get_unit(sc->mps_dev));
1614 	TUNABLE_INT_FETCH(tmpstr, &sc->max_msix);
1615 
1616 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_chains",
1617 	    device_get_unit(sc->mps_dev));
1618 	TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1619 
1620 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_io_pages",
1621 	    device_get_unit(sc->mps_dev));
1622 	TUNABLE_INT_FETCH(tmpstr, &sc->max_io_pages);
1623 
1624 	bzero(sc->exclude_ids, sizeof(sc->exclude_ids));
1625 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.exclude_ids",
1626 	    device_get_unit(sc->mps_dev));
1627 	TUNABLE_STR_FETCH(tmpstr, sc->exclude_ids, sizeof(sc->exclude_ids));
1628 
1629 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.enable_ssu",
1630 	    device_get_unit(sc->mps_dev));
1631 	TUNABLE_INT_FETCH(tmpstr, &sc->enable_ssu);
1632 
1633 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.spinup_wait_time",
1634 	    device_get_unit(sc->mps_dev));
1635 	TUNABLE_INT_FETCH(tmpstr, &sc->spinup_wait_time);
1636 
1637 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.use_phy_num",
1638 	    device_get_unit(sc->mps_dev));
1639 	TUNABLE_INT_FETCH(tmpstr, &sc->use_phynum);
1640 
1641 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_reqframes",
1642 	    device_get_unit(sc->mps_dev));
1643 	TUNABLE_INT_FETCH(tmpstr, &sc->max_reqframes);
1644 
1645 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_prireqframes",
1646 	    device_get_unit(sc->mps_dev));
1647 	TUNABLE_INT_FETCH(tmpstr, &sc->max_prireqframes);
1648 
1649 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_replyframes",
1650 	    device_get_unit(sc->mps_dev));
1651 	TUNABLE_INT_FETCH(tmpstr, &sc->max_replyframes);
1652 
1653 	snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_evtframes",
1654 	    device_get_unit(sc->mps_dev));
1655 	TUNABLE_INT_FETCH(tmpstr, &sc->max_evtframes);
1656 
1657 }
1658 
1659 static void
1660 mps_setup_sysctl(struct mps_softc *sc)
1661 {
1662 	struct sysctl_ctx_list	*sysctl_ctx = NULL;
1663 	struct sysctl_oid	*sysctl_tree = NULL;
1664 	char tmpstr[80], tmpstr2[80];
1665 
1666 	/*
1667 	 * Setup the sysctl variable so the user can change the debug level
1668 	 * on the fly.
1669 	 */
1670 	snprintf(tmpstr, sizeof(tmpstr), "MPS controller %d",
1671 	    device_get_unit(sc->mps_dev));
1672 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mps_dev));
1673 
1674 	sysctl_ctx = device_get_sysctl_ctx(sc->mps_dev);
1675 	if (sysctl_ctx != NULL)
1676 		sysctl_tree = device_get_sysctl_tree(sc->mps_dev);
1677 
1678 	if (sysctl_tree == NULL) {
1679 		sysctl_ctx_init(&sc->sysctl_ctx);
1680 		sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1681 		    SYSCTL_STATIC_CHILDREN(_hw_mps), OID_AUTO, tmpstr2,
1682 		    CTLFLAG_RD, 0, tmpstr);
1683 		if (sc->sysctl_tree == NULL)
1684 			return;
1685 		sysctl_ctx = &sc->sysctl_ctx;
1686 		sysctl_tree = sc->sysctl_tree;
1687 	}
1688 
1689 	SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1690 	    OID_AUTO, "debug_level", CTLTYPE_STRING | CTLFLAG_RW |CTLFLAG_MPSAFE,
1691 	    sc, 0, mps_debug_sysctl, "A", "mps debug level");
1692 
1693 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1694 	    OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1695 	    "Disable the use of MSI-X interrupts");
1696 
1697 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1698 	    OID_AUTO, "disable_msi", CTLFLAG_RD, &sc->disable_msi, 0,
1699 	    "Disable the use of MSI interrupts");
1700 
1701 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1702 	    OID_AUTO, "max_msix", CTLFLAG_RD, &sc->max_msix, 0,
1703 	    "User-defined maximum number of MSIX queues");
1704 
1705 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1706 	    OID_AUTO, "msix_msgs", CTLFLAG_RD, &sc->msi_msgs, 0,
1707 	    "Negotiated number of MSIX queues");
1708 
1709 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1710 	    OID_AUTO, "max_reqframes", CTLFLAG_RD, &sc->max_reqframes, 0,
1711 	    "Total number of allocated request frames");
1712 
1713 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1714 	    OID_AUTO, "max_prireqframes", CTLFLAG_RD, &sc->max_prireqframes, 0,
1715 	    "Total number of allocated high priority request frames");
1716 
1717 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1718 	    OID_AUTO, "max_replyframes", CTLFLAG_RD, &sc->max_replyframes, 0,
1719 	    "Total number of allocated reply frames");
1720 
1721 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1722 	    OID_AUTO, "max_evtframes", CTLFLAG_RD, &sc->max_evtframes, 0,
1723 	    "Total number of event frames allocated");
1724 
1725 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1726 	    OID_AUTO, "firmware_version", CTLFLAG_RW, sc->fw_version,
1727 	    strlen(sc->fw_version), "firmware version");
1728 
1729 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1730 	    OID_AUTO, "driver_version", CTLFLAG_RW, MPS_DRIVER_VERSION,
1731 	    strlen(MPS_DRIVER_VERSION), "driver version");
1732 
1733 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1734 	    OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1735 	    &sc->io_cmds_active, 0, "number of currently active commands");
1736 
1737 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1738 	    OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1739 	    &sc->io_cmds_highwater, 0, "maximum active commands seen");
1740 
1741 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1742 	    OID_AUTO, "chain_free", CTLFLAG_RD,
1743 	    &sc->chain_free, 0, "number of free chain elements");
1744 
1745 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1746 	    OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1747 	    &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1748 
1749 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1750 	    OID_AUTO, "max_chains", CTLFLAG_RD,
1751 	    &sc->max_chains, 0,"maximum chain frames that will be allocated");
1752 
1753 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1754 	    OID_AUTO, "max_io_pages", CTLFLAG_RD,
1755 	    &sc->max_io_pages, 0,"maximum pages to allow per I/O (if <1 use "
1756 	    "IOCFacts)");
1757 
1758 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1759 	    OID_AUTO, "enable_ssu", CTLFLAG_RW, &sc->enable_ssu, 0,
1760 	    "enable SSU to SATA SSD/HDD at shutdown");
1761 
1762 	SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1763 	    OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1764 	    &sc->chain_alloc_fail, "chain allocation failures");
1765 
1766 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1767 	    OID_AUTO, "spinup_wait_time", CTLFLAG_RD,
1768 	    &sc->spinup_wait_time, DEFAULT_SPINUP_WAIT, "seconds to wait for "
1769 	    "spinup after SATA ID error");
1770 
1771 	SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1772 	    OID_AUTO, "mapping_table_dump", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
1773 	    mps_mapping_dump, "A", "Mapping Table Dump");
1774 
1775 	SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1776 	    OID_AUTO, "encl_table_dump", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
1777 	    mps_mapping_encl_dump, "A", "Enclosure Table Dump");
1778 
1779 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1780 	    OID_AUTO, "use_phy_num", CTLFLAG_RD, &sc->use_phynum, 0,
1781 	    "Use the phy number for enumeration");
1782 }
1783 
1784 static struct mps_debug_string {
1785 	char	*name;
1786 	int	flag;
1787 } mps_debug_strings[] = {
1788 	{"info", MPS_INFO},
1789 	{"fault", MPS_FAULT},
1790 	{"event", MPS_EVENT},
1791 	{"log", MPS_LOG},
1792 	{"recovery", MPS_RECOVERY},
1793 	{"error", MPS_ERROR},
1794 	{"init", MPS_INIT},
1795 	{"xinfo", MPS_XINFO},
1796 	{"user", MPS_USER},
1797 	{"mapping", MPS_MAPPING},
1798 	{"trace", MPS_TRACE}
1799 };
1800 
1801 enum mps_debug_level_combiner {
1802 	COMB_NONE,
1803 	COMB_ADD,
1804 	COMB_SUB
1805 };
1806 
1807 static int
1808 mps_debug_sysctl(SYSCTL_HANDLER_ARGS)
1809 {
1810 	struct mps_softc *sc;
1811 	struct mps_debug_string *string;
1812 	struct sbuf *sbuf;
1813 	char *buffer;
1814 	size_t sz;
1815 	int i, len, debug, error;
1816 
1817 	sc = (struct mps_softc *)arg1;
1818 
1819 	error = sysctl_wire_old_buffer(req, 0);
1820 	if (error != 0)
1821 		return (error);
1822 
1823 	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
1824 	debug = sc->mps_debug;
1825 
1826 	sbuf_printf(sbuf, "%#x", debug);
1827 
1828 	sz = sizeof(mps_debug_strings) / sizeof(mps_debug_strings[0]);
1829 	for (i = 0; i < sz; i++) {
1830 		string = &mps_debug_strings[i];
1831 		if (debug & string->flag)
1832 			sbuf_printf(sbuf, ",%s", string->name);
1833 	}
1834 
1835 	error = sbuf_finish(sbuf);
1836 	sbuf_delete(sbuf);
1837 
1838 	if (error || req->newptr == NULL)
1839 		return (error);
1840 
1841 	len = req->newlen - req->newidx;
1842 	if (len == 0)
1843 		return (0);
1844 
1845 	buffer = malloc(len, M_MPT2, M_ZERO|M_WAITOK);
1846 	error = SYSCTL_IN(req, buffer, len);
1847 
1848 	mps_parse_debug(sc, buffer);
1849 
1850 	free(buffer, M_MPT2);
1851 	return (error);
1852 }
1853 
1854 static void
1855 mps_parse_debug(struct mps_softc *sc, char *list)
1856 {
1857 	struct mps_debug_string *string;
1858 	enum mps_debug_level_combiner op;
1859 	char *token, *endtoken;
1860 	size_t sz;
1861 	int flags, i;
1862 
1863 	if (list == NULL || *list == '\0')
1864 		return;
1865 
1866 	if (*list == '+') {
1867 		op = COMB_ADD;
1868 		list++;
1869 	} else if (*list == '-') {
1870 		op = COMB_SUB;
1871 		list++;
1872 	} else
1873 		op = COMB_NONE;
1874 	if (*list == '\0')
1875 		return;
1876 
1877 	flags = 0;
1878 	sz = sizeof(mps_debug_strings) / sizeof(mps_debug_strings[0]);
1879 	while ((token = strsep(&list, ":,")) != NULL) {
1880 
1881 		/* Handle integer flags */
1882 		flags |= strtol(token, &endtoken, 0);
1883 		if (token != endtoken)
1884 			continue;
1885 
1886 		/* Handle text flags */
1887 		for (i = 0; i < sz; i++) {
1888 			string = &mps_debug_strings[i];
1889 			if (strcasecmp(token, string->name) == 0) {
1890 				flags |= string->flag;
1891 				break;
1892 			}
1893 		}
1894 	}
1895 
1896 	switch (op) {
1897 	case COMB_NONE:
1898 		sc->mps_debug = flags;
1899 		break;
1900 	case COMB_ADD:
1901 		sc->mps_debug |= flags;
1902 		break;
1903 	case COMB_SUB:
1904 		sc->mps_debug &= (~flags);
1905 		break;
1906 	}
1907 
1908 	return;
1909 }
1910 
1911 int
1912 mps_attach(struct mps_softc *sc)
1913 {
1914 	int error;
1915 
1916 	MPS_FUNCTRACE(sc);
1917 	mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1918 
1919 	mtx_init(&sc->mps_mtx, "MPT2SAS lock", NULL, MTX_DEF);
1920 	callout_init_mtx(&sc->periodic, &sc->mps_mtx, 0);
1921 	callout_init_mtx(&sc->device_check_callout, &sc->mps_mtx, 0);
1922 	TAILQ_INIT(&sc->event_list);
1923 	timevalclear(&sc->lastfail);
1924 
1925 	if ((error = mps_transition_ready(sc)) != 0) {
1926 		mps_dprint(sc, MPS_INIT|MPS_FAULT, "failed to transition "
1927 		    "ready\n");
1928 		return (error);
1929 	}
1930 
1931 	sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPT2,
1932 	    M_ZERO|M_NOWAIT);
1933 	if(!sc->facts) {
1934 		mps_dprint(sc, MPS_INIT|MPS_FAULT, "Cannot allocate memory, "
1935 		    "exit\n");
1936 		return (ENOMEM);
1937 	}
1938 
1939 	/*
1940 	 * Get IOC Facts and allocate all structures based on this information.
1941 	 * A Diag Reset will also call mps_iocfacts_allocate and re-read the IOC
1942 	 * Facts. If relevant values have changed in IOC Facts, this function
1943 	 * will free all of the memory based on IOC Facts and reallocate that
1944 	 * memory.  If this fails, any allocated memory should already be freed.
1945 	 */
1946 	if ((error = mps_iocfacts_allocate(sc, TRUE)) != 0) {
1947 		mps_dprint(sc, MPS_INIT|MPS_FAULT, "IOC Facts based allocation "
1948 		    "failed with error %d, exit\n", error);
1949 		return (error);
1950 	}
1951 
1952 	/* Start the periodic watchdog check on the IOC Doorbell */
1953 	mps_periodic(sc);
1954 
1955 	/*
1956 	 * The portenable will kick off discovery events that will drive the
1957 	 * rest of the initialization process.  The CAM/SAS module will
1958 	 * hold up the boot sequence until discovery is complete.
1959 	 */
1960 	sc->mps_ich.ich_func = mps_startup;
1961 	sc->mps_ich.ich_arg = sc;
1962 	if (config_intrhook_establish(&sc->mps_ich) != 0) {
1963 		mps_dprint(sc, MPS_INIT|MPS_ERROR,
1964 		    "Cannot establish MPS config hook\n");
1965 		error = EINVAL;
1966 	}
1967 
1968 	/*
1969 	 * Allow IR to shutdown gracefully when shutdown occurs.
1970 	 */
1971 	sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
1972 	    mpssas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
1973 
1974 	if (sc->shutdown_eh == NULL)
1975 		mps_dprint(sc, MPS_INIT|MPS_ERROR,
1976 		    "shutdown event registration failed\n");
1977 
1978 	mps_setup_sysctl(sc);
1979 
1980 	sc->mps_flags |= MPS_FLAGS_ATTACH_DONE;
1981 	mps_dprint(sc, MPS_INIT, "%s exit error= %d\n", __func__, error);
1982 
1983 	return (error);
1984 }
1985 
1986 /* Run through any late-start handlers. */
1987 static void
1988 mps_startup(void *arg)
1989 {
1990 	struct mps_softc *sc;
1991 
1992 	sc = (struct mps_softc *)arg;
1993 	mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1994 
1995 	mps_lock(sc);
1996 	mps_unmask_intr(sc);
1997 
1998 	/* initialize device mapping tables */
1999 	mps_base_static_config_pages(sc);
2000 	mps_mapping_initialize(sc);
2001 	mpssas_startup(sc);
2002 	mps_unlock(sc);
2003 
2004 	mps_dprint(sc, MPS_INIT, "disestablish config intrhook\n");
2005 	config_intrhook_disestablish(&sc->mps_ich);
2006 	sc->mps_ich.ich_arg = NULL;
2007 
2008 	mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
2009 }
2010 
2011 /* Periodic watchdog.  Is called with the driver lock already held. */
2012 static void
2013 mps_periodic(void *arg)
2014 {
2015 	struct mps_softc *sc;
2016 	uint32_t db;
2017 
2018 	sc = (struct mps_softc *)arg;
2019 	if (sc->mps_flags & MPS_FLAGS_SHUTDOWN)
2020 		return;
2021 
2022 	db = mps_regread(sc, MPI2_DOORBELL_OFFSET);
2023 	if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
2024 		mps_dprint(sc, MPS_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
2025 		mps_reinit(sc);
2026 	}
2027 
2028 	callout_reset(&sc->periodic, MPS_PERIODIC_DELAY * hz, mps_periodic, sc);
2029 }
2030 
2031 static void
2032 mps_log_evt_handler(struct mps_softc *sc, uintptr_t data,
2033     MPI2_EVENT_NOTIFICATION_REPLY *event)
2034 {
2035 	MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
2036 
2037 	MPS_DPRINT_EVENT(sc, generic, event);
2038 
2039 	switch (event->Event) {
2040 	case MPI2_EVENT_LOG_DATA:
2041 		mps_dprint(sc, MPS_EVENT, "MPI2_EVENT_LOG_DATA:\n");
2042 		if (sc->mps_debug & MPS_EVENT)
2043 			hexdump(event->EventData, event->EventDataLength, NULL, 0);
2044 		break;
2045 	case MPI2_EVENT_LOG_ENTRY_ADDED:
2046 		entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
2047 		mps_dprint(sc, MPS_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
2048 		    "0x%x Sequence %d:\n", entry->LogEntryQualifier,
2049 		     entry->LogSequence);
2050 		break;
2051 	default:
2052 		break;
2053 	}
2054 	return;
2055 }
2056 
2057 static int
2058 mps_attach_log(struct mps_softc *sc)
2059 {
2060 	u32 events[MPI2_EVENT_NOTIFY_EVENTMASK_WORDS];
2061 
2062 	bzero(events, 16);
2063 	setbit(events, MPI2_EVENT_LOG_DATA);
2064 	setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
2065 
2066 	mps_register_events(sc, events, mps_log_evt_handler, NULL,
2067 	    &sc->mps_log_eh);
2068 
2069 	return (0);
2070 }
2071 
2072 static int
2073 mps_detach_log(struct mps_softc *sc)
2074 {
2075 
2076 	if (sc->mps_log_eh != NULL)
2077 		mps_deregister_events(sc, sc->mps_log_eh);
2078 	return (0);
2079 }
2080 
2081 /*
2082  * Free all of the driver resources and detach submodules.  Should be called
2083  * without the lock held.
2084  */
2085 int
2086 mps_free(struct mps_softc *sc)
2087 {
2088 	int error;
2089 
2090 	mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
2091 	/* Turn off the watchdog */
2092 	mps_lock(sc);
2093 	sc->mps_flags |= MPS_FLAGS_SHUTDOWN;
2094 	mps_unlock(sc);
2095 	/* Lock must not be held for this */
2096 	callout_drain(&sc->periodic);
2097 	callout_drain(&sc->device_check_callout);
2098 
2099 	if (((error = mps_detach_log(sc)) != 0) ||
2100 	    ((error = mps_detach_sas(sc)) != 0)) {
2101 		mps_dprint(sc, MPS_INIT|MPS_FAULT, "failed to detach "
2102 		    "subsystems, exit\n");
2103 		return (error);
2104 	}
2105 
2106 	mps_detach_user(sc);
2107 
2108 	/* Put the IOC back in the READY state. */
2109 	mps_lock(sc);
2110 	if ((error = mps_transition_ready(sc)) != 0) {
2111 		mps_unlock(sc);
2112 		return (error);
2113 	}
2114 	mps_unlock(sc);
2115 
2116 	if (sc->facts != NULL)
2117 		free(sc->facts, M_MPT2);
2118 
2119 	/*
2120 	 * Free all buffers that are based on IOC Facts.  A Diag Reset may need
2121 	 * to free these buffers too.
2122 	 */
2123 	mps_iocfacts_free(sc);
2124 
2125 	if (sc->sysctl_tree != NULL)
2126 		sysctl_ctx_free(&sc->sysctl_ctx);
2127 
2128 	/* Deregister the shutdown function */
2129 	if (sc->shutdown_eh != NULL)
2130 		EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
2131 
2132 	mtx_destroy(&sc->mps_mtx);
2133 	mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
2134 
2135 	return (0);
2136 }
2137 
2138 static __inline void
2139 mps_complete_command(struct mps_softc *sc, struct mps_command *cm)
2140 {
2141 	MPS_FUNCTRACE(sc);
2142 
2143 	if (cm == NULL) {
2144 		mps_dprint(sc, MPS_ERROR, "Completing NULL command\n");
2145 		return;
2146 	}
2147 
2148 	if (cm->cm_flags & MPS_CM_FLAGS_POLLED)
2149 		cm->cm_flags |= MPS_CM_FLAGS_COMPLETE;
2150 
2151 	if (cm->cm_complete != NULL) {
2152 		mps_dprint(sc, MPS_TRACE,
2153 			   "%s cm %p calling cm_complete %p data %p reply %p\n",
2154 			   __func__, cm, cm->cm_complete, cm->cm_complete_data,
2155 			   cm->cm_reply);
2156 		cm->cm_complete(sc, cm);
2157 	}
2158 
2159 	if (cm->cm_flags & MPS_CM_FLAGS_WAKEUP) {
2160 		mps_dprint(sc, MPS_TRACE, "waking up %p\n", cm);
2161 		wakeup(cm);
2162 	}
2163 
2164 	if (cm->cm_sc->io_cmds_active != 0) {
2165 		cm->cm_sc->io_cmds_active--;
2166 	} else {
2167 		mps_dprint(sc, MPS_ERROR, "Warning: io_cmds_active is "
2168 		    "out of sync - resynching to 0\n");
2169 	}
2170 }
2171 
2172 
2173 static void
2174 mps_sas_log_info(struct mps_softc *sc , u32 log_info)
2175 {
2176 	union loginfo_type {
2177 		u32     loginfo;
2178 		struct {
2179 			u32     subcode:16;
2180 			u32     code:8;
2181 			u32     originator:4;
2182 			u32     bus_type:4;
2183 		} dw;
2184 	};
2185 	union loginfo_type sas_loginfo;
2186 	char *originator_str = NULL;
2187 
2188 	sas_loginfo.loginfo = log_info;
2189 	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
2190 		return;
2191 
2192 	/* each nexus loss loginfo */
2193 	if (log_info == 0x31170000)
2194 		return;
2195 
2196 	/* eat the loginfos associated with task aborts */
2197 	if ((log_info == 30050000 || log_info ==
2198 	    0x31140000 || log_info == 0x31130000))
2199 		return;
2200 
2201 	switch (sas_loginfo.dw.originator) {
2202 	case 0:
2203 		originator_str = "IOP";
2204 		break;
2205 	case 1:
2206 		originator_str = "PL";
2207 		break;
2208 	case 2:
2209 		originator_str = "IR";
2210 		break;
2211 }
2212 
2213 	mps_dprint(sc, MPS_LOG, "log_info(0x%08x): originator(%s), "
2214 	"code(0x%02x), sub_code(0x%04x)\n", log_info,
2215 	originator_str, sas_loginfo.dw.code,
2216 	sas_loginfo.dw.subcode);
2217 }
2218 
2219 static void
2220 mps_display_reply_info(struct mps_softc *sc, uint8_t *reply)
2221 {
2222 	MPI2DefaultReply_t *mpi_reply;
2223 	u16 sc_status;
2224 
2225 	mpi_reply = (MPI2DefaultReply_t*)reply;
2226 	sc_status = le16toh(mpi_reply->IOCStatus);
2227 	if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
2228 		mps_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
2229 }
2230 void
2231 mps_intr(void *data)
2232 {
2233 	struct mps_softc *sc;
2234 	uint32_t status;
2235 
2236 	sc = (struct mps_softc *)data;
2237 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2238 
2239 	/*
2240 	 * Check interrupt status register to flush the bus.  This is
2241 	 * needed for both INTx interrupts and driver-driven polling
2242 	 */
2243 	status = mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
2244 	if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
2245 		return;
2246 
2247 	mps_lock(sc);
2248 	mps_intr_locked(data);
2249 	mps_unlock(sc);
2250 	return;
2251 }
2252 
2253 /*
2254  * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
2255  * chip.  Hopefully this theory is correct.
2256  */
2257 void
2258 mps_intr_msi(void *data)
2259 {
2260 	struct mps_softc *sc;
2261 
2262 	sc = (struct mps_softc *)data;
2263 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2264 	mps_lock(sc);
2265 	mps_intr_locked(data);
2266 	mps_unlock(sc);
2267 	return;
2268 }
2269 
2270 /*
2271  * The locking is overly broad and simplistic, but easy to deal with for now.
2272  */
2273 void
2274 mps_intr_locked(void *data)
2275 {
2276 	MPI2_REPLY_DESCRIPTORS_UNION *desc;
2277 	struct mps_softc *sc;
2278 	struct mps_command *cm = NULL;
2279 	uint8_t flags;
2280 	u_int pq;
2281 	MPI2_DIAG_RELEASE_REPLY *rel_rep;
2282 	mps_fw_diagnostic_buffer_t *pBuffer;
2283 
2284 	sc = (struct mps_softc *)data;
2285 
2286 	pq = sc->replypostindex;
2287 	mps_dprint(sc, MPS_TRACE,
2288 	    "%s sc %p starting with replypostindex %u\n",
2289 	    __func__, sc, sc->replypostindex);
2290 
2291 	for ( ;; ) {
2292 		cm = NULL;
2293 		desc = &sc->post_queue[sc->replypostindex];
2294 		flags = desc->Default.ReplyFlags &
2295 		    MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
2296 		if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
2297 		 || (le32toh(desc->Words.High) == 0xffffffff))
2298 			break;
2299 
2300 		/* increment the replypostindex now, so that event handlers
2301 		 * and cm completion handlers which decide to do a diag
2302 		 * reset can zero it without it getting incremented again
2303 		 * afterwards, and we break out of this loop on the next
2304 		 * iteration since the reply post queue has been cleared to
2305 		 * 0xFF and all descriptors look unused (which they are).
2306 		 */
2307 		if (++sc->replypostindex >= sc->pqdepth)
2308 			sc->replypostindex = 0;
2309 
2310 		switch (flags) {
2311 		case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
2312 			cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
2313 			KASSERT(cm->cm_state == MPS_CM_STATE_INQUEUE,
2314 			    ("command not inqueue\n"));
2315 			cm->cm_state = MPS_CM_STATE_BUSY;
2316 			cm->cm_reply = NULL;
2317 			break;
2318 		case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
2319 		{
2320 			uint32_t baddr;
2321 			uint8_t *reply;
2322 
2323 			/*
2324 			 * Re-compose the reply address from the address
2325 			 * sent back from the chip.  The ReplyFrameAddress
2326 			 * is the lower 32 bits of the physical address of
2327 			 * particular reply frame.  Convert that address to
2328 			 * host format, and then use that to provide the
2329 			 * offset against the virtual address base
2330 			 * (sc->reply_frames).
2331 			 */
2332 			baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
2333 			reply = sc->reply_frames +
2334 				(baddr - ((uint32_t)sc->reply_busaddr));
2335 			/*
2336 			 * Make sure the reply we got back is in a valid
2337 			 * range.  If not, go ahead and panic here, since
2338 			 * we'll probably panic as soon as we deference the
2339 			 * reply pointer anyway.
2340 			 */
2341 			if ((reply < sc->reply_frames)
2342 			 || (reply > (sc->reply_frames +
2343 			     (sc->fqdepth * sc->replyframesz)))) {
2344 				printf("%s: WARNING: reply %p out of range!\n",
2345 				       __func__, reply);
2346 				printf("%s: reply_frames %p, fqdepth %d, "
2347 				       "frame size %d\n", __func__,
2348 				       sc->reply_frames, sc->fqdepth,
2349 				       sc->replyframesz);
2350 				printf("%s: baddr %#x,\n", __func__, baddr);
2351 				/* LSI-TODO. See Linux Code for Graceful exit */
2352 				panic("Reply address out of range");
2353 			}
2354 			if (le16toh(desc->AddressReply.SMID) == 0) {
2355 				if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
2356 				    MPI2_FUNCTION_DIAG_BUFFER_POST) {
2357 					/*
2358 					 * If SMID is 0 for Diag Buffer Post,
2359 					 * this implies that the reply is due to
2360 					 * a release function with a status that
2361 					 * the buffer has been released.  Set
2362 					 * the buffer flags accordingly.
2363 					 */
2364 					rel_rep =
2365 					    (MPI2_DIAG_RELEASE_REPLY *)reply;
2366 					if ((le16toh(rel_rep->IOCStatus) &
2367 					    MPI2_IOCSTATUS_MASK) ==
2368 					    MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
2369 					{
2370 						pBuffer =
2371 						    &sc->fw_diag_buffer_list[
2372 						    rel_rep->BufferType];
2373 						pBuffer->valid_data = TRUE;
2374 						pBuffer->owned_by_firmware =
2375 						    FALSE;
2376 						pBuffer->immediate = FALSE;
2377 					}
2378 				} else
2379 					mps_dispatch_event(sc, baddr,
2380 					    (MPI2_EVENT_NOTIFICATION_REPLY *)
2381 					    reply);
2382 			} else {
2383 				cm = &sc->commands[
2384 				    le16toh(desc->AddressReply.SMID)];
2385 				KASSERT(cm->cm_state == MPS_CM_STATE_INQUEUE,
2386 				    ("command not inqueue\n"));
2387 				cm->cm_state = MPS_CM_STATE_BUSY;
2388 				cm->cm_reply = reply;
2389 				cm->cm_reply_data = le32toh(
2390 				    desc->AddressReply.ReplyFrameAddress);
2391 			}
2392 			break;
2393 		}
2394 		case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
2395 		case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
2396 		case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
2397 		default:
2398 			/* Unhandled */
2399 			mps_dprint(sc, MPS_ERROR, "Unhandled reply 0x%x\n",
2400 			    desc->Default.ReplyFlags);
2401 			cm = NULL;
2402 			break;
2403 		}
2404 
2405 
2406 		if (cm != NULL) {
2407 			// Print Error reply frame
2408 			if (cm->cm_reply)
2409 				mps_display_reply_info(sc,cm->cm_reply);
2410 			mps_complete_command(sc, cm);
2411 		}
2412 
2413 		desc->Words.Low = 0xffffffff;
2414 		desc->Words.High = 0xffffffff;
2415 	}
2416 
2417 	if (pq != sc->replypostindex) {
2418 		mps_dprint(sc, MPS_TRACE, "%s sc %p writing postindex %d\n",
2419 		    __func__, sc, sc->replypostindex);
2420 		mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET,
2421 		    sc->replypostindex);
2422 	}
2423 
2424 	return;
2425 }
2426 
2427 static void
2428 mps_dispatch_event(struct mps_softc *sc, uintptr_t data,
2429     MPI2_EVENT_NOTIFICATION_REPLY *reply)
2430 {
2431 	struct mps_event_handle *eh;
2432 	int event, handled = 0;
2433 
2434 	event = le16toh(reply->Event);
2435 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2436 		if (isset(eh->mask, event)) {
2437 			eh->callback(sc, data, reply);
2438 			handled++;
2439 		}
2440 	}
2441 
2442 	if (handled == 0)
2443 		mps_dprint(sc, MPS_EVENT, "Unhandled event 0x%x\n", le16toh(event));
2444 
2445 	/*
2446 	 * This is the only place that the event/reply should be freed.
2447 	 * Anything wanting to hold onto the event data should have
2448 	 * already copied it into their own storage.
2449 	 */
2450 	mps_free_reply(sc, data);
2451 }
2452 
2453 static void
2454 mps_reregister_events_complete(struct mps_softc *sc, struct mps_command *cm)
2455 {
2456 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2457 
2458 	if (cm->cm_reply)
2459 		MPS_DPRINT_EVENT(sc, generic,
2460 			(MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
2461 
2462 	mps_free_command(sc, cm);
2463 
2464 	/* next, send a port enable */
2465 	mpssas_startup(sc);
2466 }
2467 
2468 /*
2469  * For both register_events and update_events, the caller supplies a bitmap
2470  * of events that it _wants_.  These functions then turn that into a bitmask
2471  * suitable for the controller.
2472  */
2473 int
2474 mps_register_events(struct mps_softc *sc, u32 *mask,
2475     mps_evt_callback_t *cb, void *data, struct mps_event_handle **handle)
2476 {
2477 	struct mps_event_handle *eh;
2478 	int error = 0;
2479 
2480 	eh = malloc(sizeof(struct mps_event_handle), M_MPT2, M_WAITOK|M_ZERO);
2481 	if(!eh) {
2482 		mps_dprint(sc, MPS_ERROR, "Cannot allocate event memory\n");
2483 		return (ENOMEM);
2484 	}
2485 	eh->callback = cb;
2486 	eh->data = data;
2487 	TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
2488 	if (mask != NULL)
2489 		error = mps_update_events(sc, eh, mask);
2490 	*handle = eh;
2491 
2492 	return (error);
2493 }
2494 
2495 int
2496 mps_update_events(struct mps_softc *sc, struct mps_event_handle *handle,
2497     u32 *mask)
2498 {
2499 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2500 	MPI2_EVENT_NOTIFICATION_REPLY *reply = NULL;
2501 	struct mps_command *cm;
2502 	int error, i;
2503 
2504 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2505 
2506 	if ((mask != NULL) && (handle != NULL))
2507 		bcopy(mask, &handle->mask[0], sizeof(u32) *
2508 				MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
2509 
2510 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2511 		sc->event_mask[i] = -1;
2512 
2513 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2514 		sc->event_mask[i] &= ~handle->mask[i];
2515 
2516 
2517 	if ((cm = mps_alloc_command(sc)) == NULL)
2518 		return (EBUSY);
2519 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2520 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2521 	evtreq->MsgFlags = 0;
2522 	evtreq->SASBroadcastPrimitiveMasks = 0;
2523 #ifdef MPS_DEBUG_ALL_EVENTS
2524 	{
2525 		u_char fullmask[16];
2526 		memset(fullmask, 0x00, 16);
2527 		bcopy(fullmask, &evtreq->EventMasks[0], sizeof(u32) *
2528 				MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
2529 	}
2530 #else
2531         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2532                 evtreq->EventMasks[i] =
2533                     htole32(sc->event_mask[i]);
2534 #endif
2535 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2536 	cm->cm_data = NULL;
2537 
2538 	error = mps_wait_command(sc, &cm, 60, 0);
2539 	if (cm != NULL)
2540 		reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
2541 	if ((reply == NULL) ||
2542 	    (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
2543 		error = ENXIO;
2544 
2545 	if (reply)
2546 		MPS_DPRINT_EVENT(sc, generic, reply);
2547 
2548 	mps_dprint(sc, MPS_TRACE, "%s finished error %d\n", __func__, error);
2549 
2550 	if (cm != NULL)
2551 		mps_free_command(sc, cm);
2552 	return (error);
2553 }
2554 
2555 static int
2556 mps_reregister_events(struct mps_softc *sc)
2557 {
2558 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2559 	struct mps_command *cm;
2560 	struct mps_event_handle *eh;
2561 	int error, i;
2562 
2563 	mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2564 
2565 	/* first, reregister events */
2566 
2567 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2568 		sc->event_mask[i] = -1;
2569 
2570 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2571 		for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2572 			sc->event_mask[i] &= ~eh->mask[i];
2573 	}
2574 
2575 	if ((cm = mps_alloc_command(sc)) == NULL)
2576 		return (EBUSY);
2577 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2578 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2579 	evtreq->MsgFlags = 0;
2580 	evtreq->SASBroadcastPrimitiveMasks = 0;
2581 #ifdef MPS_DEBUG_ALL_EVENTS
2582 	{
2583 		u_char fullmask[16];
2584 		memset(fullmask, 0x00, 16);
2585 		bcopy(fullmask, &evtreq->EventMasks[0], sizeof(u32) *
2586 			MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
2587 	}
2588 #else
2589         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2590                 evtreq->EventMasks[i] =
2591                     htole32(sc->event_mask[i]);
2592 #endif
2593 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2594 	cm->cm_data = NULL;
2595 	cm->cm_complete = mps_reregister_events_complete;
2596 
2597 	error = mps_map_command(sc, cm);
2598 
2599 	mps_dprint(sc, MPS_TRACE, "%s finished with error %d\n", __func__,
2600 	    error);
2601 	return (error);
2602 }
2603 
2604 void
2605 mps_deregister_events(struct mps_softc *sc, struct mps_event_handle *handle)
2606 {
2607 
2608 	TAILQ_REMOVE(&sc->event_list, handle, eh_list);
2609 	free(handle, M_MPT2);
2610 }
2611 
2612 /*
2613  * Add a chain element as the next SGE for the specified command.
2614  * Reset cm_sge and cm_sgesize to indicate all the available space.
2615  */
2616 static int
2617 mps_add_chain(struct mps_command *cm)
2618 {
2619 	MPI2_SGE_CHAIN32 *sgc;
2620 	struct mps_chain *chain;
2621 	u_int space;
2622 
2623 	if (cm->cm_sglsize < MPS_SGC_SIZE)
2624 		panic("MPS: Need SGE Error Code\n");
2625 
2626 	chain = mps_alloc_chain(cm->cm_sc);
2627 	if (chain == NULL)
2628 		return (ENOBUFS);
2629 
2630 	space = cm->cm_sc->reqframesz;
2631 
2632 	/*
2633 	 * Note: a double-linked list is used to make it easier to
2634 	 * walk for debugging.
2635 	 */
2636 	TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
2637 
2638 	sgc = (MPI2_SGE_CHAIN32 *)&cm->cm_sge->MpiChain;
2639 	sgc->Length = htole16(space);
2640 	sgc->NextChainOffset = 0;
2641 	/* TODO Looks like bug in Setting sgc->Flags.
2642 	 *	sgc->Flags = ( MPI2_SGE_FLAGS_CHAIN_ELEMENT | MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
2643 	 *	            MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT
2644 	 *	This is fine.. because we are not using simple element. In case of
2645 	 *	MPI2_SGE_CHAIN32, we have separate Length and Flags feild.
2646  	 */
2647 	sgc->Flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT;
2648 	sgc->Address = htole32(chain->chain_busaddr);
2649 
2650 	cm->cm_sge = (MPI2_SGE_IO_UNION *)&chain->chain->MpiSimple;
2651 	cm->cm_sglsize = space;
2652 	return (0);
2653 }
2654 
2655 /*
2656  * Add one scatter-gather element (chain, simple, transaction context)
2657  * to the scatter-gather list for a command.  Maintain cm_sglsize and
2658  * cm_sge as the remaining size and pointer to the next SGE to fill
2659  * in, respectively.
2660  */
2661 int
2662 mps_push_sge(struct mps_command *cm, void *sgep, size_t len, int segsleft)
2663 {
2664 	MPI2_SGE_TRANSACTION_UNION *tc = sgep;
2665 	MPI2_SGE_SIMPLE64 *sge = sgep;
2666 	int error, type;
2667 	uint32_t saved_buf_len, saved_address_low, saved_address_high;
2668 
2669 	type = (tc->Flags & MPI2_SGE_FLAGS_ELEMENT_MASK);
2670 
2671 #ifdef INVARIANTS
2672 	switch (type) {
2673 	case MPI2_SGE_FLAGS_TRANSACTION_ELEMENT: {
2674 		if (len != tc->DetailsLength + 4)
2675 			panic("TC %p length %u or %zu?", tc,
2676 			    tc->DetailsLength + 4, len);
2677 		}
2678 		break;
2679 	case MPI2_SGE_FLAGS_CHAIN_ELEMENT:
2680 		/* Driver only uses 32-bit chain elements */
2681 		if (len != MPS_SGC_SIZE)
2682 			panic("CHAIN %p length %u or %zu?", sgep,
2683 			    MPS_SGC_SIZE, len);
2684 		break;
2685 	case MPI2_SGE_FLAGS_SIMPLE_ELEMENT:
2686 		/* Driver only uses 64-bit SGE simple elements */
2687 		if (len != MPS_SGE64_SIZE)
2688 			panic("SGE simple %p length %u or %zu?", sge,
2689 			    MPS_SGE64_SIZE, len);
2690 		if (((le32toh(sge->FlagsLength) >> MPI2_SGE_FLAGS_SHIFT) &
2691 		    MPI2_SGE_FLAGS_ADDRESS_SIZE) == 0)
2692 			panic("SGE simple %p not marked 64-bit?", sge);
2693 
2694 		break;
2695 	default:
2696 		panic("Unexpected SGE %p, flags %02x", tc, tc->Flags);
2697 	}
2698 #endif
2699 
2700 	/*
2701 	 * case 1: 1 more segment, enough room for it
2702 	 * case 2: 2 more segments, enough room for both
2703 	 * case 3: >=2 more segments, only enough room for 1 and a chain
2704 	 * case 4: >=1 more segment, enough room for only a chain
2705 	 * case 5: >=1 more segment, no room for anything (error)
2706          */
2707 
2708 	/*
2709 	 * There should be room for at least a chain element, or this
2710 	 * code is buggy.  Case (5).
2711 	 */
2712 	if (cm->cm_sglsize < MPS_SGC_SIZE)
2713 		panic("MPS: Need SGE Error Code\n");
2714 
2715 	if (segsleft >= 1 && cm->cm_sglsize < len + MPS_SGC_SIZE) {
2716 		/*
2717 		 * 1 or more segment, enough room for only a chain.
2718 		 * Hope the previous element wasn't a Simple entry
2719 		 * that needed to be marked with
2720 		 * MPI2_SGE_FLAGS_LAST_ELEMENT.  Case (4).
2721 		 */
2722 		if ((error = mps_add_chain(cm)) != 0)
2723 			return (error);
2724 	}
2725 
2726 	if (segsleft >= 2 &&
2727 	    cm->cm_sglsize < len + MPS_SGC_SIZE + MPS_SGE64_SIZE) {
2728 		/*
2729 		 * There are 2 or more segments left to add, and only
2730 		 * enough room for 1 and a chain.  Case (3).
2731 		 *
2732 		 * Mark as last element in this chain if necessary.
2733 		 */
2734 		if (type == MPI2_SGE_FLAGS_SIMPLE_ELEMENT) {
2735 			sge->FlagsLength |= htole32(
2736 			    MPI2_SGE_FLAGS_LAST_ELEMENT << MPI2_SGE_FLAGS_SHIFT);
2737 		}
2738 
2739 		/*
2740 		 * Add the item then a chain.  Do the chain now,
2741 		 * rather than on the next iteration, to simplify
2742 		 * understanding the code.
2743 		 */
2744 		cm->cm_sglsize -= len;
2745 		bcopy(sgep, cm->cm_sge, len);
2746 		cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2747 		return (mps_add_chain(cm));
2748 	}
2749 
2750 #ifdef INVARIANTS
2751 	/* Case 1: 1 more segment, enough room for it. */
2752 	if (segsleft == 1 && cm->cm_sglsize < len)
2753 		panic("1 seg left and no room? %u versus %zu",
2754 		    cm->cm_sglsize, len);
2755 
2756 	/* Case 2: 2 more segments, enough room for both */
2757 	if (segsleft == 2 && cm->cm_sglsize < len + MPS_SGE64_SIZE)
2758 		panic("2 segs left and no room? %u versus %zu",
2759 		    cm->cm_sglsize, len);
2760 #endif
2761 
2762 	if (segsleft == 1 && type == MPI2_SGE_FLAGS_SIMPLE_ELEMENT) {
2763 		/*
2764 		 * If this is a bi-directional request, need to account for that
2765 		 * here.  Save the pre-filled sge values.  These will be used
2766 		 * either for the 2nd SGL or for a single direction SGL.  If
2767 		 * cm_out_len is non-zero, this is a bi-directional request, so
2768 		 * fill in the OUT SGL first, then the IN SGL, otherwise just
2769 		 * fill in the IN SGL.  Note that at this time, when filling in
2770 		 * 2 SGL's for a bi-directional request, they both use the same
2771 		 * DMA buffer (same cm command).
2772 		 */
2773 		saved_buf_len = le32toh(sge->FlagsLength) & 0x00FFFFFF;
2774 		saved_address_low = sge->Address.Low;
2775 		saved_address_high = sge->Address.High;
2776 		if (cm->cm_out_len) {
2777 			sge->FlagsLength = htole32(cm->cm_out_len |
2778 			    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2779 			    MPI2_SGE_FLAGS_END_OF_BUFFER |
2780 			    MPI2_SGE_FLAGS_HOST_TO_IOC |
2781 			    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2782 			    MPI2_SGE_FLAGS_SHIFT));
2783 			cm->cm_sglsize -= len;
2784 			bcopy(sgep, cm->cm_sge, len);
2785 			cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge
2786 			    + len);
2787 		}
2788 		saved_buf_len |=
2789 		    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2790 		    MPI2_SGE_FLAGS_END_OF_BUFFER |
2791 		    MPI2_SGE_FLAGS_LAST_ELEMENT |
2792 		    MPI2_SGE_FLAGS_END_OF_LIST |
2793 		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2794 		    MPI2_SGE_FLAGS_SHIFT);
2795 		if (cm->cm_flags & MPS_CM_FLAGS_DATAIN) {
2796 			saved_buf_len |=
2797 			    ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
2798 			    MPI2_SGE_FLAGS_SHIFT);
2799 		} else {
2800 			saved_buf_len |=
2801 			    ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
2802 			    MPI2_SGE_FLAGS_SHIFT);
2803 		}
2804 		sge->FlagsLength = htole32(saved_buf_len);
2805 		sge->Address.Low = saved_address_low;
2806 		sge->Address.High = saved_address_high;
2807 	}
2808 
2809 	cm->cm_sglsize -= len;
2810 	bcopy(sgep, cm->cm_sge, len);
2811 	cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2812 	return (0);
2813 }
2814 
2815 /*
2816  * Add one dma segment to the scatter-gather list for a command.
2817  */
2818 int
2819 mps_add_dmaseg(struct mps_command *cm, vm_paddr_t pa, size_t len, u_int flags,
2820     int segsleft)
2821 {
2822 	MPI2_SGE_SIMPLE64 sge;
2823 
2824 	/*
2825 	 * This driver always uses 64-bit address elements for simplicity.
2826 	 */
2827 	bzero(&sge, sizeof(sge));
2828 	flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2829 	    MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
2830 	sge.FlagsLength = htole32(len | (flags << MPI2_SGE_FLAGS_SHIFT));
2831 	mps_from_u64(pa, &sge.Address);
2832 
2833 	return (mps_push_sge(cm, &sge, sizeof sge, segsleft));
2834 }
2835 
2836 static void
2837 mps_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2838 {
2839 	struct mps_softc *sc;
2840 	struct mps_command *cm;
2841 	u_int i, dir, sflags;
2842 
2843 	cm = (struct mps_command *)arg;
2844 	sc = cm->cm_sc;
2845 
2846 	/*
2847 	 * In this case, just print out a warning and let the chip tell the
2848 	 * user they did the wrong thing.
2849 	 */
2850 	if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
2851 		mps_dprint(sc, MPS_ERROR,
2852 			   "%s: warning: busdma returned %d segments, "
2853 			   "more than the %d allowed\n", __func__, nsegs,
2854 			   cm->cm_max_segs);
2855 	}
2856 
2857 	/*
2858 	 * Set up DMA direction flags.  Bi-directional requests are also handled
2859 	 * here.  In that case, both direction flags will be set.
2860 	 */
2861 	sflags = 0;
2862 	if (cm->cm_flags & MPS_CM_FLAGS_SMP_PASS) {
2863 		/*
2864 		 * We have to add a special case for SMP passthrough, there
2865 		 * is no easy way to generically handle it.  The first
2866 		 * S/G element is used for the command (therefore the
2867 		 * direction bit needs to be set).  The second one is used
2868 		 * for the reply.  We'll leave it to the caller to make
2869 		 * sure we only have two buffers.
2870 		 */
2871 		/*
2872 		 * Even though the busdma man page says it doesn't make
2873 		 * sense to have both direction flags, it does in this case.
2874 		 * We have one s/g element being accessed in each direction.
2875 		 */
2876 		dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
2877 
2878 		/*
2879 		 * Set the direction flag on the first buffer in the SMP
2880 		 * passthrough request.  We'll clear it for the second one.
2881 		 */
2882 		sflags |= MPI2_SGE_FLAGS_DIRECTION |
2883 			  MPI2_SGE_FLAGS_END_OF_BUFFER;
2884 	} else if (cm->cm_flags & MPS_CM_FLAGS_DATAOUT) {
2885 		sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2886 		dir = BUS_DMASYNC_PREWRITE;
2887 	} else
2888 		dir = BUS_DMASYNC_PREREAD;
2889 
2890 	for (i = 0; i < nsegs; i++) {
2891 		if ((cm->cm_flags & MPS_CM_FLAGS_SMP_PASS) && (i != 0)) {
2892 			sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
2893 		}
2894 		error = mps_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
2895 		    sflags, nsegs - i);
2896 		if (error != 0) {
2897 			/* Resource shortage, roll back! */
2898 			if (ratecheck(&sc->lastfail, &mps_chainfail_interval))
2899 				mps_dprint(sc, MPS_INFO, "Out of chain frames, "
2900 				    "consider increasing hw.mps.max_chains.\n");
2901 			cm->cm_flags |= MPS_CM_FLAGS_CHAIN_FAILED;
2902 			mps_complete_command(sc, cm);
2903 			return;
2904 		}
2905 	}
2906 
2907 	bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
2908 	mps_enqueue_request(sc, cm);
2909 
2910 	return;
2911 }
2912 
2913 static void
2914 mps_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
2915 	     int error)
2916 {
2917 	mps_data_cb(arg, segs, nsegs, error);
2918 }
2919 
2920 /*
2921  * This is the routine to enqueue commands ansynchronously.
2922  * Note that the only error path here is from bus_dmamap_load(), which can
2923  * return EINPROGRESS if it is waiting for resources.  Other than this, it's
2924  * assumed that if you have a command in-hand, then you have enough credits
2925  * to use it.
2926  */
2927 int
2928 mps_map_command(struct mps_softc *sc, struct mps_command *cm)
2929 {
2930 	int error = 0;
2931 
2932 	if (cm->cm_flags & MPS_CM_FLAGS_USE_UIO) {
2933 		error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
2934 		    &cm->cm_uio, mps_data_cb2, cm, 0);
2935 	} else if (cm->cm_flags & MPS_CM_FLAGS_USE_CCB) {
2936 		error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
2937 		    cm->cm_data, mps_data_cb, cm, 0);
2938 	} else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
2939 		error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
2940 		    cm->cm_data, cm->cm_length, mps_data_cb, cm, 0);
2941 	} else {
2942 		/* Add a zero-length element as needed */
2943 		if (cm->cm_sge != NULL)
2944 			mps_add_dmaseg(cm, 0, 0, 0, 1);
2945 		mps_enqueue_request(sc, cm);
2946 	}
2947 
2948 	return (error);
2949 }
2950 
2951 /*
2952  * This is the routine to enqueue commands synchronously.  An error of
2953  * EINPROGRESS from mps_map_command() is ignored since the command will
2954  * be executed and enqueued automatically.  Other errors come from msleep().
2955  */
2956 int
2957 mps_wait_command(struct mps_softc *sc, struct mps_command **cmp, int timeout,
2958     int sleep_flag)
2959 {
2960 	int error, rc;
2961 	struct timeval cur_time, start_time;
2962 	struct mps_command *cm = *cmp;
2963 
2964 	if (sc->mps_flags & MPS_FLAGS_DIAGRESET)
2965 		return  EBUSY;
2966 
2967 	cm->cm_complete = NULL;
2968 	cm->cm_flags |= MPS_CM_FLAGS_POLLED;
2969 	error = mps_map_command(sc, cm);
2970 	if ((error != 0) && (error != EINPROGRESS))
2971 		return (error);
2972 
2973 	/*
2974 	 * Check for context and wait for 50 mSec at a time until time has
2975 	 * expired or the command has finished.  If msleep can't be used, need
2976 	 * to poll.
2977 	 */
2978 	if (curthread->td_no_sleeping != 0)
2979 		sleep_flag = NO_SLEEP;
2980 	getmicrouptime(&start_time);
2981 	if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP) {
2982 		cm->cm_flags |= MPS_CM_FLAGS_WAKEUP;
2983 		error = msleep(cm, &sc->mps_mtx, 0, "mpswait", timeout*hz);
2984 		if (error == EWOULDBLOCK) {
2985 			/*
2986 			 * Record the actual elapsed time in the case of a
2987 			 * timeout for the message below.
2988 			 */
2989 			getmicrouptime(&cur_time);
2990 			timevalsub(&cur_time, &start_time);
2991 		}
2992 	} else {
2993 		while ((cm->cm_flags & MPS_CM_FLAGS_COMPLETE) == 0) {
2994 			mps_intr_locked(sc);
2995 			if (sleep_flag == CAN_SLEEP)
2996 				pause("mpswait", hz/20);
2997 			else
2998 				DELAY(50000);
2999 
3000 			getmicrouptime(&cur_time);
3001 			timevalsub(&cur_time, &start_time);
3002 			if (cur_time.tv_sec > timeout) {
3003 				error = EWOULDBLOCK;
3004 				break;
3005 			}
3006 		}
3007 	}
3008 
3009 	if (error == EWOULDBLOCK) {
3010 		mps_dprint(sc, MPS_FAULT, "Calling Reinit from %s, timeout=%d,"
3011 		    " elapsed=%jd\n", __func__, timeout,
3012 		    (intmax_t)cur_time.tv_sec);
3013 		rc = mps_reinit(sc);
3014 		mps_dprint(sc, MPS_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3015 		    "failed");
3016 		if (sc->mps_flags & MPS_FLAGS_REALLOCATED) {
3017 			/*
3018 			 * Tell the caller that we freed the command in a
3019 			 * reinit.
3020 			 */
3021 			*cmp = NULL;
3022 		}
3023 		error = ETIMEDOUT;
3024 	}
3025 	return (error);
3026 }
3027 
3028 /*
3029  * The MPT driver had a verbose interface for config pages.  In this driver,
3030  * reduce it to much simpler terms, similar to the Linux driver.
3031  */
3032 int
3033 mps_read_config_page(struct mps_softc *sc, struct mps_config_params *params)
3034 {
3035 	MPI2_CONFIG_REQUEST *req;
3036 	struct mps_command *cm;
3037 	int error;
3038 
3039 	if (sc->mps_flags & MPS_FLAGS_BUSY) {
3040 		return (EBUSY);
3041 	}
3042 
3043 	cm = mps_alloc_command(sc);
3044 	if (cm == NULL) {
3045 		return (EBUSY);
3046 	}
3047 
3048 	req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
3049 	req->Function = MPI2_FUNCTION_CONFIG;
3050 	req->Action = params->action;
3051 	req->SGLFlags = 0;
3052 	req->ChainOffset = 0;
3053 	req->PageAddress = params->page_address;
3054 	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3055 		MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
3056 
3057 		hdr = &params->hdr.Ext;
3058 		req->ExtPageType = hdr->ExtPageType;
3059 		req->ExtPageLength = hdr->ExtPageLength;
3060 		req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
3061 		req->Header.PageLength = 0; /* Must be set to zero */
3062 		req->Header.PageNumber = hdr->PageNumber;
3063 		req->Header.PageVersion = hdr->PageVersion;
3064 	} else {
3065 		MPI2_CONFIG_PAGE_HEADER *hdr;
3066 
3067 		hdr = &params->hdr.Struct;
3068 		req->Header.PageType = hdr->PageType;
3069 		req->Header.PageNumber = hdr->PageNumber;
3070 		req->Header.PageLength = hdr->PageLength;
3071 		req->Header.PageVersion = hdr->PageVersion;
3072 	}
3073 
3074 	cm->cm_data = params->buffer;
3075 	cm->cm_length = params->length;
3076 	if (cm->cm_data != NULL) {
3077 		cm->cm_sge = &req->PageBufferSGE;
3078 		cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
3079 		cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_DATAIN;
3080 	} else
3081 		cm->cm_sge = NULL;
3082 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3083 
3084 	cm->cm_complete_data = params;
3085 	if (params->callback != NULL) {
3086 		cm->cm_complete = mps_config_complete;
3087 		return (mps_map_command(sc, cm));
3088 	} else {
3089 		error = mps_wait_command(sc, &cm, 0, CAN_SLEEP);
3090 		if (error) {
3091 			mps_dprint(sc, MPS_FAULT,
3092 			    "Error %d reading config page\n", error);
3093 			if (cm != NULL)
3094 				mps_free_command(sc, cm);
3095 			return (error);
3096 		}
3097 		mps_config_complete(sc, cm);
3098 	}
3099 
3100 	return (0);
3101 }
3102 
3103 int
3104 mps_write_config_page(struct mps_softc *sc, struct mps_config_params *params)
3105 {
3106 	return (EINVAL);
3107 }
3108 
3109 static void
3110 mps_config_complete(struct mps_softc *sc, struct mps_command *cm)
3111 {
3112 	MPI2_CONFIG_REPLY *reply;
3113 	struct mps_config_params *params;
3114 
3115 	MPS_FUNCTRACE(sc);
3116 	params = cm->cm_complete_data;
3117 
3118 	if (cm->cm_data != NULL) {
3119 		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
3120 		    BUS_DMASYNC_POSTREAD);
3121 		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
3122 	}
3123 
3124 	/*
3125 	 * XXX KDM need to do more error recovery?  This results in the
3126 	 * device in question not getting probed.
3127 	 */
3128 	if ((cm->cm_flags & MPS_CM_FLAGS_ERROR_MASK) != 0) {
3129 		params->status = MPI2_IOCSTATUS_BUSY;
3130 		goto done;
3131 	}
3132 
3133 	reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
3134 	if (reply == NULL) {
3135 		params->status = MPI2_IOCSTATUS_BUSY;
3136 		goto done;
3137 	}
3138 	params->status = reply->IOCStatus;
3139 	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3140 		params->hdr.Ext.ExtPageType = reply->ExtPageType;
3141 		params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
3142 		params->hdr.Ext.PageType = reply->Header.PageType;
3143 		params->hdr.Ext.PageNumber = reply->Header.PageNumber;
3144 		params->hdr.Ext.PageVersion = reply->Header.PageVersion;
3145 	} else {
3146 		params->hdr.Struct.PageType = reply->Header.PageType;
3147 		params->hdr.Struct.PageNumber = reply->Header.PageNumber;
3148 		params->hdr.Struct.PageLength = reply->Header.PageLength;
3149 		params->hdr.Struct.PageVersion = reply->Header.PageVersion;
3150 	}
3151 
3152 done:
3153 	mps_free_command(sc, cm);
3154 	if (params->callback != NULL)
3155 		params->callback(sc, params);
3156 
3157 	return;
3158 }
3159