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