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