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