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