xref: /freebsd/sys/dev/aac/aac.c (revision 2546665afcaf0d53dc2c7058fee96354b3680f5a)
1 /*-
2  * Copyright (c) 2000 Michael Smith
3  * Copyright (c) 2001 Scott Long
4  * Copyright (c) 2000 BSDi
5  * Copyright (c) 2001 Adaptec, Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 /*
34  * Driver for the Adaptec 'FSA' family of PCI/SCSI RAID adapters.
35  */
36 
37 #include "opt_aac.h"
38 
39 /* #include <stddef.h> */
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/malloc.h>
43 #include <sys/kernel.h>
44 #include <sys/kthread.h>
45 #include <sys/sysctl.h>
46 #include <sys/poll.h>
47 #include <sys/ioccom.h>
48 
49 #include <sys/bus.h>
50 #include <sys/conf.h>
51 #include <sys/signalvar.h>
52 #include <sys/time.h>
53 #include <sys/eventhandler.h>
54 
55 #include <machine/bus_memio.h>
56 #include <machine/bus.h>
57 #include <machine/resource.h>
58 
59 #include <dev/aac/aacreg.h>
60 #include <dev/aac/aac_ioctl.h>
61 #include <dev/aac/aacvar.h>
62 #include <dev/aac/aac_tables.h>
63 
64 static void	aac_startup(void *arg);
65 static void	aac_add_container(struct aac_softc *sc,
66 				  struct aac_mntinforesp *mir, int f);
67 static void	aac_get_bus_info(struct aac_softc *sc);
68 
69 /* Command Processing */
70 static void	aac_timeout(struct aac_softc *sc);
71 static void	aac_complete(void *context, int pending);
72 static int	aac_bio_command(struct aac_softc *sc, struct aac_command **cmp);
73 static void	aac_bio_complete(struct aac_command *cm);
74 static int	aac_wait_command(struct aac_command *cm);
75 static void	aac_command_thread(struct aac_softc *sc);
76 
77 /* Command Buffer Management */
78 static void	aac_map_command_sg(void *arg, bus_dma_segment_t *segs,
79 				   int nseg, int error);
80 static void	aac_map_command_helper(void *arg, bus_dma_segment_t *segs,
81 				       int nseg, int error);
82 static int	aac_alloc_commands(struct aac_softc *sc);
83 static void	aac_free_commands(struct aac_softc *sc);
84 static void	aac_unmap_command(struct aac_command *cm);
85 
86 /* Hardware Interface */
87 static void	aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg,
88 			       int error);
89 static int	aac_check_firmware(struct aac_softc *sc);
90 static int	aac_init(struct aac_softc *sc);
91 static int	aac_sync_command(struct aac_softc *sc, u_int32_t command,
92 				 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2,
93 				 u_int32_t arg3, u_int32_t *sp);
94 static int	aac_enqueue_fib(struct aac_softc *sc, int queue,
95 				struct aac_command *cm);
96 static int	aac_dequeue_fib(struct aac_softc *sc, int queue,
97 				u_int32_t *fib_size, struct aac_fib **fib_addr);
98 static int	aac_enqueue_response(struct aac_softc *sc, int queue,
99 				     struct aac_fib *fib);
100 
101 /* Falcon/PPC interface */
102 static int	aac_fa_get_fwstatus(struct aac_softc *sc);
103 static void	aac_fa_qnotify(struct aac_softc *sc, int qbit);
104 static int	aac_fa_get_istatus(struct aac_softc *sc);
105 static void	aac_fa_clear_istatus(struct aac_softc *sc, int mask);
106 static void	aac_fa_set_mailbox(struct aac_softc *sc, u_int32_t command,
107 				   u_int32_t arg0, u_int32_t arg1,
108 				   u_int32_t arg2, u_int32_t arg3);
109 static int	aac_fa_get_mailbox(struct aac_softc *sc, int mb);
110 static void	aac_fa_set_interrupts(struct aac_softc *sc, int enable);
111 
112 struct aac_interface aac_fa_interface = {
113 	aac_fa_get_fwstatus,
114 	aac_fa_qnotify,
115 	aac_fa_get_istatus,
116 	aac_fa_clear_istatus,
117 	aac_fa_set_mailbox,
118 	aac_fa_get_mailbox,
119 	aac_fa_set_interrupts
120 };
121 
122 /* StrongARM interface */
123 static int	aac_sa_get_fwstatus(struct aac_softc *sc);
124 static void	aac_sa_qnotify(struct aac_softc *sc, int qbit);
125 static int	aac_sa_get_istatus(struct aac_softc *sc);
126 static void	aac_sa_clear_istatus(struct aac_softc *sc, int mask);
127 static void	aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
128 				   u_int32_t arg0, u_int32_t arg1,
129 				   u_int32_t arg2, u_int32_t arg3);
130 static int	aac_sa_get_mailbox(struct aac_softc *sc, int mb);
131 static void	aac_sa_set_interrupts(struct aac_softc *sc, int enable);
132 
133 struct aac_interface aac_sa_interface = {
134 	aac_sa_get_fwstatus,
135 	aac_sa_qnotify,
136 	aac_sa_get_istatus,
137 	aac_sa_clear_istatus,
138 	aac_sa_set_mailbox,
139 	aac_sa_get_mailbox,
140 	aac_sa_set_interrupts
141 };
142 
143 /* i960Rx interface */
144 static int	aac_rx_get_fwstatus(struct aac_softc *sc);
145 static void	aac_rx_qnotify(struct aac_softc *sc, int qbit);
146 static int	aac_rx_get_istatus(struct aac_softc *sc);
147 static void	aac_rx_clear_istatus(struct aac_softc *sc, int mask);
148 static void	aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
149 				   u_int32_t arg0, u_int32_t arg1,
150 				   u_int32_t arg2, u_int32_t arg3);
151 static int	aac_rx_get_mailbox(struct aac_softc *sc, int mb);
152 static void	aac_rx_set_interrupts(struct aac_softc *sc, int enable);
153 
154 struct aac_interface aac_rx_interface = {
155 	aac_rx_get_fwstatus,
156 	aac_rx_qnotify,
157 	aac_rx_get_istatus,
158 	aac_rx_clear_istatus,
159 	aac_rx_set_mailbox,
160 	aac_rx_get_mailbox,
161 	aac_rx_set_interrupts
162 };
163 
164 /* Debugging and Diagnostics */
165 static void	aac_describe_controller(struct aac_softc *sc);
166 static char	*aac_describe_code(struct aac_code_lookup *table,
167 				   u_int32_t code);
168 
169 /* Management Interface */
170 static d_open_t		aac_open;
171 static d_close_t	aac_close;
172 static d_ioctl_t	aac_ioctl;
173 static d_poll_t		aac_poll;
174 static int		aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib);
175 static void		aac_handle_aif(struct aac_softc *sc,
176 					   struct aac_fib *fib);
177 static int		aac_rev_check(struct aac_softc *sc, caddr_t udata);
178 static int		aac_getnext_aif(struct aac_softc *sc, caddr_t arg);
179 static int		aac_return_aif(struct aac_softc *sc, caddr_t uptr);
180 static int		aac_query_disk(struct aac_softc *sc, caddr_t uptr);
181 
182 static struct cdevsw aac_cdevsw = {
183 	.d_version =	D_VERSION,
184 	.d_flags =	D_NEEDGIANT,
185 	.d_open =	aac_open,
186 	.d_close =	aac_close,
187 	.d_ioctl =	aac_ioctl,
188 	.d_poll =	aac_poll,
189 	.d_name =	"aac",
190 };
191 
192 MALLOC_DEFINE(M_AACBUF, "aacbuf", "Buffers for the AAC driver");
193 
194 /* sysctl node */
195 SYSCTL_NODE(_hw, OID_AUTO, aac, CTLFLAG_RD, 0, "AAC driver parameters");
196 
197 /*
198  * Device Interface
199  */
200 
201 /*
202  * Initialise the controller and softc
203  */
204 int
205 aac_attach(struct aac_softc *sc)
206 {
207 	int error, unit;
208 
209 	debug_called(1);
210 
211 	/*
212 	 * Initialise per-controller queues.
213 	 */
214 	aac_initq_free(sc);
215 	aac_initq_ready(sc);
216 	aac_initq_busy(sc);
217 	aac_initq_bio(sc);
218 
219 	/*
220 	 * Initialise command-completion task.
221 	 */
222 	TASK_INIT(&sc->aac_task_complete, 0, aac_complete, sc);
223 
224 	/* disable interrupts before we enable anything */
225 	AAC_MASK_INTERRUPTS(sc);
226 
227 	/* mark controller as suspended until we get ourselves organised */
228 	sc->aac_state |= AAC_STATE_SUSPEND;
229 
230 	/*
231 	 * Check that the firmware on the card is supported.
232 	 */
233 	if ((error = aac_check_firmware(sc)) != 0)
234 		return(error);
235 
236 	/*
237 	 * Initialize locks
238 	 */
239 	AAC_LOCK_INIT(&sc->aac_aifq_lock, "AAC AIF lock");
240 	AAC_LOCK_INIT(&sc->aac_io_lock, "AAC I/O lock");
241 	AAC_LOCK_INIT(&sc->aac_container_lock, "AAC container lock");
242 	TAILQ_INIT(&sc->aac_container_tqh);
243 
244 	/* Initialize the local AIF queue pointers */
245 	sc->aac_aifq_head = sc->aac_aifq_tail = AAC_AIFQ_LENGTH;
246 
247 	/*
248 	 * Initialise the adapter.
249 	 */
250 	if ((error = aac_init(sc)) != 0)
251 		return(error);
252 
253 	/*
254 	 * Print a little information about the controller.
255 	 */
256 	aac_describe_controller(sc);
257 
258 	/*
259 	 * Register to probe our containers later.
260 	 */
261 	sc->aac_ich.ich_func = aac_startup;
262 	sc->aac_ich.ich_arg = sc;
263 	if (config_intrhook_establish(&sc->aac_ich) != 0) {
264 		device_printf(sc->aac_dev,
265 			      "can't establish configuration hook\n");
266 		return(ENXIO);
267 	}
268 
269 	/*
270 	 * Make the control device.
271 	 */
272 	unit = device_get_unit(sc->aac_dev);
273 	sc->aac_dev_t = make_dev(&aac_cdevsw, unit, UID_ROOT, GID_OPERATOR,
274 				 0640, "aac%d", unit);
275 	(void)make_dev_alias(sc->aac_dev_t, "afa%d", unit);
276 	(void)make_dev_alias(sc->aac_dev_t, "hpn%d", unit);
277 	sc->aac_dev_t->si_drv1 = sc;
278 
279 	/* Create the AIF thread */
280 	if (kthread_create((void(*)(void *))aac_command_thread, sc,
281 			   &sc->aifthread, 0, 0, "aac%daif", unit))
282 		panic("Could not create AIF thread\n");
283 
284 	/* Register the shutdown method to only be called post-dump */
285 	if ((sc->eh = EVENTHANDLER_REGISTER(shutdown_final, aac_shutdown,
286 	    sc->aac_dev, SHUTDOWN_PRI_DEFAULT)) == NULL)
287 		device_printf(sc->aac_dev,
288 			      "shutdown event registration failed\n");
289 
290 	/* Register with CAM for the non-DASD devices */
291 	if ((sc->flags & AAC_FLAGS_ENABLE_CAM) != 0) {
292 		TAILQ_INIT(&sc->aac_sim_tqh);
293 		aac_get_bus_info(sc);
294 	}
295 
296 	return(0);
297 }
298 
299 /*
300  * Probe for containers, create disks.
301  */
302 static void
303 aac_startup(void *arg)
304 {
305 	struct aac_softc *sc;
306 	struct aac_fib *fib;
307 	struct aac_mntinfo *mi;
308 	struct aac_mntinforesp *mir = NULL;
309 	int count = 0, i = 0;
310 
311 	debug_called(1);
312 
313 	sc = (struct aac_softc *)arg;
314 
315 	/* disconnect ourselves from the intrhook chain */
316 	config_intrhook_disestablish(&sc->aac_ich);
317 
318 	aac_alloc_sync_fib(sc, &fib);
319 	mi = (struct aac_mntinfo *)&fib->data[0];
320 
321 	/* loop over possible containers */
322 	do {
323 		/* request information on this container */
324 		bzero(mi, sizeof(struct aac_mntinfo));
325 		mi->Command = VM_NameServe;
326 		mi->MntType = FT_FILESYS;
327 		mi->MntCount = i;
328 		if (aac_sync_fib(sc, ContainerCommand, 0, fib,
329 				 sizeof(struct aac_mntinfo))) {
330 			printf("error probing container %d", i);
331 			continue;
332 		}
333 
334 		mir = (struct aac_mntinforesp *)&fib->data[0];
335 		/* XXX Need to check if count changed */
336 		count = mir->MntRespCount;
337 		aac_add_container(sc, mir, 0);
338 		i++;
339 	} while ((i < count) && (i < AAC_MAX_CONTAINERS));
340 
341 	aac_release_sync_fib(sc);
342 
343 	/* poke the bus to actually attach the child devices */
344 	if (bus_generic_attach(sc->aac_dev))
345 		device_printf(sc->aac_dev, "bus_generic_attach failed\n");
346 
347 	/* mark the controller up */
348 	sc->aac_state &= ~AAC_STATE_SUSPEND;
349 
350 	/* enable interrupts now */
351 	AAC_UNMASK_INTERRUPTS(sc);
352 }
353 
354 /*
355  * Create a device to respresent a new container
356  */
357 static void
358 aac_add_container(struct aac_softc *sc, struct aac_mntinforesp *mir, int f)
359 {
360 	struct aac_container *co;
361 	device_t child;
362 
363 	/*
364 	 * Check container volume type for validity.  Note that many of
365 	 * the possible types may never show up.
366 	 */
367 	if ((mir->Status == ST_OK) && (mir->MntTable[0].VolType != CT_NONE)) {
368 		co = (struct aac_container *)malloc(sizeof *co, M_AACBUF,
369 		       M_NOWAIT | M_ZERO);
370 		if (co == NULL)
371 			panic("Out of memory?!\n");
372 		debug(1, "id %x  name '%.16s'  size %u  type %d",
373 		      mir->MntTable[0].ObjectId,
374 		      mir->MntTable[0].FileSystemName,
375 		      mir->MntTable[0].Capacity, mir->MntTable[0].VolType);
376 
377 		if ((child = device_add_child(sc->aac_dev, "aacd", -1)) == NULL)
378 			device_printf(sc->aac_dev, "device_add_child failed\n");
379 		else
380 			device_set_ivars(child, co);
381 		device_set_desc(child, aac_describe_code(aac_container_types,
382 				mir->MntTable[0].VolType));
383 		co->co_disk = child;
384 		co->co_found = f;
385 		bcopy(&mir->MntTable[0], &co->co_mntobj,
386 		      sizeof(struct aac_mntobj));
387 		AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
388 		TAILQ_INSERT_TAIL(&sc->aac_container_tqh, co, co_link);
389 		AAC_LOCK_RELEASE(&sc->aac_container_lock);
390 	}
391 }
392 
393 /*
394  * Free all of the resources associated with (sc)
395  *
396  * Should not be called if the controller is active.
397  */
398 void
399 aac_free(struct aac_softc *sc)
400 {
401 
402 	debug_called(1);
403 
404 	/* remove the control device */
405 	if (sc->aac_dev_t != NULL)
406 		destroy_dev(sc->aac_dev_t);
407 
408 	/* throw away any FIB buffers, discard the FIB DMA tag */
409 	aac_free_commands(sc);
410 	if (sc->aac_fib_dmat)
411 		bus_dma_tag_destroy(sc->aac_fib_dmat);
412 
413 	free(sc->aac_commands, M_AACBUF);
414 
415 	/* destroy the common area */
416 	if (sc->aac_common) {
417 		bus_dmamap_unload(sc->aac_common_dmat, sc->aac_common_dmamap);
418 		bus_dmamem_free(sc->aac_common_dmat, sc->aac_common,
419 				sc->aac_common_dmamap);
420 	}
421 	if (sc->aac_common_dmat)
422 		bus_dma_tag_destroy(sc->aac_common_dmat);
423 
424 	/* disconnect the interrupt handler */
425 	if (sc->aac_intr)
426 		bus_teardown_intr(sc->aac_dev, sc->aac_irq, sc->aac_intr);
427 	if (sc->aac_irq != NULL)
428 		bus_release_resource(sc->aac_dev, SYS_RES_IRQ, sc->aac_irq_rid,
429 				     sc->aac_irq);
430 
431 	/* destroy data-transfer DMA tag */
432 	if (sc->aac_buffer_dmat)
433 		bus_dma_tag_destroy(sc->aac_buffer_dmat);
434 
435 	/* destroy the parent DMA tag */
436 	if (sc->aac_parent_dmat)
437 		bus_dma_tag_destroy(sc->aac_parent_dmat);
438 
439 	/* release the register window mapping */
440 	if (sc->aac_regs_resource != NULL)
441 		bus_release_resource(sc->aac_dev, SYS_RES_MEMORY,
442 				     sc->aac_regs_rid, sc->aac_regs_resource);
443 }
444 
445 /*
446  * Disconnect from the controller completely, in preparation for unload.
447  */
448 int
449 aac_detach(device_t dev)
450 {
451 	struct aac_softc *sc;
452 	struct aac_container *co;
453 	struct aac_sim	*sim;
454 	int error;
455 
456 	debug_called(1);
457 
458 	sc = device_get_softc(dev);
459 
460 	if (sc->aac_state & AAC_STATE_OPEN)
461 		return(EBUSY);
462 
463 	/* Remove the child containers */
464 	while ((co = TAILQ_FIRST(&sc->aac_container_tqh)) != NULL) {
465 		error = device_delete_child(dev, co->co_disk);
466 		if (error)
467 			return (error);
468 		TAILQ_REMOVE(&sc->aac_container_tqh, co, co_link);
469 		free(co, M_AACBUF);
470 	}
471 
472 	/* Remove the CAM SIMs */
473 	while ((sim = TAILQ_FIRST(&sc->aac_sim_tqh)) != NULL) {
474 		TAILQ_REMOVE(&sc->aac_sim_tqh, sim, sim_link);
475 		error = device_delete_child(dev, sim->sim_dev);
476 		if (error)
477 			return (error);
478 		free(sim, M_AACBUF);
479 	}
480 
481 	if (sc->aifflags & AAC_AIFFLAGS_RUNNING) {
482 		sc->aifflags |= AAC_AIFFLAGS_EXIT;
483 		wakeup(sc->aifthread);
484 		tsleep(sc->aac_dev, PUSER | PCATCH, "aacdch", 30 * hz);
485 	}
486 
487 	if (sc->aifflags & AAC_AIFFLAGS_RUNNING)
488 		panic("Cannot shutdown AIF thread\n");
489 
490 	if ((error = aac_shutdown(dev)))
491 		return(error);
492 
493 	EVENTHANDLER_DEREGISTER(shutdown_final, sc->eh);
494 
495 	aac_free(sc);
496 
497 	return(0);
498 }
499 
500 /*
501  * Bring the controller down to a dormant state and detach all child devices.
502  *
503  * This function is called before detach or system shutdown.
504  *
505  * Note that we can assume that the bioq on the controller is empty, as we won't
506  * allow shutdown if any device is open.
507  */
508 int
509 aac_shutdown(device_t dev)
510 {
511 	struct aac_softc *sc;
512 	struct aac_fib *fib;
513 	struct aac_close_command *cc;
514 
515 	debug_called(1);
516 
517 	sc = device_get_softc(dev);
518 
519 	sc->aac_state |= AAC_STATE_SUSPEND;
520 
521 	/*
522 	 * Send a Container shutdown followed by a HostShutdown FIB to the
523 	 * controller to convince it that we don't want to talk to it anymore.
524 	 * We've been closed and all I/O completed already
525 	 */
526 	device_printf(sc->aac_dev, "shutting down controller...");
527 
528 	aac_alloc_sync_fib(sc, &fib);
529 	cc = (struct aac_close_command *)&fib->data[0];
530 
531 	bzero(cc, sizeof(struct aac_close_command));
532 	cc->Command = VM_CloseAll;
533 	cc->ContainerId = 0xffffffff;
534 	if (aac_sync_fib(sc, ContainerCommand, 0, fib,
535 	    sizeof(struct aac_close_command)))
536 		printf("FAILED.\n");
537 	else
538 		printf("done\n");
539 #if 0
540 	else {
541 		fib->data[0] = 0;
542 		/*
543 		 * XXX Issuing this command to the controller makes it shut down
544 		 * but also keeps it from coming back up without a reset of the
545 		 * PCI bus.  This is not desirable if you are just unloading the
546 		 * driver module with the intent to reload it later.
547 		 */
548 		if (aac_sync_fib(sc, FsaHostShutdown, AAC_FIBSTATE_SHUTDOWN,
549 		    fib, 1)) {
550 			printf("FAILED.\n");
551 		} else {
552 			printf("done.\n");
553 		}
554 	}
555 #endif
556 
557 	AAC_MASK_INTERRUPTS(sc);
558 
559 	return(0);
560 }
561 
562 /*
563  * Bring the controller to a quiescent state, ready for system suspend.
564  */
565 int
566 aac_suspend(device_t dev)
567 {
568 	struct aac_softc *sc;
569 
570 	debug_called(1);
571 
572 	sc = device_get_softc(dev);
573 
574 	sc->aac_state |= AAC_STATE_SUSPEND;
575 
576 	AAC_MASK_INTERRUPTS(sc);
577 	return(0);
578 }
579 
580 /*
581  * Bring the controller back to a state ready for operation.
582  */
583 int
584 aac_resume(device_t dev)
585 {
586 	struct aac_softc *sc;
587 
588 	debug_called(1);
589 
590 	sc = device_get_softc(dev);
591 
592 	sc->aac_state &= ~AAC_STATE_SUSPEND;
593 	AAC_UNMASK_INTERRUPTS(sc);
594 	return(0);
595 }
596 
597 /*
598  * Take an interrupt.
599  */
600 void
601 aac_intr(void *arg)
602 {
603 	struct aac_softc *sc;
604 	u_int16_t reason;
605 
606 	debug_called(2);
607 
608 	sc = (struct aac_softc *)arg;
609 
610 	/*
611 	 * Read the status register directly.  This is faster than taking the
612 	 * driver lock and reading the queues directly.  It also saves having
613 	 * to turn parts of the driver lock into a spin mutex, which would be
614 	 * ugly.
615 	 */
616 	reason = AAC_GET_ISTATUS(sc);
617 	AAC_CLEAR_ISTATUS(sc, reason);
618 
619 	/* handle completion processing */
620 	if (reason & AAC_DB_RESPONSE_READY)
621 		taskqueue_enqueue_fast(taskqueue_fast, &sc->aac_task_complete);
622 
623 	/* controller wants to talk to us */
624 	if (reason & (AAC_DB_PRINTF | AAC_DB_COMMAND_READY)) {
625 		/*
626 		 * XXX Make sure that we don't get fooled by strange messages
627 		 * that start with a NULL.
628 		 */
629 		if ((reason & AAC_DB_PRINTF) &&
630 		    (sc->aac_common->ac_printf[0] == 0))
631 			sc->aac_common->ac_printf[0] = 32;
632 
633 		/*
634 		 * This might miss doing the actual wakeup.  However, the
635 		 * msleep that this is waking up has a timeout, so it will
636 		 * wake up eventually.  AIFs and printfs are low enough
637 		 * priority that they can handle hanging out for a few seconds
638 		 * if needed.
639 		 */
640 		wakeup(sc->aifthread);
641 	}
642 }
643 
644 /*
645  * Command Processing
646  */
647 
648 /*
649  * Start as much queued I/O as possible on the controller
650  */
651 void
652 aac_startio(struct aac_softc *sc)
653 {
654 	struct aac_command *cm;
655 	int error;
656 
657 	debug_called(2);
658 
659 	for (;;) {
660 		/*
661 		 * This flag might be set if the card is out of resources.
662 		 * Checking it here prevents an infinite loop of deferrals.
663 		 */
664 		if (sc->flags & AAC_QUEUE_FRZN)
665 			break;
666 
667 		/*
668 		 * Try to get a command that's been put off for lack of
669 		 * resources
670 		 */
671 		cm = aac_dequeue_ready(sc);
672 
673 		/*
674 		 * Try to build a command off the bio queue (ignore error
675 		 * return)
676 		 */
677 		if (cm == NULL)
678 			aac_bio_command(sc, &cm);
679 
680 		/* nothing to do? */
681 		if (cm == NULL)
682 			break;
683 
684 		/* don't map more than once */
685 		if (cm->cm_flags & AAC_CMD_MAPPED)
686 			panic("aac: command %p already mapped", cm);
687 
688 		/*
689 		 * Set up the command to go to the controller.  If there are no
690 		 * data buffers associated with the command then it can bypass
691 		 * busdma.
692 		 */
693 		if (cm->cm_datalen != 0) {
694 			error = bus_dmamap_load(sc->aac_buffer_dmat,
695 						cm->cm_datamap, cm->cm_data,
696 						cm->cm_datalen,
697 						aac_map_command_sg, cm, 0);
698 			if (error == EINPROGRESS) {
699 				debug(1, "freezing queue\n");
700 				sc->flags |= AAC_QUEUE_FRZN;
701 				error = 0;
702 			} else if (error != 0)
703 				panic("aac_startio: unexpected error %d from "
704 				      "busdma\n", error);
705 		} else
706 			aac_map_command_sg(cm, NULL, 0, 0);
707 	}
708 }
709 
710 /*
711  * Handle notification of one or more FIBs coming from the controller.
712  */
713 static void
714 aac_command_thread(struct aac_softc *sc)
715 {
716 	struct aac_fib *fib;
717 	u_int32_t fib_size;
718 	int size, retval;
719 
720 	debug_called(2);
721 
722 	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
723 	sc->aifflags = AAC_AIFFLAGS_RUNNING;
724 
725 	while ((sc->aifflags & AAC_AIFFLAGS_EXIT) == 0) {
726 
727 		retval = 0;
728 		if ((sc->aifflags & AAC_AIFFLAGS_PENDING) == 0)
729 			retval = msleep(sc->aifthread, &sc->aac_io_lock, PRIBIO,
730 					"aifthd", AAC_PERIODIC_INTERVAL * hz);
731 
732 		/*
733 		 * First see if any FIBs need to be allocated.  This needs
734 		 * to be called without the driver lock because contigmalloc
735 		 * will grab Giant, and would result in an LOR.
736 		 */
737 		if ((sc->aifflags & AAC_AIFFLAGS_ALLOCFIBS) != 0) {
738 			AAC_LOCK_RELEASE(&sc->aac_io_lock);
739 			aac_alloc_commands(sc);
740 			AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
741 			sc->aifflags &= ~AAC_AIFFLAGS_ALLOCFIBS;
742 			aac_startio(sc);
743 		}
744 
745 		/*
746 		 * While we're here, check to see if any commands are stuck.
747 		 * This is pretty low-priority, so it's ok if it doesn't
748 		 * always fire.
749 		 */
750 		if (retval == EWOULDBLOCK)
751 			aac_timeout(sc);
752 
753 		/* Check the hardware printf message buffer */
754 		if (sc->aac_common->ac_printf[0] != 0)
755 			aac_print_printf(sc);
756 
757 		/* Also check to see if the adapter has a command for us. */
758 		while (aac_dequeue_fib(sc, AAC_HOST_NORM_CMD_QUEUE,
759 				       &fib_size, &fib) == 0) {
760 
761 			AAC_PRINT_FIB(sc, fib);
762 
763 			switch (fib->Header.Command) {
764 			case AifRequest:
765 				aac_handle_aif(sc, fib);
766 				break;
767 			default:
768 				device_printf(sc->aac_dev, "unknown command "
769 					      "from controller\n");
770 				break;
771 			}
772 
773 			if ((fib->Header.XferState == 0) ||
774 			    (fib->Header.StructType != AAC_FIBTYPE_TFIB))
775 				break;
776 
777 			/* Return the AIF to the controller. */
778 			if (fib->Header.XferState & AAC_FIBSTATE_FROMADAP) {
779 				fib->Header.XferState |= AAC_FIBSTATE_DONEHOST;
780 				*(AAC_FSAStatus*)fib->data = ST_OK;
781 
782 				/* XXX Compute the Size field? */
783 				size = fib->Header.Size;
784 				if (size > sizeof(struct aac_fib)) {
785 					size = sizeof(struct aac_fib);
786 					fib->Header.Size = size;
787 				}
788 				/*
789 				 * Since we did not generate this command, it
790 				 * cannot go through the normal
791 				 * enqueue->startio chain.
792 				 */
793 				aac_enqueue_response(sc,
794 						     AAC_ADAP_NORM_RESP_QUEUE,
795 						     fib);
796 			}
797 		}
798 	}
799 	sc->aifflags &= ~AAC_AIFFLAGS_RUNNING;
800 	AAC_LOCK_RELEASE(&sc->aac_io_lock);
801 	wakeup(sc->aac_dev);
802 
803 	kthread_exit(0);
804 }
805 
806 /*
807  * Process completed commands.
808  */
809 static void
810 aac_complete(void *context, int pending)
811 {
812 	struct aac_softc *sc;
813 	struct aac_command *cm;
814 	struct aac_fib *fib;
815 	u_int32_t fib_size;
816 
817 	debug_called(2);
818 
819 	sc = (struct aac_softc *)context;
820 
821 	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
822 
823 	/* pull completed commands off the queue */
824 	for (;;) {
825 		/* look for completed FIBs on our queue */
826 		if (aac_dequeue_fib(sc, AAC_HOST_NORM_RESP_QUEUE, &fib_size,
827 				    &fib))
828 			break;	/* nothing to do */
829 
830 		/* get the command, unmap and hand off for processing */
831 		cm = sc->aac_commands + fib->Header.SenderData;
832 		if (cm == NULL) {
833 			AAC_PRINT_FIB(sc, fib);
834 			break;
835 		}
836 
837 		aac_remove_busy(cm);
838 		aac_unmap_command(cm);
839 		cm->cm_flags |= AAC_CMD_COMPLETED;
840 
841 		/* is there a completion handler? */
842 		if (cm->cm_complete != NULL) {
843 			cm->cm_complete(cm);
844 		} else {
845 			/* assume that someone is sleeping on this command */
846 			wakeup(cm);
847 		}
848 	}
849 
850 	/* see if we can start some more I/O */
851 	sc->flags &= ~AAC_QUEUE_FRZN;
852 	aac_startio(sc);
853 
854 	AAC_LOCK_RELEASE(&sc->aac_io_lock);
855 }
856 
857 /*
858  * Handle a bio submitted from a disk device.
859  */
860 void
861 aac_submit_bio(struct bio *bp)
862 {
863 	struct aac_disk *ad;
864 	struct aac_softc *sc;
865 
866 	debug_called(2);
867 
868 	ad = (struct aac_disk *)bp->bio_disk->d_drv1;
869 	sc = ad->ad_controller;
870 
871 	/* queue the BIO and try to get some work done */
872 	aac_enqueue_bio(sc, bp);
873 	aac_startio(sc);
874 }
875 
876 /*
877  * Get a bio and build a command to go with it.
878  */
879 static int
880 aac_bio_command(struct aac_softc *sc, struct aac_command **cmp)
881 {
882 	struct aac_command *cm;
883 	struct aac_fib *fib;
884 	struct aac_disk *ad;
885 	struct bio *bp;
886 
887 	debug_called(2);
888 
889 	/* get the resources we will need */
890 	cm = NULL;
891 	bp = NULL;
892 	if (aac_alloc_command(sc, &cm))	/* get a command */
893 		goto fail;
894 	if ((bp = aac_dequeue_bio(sc)) == NULL)
895 		goto fail;
896 
897 	/* fill out the command */
898 	cm->cm_data = (void *)bp->bio_data;
899 	cm->cm_datalen = bp->bio_bcount;
900 	cm->cm_complete = aac_bio_complete;
901 	cm->cm_private = bp;
902 	cm->cm_timestamp = time_second;
903 	cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
904 
905 	/* build the FIB */
906 	fib = cm->cm_fib;
907 	fib->Header.Size = sizeof(struct aac_fib_header);
908 	fib->Header.XferState =
909 		AAC_FIBSTATE_HOSTOWNED   |
910 		AAC_FIBSTATE_INITIALISED |
911 		AAC_FIBSTATE_EMPTY	 |
912 		AAC_FIBSTATE_FROMHOST	 |
913 		AAC_FIBSTATE_REXPECTED   |
914 		AAC_FIBSTATE_NORM	 |
915 		AAC_FIBSTATE_ASYNC	 |
916 		AAC_FIBSTATE_FAST_RESPONSE;
917 
918 	/* build the read/write request */
919 	ad = (struct aac_disk *)bp->bio_disk->d_drv1;
920 
921 	if ((sc->flags & AAC_FLAGS_SG_64BIT) == 0) {
922 		fib->Header.Command = ContainerCommand;
923 		if (bp->bio_cmd == BIO_READ) {
924 			struct aac_blockread *br;
925 			br = (struct aac_blockread *)&fib->data[0];
926 			br->Command = VM_CtBlockRead;
927 			br->ContainerId = ad->ad_container->co_mntobj.ObjectId;
928 			br->BlockNumber = bp->bio_pblkno;
929 			br->ByteCount = bp->bio_bcount;
930 			fib->Header.Size += sizeof(struct aac_blockread);
931 			cm->cm_sgtable = &br->SgMap;
932 			cm->cm_flags |= AAC_CMD_DATAIN;
933 		} else {
934 			struct aac_blockwrite *bw;
935 			bw = (struct aac_blockwrite *)&fib->data[0];
936 			bw->Command = VM_CtBlockWrite;
937 			bw->ContainerId = ad->ad_container->co_mntobj.ObjectId;
938 			bw->BlockNumber = bp->bio_pblkno;
939 			bw->ByteCount = bp->bio_bcount;
940 			bw->Stable = CUNSTABLE;
941 			fib->Header.Size += sizeof(struct aac_blockwrite);
942 			cm->cm_flags |= AAC_CMD_DATAOUT;
943 			cm->cm_sgtable = &bw->SgMap;
944 		}
945 	} else {
946 		fib->Header.Command = ContainerCommand64;
947 		if (bp->bio_cmd == BIO_READ) {
948 			struct aac_blockread64 *br;
949 			br = (struct aac_blockread64 *)&fib->data[0];
950 			br->Command = VM_CtHostRead64;
951 			br->ContainerId = ad->ad_container->co_mntobj.ObjectId;
952 			br->SectorCount = bp->bio_bcount / AAC_BLOCK_SIZE;
953 			br->BlockNumber = bp->bio_pblkno;
954 			br->Pad = 0;
955 			br->Flags = 0;
956 			fib->Header.Size += sizeof(struct aac_blockread64);
957 			cm->cm_flags |= AAC_CMD_DATAOUT;
958 			cm->cm_sgtable = (struct aac_sg_table *)&br->SgMap64;
959 		} else {
960 			struct aac_blockwrite64 *bw;
961 			bw = (struct aac_blockwrite64 *)&fib->data[0];
962 			bw->Command = VM_CtHostWrite64;
963 			bw->ContainerId = ad->ad_container->co_mntobj.ObjectId;
964 			bw->SectorCount = bp->bio_bcount / AAC_BLOCK_SIZE;
965 			bw->BlockNumber = bp->bio_pblkno;
966 			bw->Pad = 0;
967 			bw->Flags = 0;
968 			fib->Header.Size += sizeof(struct aac_blockwrite64);
969 			cm->cm_flags |= AAC_CMD_DATAIN;
970 			cm->cm_sgtable = (struct aac_sg_table *)&bw->SgMap64;
971 		}
972 	}
973 
974 	*cmp = cm;
975 	return(0);
976 
977 fail:
978 	if (bp != NULL)
979 		aac_enqueue_bio(sc, bp);
980 	if (cm != NULL)
981 		aac_release_command(cm);
982 	return(ENOMEM);
983 }
984 
985 /*
986  * Handle a bio-instigated command that has been completed.
987  */
988 static void
989 aac_bio_complete(struct aac_command *cm)
990 {
991 	struct aac_blockread_response *brr;
992 	struct aac_blockwrite_response *bwr;
993 	struct bio *bp;
994 	AAC_FSAStatus status;
995 
996 	/* fetch relevant status and then release the command */
997 	bp = (struct bio *)cm->cm_private;
998 	if (bp->bio_cmd == BIO_READ) {
999 		brr = (struct aac_blockread_response *)&cm->cm_fib->data[0];
1000 		status = brr->Status;
1001 	} else {
1002 		bwr = (struct aac_blockwrite_response *)&cm->cm_fib->data[0];
1003 		status = bwr->Status;
1004 	}
1005 	aac_release_command(cm);
1006 
1007 	/* fix up the bio based on status */
1008 	if (status == ST_OK) {
1009 		bp->bio_resid = 0;
1010 	} else {
1011 		bp->bio_error = EIO;
1012 		bp->bio_flags |= BIO_ERROR;
1013 		/* pass an error string out to the disk layer */
1014 		bp->bio_driver1 = aac_describe_code(aac_command_status_table,
1015 						    status);
1016 	}
1017 	aac_biodone(bp);
1018 }
1019 
1020 /*
1021  * Submit a command to the controller, return when it completes.
1022  * XXX This is very dangerous!  If the card has gone out to lunch, we could
1023  *     be stuck here forever.  At the same time, signals are not caught
1024  *     because there is a risk that a signal could wakeup the sleep before
1025  *     the card has a chance to complete the command.  Since there is no way
1026  *     to cancel a command that is in progress, we can't protect against the
1027  *     card completing a command late and spamming the command and data
1028  *     memory.  So, we are held hostage until the command completes.
1029  */
1030 static int
1031 aac_wait_command(struct aac_command *cm)
1032 {
1033 	struct aac_softc *sc;
1034 	int error;
1035 
1036 	debug_called(2);
1037 
1038 	sc = cm->cm_sc;
1039 
1040 	/* Put the command on the ready queue and get things going */
1041 	cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
1042 	aac_enqueue_ready(cm);
1043 	aac_startio(sc);
1044 	error = msleep(cm, &sc->aac_io_lock, PRIBIO, "aacwait", 0);
1045 	return(error);
1046 }
1047 
1048 /*
1049  *Command Buffer Management
1050  */
1051 
1052 /*
1053  * Allocate a command.
1054  */
1055 int
1056 aac_alloc_command(struct aac_softc *sc, struct aac_command **cmp)
1057 {
1058 	struct aac_command *cm;
1059 
1060 	debug_called(3);
1061 
1062 	if ((cm = aac_dequeue_free(sc)) == NULL) {
1063 		if (sc->total_fibs < sc->aac_max_fibs) {
1064 			sc->aifflags |= AAC_AIFFLAGS_ALLOCFIBS;
1065 			wakeup(sc->aifthread);
1066 		}
1067 		return (EBUSY);
1068 	}
1069 
1070 	*cmp = cm;
1071 	return(0);
1072 }
1073 
1074 /*
1075  * Release a command back to the freelist.
1076  */
1077 void
1078 aac_release_command(struct aac_command *cm)
1079 {
1080 	debug_called(3);
1081 
1082 	/* (re)initialise the command/FIB */
1083 	cm->cm_sgtable = NULL;
1084 	cm->cm_flags = 0;
1085 	cm->cm_complete = NULL;
1086 	cm->cm_private = NULL;
1087 	cm->cm_fib->Header.XferState = AAC_FIBSTATE_EMPTY;
1088 	cm->cm_fib->Header.StructType = AAC_FIBTYPE_TFIB;
1089 	cm->cm_fib->Header.Flags = 0;
1090 	cm->cm_fib->Header.SenderSize = sizeof(struct aac_fib);
1091 
1092 	/*
1093 	 * These are duplicated in aac_start to cover the case where an
1094 	 * intermediate stage may have destroyed them.  They're left
1095 	 * initialised here for debugging purposes only.
1096 	 */
1097 	cm->cm_fib->Header.ReceiverFibAddress = (u_int32_t)cm->cm_fibphys;
1098 	cm->cm_fib->Header.SenderData = 0;
1099 
1100 	aac_enqueue_free(cm);
1101 }
1102 
1103 /*
1104  * Map helper for command/FIB allocation.
1105  */
1106 static void
1107 aac_map_command_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1108 {
1109 	uint32_t	*fibphys;
1110 
1111 	fibphys = (uint32_t *)arg;
1112 
1113 	debug_called(3);
1114 
1115 	*fibphys = segs[0].ds_addr;
1116 }
1117 
1118 /*
1119  * Allocate and initialise commands/FIBs for this adapter.
1120  */
1121 static int
1122 aac_alloc_commands(struct aac_softc *sc)
1123 {
1124 	struct aac_command *cm;
1125 	struct aac_fibmap *fm;
1126 	uint32_t fibphys;
1127 	int i, error;
1128 
1129 	debug_called(2);
1130 
1131 	if (sc->total_fibs + AAC_FIB_COUNT > sc->aac_max_fibs)
1132 		return (ENOMEM);
1133 
1134 	fm = malloc(sizeof(struct aac_fibmap), M_AACBUF, M_NOWAIT|M_ZERO);
1135 	if (fm == NULL)
1136 		return (ENOMEM);
1137 
1138 	/* allocate the FIBs in DMAable memory and load them */
1139 	if (bus_dmamem_alloc(sc->aac_fib_dmat, (void **)&fm->aac_fibs,
1140 			     BUS_DMA_NOWAIT, &fm->aac_fibmap)) {
1141 		device_printf(sc->aac_dev,
1142 			      "Not enough contiguous memory available.\n");
1143 		free(fm, M_AACBUF);
1144 		return (ENOMEM);
1145 	}
1146 
1147 	/* Ignore errors since this doesn't bounce */
1148 	(void)bus_dmamap_load(sc->aac_fib_dmat, fm->aac_fibmap, fm->aac_fibs,
1149 			      AAC_FIB_COUNT * sizeof(struct aac_fib),
1150 			      aac_map_command_helper, &fibphys, 0);
1151 
1152 	/* initialise constant fields in the command structure */
1153 	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
1154 	bzero(fm->aac_fibs, AAC_FIB_COUNT * sizeof(struct aac_fib));
1155 	for (i = 0; i < AAC_FIB_COUNT; i++) {
1156 		cm = sc->aac_commands + sc->total_fibs;
1157 		fm->aac_commands = cm;
1158 		cm->cm_sc = sc;
1159 		cm->cm_fib = fm->aac_fibs + i;
1160 		cm->cm_fibphys = fibphys + (i * sizeof(struct aac_fib));
1161 		cm->cm_index = sc->total_fibs;
1162 
1163 		if ((error = bus_dmamap_create(sc->aac_buffer_dmat, 0,
1164 					       &cm->cm_datamap)) == 0)
1165 			aac_release_command(cm);
1166 		else
1167 			break;
1168 		sc->total_fibs++;
1169 	}
1170 
1171 	if (i > 0) {
1172 		TAILQ_INSERT_TAIL(&sc->aac_fibmap_tqh, fm, fm_link);
1173 		debug(1, "total_fibs= %d\n", sc->total_fibs);
1174 		AAC_LOCK_RELEASE(&sc->aac_io_lock);
1175 		return (0);
1176 	}
1177 
1178 	AAC_LOCK_RELEASE(&sc->aac_io_lock);
1179 	bus_dmamap_unload(sc->aac_fib_dmat, fm->aac_fibmap);
1180 	bus_dmamem_free(sc->aac_fib_dmat, fm->aac_fibs, fm->aac_fibmap);
1181 	free(fm, M_AACBUF);
1182 	return (ENOMEM);
1183 }
1184 
1185 /*
1186  * Free FIBs owned by this adapter.
1187  */
1188 static void
1189 aac_free_commands(struct aac_softc *sc)
1190 {
1191 	struct aac_fibmap *fm;
1192 	struct aac_command *cm;
1193 	int i;
1194 
1195 	debug_called(1);
1196 
1197 	while ((fm = TAILQ_FIRST(&sc->aac_fibmap_tqh)) != NULL) {
1198 
1199 		TAILQ_REMOVE(&sc->aac_fibmap_tqh, fm, fm_link);
1200 		/*
1201 		 * We check against total_fibs to handle partially
1202 		 * allocated blocks.
1203 		 */
1204 		for (i = 0; i < AAC_FIB_COUNT && sc->total_fibs--; i++) {
1205 			cm = fm->aac_commands + i;
1206 			bus_dmamap_destroy(sc->aac_buffer_dmat, cm->cm_datamap);
1207 		}
1208 		bus_dmamap_unload(sc->aac_fib_dmat, fm->aac_fibmap);
1209 		bus_dmamem_free(sc->aac_fib_dmat, fm->aac_fibs, fm->aac_fibmap);
1210 		free(fm, M_AACBUF);
1211 	}
1212 }
1213 
1214 /*
1215  * Command-mapping helper function - populate this command's s/g table.
1216  */
1217 static void
1218 aac_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1219 {
1220 	struct aac_softc *sc;
1221 	struct aac_command *cm;
1222 	struct aac_fib *fib;
1223 	int i;
1224 
1225 	debug_called(3);
1226 
1227 	cm = (struct aac_command *)arg;
1228 	sc = cm->cm_sc;
1229 	fib = cm->cm_fib;
1230 
1231 	/* copy into the FIB */
1232 	if (cm->cm_sgtable != NULL) {
1233 		if ((cm->cm_sc->flags & AAC_FLAGS_SG_64BIT) == 0) {
1234 			struct aac_sg_table *sg;
1235 			sg = cm->cm_sgtable;
1236 			sg->SgCount = nseg;
1237 			for (i = 0; i < nseg; i++) {
1238 				sg->SgEntry[i].SgAddress = segs[i].ds_addr;
1239 				sg->SgEntry[i].SgByteCount = segs[i].ds_len;
1240 			}
1241 			/* update the FIB size for the s/g count */
1242 			fib->Header.Size += nseg * sizeof(struct aac_sg_entry);
1243 		} else {
1244 			struct aac_sg_table64 *sg;
1245 			sg = (struct aac_sg_table64 *)cm->cm_sgtable;
1246 			sg->SgCount = nseg;
1247 			for (i = 0; i < nseg; i++) {
1248 				sg->SgEntry64[i].SgAddress = segs[i].ds_addr;
1249 				sg->SgEntry64[i].SgByteCount = segs[i].ds_len;
1250 			}
1251 			/* update the FIB size for the s/g count */
1252 			fib->Header.Size += nseg*sizeof(struct aac_sg_entry64);
1253 		}
1254 	}
1255 
1256 	/* Fix up the address values in the FIB.  Use the command array index
1257 	 * instead of a pointer since these fields are only 32 bits.  Shift
1258 	 * the SenderFibAddress over to make room for the fast response bit.
1259 	 */
1260 	cm->cm_fib->Header.SenderFibAddress = (cm->cm_index << 1);
1261 	cm->cm_fib->Header.ReceiverFibAddress = cm->cm_fibphys;
1262 
1263 	/* save a pointer to the command for speedy reverse-lookup */
1264 	cm->cm_fib->Header.SenderData = cm->cm_index;
1265 
1266 	if (cm->cm_flags & AAC_CMD_DATAIN)
1267 		bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1268 				BUS_DMASYNC_PREREAD);
1269 	if (cm->cm_flags & AAC_CMD_DATAOUT)
1270 		bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1271 				BUS_DMASYNC_PREWRITE);
1272 	cm->cm_flags |= AAC_CMD_MAPPED;
1273 
1274 	/* Put the FIB on the outbound queue */
1275 	if (aac_enqueue_fib(sc, cm->cm_queue, cm) == EBUSY) {
1276 		aac_unmap_command(cm);
1277 		sc->flags |= AAC_QUEUE_FRZN;
1278 		aac_requeue_ready(cm);
1279 	}
1280 
1281 	return;
1282 }
1283 
1284 /*
1285  * Unmap a command from controller-visible space.
1286  */
1287 static void
1288 aac_unmap_command(struct aac_command *cm)
1289 {
1290 	struct aac_softc *sc;
1291 
1292 	debug_called(2);
1293 
1294 	sc = cm->cm_sc;
1295 
1296 	if (!(cm->cm_flags & AAC_CMD_MAPPED))
1297 		return;
1298 
1299 	if (cm->cm_datalen != 0) {
1300 		if (cm->cm_flags & AAC_CMD_DATAIN)
1301 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1302 					BUS_DMASYNC_POSTREAD);
1303 		if (cm->cm_flags & AAC_CMD_DATAOUT)
1304 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1305 					BUS_DMASYNC_POSTWRITE);
1306 
1307 		bus_dmamap_unload(sc->aac_buffer_dmat, cm->cm_datamap);
1308 	}
1309 	cm->cm_flags &= ~AAC_CMD_MAPPED;
1310 }
1311 
1312 /*
1313  * Hardware Interface
1314  */
1315 
1316 /*
1317  * Initialise the adapter.
1318  */
1319 static void
1320 aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1321 {
1322 	struct aac_softc *sc;
1323 
1324 	debug_called(1);
1325 
1326 	sc = (struct aac_softc *)arg;
1327 
1328 	sc->aac_common_busaddr = segs[0].ds_addr;
1329 }
1330 
1331 static int
1332 aac_check_firmware(struct aac_softc *sc)
1333 {
1334 	u_int32_t major, minor, options;
1335 
1336 	debug_called(1);
1337 
1338 	/*
1339 	 * Retrieve the firmware version numbers.  Dell PERC2/QC cards with
1340 	 * firmware version 1.x are not compatible with this driver.
1341 	 */
1342 	if (sc->flags & AAC_FLAGS_PERC2QC) {
1343 		if (aac_sync_command(sc, AAC_MONKER_GETKERNVER, 0, 0, 0, 0,
1344 				     NULL)) {
1345 			device_printf(sc->aac_dev,
1346 				      "Error reading firmware version\n");
1347 			return (EIO);
1348 		}
1349 
1350 		/* These numbers are stored as ASCII! */
1351 		major = (AAC_GET_MAILBOX(sc, 1) & 0xff) - 0x30;
1352 		minor = (AAC_GET_MAILBOX(sc, 2) & 0xff) - 0x30;
1353 		if (major == 1) {
1354 			device_printf(sc->aac_dev,
1355 			    "Firmware version %d.%d is not supported.\n",
1356 			    major, minor);
1357 			return (EINVAL);
1358 		}
1359 	}
1360 
1361 	/*
1362 	 * Retrieve the capabilities/supported options word so we know what
1363 	 * work-arounds to enable.
1364 	 */
1365 	if (aac_sync_command(sc, AAC_MONKER_GETINFO, 0, 0, 0, 0, NULL)) {
1366 		device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
1367 		return (EIO);
1368 	}
1369 	options = AAC_GET_MAILBOX(sc, 1);
1370 	sc->supported_options = options;
1371 
1372 	if ((options & AAC_SUPPORTED_4GB_WINDOW) != 0 &&
1373 	    (sc->flags & AAC_FLAGS_NO4GB) == 0)
1374 		sc->flags |= AAC_FLAGS_4GB_WINDOW;
1375 	if (options & AAC_SUPPORTED_NONDASD)
1376 		sc->flags |= AAC_FLAGS_ENABLE_CAM;
1377 	if ((options & AAC_SUPPORTED_SGMAP_HOST64) != 0
1378 	     && (sizeof(bus_addr_t) > 4)) {
1379 		device_printf(sc->aac_dev, "Enabling 64-bit address support\n");
1380 		sc->flags |= AAC_FLAGS_SG_64BIT;
1381 	}
1382 
1383 	/* Check for broken hardware that does a lower number of commands */
1384 	if ((sc->flags & AAC_FLAGS_256FIBS) == 0)
1385 		sc->aac_max_fibs = AAC_MAX_FIBS;
1386 	else
1387 		sc->aac_max_fibs = 256;
1388 
1389 	return (0);
1390 }
1391 
1392 static int
1393 aac_init(struct aac_softc *sc)
1394 {
1395 	struct aac_adapter_init	*ip;
1396 	time_t then;
1397 	u_int32_t code, qoffset;
1398 	int error;
1399 
1400 	debug_called(1);
1401 
1402 	/*
1403 	 * First wait for the adapter to come ready.
1404 	 */
1405 	then = time_second;
1406 	do {
1407 		code = AAC_GET_FWSTATUS(sc);
1408 		if (code & AAC_SELF_TEST_FAILED) {
1409 			device_printf(sc->aac_dev, "FATAL: selftest failed\n");
1410 			return(ENXIO);
1411 		}
1412 		if (code & AAC_KERNEL_PANIC) {
1413 			device_printf(sc->aac_dev,
1414 				      "FATAL: controller kernel panic\n");
1415 			return(ENXIO);
1416 		}
1417 		if (time_second > (then + AAC_BOOT_TIMEOUT)) {
1418 			device_printf(sc->aac_dev,
1419 				      "FATAL: controller not coming ready, "
1420 					   "status %x\n", code);
1421 			return(ENXIO);
1422 		}
1423 	} while (!(code & AAC_UP_AND_RUNNING));
1424 
1425 	error = ENOMEM;
1426 	/*
1427 	 * Create DMA tag for mapping buffers into controller-addressable space.
1428 	 */
1429 	if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1430 			       1, 0, 			/* algnmnt, boundary */
1431 			       (sc->flags & AAC_FLAGS_SG_64BIT) ?
1432 			       BUS_SPACE_MAXADDR :
1433 			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1434 			       BUS_SPACE_MAXADDR, 	/* highaddr */
1435 			       NULL, NULL, 		/* filter, filterarg */
1436 			       MAXBSIZE,		/* maxsize */
1437 			       AAC_MAXSGENTRIES,	/* nsegments */
1438 			       MAXBSIZE,		/* maxsegsize */
1439 			       BUS_DMA_ALLOCNOW,	/* flags */
1440 			       busdma_lock_mutex,	/* lockfunc */
1441 			       &sc->aac_io_lock,	/* lockfuncarg */
1442 			       &sc->aac_buffer_dmat)) {
1443 		device_printf(sc->aac_dev, "can't allocate buffer DMA tag\n");
1444 		goto out;
1445 	}
1446 
1447 	/*
1448 	 * Create DMA tag for mapping FIBs into controller-addressable space..
1449 	 */
1450 	if (bus_dma_tag_create(sc->aac_parent_dmat,	/* parent */
1451 			       1, 0, 			/* algnmnt, boundary */
1452 			       (sc->flags & AAC_FLAGS_4GB_WINDOW) ?
1453 			       BUS_SPACE_MAXADDR_32BIT :
1454 			       0x7fffffff,		/* lowaddr */
1455 			       BUS_SPACE_MAXADDR, 	/* highaddr */
1456 			       NULL, NULL, 		/* filter, filterarg */
1457 			       AAC_FIB_COUNT *
1458 			       sizeof(struct aac_fib),  /* maxsize */
1459 			       1,			/* nsegments */
1460 			       AAC_FIB_COUNT *
1461 			       sizeof(struct aac_fib),	/* maxsegsize */
1462 			       BUS_DMA_ALLOCNOW,	/* flags */
1463 			       NULL, NULL,		/* No locking needed */
1464 			       &sc->aac_fib_dmat)) {
1465 		device_printf(sc->aac_dev, "can't allocate FIB DMA tag\n");;
1466 		goto out;
1467 	}
1468 
1469 	/*
1470 	 * Create DMA tag for the common structure and allocate it.
1471 	 */
1472 	if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1473 			       1, 0,			/* algnmnt, boundary */
1474 			       (sc->flags & AAC_FLAGS_4GB_WINDOW) ?
1475 			       BUS_SPACE_MAXADDR_32BIT :
1476 			       0x7fffffff,		/* lowaddr */
1477 			       BUS_SPACE_MAXADDR, 	/* highaddr */
1478 			       NULL, NULL, 		/* filter, filterarg */
1479 			       8192 + sizeof(struct aac_common), /* maxsize */
1480 			       1,			/* nsegments */
1481 			       BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1482 			       BUS_DMA_ALLOCNOW,	/* flags */
1483 			       NULL, NULL,		/* No locking needed */
1484 			       &sc->aac_common_dmat)) {
1485 		device_printf(sc->aac_dev,
1486 			      "can't allocate common structure DMA tag\n");
1487 		goto out;
1488 	}
1489 	if (bus_dmamem_alloc(sc->aac_common_dmat, (void **)&sc->aac_common,
1490 			     BUS_DMA_NOWAIT, &sc->aac_common_dmamap)) {
1491 		device_printf(sc->aac_dev, "can't allocate common structure\n");
1492 		goto out;
1493 	}
1494 
1495 	/*
1496 	 * Work around a bug in the 2120 and 2200 that cannot DMA commands
1497 	 * below address 8192 in physical memory.
1498 	 * XXX If the padding is not needed, can it be put to use instead
1499 	 * of ignored?
1500 	 */
1501 	(void)bus_dmamap_load(sc->aac_common_dmat, sc->aac_common_dmamap,
1502 			sc->aac_common, 8192 + sizeof(*sc->aac_common),
1503 			aac_common_map, sc, 0);
1504 
1505 	if (sc->aac_common_busaddr < 8192) {
1506 		sc->aac_common = (struct aac_common *)
1507 		    ((uint8_t *)sc->aac_common + 8192);
1508 		sc->aac_common_busaddr += 8192;
1509 	}
1510 	bzero(sc->aac_common, sizeof(*sc->aac_common));
1511 
1512 	/* Allocate some FIBs and associated command structs */
1513 	TAILQ_INIT(&sc->aac_fibmap_tqh);
1514 	sc->aac_commands = malloc(AAC_MAX_FIBS * sizeof(struct aac_command),
1515 				  M_AACBUF, M_WAITOK|M_ZERO);
1516 	while (sc->total_fibs < AAC_PREALLOCATE_FIBS) {
1517 		if (aac_alloc_commands(sc) != 0)
1518 			break;
1519 	}
1520 	if (sc->total_fibs == 0)
1521 		goto out;
1522 
1523 	/*
1524 	 * Fill in the init structure.  This tells the adapter about the
1525 	 * physical location of various important shared data structures.
1526 	 */
1527 	ip = &sc->aac_common->ac_init;
1528 	ip->InitStructRevision = AAC_INIT_STRUCT_REVISION;
1529 	ip->MiniPortRevision = AAC_INIT_STRUCT_MINIPORT_REVISION;
1530 
1531 	ip->AdapterFibsPhysicalAddress = sc->aac_common_busaddr +
1532 					 offsetof(struct aac_common, ac_fibs);
1533 	ip->AdapterFibsVirtualAddress = 0;
1534 	ip->AdapterFibsSize = AAC_ADAPTER_FIBS * sizeof(struct aac_fib);
1535 	ip->AdapterFibAlign = sizeof(struct aac_fib);
1536 
1537 	ip->PrintfBufferAddress = sc->aac_common_busaddr +
1538 				  offsetof(struct aac_common, ac_printf);
1539 	ip->PrintfBufferSize = AAC_PRINTF_BUFSIZE;
1540 
1541 	/*
1542 	 * The adapter assumes that pages are 4K in size, except on some
1543  	 * broken firmware versions that do the page->byte conversion twice,
1544 	 * therefore 'assuming' that this value is in 16MB units (2^24).
1545 	 * Round up since the granularity is so high.
1546 	 */
1547 	ip->HostPhysMemPages = ctob(physmem) / AAC_PAGE_SIZE;
1548 	if (sc->flags & AAC_FLAGS_BROKEN_MEMMAP) {
1549 		ip->HostPhysMemPages =
1550 		    (ip->HostPhysMemPages + AAC_PAGE_SIZE) / AAC_PAGE_SIZE;
1551 	}
1552 	ip->HostElapsedSeconds = time_second;	/* reset later if invalid */
1553 
1554 	/*
1555 	 * Initialise FIB queues.  Note that it appears that the layout of the
1556 	 * indexes and the segmentation of the entries may be mandated by the
1557 	 * adapter, which is only told about the base of the queue index fields.
1558 	 *
1559 	 * The initial values of the indices are assumed to inform the adapter
1560 	 * of the sizes of the respective queues, and theoretically it could
1561 	 * work out the entire layout of the queue structures from this.  We
1562 	 * take the easy route and just lay this area out like everyone else
1563 	 * does.
1564 	 *
1565 	 * The Linux driver uses a much more complex scheme whereby several
1566 	 * header records are kept for each queue.  We use a couple of generic
1567 	 * list manipulation functions which 'know' the size of each list by
1568 	 * virtue of a table.
1569 	 */
1570 	qoffset = offsetof(struct aac_common, ac_qbuf) + AAC_QUEUE_ALIGN;
1571 	qoffset &= ~(AAC_QUEUE_ALIGN - 1);
1572 	sc->aac_queues =
1573 	    (struct aac_queue_table *)((uintptr_t)sc->aac_common + qoffset);
1574 	ip->CommHeaderAddress = sc->aac_common_busaddr + qoffset;
1575 
1576 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1577 		AAC_HOST_NORM_CMD_ENTRIES;
1578 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1579 		AAC_HOST_NORM_CMD_ENTRIES;
1580 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1581 		AAC_HOST_HIGH_CMD_ENTRIES;
1582 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1583 		AAC_HOST_HIGH_CMD_ENTRIES;
1584 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1585 		AAC_ADAP_NORM_CMD_ENTRIES;
1586 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1587 		AAC_ADAP_NORM_CMD_ENTRIES;
1588 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1589 		AAC_ADAP_HIGH_CMD_ENTRIES;
1590 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1591 		AAC_ADAP_HIGH_CMD_ENTRIES;
1592 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1593 		AAC_HOST_NORM_RESP_ENTRIES;
1594 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1595 		AAC_HOST_NORM_RESP_ENTRIES;
1596 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1597 		AAC_HOST_HIGH_RESP_ENTRIES;
1598 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1599 		AAC_HOST_HIGH_RESP_ENTRIES;
1600 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1601 		AAC_ADAP_NORM_RESP_ENTRIES;
1602 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1603 		AAC_ADAP_NORM_RESP_ENTRIES;
1604 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1605 		AAC_ADAP_HIGH_RESP_ENTRIES;
1606 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1607 		AAC_ADAP_HIGH_RESP_ENTRIES;
1608 	sc->aac_qentries[AAC_HOST_NORM_CMD_QUEUE] =
1609 		&sc->aac_queues->qt_HostNormCmdQueue[0];
1610 	sc->aac_qentries[AAC_HOST_HIGH_CMD_QUEUE] =
1611 		&sc->aac_queues->qt_HostHighCmdQueue[0];
1612 	sc->aac_qentries[AAC_ADAP_NORM_CMD_QUEUE] =
1613 		&sc->aac_queues->qt_AdapNormCmdQueue[0];
1614 	sc->aac_qentries[AAC_ADAP_HIGH_CMD_QUEUE] =
1615 		&sc->aac_queues->qt_AdapHighCmdQueue[0];
1616 	sc->aac_qentries[AAC_HOST_NORM_RESP_QUEUE] =
1617 		&sc->aac_queues->qt_HostNormRespQueue[0];
1618 	sc->aac_qentries[AAC_HOST_HIGH_RESP_QUEUE] =
1619 		&sc->aac_queues->qt_HostHighRespQueue[0];
1620 	sc->aac_qentries[AAC_ADAP_NORM_RESP_QUEUE] =
1621 		&sc->aac_queues->qt_AdapNormRespQueue[0];
1622 	sc->aac_qentries[AAC_ADAP_HIGH_RESP_QUEUE] =
1623 		&sc->aac_queues->qt_AdapHighRespQueue[0];
1624 
1625 	/*
1626 	 * Do controller-type-specific initialisation
1627 	 */
1628 	switch (sc->aac_hwif) {
1629 	case AAC_HWIF_I960RX:
1630 		AAC_SETREG4(sc, AAC_RX_ODBR, ~0);
1631 		break;
1632 	}
1633 
1634 	/*
1635 	 * Give the init structure to the controller.
1636 	 */
1637 	if (aac_sync_command(sc, AAC_MONKER_INITSTRUCT,
1638 			     sc->aac_common_busaddr +
1639 			     offsetof(struct aac_common, ac_init), 0, 0, 0,
1640 			     NULL)) {
1641 		device_printf(sc->aac_dev,
1642 			      "error establishing init structure\n");
1643 		error = EIO;
1644 		goto out;
1645 	}
1646 
1647 	error = 0;
1648 out:
1649 	return(error);
1650 }
1651 
1652 /*
1653  * Send a synchronous command to the controller and wait for a result.
1654  */
1655 static int
1656 aac_sync_command(struct aac_softc *sc, u_int32_t command,
1657 		 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3,
1658 		 u_int32_t *sp)
1659 {
1660 	time_t then;
1661 	u_int32_t status;
1662 
1663 	debug_called(3);
1664 
1665 	/* populate the mailbox */
1666 	AAC_SET_MAILBOX(sc, command, arg0, arg1, arg2, arg3);
1667 
1668 	/* ensure the sync command doorbell flag is cleared */
1669 	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1670 
1671 	/* then set it to signal the adapter */
1672 	AAC_QNOTIFY(sc, AAC_DB_SYNC_COMMAND);
1673 
1674 	/* spin waiting for the command to complete */
1675 	then = time_second;
1676 	do {
1677 		if (time_second > (then + AAC_IMMEDIATE_TIMEOUT)) {
1678 			debug(1, "timed out");
1679 			return(EIO);
1680 		}
1681 	} while (!(AAC_GET_ISTATUS(sc) & AAC_DB_SYNC_COMMAND));
1682 
1683 	/* clear the completion flag */
1684 	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1685 
1686 	/* get the command status */
1687 	status = AAC_GET_MAILBOX(sc, 0);
1688 	if (sp != NULL)
1689 		*sp = status;
1690 	return(0);
1691 }
1692 
1693 int
1694 aac_sync_fib(struct aac_softc *sc, u_int32_t command, u_int32_t xferstate,
1695 		 struct aac_fib *fib, u_int16_t datasize)
1696 {
1697 	debug_called(3);
1698 
1699 	if (datasize > AAC_FIB_DATASIZE)
1700 		return(EINVAL);
1701 
1702 	/*
1703 	 * Set up the sync FIB
1704 	 */
1705 	fib->Header.XferState = AAC_FIBSTATE_HOSTOWNED |
1706 				AAC_FIBSTATE_INITIALISED |
1707 				AAC_FIBSTATE_EMPTY;
1708 	fib->Header.XferState |= xferstate;
1709 	fib->Header.Command = command;
1710 	fib->Header.StructType = AAC_FIBTYPE_TFIB;
1711 	fib->Header.Size = sizeof(struct aac_fib) + datasize;
1712 	fib->Header.SenderSize = sizeof(struct aac_fib);
1713 	fib->Header.SenderFibAddress = 0;	/* Not needed */
1714 	fib->Header.ReceiverFibAddress = sc->aac_common_busaddr +
1715 					 offsetof(struct aac_common,
1716 						  ac_sync_fib);
1717 
1718 	/*
1719 	 * Give the FIB to the controller, wait for a response.
1720 	 */
1721 	if (aac_sync_command(sc, AAC_MONKER_SYNCFIB,
1722 			     fib->Header.ReceiverFibAddress, 0, 0, 0, NULL)) {
1723 		debug(2, "IO error");
1724 		return(EIO);
1725 	}
1726 
1727 	return (0);
1728 }
1729 
1730 /*
1731  * Adapter-space FIB queue manipulation
1732  *
1733  * Note that the queue implementation here is a little funky; neither the PI or
1734  * CI will ever be zero.  This behaviour is a controller feature.
1735  */
1736 static struct {
1737 	int		size;
1738 	int		notify;
1739 } aac_qinfo[] = {
1740 	{AAC_HOST_NORM_CMD_ENTRIES, AAC_DB_COMMAND_NOT_FULL},
1741 	{AAC_HOST_HIGH_CMD_ENTRIES, 0},
1742 	{AAC_ADAP_NORM_CMD_ENTRIES, AAC_DB_COMMAND_READY},
1743 	{AAC_ADAP_HIGH_CMD_ENTRIES, 0},
1744 	{AAC_HOST_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_NOT_FULL},
1745 	{AAC_HOST_HIGH_RESP_ENTRIES, 0},
1746 	{AAC_ADAP_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_READY},
1747 	{AAC_ADAP_HIGH_RESP_ENTRIES, 0}
1748 };
1749 
1750 /*
1751  * Atomically insert an entry into the nominated queue, returns 0 on success or
1752  * EBUSY if the queue is full.
1753  *
1754  * Note: it would be more efficient to defer notifying the controller in
1755  *	 the case where we may be inserting several entries in rapid succession,
1756  *	 but implementing this usefully may be difficult (it would involve a
1757  *	 separate queue/notify interface).
1758  */
1759 static int
1760 aac_enqueue_fib(struct aac_softc *sc, int queue, struct aac_command *cm)
1761 {
1762 	u_int32_t pi, ci;
1763 	int error;
1764 	u_int32_t fib_size;
1765 	u_int32_t fib_addr;
1766 
1767 	debug_called(3);
1768 
1769 	fib_size = cm->cm_fib->Header.Size;
1770 	fib_addr = cm->cm_fib->Header.ReceiverFibAddress;
1771 
1772 	/* get the producer/consumer indices */
1773 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1774 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1775 
1776 	/* wrap the queue? */
1777 	if (pi >= aac_qinfo[queue].size)
1778 		pi = 0;
1779 
1780 	/* check for queue full */
1781 	if ((pi + 1) == ci) {
1782 		error = EBUSY;
1783 		goto out;
1784 	}
1785 
1786 	/*
1787 	 * To avoid a race with its completion interrupt, place this command on
1788 	 * the busy queue prior to advertising it to the controller.
1789 	 */
1790 	aac_enqueue_busy(cm);
1791 
1792 	/* populate queue entry */
1793 	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1794 	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1795 
1796 	/* update producer index */
1797 	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1798 
1799 	/* notify the adapter if we know how */
1800 	if (aac_qinfo[queue].notify != 0)
1801 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1802 
1803 	error = 0;
1804 
1805 out:
1806 	return(error);
1807 }
1808 
1809 /*
1810  * Atomically remove one entry from the nominated queue, returns 0 on
1811  * success or ENOENT if the queue is empty.
1812  */
1813 static int
1814 aac_dequeue_fib(struct aac_softc *sc, int queue, u_int32_t *fib_size,
1815 		struct aac_fib **fib_addr)
1816 {
1817 	u_int32_t pi, ci;
1818 	u_int32_t fib_index;
1819 	int error;
1820 	int notify;
1821 
1822 	debug_called(3);
1823 
1824 	/* get the producer/consumer indices */
1825 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1826 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1827 
1828 	/* check for queue empty */
1829 	if (ci == pi) {
1830 		error = ENOENT;
1831 		goto out;
1832 	}
1833 
1834 	/* wrap the pi so the following test works */
1835 	if (pi >= aac_qinfo[queue].size)
1836 		pi = 0;
1837 
1838 	notify = 0;
1839 	if (ci == pi + 1)
1840 		notify++;
1841 
1842 	/* wrap the queue? */
1843 	if (ci >= aac_qinfo[queue].size)
1844 		ci = 0;
1845 
1846 	/* fetch the entry */
1847 	*fib_size = (sc->aac_qentries[queue] + ci)->aq_fib_size;
1848 
1849 	switch (queue) {
1850 	case AAC_HOST_NORM_CMD_QUEUE:
1851 	case AAC_HOST_HIGH_CMD_QUEUE:
1852 		/*
1853 		 * The aq_fib_addr is only 32 bits wide so it can't be counted
1854 		 * on to hold an address.  For AIF's, the adapter assumes
1855 		 * that it's giving us an address into the array of AIF fibs.
1856 		 * Therefore, we have to convert it to an index.
1857 		 */
1858 		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr /
1859 			sizeof(struct aac_fib);
1860 		*fib_addr = &sc->aac_common->ac_fibs[fib_index];
1861 		break;
1862 
1863 	case AAC_HOST_NORM_RESP_QUEUE:
1864 	case AAC_HOST_HIGH_RESP_QUEUE:
1865 	{
1866 		struct aac_command *cm;
1867 
1868 		/*
1869 		 * As above, an index is used instead of an actual address.
1870 		 * Gotta shift the index to account for the fast response
1871 		 * bit.  No other correction is needed since this value was
1872 		 * originally provided by the driver via the SenderFibAddress
1873 		 * field.
1874 		 */
1875 		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr;
1876 		cm = sc->aac_commands + (fib_index >> 1);
1877 		*fib_addr = cm->cm_fib;
1878 
1879 		/*
1880 		 * Is this a fast response? If it is, update the fib fields in
1881 		 * local memory since the whole fib isn't DMA'd back up.
1882 		 */
1883 		if (fib_index & 0x01) {
1884 			(*fib_addr)->Header.XferState |= AAC_FIBSTATE_DONEADAP;
1885 			*((u_int32_t*)((*fib_addr)->data)) = AAC_ERROR_NORMAL;
1886 		}
1887 		break;
1888 	}
1889 	default:
1890 		panic("Invalid queue in aac_dequeue_fib()");
1891 		break;
1892 	}
1893 
1894 	/* update consumer index */
1895 	sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX] = ci + 1;
1896 
1897 	/* if we have made the queue un-full, notify the adapter */
1898 	if (notify && (aac_qinfo[queue].notify != 0))
1899 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1900 	error = 0;
1901 
1902 out:
1903 	return(error);
1904 }
1905 
1906 /*
1907  * Put our response to an Adapter Initialed Fib on the response queue
1908  */
1909 static int
1910 aac_enqueue_response(struct aac_softc *sc, int queue, struct aac_fib *fib)
1911 {
1912 	u_int32_t pi, ci;
1913 	int error;
1914 	u_int32_t fib_size;
1915 	u_int32_t fib_addr;
1916 
1917 	debug_called(1);
1918 
1919 	/* Tell the adapter where the FIB is */
1920 	fib_size = fib->Header.Size;
1921 	fib_addr = fib->Header.SenderFibAddress;
1922 	fib->Header.ReceiverFibAddress = fib_addr;
1923 
1924 	/* get the producer/consumer indices */
1925 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1926 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1927 
1928 	/* wrap the queue? */
1929 	if (pi >= aac_qinfo[queue].size)
1930 		pi = 0;
1931 
1932 	/* check for queue full */
1933 	if ((pi + 1) == ci) {
1934 		error = EBUSY;
1935 		goto out;
1936 	}
1937 
1938 	/* populate queue entry */
1939 	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1940 	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1941 
1942 	/* update producer index */
1943 	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1944 
1945 	/* notify the adapter if we know how */
1946 	if (aac_qinfo[queue].notify != 0)
1947 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1948 
1949 	error = 0;
1950 
1951 out:
1952 	return(error);
1953 }
1954 
1955 /*
1956  * Check for commands that have been outstanding for a suspiciously long time,
1957  * and complain about them.
1958  */
1959 static void
1960 aac_timeout(struct aac_softc *sc)
1961 {
1962 	struct aac_command *cm;
1963 	time_t deadline;
1964 
1965 	/*
1966 	 * Traverse the busy command list, bitch about late commands once
1967 	 * only.
1968 	 */
1969 	deadline = time_second - AAC_CMD_TIMEOUT;
1970 	TAILQ_FOREACH(cm, &sc->aac_busy, cm_link) {
1971 		if ((cm->cm_timestamp  < deadline)
1972 			/* && !(cm->cm_flags & AAC_CMD_TIMEDOUT) */) {
1973 			cm->cm_flags |= AAC_CMD_TIMEDOUT;
1974 			device_printf(sc->aac_dev,
1975 				      "COMMAND %p TIMEOUT AFTER %d SECONDS\n",
1976 				      cm, (int)(time_second-cm->cm_timestamp));
1977 			AAC_PRINT_FIB(sc, cm->cm_fib);
1978 		}
1979 	}
1980 
1981 	return;
1982 }
1983 
1984 /*
1985  * Interface Function Vectors
1986  */
1987 
1988 /*
1989  * Read the current firmware status word.
1990  */
1991 static int
1992 aac_sa_get_fwstatus(struct aac_softc *sc)
1993 {
1994 	debug_called(3);
1995 
1996 	return(AAC_GETREG4(sc, AAC_SA_FWSTATUS));
1997 }
1998 
1999 static int
2000 aac_rx_get_fwstatus(struct aac_softc *sc)
2001 {
2002 	debug_called(3);
2003 
2004 	return(AAC_GETREG4(sc, AAC_RX_FWSTATUS));
2005 }
2006 
2007 static int
2008 aac_fa_get_fwstatus(struct aac_softc *sc)
2009 {
2010 	int val;
2011 
2012 	debug_called(3);
2013 
2014 	val = AAC_GETREG4(sc, AAC_FA_FWSTATUS);
2015 	return (val);
2016 }
2017 
2018 /*
2019  * Notify the controller of a change in a given queue
2020  */
2021 
2022 static void
2023 aac_sa_qnotify(struct aac_softc *sc, int qbit)
2024 {
2025 	debug_called(3);
2026 
2027 	AAC_SETREG2(sc, AAC_SA_DOORBELL1_SET, qbit);
2028 }
2029 
2030 static void
2031 aac_rx_qnotify(struct aac_softc *sc, int qbit)
2032 {
2033 	debug_called(3);
2034 
2035 	AAC_SETREG4(sc, AAC_RX_IDBR, qbit);
2036 }
2037 
2038 static void
2039 aac_fa_qnotify(struct aac_softc *sc, int qbit)
2040 {
2041 	debug_called(3);
2042 
2043 	AAC_SETREG2(sc, AAC_FA_DOORBELL1, qbit);
2044 	AAC_FA_HACK(sc);
2045 }
2046 
2047 /*
2048  * Get the interrupt reason bits
2049  */
2050 static int
2051 aac_sa_get_istatus(struct aac_softc *sc)
2052 {
2053 	debug_called(3);
2054 
2055 	return(AAC_GETREG2(sc, AAC_SA_DOORBELL0));
2056 }
2057 
2058 static int
2059 aac_rx_get_istatus(struct aac_softc *sc)
2060 {
2061 	debug_called(3);
2062 
2063 	return(AAC_GETREG4(sc, AAC_RX_ODBR));
2064 }
2065 
2066 static int
2067 aac_fa_get_istatus(struct aac_softc *sc)
2068 {
2069 	int val;
2070 
2071 	debug_called(3);
2072 
2073 	val = AAC_GETREG2(sc, AAC_FA_DOORBELL0);
2074 	return (val);
2075 }
2076 
2077 /*
2078  * Clear some interrupt reason bits
2079  */
2080 static void
2081 aac_sa_clear_istatus(struct aac_softc *sc, int mask)
2082 {
2083 	debug_called(3);
2084 
2085 	AAC_SETREG2(sc, AAC_SA_DOORBELL0_CLEAR, mask);
2086 }
2087 
2088 static void
2089 aac_rx_clear_istatus(struct aac_softc *sc, int mask)
2090 {
2091 	debug_called(3);
2092 
2093 	AAC_SETREG4(sc, AAC_RX_ODBR, mask);
2094 }
2095 
2096 static void
2097 aac_fa_clear_istatus(struct aac_softc *sc, int mask)
2098 {
2099 	debug_called(3);
2100 
2101 	AAC_SETREG2(sc, AAC_FA_DOORBELL0_CLEAR, mask);
2102 	AAC_FA_HACK(sc);
2103 }
2104 
2105 /*
2106  * Populate the mailbox and set the command word
2107  */
2108 static void
2109 aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
2110 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2111 {
2112 	debug_called(4);
2113 
2114 	AAC_SETREG4(sc, AAC_SA_MAILBOX, command);
2115 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 4, arg0);
2116 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 8, arg1);
2117 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 12, arg2);
2118 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 16, arg3);
2119 }
2120 
2121 static void
2122 aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
2123 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2124 {
2125 	debug_called(4);
2126 
2127 	AAC_SETREG4(sc, AAC_RX_MAILBOX, command);
2128 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 4, arg0);
2129 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 8, arg1);
2130 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 12, arg2);
2131 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 16, arg3);
2132 }
2133 
2134 static void
2135 aac_fa_set_mailbox(struct aac_softc *sc, u_int32_t command,
2136 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2137 {
2138 	debug_called(4);
2139 
2140 	AAC_SETREG4(sc, AAC_FA_MAILBOX, command);
2141 	AAC_FA_HACK(sc);
2142 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 4, arg0);
2143 	AAC_FA_HACK(sc);
2144 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 8, arg1);
2145 	AAC_FA_HACK(sc);
2146 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 12, arg2);
2147 	AAC_FA_HACK(sc);
2148 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 16, arg3);
2149 	AAC_FA_HACK(sc);
2150 }
2151 
2152 /*
2153  * Fetch the immediate command status word
2154  */
2155 static int
2156 aac_sa_get_mailbox(struct aac_softc *sc, int mb)
2157 {
2158 	debug_called(4);
2159 
2160 	return(AAC_GETREG4(sc, AAC_SA_MAILBOX + (mb * 4)));
2161 }
2162 
2163 static int
2164 aac_rx_get_mailbox(struct aac_softc *sc, int mb)
2165 {
2166 	debug_called(4);
2167 
2168 	return(AAC_GETREG4(sc, AAC_RX_MAILBOX + (mb * 4)));
2169 }
2170 
2171 static int
2172 aac_fa_get_mailbox(struct aac_softc *sc, int mb)
2173 {
2174 	int val;
2175 
2176 	debug_called(4);
2177 
2178 	val = AAC_GETREG4(sc, AAC_FA_MAILBOX + (mb * 4));
2179 	return (val);
2180 }
2181 
2182 /*
2183  * Set/clear interrupt masks
2184  */
2185 static void
2186 aac_sa_set_interrupts(struct aac_softc *sc, int enable)
2187 {
2188 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2189 
2190 	if (enable) {
2191 		AAC_SETREG2((sc), AAC_SA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2192 	} else {
2193 		AAC_SETREG2((sc), AAC_SA_MASK0_SET, ~0);
2194 	}
2195 }
2196 
2197 static void
2198 aac_rx_set_interrupts(struct aac_softc *sc, int enable)
2199 {
2200 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2201 
2202 	if (enable) {
2203 		AAC_SETREG4(sc, AAC_RX_OIMR, ~AAC_DB_INTERRUPTS);
2204 	} else {
2205 		AAC_SETREG4(sc, AAC_RX_OIMR, ~0);
2206 	}
2207 }
2208 
2209 static void
2210 aac_fa_set_interrupts(struct aac_softc *sc, int enable)
2211 {
2212 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2213 
2214 	if (enable) {
2215 		AAC_SETREG2((sc), AAC_FA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2216 		AAC_FA_HACK(sc);
2217 	} else {
2218 		AAC_SETREG2((sc), AAC_FA_MASK0, ~0);
2219 		AAC_FA_HACK(sc);
2220 	}
2221 }
2222 
2223 /*
2224  * Debugging and Diagnostics
2225  */
2226 
2227 /*
2228  * Print some information about the controller.
2229  */
2230 static void
2231 aac_describe_controller(struct aac_softc *sc)
2232 {
2233 	struct aac_fib *fib;
2234 	struct aac_adapter_info	*info;
2235 
2236 	debug_called(2);
2237 
2238 	aac_alloc_sync_fib(sc, &fib);
2239 
2240 	fib->data[0] = 0;
2241 	if (aac_sync_fib(sc, RequestAdapterInfo, 0, fib, 1)) {
2242 		device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
2243 		aac_release_sync_fib(sc);
2244 		return;
2245 	}
2246 	info = (struct aac_adapter_info *)&fib->data[0];
2247 
2248 	device_printf(sc->aac_dev, "%s %dMHz, %dMB cache memory, %s\n",
2249 		      aac_describe_code(aac_cpu_variant, info->CpuVariant),
2250 		      info->ClockSpeed, info->BufferMem / (1024 * 1024),
2251 		      aac_describe_code(aac_battery_platform,
2252 					info->batteryPlatform));
2253 
2254 	/* save the kernel revision structure for later use */
2255 	sc->aac_revision = info->KernelRevision;
2256 	device_printf(sc->aac_dev, "Kernel %d.%d-%d, Build %d, S/N %6X\n",
2257 		      info->KernelRevision.external.comp.major,
2258 		      info->KernelRevision.external.comp.minor,
2259 		      info->KernelRevision.external.comp.dash,
2260 		      info->KernelRevision.buildNumber,
2261 		      (u_int32_t)(info->SerialNumber & 0xffffff));
2262 
2263 	aac_release_sync_fib(sc);
2264 
2265 	if (1 || bootverbose) {
2266 		device_printf(sc->aac_dev, "Supported Options=%b\n",
2267 			      sc->supported_options,
2268 			      "\20"
2269 			      "\1SNAPSHOT"
2270 			      "\2CLUSTERS"
2271 			      "\3WCACHE"
2272 			      "\4DATA64"
2273 			      "\5HOSTTIME"
2274 			      "\6RAID50"
2275 			      "\7WINDOW4GB"
2276 			      "\10SCSIUPGD"
2277 			      "\11SOFTERR"
2278 			      "\12NORECOND"
2279 			      "\13SGMAP64"
2280 			      "\14ALARM"
2281 			      "\15NONDASD");
2282 	}
2283 }
2284 
2285 /*
2286  * Look up a text description of a numeric error code and return a pointer to
2287  * same.
2288  */
2289 static char *
2290 aac_describe_code(struct aac_code_lookup *table, u_int32_t code)
2291 {
2292 	int i;
2293 
2294 	for (i = 0; table[i].string != NULL; i++)
2295 		if (table[i].code == code)
2296 			return(table[i].string);
2297 	return(table[i + 1].string);
2298 }
2299 
2300 /*
2301  * Management Interface
2302  */
2303 
2304 static int
2305 aac_open(struct cdev *dev, int flags, int fmt, d_thread_t *td)
2306 {
2307 	struct aac_softc *sc;
2308 
2309 	debug_called(2);
2310 
2311 	sc = dev->si_drv1;
2312 
2313 	/* Check to make sure the device isn't already open */
2314 	if (sc->aac_state & AAC_STATE_OPEN) {
2315 		return EBUSY;
2316 	}
2317 	sc->aac_state |= AAC_STATE_OPEN;
2318 
2319 	return 0;
2320 }
2321 
2322 static int
2323 aac_close(struct cdev *dev, int flags, int fmt, d_thread_t *td)
2324 {
2325 	struct aac_softc *sc;
2326 
2327 	debug_called(2);
2328 
2329 	sc = dev->si_drv1;
2330 
2331 	/* Mark this unit as no longer open  */
2332 	sc->aac_state &= ~AAC_STATE_OPEN;
2333 
2334 	return 0;
2335 }
2336 
2337 static int
2338 aac_ioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, d_thread_t *td)
2339 {
2340 	union aac_statrequest *as;
2341 	struct aac_softc *sc;
2342 	int error = 0;
2343 	uint32_t cookie;
2344 
2345 	debug_called(2);
2346 
2347 	as = (union aac_statrequest *)arg;
2348 	sc = dev->si_drv1;
2349 
2350 	switch (cmd) {
2351 	case AACIO_STATS:
2352 		switch (as->as_item) {
2353 		case AACQ_FREE:
2354 		case AACQ_BIO:
2355 		case AACQ_READY:
2356 		case AACQ_BUSY:
2357 			bcopy(&sc->aac_qstat[as->as_item], &as->as_qstat,
2358 			      sizeof(struct aac_qstat));
2359 			break;
2360 		default:
2361 			error = ENOENT;
2362 			break;
2363 		}
2364 	break;
2365 
2366 	case FSACTL_SENDFIB:
2367 		arg = *(caddr_t*)arg;
2368 	case FSACTL_LNX_SENDFIB:
2369 		debug(1, "FSACTL_SENDFIB");
2370 		error = aac_ioctl_sendfib(sc, arg);
2371 		break;
2372 	case FSACTL_AIF_THREAD:
2373 	case FSACTL_LNX_AIF_THREAD:
2374 		debug(1, "FSACTL_AIF_THREAD");
2375 		error = EINVAL;
2376 		break;
2377 	case FSACTL_OPEN_GET_ADAPTER_FIB:
2378 		arg = *(caddr_t*)arg;
2379 	case FSACTL_LNX_OPEN_GET_ADAPTER_FIB:
2380 		debug(1, "FSACTL_OPEN_GET_ADAPTER_FIB");
2381 		/*
2382 		 * Pass the caller out an AdapterFibContext.
2383 		 *
2384 		 * Note that because we only support one opener, we
2385 		 * basically ignore this.  Set the caller's context to a magic
2386 		 * number just in case.
2387 		 *
2388 		 * The Linux code hands the driver a pointer into kernel space,
2389 		 * and then trusts it when the caller hands it back.  Aiee!
2390 		 * Here, we give it the proc pointer of the per-adapter aif
2391 		 * thread. It's only used as a sanity check in other calls.
2392 		 */
2393 		cookie = (uint32_t)(uintptr_t)sc->aifthread;
2394 		error = copyout(&cookie, arg, sizeof(cookie));
2395 		break;
2396 	case FSACTL_GET_NEXT_ADAPTER_FIB:
2397 		arg = *(caddr_t*)arg;
2398 	case FSACTL_LNX_GET_NEXT_ADAPTER_FIB:
2399 		debug(1, "FSACTL_GET_NEXT_ADAPTER_FIB");
2400 		error = aac_getnext_aif(sc, arg);
2401 		break;
2402 	case FSACTL_CLOSE_GET_ADAPTER_FIB:
2403 	case FSACTL_LNX_CLOSE_GET_ADAPTER_FIB:
2404 		debug(1, "FSACTL_CLOSE_GET_ADAPTER_FIB");
2405 		/* don't do anything here */
2406 		break;
2407 	case FSACTL_MINIPORT_REV_CHECK:
2408 		arg = *(caddr_t*)arg;
2409 	case FSACTL_LNX_MINIPORT_REV_CHECK:
2410 		debug(1, "FSACTL_MINIPORT_REV_CHECK");
2411 		error = aac_rev_check(sc, arg);
2412 		break;
2413 	case FSACTL_QUERY_DISK:
2414 		arg = *(caddr_t*)arg;
2415 	case FSACTL_LNX_QUERY_DISK:
2416 		debug(1, "FSACTL_QUERY_DISK");
2417 		error = aac_query_disk(sc, arg);
2418 			break;
2419 	case FSACTL_DELETE_DISK:
2420 	case FSACTL_LNX_DELETE_DISK:
2421 		/*
2422 		 * We don't trust the underland to tell us when to delete a
2423 		 * container, rather we rely on an AIF coming from the
2424 		 * controller
2425 		 */
2426 		error = 0;
2427 		break;
2428 	default:
2429 		debug(1, "unsupported cmd 0x%lx\n", cmd);
2430 		error = EINVAL;
2431 		break;
2432 	}
2433 	return(error);
2434 }
2435 
2436 static int
2437 aac_poll(struct cdev *dev, int poll_events, d_thread_t *td)
2438 {
2439 	struct aac_softc *sc;
2440 	int revents;
2441 
2442 	sc = dev->si_drv1;
2443 	revents = 0;
2444 
2445 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2446 	if ((poll_events & (POLLRDNORM | POLLIN)) != 0) {
2447 		if (sc->aac_aifq_tail != sc->aac_aifq_head)
2448 			revents |= poll_events & (POLLIN | POLLRDNORM);
2449 	}
2450 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2451 
2452 	if (revents == 0) {
2453 		if (poll_events & (POLLIN | POLLRDNORM))
2454 			selrecord(td, &sc->rcv_select);
2455 	}
2456 
2457 	return (revents);
2458 }
2459 
2460 /*
2461  * Send a FIB supplied from userspace
2462  */
2463 static int
2464 aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib)
2465 {
2466 	struct aac_command *cm;
2467 	int size, error;
2468 
2469 	debug_called(2);
2470 
2471 	cm = NULL;
2472 
2473 	/*
2474 	 * Get a command
2475 	 */
2476 	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
2477 	if (aac_alloc_command(sc, &cm)) {
2478 		error = EBUSY;
2479 		goto out;
2480 	}
2481 
2482 	/*
2483 	 * Fetch the FIB header, then re-copy to get data as well.
2484 	 */
2485 	if ((error = copyin(ufib, cm->cm_fib,
2486 			    sizeof(struct aac_fib_header))) != 0)
2487 		goto out;
2488 	size = cm->cm_fib->Header.Size + sizeof(struct aac_fib_header);
2489 	if (size > sizeof(struct aac_fib)) {
2490 		device_printf(sc->aac_dev, "incoming FIB oversized (%d > %zd)\n",
2491 			      size, sizeof(struct aac_fib));
2492 		size = sizeof(struct aac_fib);
2493 	}
2494 	if ((error = copyin(ufib, cm->cm_fib, size)) != 0)
2495 		goto out;
2496 	cm->cm_fib->Header.Size = size;
2497 	cm->cm_timestamp = time_second;
2498 
2499 	/*
2500 	 * Pass the FIB to the controller, wait for it to complete.
2501 	 */
2502 	if ((error = aac_wait_command(cm)) != 0) {
2503 		device_printf(sc->aac_dev,
2504 			      "aac_wait_command return %d\n", error);
2505 		goto out;
2506 	}
2507 
2508 	/*
2509 	 * Copy the FIB and data back out to the caller.
2510 	 */
2511 	size = cm->cm_fib->Header.Size;
2512 	if (size > sizeof(struct aac_fib)) {
2513 		device_printf(sc->aac_dev, "outbound FIB oversized (%d > %zd)\n",
2514 			      size, sizeof(struct aac_fib));
2515 		size = sizeof(struct aac_fib);
2516 	}
2517 	error = copyout(cm->cm_fib, ufib, size);
2518 
2519 out:
2520 	if (cm != NULL) {
2521 		aac_release_command(cm);
2522 	}
2523 
2524 	AAC_LOCK_RELEASE(&sc->aac_io_lock);
2525 	return(error);
2526 }
2527 
2528 /*
2529  * Handle an AIF sent to us by the controller; queue it for later reference.
2530  * If the queue fills up, then drop the older entries.
2531  */
2532 static void
2533 aac_handle_aif(struct aac_softc *sc, struct aac_fib *fib)
2534 {
2535 	struct aac_aif_command *aif;
2536 	struct aac_container *co, *co_next;
2537 	struct aac_mntinfo *mi;
2538 	struct aac_mntinforesp *mir = NULL;
2539 	u_int16_t rsize;
2540 	int next, found;
2541 	int count = 0, added = 0, i = 0;
2542 
2543 	debug_called(2);
2544 
2545 	aif = (struct aac_aif_command*)&fib->data[0];
2546 	aac_print_aif(sc, aif);
2547 
2548 	/* Is it an event that we should care about? */
2549 	switch (aif->command) {
2550 	case AifCmdEventNotify:
2551 		switch (aif->data.EN.type) {
2552 		case AifEnAddContainer:
2553 		case AifEnDeleteContainer:
2554 			/*
2555 			 * A container was added or deleted, but the message
2556 			 * doesn't tell us anything else!  Re-enumerate the
2557 			 * containers and sort things out.
2558 			 */
2559 			aac_alloc_sync_fib(sc, &fib);
2560 			mi = (struct aac_mntinfo *)&fib->data[0];
2561 			do {
2562 				/*
2563 				 * Ask the controller for its containers one at
2564 				 * a time.
2565 				 * XXX What if the controller's list changes
2566 				 * midway through this enumaration?
2567 				 * XXX This should be done async.
2568 				 */
2569 				bzero(mi, sizeof(struct aac_mntinfo));
2570 				mi->Command = VM_NameServe;
2571 				mi->MntType = FT_FILESYS;
2572 				mi->MntCount = i;
2573 				rsize = sizeof(mir);
2574 				if (aac_sync_fib(sc, ContainerCommand, 0, fib,
2575 						 sizeof(struct aac_mntinfo))) {
2576 					printf("Error probing container %d\n",
2577 					      i);
2578 					continue;
2579 				}
2580 				mir = (struct aac_mntinforesp *)&fib->data[0];
2581 				/* XXX Need to check if count changed */
2582 				count = mir->MntRespCount;
2583 				/*
2584 				 * Check the container against our list.
2585 				 * co->co_found was already set to 0 in a
2586 				 * previous run.
2587 				 */
2588 				if ((mir->Status == ST_OK) &&
2589 				    (mir->MntTable[0].VolType != CT_NONE)) {
2590 					found = 0;
2591 					TAILQ_FOREACH(co,
2592 						      &sc->aac_container_tqh,
2593 						      co_link) {
2594 						if (co->co_mntobj.ObjectId ==
2595 						    mir->MntTable[0].ObjectId) {
2596 							co->co_found = 1;
2597 							found = 1;
2598 							break;
2599 						}
2600 					}
2601 					/*
2602 					 * If the container matched, continue
2603 					 * in the list.
2604 					 */
2605 					if (found) {
2606 						i++;
2607 						continue;
2608 					}
2609 
2610 					/*
2611 					 * This is a new container.  Do all the
2612 					 * appropriate things to set it up.
2613 					 */
2614 					aac_add_container(sc, mir, 1);
2615 					added = 1;
2616 				}
2617 				i++;
2618 			} while ((i < count) && (i < AAC_MAX_CONTAINERS));
2619 			aac_release_sync_fib(sc);
2620 
2621 			/*
2622 			 * Go through our list of containers and see which ones
2623 			 * were not marked 'found'.  Since the controller didn't
2624 			 * list them they must have been deleted.  Do the
2625 			 * appropriate steps to destroy the device.  Also reset
2626 			 * the co->co_found field.
2627 			 */
2628 			co = TAILQ_FIRST(&sc->aac_container_tqh);
2629 			while (co != NULL) {
2630 				if (co->co_found == 0) {
2631 					device_delete_child(sc->aac_dev,
2632 							    co->co_disk);
2633 					co_next = TAILQ_NEXT(co, co_link);
2634 					AAC_LOCK_ACQUIRE(&sc->
2635 							aac_container_lock);
2636 					TAILQ_REMOVE(&sc->aac_container_tqh, co,
2637 						     co_link);
2638 					AAC_LOCK_RELEASE(&sc->
2639 							 aac_container_lock);
2640 					FREE(co, M_AACBUF);
2641 					co = co_next;
2642 				} else {
2643 					co->co_found = 0;
2644 					co = TAILQ_NEXT(co, co_link);
2645 				}
2646 			}
2647 
2648 			/* Attach the newly created containers */
2649 			if (added)
2650 				bus_generic_attach(sc->aac_dev);
2651 
2652 			break;
2653 
2654 		default:
2655 			break;
2656 		}
2657 
2658 	default:
2659 		break;
2660 	}
2661 
2662 	/* Copy the AIF data to the AIF queue for ioctl retrieval */
2663 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2664 	next = (sc->aac_aifq_head + 1) % AAC_AIFQ_LENGTH;
2665 	if (next != sc->aac_aifq_tail) {
2666 		bcopy(aif, &sc->aac_aifq[next], sizeof(struct aac_aif_command));
2667 		sc->aac_aifq_head = next;
2668 
2669 		/* On the off chance that someone is sleeping for an aif... */
2670 		if (sc->aac_state & AAC_STATE_AIF_SLEEPER)
2671 			wakeup(sc->aac_aifq);
2672 		/* Wakeup any poll()ers */
2673 		selwakeuppri(&sc->rcv_select, PRIBIO);
2674 	}
2675 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2676 
2677 	return;
2678 }
2679 
2680 /*
2681  * Return the Revision of the driver to userspace and check to see if the
2682  * userspace app is possibly compatible.  This is extremely bogus since
2683  * our driver doesn't follow Adaptec's versioning system.  Cheat by just
2684  * returning what the card reported.
2685  */
2686 static int
2687 aac_rev_check(struct aac_softc *sc, caddr_t udata)
2688 {
2689 	struct aac_rev_check rev_check;
2690 	struct aac_rev_check_resp rev_check_resp;
2691 	int error = 0;
2692 
2693 	debug_called(2);
2694 
2695 	/*
2696 	 * Copyin the revision struct from userspace
2697 	 */
2698 	if ((error = copyin(udata, (caddr_t)&rev_check,
2699 			sizeof(struct aac_rev_check))) != 0) {
2700 		return error;
2701 	}
2702 
2703 	debug(2, "Userland revision= %d\n",
2704 	      rev_check.callingRevision.buildNumber);
2705 
2706 	/*
2707 	 * Doctor up the response struct.
2708 	 */
2709 	rev_check_resp.possiblyCompatible = 1;
2710 	rev_check_resp.adapterSWRevision.external.ul =
2711 	    sc->aac_revision.external.ul;
2712 	rev_check_resp.adapterSWRevision.buildNumber =
2713 	    sc->aac_revision.buildNumber;
2714 
2715 	return(copyout((caddr_t)&rev_check_resp, udata,
2716 			sizeof(struct aac_rev_check_resp)));
2717 }
2718 
2719 /*
2720  * Pass the caller the next AIF in their queue
2721  */
2722 static int
2723 aac_getnext_aif(struct aac_softc *sc, caddr_t arg)
2724 {
2725 	struct get_adapter_fib_ioctl agf;
2726 	int error;
2727 
2728 	debug_called(2);
2729 
2730 	if ((error = copyin(arg, &agf, sizeof(agf))) == 0) {
2731 
2732 		/*
2733 		 * Check the magic number that we gave the caller.
2734 		 */
2735 		if (agf.AdapterFibContext != (int)(uintptr_t)sc->aifthread) {
2736 			error = EFAULT;
2737 		} else {
2738 			error = aac_return_aif(sc, agf.AifFib);
2739 			if ((error == EAGAIN) && (agf.Wait)) {
2740 				sc->aac_state |= AAC_STATE_AIF_SLEEPER;
2741 				while (error == EAGAIN) {
2742 					error = tsleep(sc->aac_aifq, PRIBIO |
2743 						       PCATCH, "aacaif", 0);
2744 					if (error == 0)
2745 						error = aac_return_aif(sc,
2746 						    agf.AifFib);
2747 				}
2748 				sc->aac_state &= ~AAC_STATE_AIF_SLEEPER;
2749 			}
2750 		}
2751 	}
2752 	return(error);
2753 }
2754 
2755 /*
2756  * Hand the next AIF off the top of the queue out to userspace.
2757  */
2758 static int
2759 aac_return_aif(struct aac_softc *sc, caddr_t uptr)
2760 {
2761 	int next, error;
2762 
2763 	debug_called(2);
2764 
2765 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2766 	if (sc->aac_aifq_tail == sc->aac_aifq_head) {
2767 		AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2768 		return (EAGAIN);
2769 	}
2770 
2771 	next = (sc->aac_aifq_tail + 1) % AAC_AIFQ_LENGTH;
2772 	error = copyout(&sc->aac_aifq[next], uptr,
2773 			sizeof(struct aac_aif_command));
2774 	if (error)
2775 		device_printf(sc->aac_dev,
2776 		    "aac_return_aif: copyout returned %d\n", error);
2777 	else
2778 		sc->aac_aifq_tail = next;
2779 
2780 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2781 	return(error);
2782 }
2783 
2784 /*
2785  * Give the userland some information about the container.  The AAC arch
2786  * expects the driver to be a SCSI passthrough type driver, so it expects
2787  * the containers to have b:t:l numbers.  Fake it.
2788  */
2789 static int
2790 aac_query_disk(struct aac_softc *sc, caddr_t uptr)
2791 {
2792 	struct aac_query_disk query_disk;
2793 	struct aac_container *co;
2794 	struct aac_disk	*disk;
2795 	int error, id;
2796 
2797 	debug_called(2);
2798 
2799 	disk = NULL;
2800 
2801 	error = copyin(uptr, (caddr_t)&query_disk,
2802 		       sizeof(struct aac_query_disk));
2803 	if (error)
2804 		return (error);
2805 
2806 	id = query_disk.ContainerNumber;
2807 	if (id == -1)
2808 		return (EINVAL);
2809 
2810 	AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
2811 	TAILQ_FOREACH(co, &sc->aac_container_tqh, co_link) {
2812 		if (co->co_mntobj.ObjectId == id)
2813 			break;
2814 		}
2815 
2816 	if (co == NULL) {
2817 			query_disk.Valid = 0;
2818 			query_disk.Locked = 0;
2819 			query_disk.Deleted = 1;		/* XXX is this right? */
2820 	} else {
2821 		disk = device_get_softc(co->co_disk);
2822 		query_disk.Valid = 1;
2823 		query_disk.Locked =
2824 		    (disk->ad_flags & AAC_DISK_OPEN) ? 1 : 0;
2825 		query_disk.Deleted = 0;
2826 		query_disk.Bus = device_get_unit(sc->aac_dev);
2827 		query_disk.Target = disk->unit;
2828 		query_disk.Lun = 0;
2829 		query_disk.UnMapped = 0;
2830 		sprintf(&query_disk.diskDeviceName[0], "%s%d",
2831 		        disk->ad_disk->d_name, disk->ad_disk->d_unit);
2832 	}
2833 	AAC_LOCK_RELEASE(&sc->aac_container_lock);
2834 
2835 	error = copyout((caddr_t)&query_disk, uptr,
2836 			sizeof(struct aac_query_disk));
2837 
2838 	return (error);
2839 }
2840 
2841 static void
2842 aac_get_bus_info(struct aac_softc *sc)
2843 {
2844 	struct aac_fib *fib;
2845 	struct aac_ctcfg *c_cmd;
2846 	struct aac_ctcfg_resp *c_resp;
2847 	struct aac_vmioctl *vmi;
2848 	struct aac_vmi_businf_resp *vmi_resp;
2849 	struct aac_getbusinf businfo;
2850 	struct aac_sim *caminf;
2851 	device_t child;
2852 	int i, found, error;
2853 
2854 	aac_alloc_sync_fib(sc, &fib);
2855 	c_cmd = (struct aac_ctcfg *)&fib->data[0];
2856 	bzero(c_cmd, sizeof(struct aac_ctcfg));
2857 
2858 	c_cmd->Command = VM_ContainerConfig;
2859 	c_cmd->cmd = CT_GET_SCSI_METHOD;
2860 	c_cmd->param = 0;
2861 
2862 	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2863 	    sizeof(struct aac_ctcfg));
2864 	if (error) {
2865 		device_printf(sc->aac_dev, "Error %d sending "
2866 		    "VM_ContainerConfig command\n", error);
2867 		aac_release_sync_fib(sc);
2868 		return;
2869 	}
2870 
2871 	c_resp = (struct aac_ctcfg_resp *)&fib->data[0];
2872 	if (c_resp->Status != ST_OK) {
2873 		device_printf(sc->aac_dev, "VM_ContainerConfig returned 0x%x\n",
2874 		    c_resp->Status);
2875 		aac_release_sync_fib(sc);
2876 		return;
2877 	}
2878 
2879 	sc->scsi_method_id = c_resp->param;
2880 
2881 	vmi = (struct aac_vmioctl *)&fib->data[0];
2882 	bzero(vmi, sizeof(struct aac_vmioctl));
2883 
2884 	vmi->Command = VM_Ioctl;
2885 	vmi->ObjType = FT_DRIVE;
2886 	vmi->MethId = sc->scsi_method_id;
2887 	vmi->ObjId = 0;
2888 	vmi->IoctlCmd = GetBusInfo;
2889 
2890 	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2891 	    sizeof(struct aac_vmioctl));
2892 	if (error) {
2893 		device_printf(sc->aac_dev, "Error %d sending VMIoctl command\n",
2894 		    error);
2895 		aac_release_sync_fib(sc);
2896 		return;
2897 	}
2898 
2899 	vmi_resp = (struct aac_vmi_businf_resp *)&fib->data[0];
2900 	if (vmi_resp->Status != ST_OK) {
2901 		device_printf(sc->aac_dev, "VM_Ioctl returned %d\n",
2902 		    vmi_resp->Status);
2903 		aac_release_sync_fib(sc);
2904 		return;
2905 	}
2906 
2907 	bcopy(&vmi_resp->BusInf, &businfo, sizeof(struct aac_getbusinf));
2908 	aac_release_sync_fib(sc);
2909 
2910 	found = 0;
2911 	for (i = 0; i < businfo.BusCount; i++) {
2912 		if (businfo.BusValid[i] != AAC_BUS_VALID)
2913 			continue;
2914 
2915 		caminf = (struct aac_sim *)malloc( sizeof(struct aac_sim),
2916 		    M_AACBUF, M_NOWAIT | M_ZERO);
2917 		if (caminf == NULL)
2918 			continue;
2919 
2920 		child = device_add_child(sc->aac_dev, "aacp", -1);
2921 		if (child == NULL) {
2922 			device_printf(sc->aac_dev, "device_add_child failed\n");
2923 			continue;
2924 		}
2925 
2926 		caminf->TargetsPerBus = businfo.TargetsPerBus;
2927 		caminf->BusNumber = i;
2928 		caminf->InitiatorBusId = businfo.InitiatorBusId[i];
2929 		caminf->aac_sc = sc;
2930 		caminf->sim_dev = child;
2931 
2932 		device_set_ivars(child, caminf);
2933 		device_set_desc(child, "SCSI Passthrough Bus");
2934 		TAILQ_INSERT_TAIL(&sc->aac_sim_tqh, caminf, sim_link);
2935 
2936 		found = 1;
2937 	}
2938 
2939 	if (found)
2940 		bus_generic_attach(sc->aac_dev);
2941 
2942 	return;
2943 }
2944