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