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