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