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