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