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