xref: /freebsd/sys/dev/aac/aac.c (revision 12dd6da62c8dcd06a0b3c408c81b25edcbb3bf9e)
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 	mtx_lock(&Giant);
818 	kthread_exit(0);
819 }
820 
821 /*
822  * Process completed commands.
823  */
824 static void
825 aac_complete(void *context, int pending)
826 {
827 	struct aac_softc *sc;
828 	struct aac_command *cm;
829 	struct aac_fib *fib;
830 	u_int32_t fib_size;
831 
832 	debug_called(2);
833 
834 	sc = (struct aac_softc *)context;
835 
836 	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
837 
838 	/* pull completed commands off the queue */
839 	for (;;) {
840 		/* look for completed FIBs on our queue */
841 		if (aac_dequeue_fib(sc, AAC_HOST_NORM_RESP_QUEUE, &fib_size,
842 				    &fib))
843 			break;	/* nothing to do */
844 
845 		/* get the command, unmap and hand off for processing */
846 		cm = sc->aac_commands + fib->Header.SenderData;
847 		if (cm == NULL) {
848 			AAC_PRINT_FIB(sc, fib);
849 			break;
850 		}
851 
852 		aac_remove_busy(cm);
853 		aac_unmap_command(cm);
854 		cm->cm_flags |= AAC_CMD_COMPLETED;
855 
856 		/* is there a completion handler? */
857 		if (cm->cm_complete != NULL) {
858 			cm->cm_complete(cm);
859 		} else {
860 			/* assume that someone is sleeping on this command */
861 			wakeup(cm);
862 		}
863 	}
864 
865 	/* see if we can start some more I/O */
866 	sc->flags &= ~AAC_QUEUE_FRZN;
867 	aac_startio(sc);
868 
869 	AAC_LOCK_RELEASE(&sc->aac_io_lock);
870 }
871 
872 /*
873  * Handle a bio submitted from a disk device.
874  */
875 void
876 aac_submit_bio(struct bio *bp)
877 {
878 	struct aac_disk *ad;
879 	struct aac_softc *sc;
880 
881 	debug_called(2);
882 
883 	ad = (struct aac_disk *)bp->bio_disk->d_drv1;
884 	sc = ad->ad_controller;
885 
886 	/* queue the BIO and try to get some work done */
887 	aac_enqueue_bio(sc, bp);
888 	aac_startio(sc);
889 }
890 
891 /*
892  * Get a bio and build a command to go with it.
893  */
894 static int
895 aac_bio_command(struct aac_softc *sc, struct aac_command **cmp)
896 {
897 	struct aac_command *cm;
898 	struct aac_fib *fib;
899 	struct aac_disk *ad;
900 	struct bio *bp;
901 
902 	debug_called(2);
903 
904 	/* get the resources we will need */
905 	cm = NULL;
906 	bp = NULL;
907 	if (aac_alloc_command(sc, &cm))	/* get a command */
908 		goto fail;
909 	if ((bp = aac_dequeue_bio(sc)) == NULL)
910 		goto fail;
911 
912 	/* fill out the command */
913 	cm->cm_data = (void *)bp->bio_data;
914 	cm->cm_datalen = bp->bio_bcount;
915 	cm->cm_complete = aac_bio_complete;
916 	cm->cm_private = bp;
917 	cm->cm_timestamp = time_second;
918 	cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
919 
920 	/* build the FIB */
921 	fib = cm->cm_fib;
922 	fib->Header.Size = sizeof(struct aac_fib_header);
923 	fib->Header.XferState =
924 		AAC_FIBSTATE_HOSTOWNED   |
925 		AAC_FIBSTATE_INITIALISED |
926 		AAC_FIBSTATE_EMPTY	 |
927 		AAC_FIBSTATE_FROMHOST	 |
928 		AAC_FIBSTATE_REXPECTED   |
929 		AAC_FIBSTATE_NORM	 |
930 		AAC_FIBSTATE_ASYNC	 |
931 		AAC_FIBSTATE_FAST_RESPONSE;
932 
933 	/* build the read/write request */
934 	ad = (struct aac_disk *)bp->bio_disk->d_drv1;
935 
936 	if ((sc->flags & AAC_FLAGS_SG_64BIT) == 0) {
937 		fib->Header.Command = ContainerCommand;
938 		if (bp->bio_cmd == BIO_READ) {
939 			struct aac_blockread *br;
940 			br = (struct aac_blockread *)&fib->data[0];
941 			br->Command = VM_CtBlockRead;
942 			br->ContainerId = ad->ad_container->co_mntobj.ObjectId;
943 			br->BlockNumber = bp->bio_pblkno;
944 			br->ByteCount = bp->bio_bcount;
945 			fib->Header.Size += sizeof(struct aac_blockread);
946 			cm->cm_sgtable = &br->SgMap;
947 			cm->cm_flags |= AAC_CMD_DATAIN;
948 		} else {
949 			struct aac_blockwrite *bw;
950 			bw = (struct aac_blockwrite *)&fib->data[0];
951 			bw->Command = VM_CtBlockWrite;
952 			bw->ContainerId = ad->ad_container->co_mntobj.ObjectId;
953 			bw->BlockNumber = bp->bio_pblkno;
954 			bw->ByteCount = bp->bio_bcount;
955 			bw->Stable = CUNSTABLE;
956 			fib->Header.Size += sizeof(struct aac_blockwrite);
957 			cm->cm_flags |= AAC_CMD_DATAOUT;
958 			cm->cm_sgtable = &bw->SgMap;
959 		}
960 	} else {
961 		fib->Header.Command = ContainerCommand64;
962 		if (bp->bio_cmd == BIO_READ) {
963 			struct aac_blockread64 *br;
964 			br = (struct aac_blockread64 *)&fib->data[0];
965 			br->Command = VM_CtHostRead64;
966 			br->ContainerId = ad->ad_container->co_mntobj.ObjectId;
967 			br->SectorCount = bp->bio_bcount / AAC_BLOCK_SIZE;
968 			br->BlockNumber = bp->bio_pblkno;
969 			br->Pad = 0;
970 			br->Flags = 0;
971 			fib->Header.Size += sizeof(struct aac_blockread64);
972 			cm->cm_flags |= AAC_CMD_DATAOUT;
973 			(struct aac_sg_table64 *)cm->cm_sgtable = &br->SgMap64;
974 		} else {
975 			struct aac_blockwrite64 *bw;
976 			bw = (struct aac_blockwrite64 *)&fib->data[0];
977 			bw->Command = VM_CtHostWrite64;
978 			bw->ContainerId = ad->ad_container->co_mntobj.ObjectId;
979 			bw->SectorCount = bp->bio_bcount / AAC_BLOCK_SIZE;
980 			bw->BlockNumber = bp->bio_pblkno;
981 			bw->Pad = 0;
982 			bw->Flags = 0;
983 			fib->Header.Size += sizeof(struct aac_blockwrite64);
984 			cm->cm_flags |= AAC_CMD_DATAIN;
985 			(struct aac_sg_table64 *)cm->cm_sgtable = &bw->SgMap64;
986 		}
987 	}
988 
989 	*cmp = cm;
990 	return(0);
991 
992 fail:
993 	if (bp != NULL)
994 		aac_enqueue_bio(sc, bp);
995 	if (cm != NULL)
996 		aac_release_command(cm);
997 	return(ENOMEM);
998 }
999 
1000 /*
1001  * Handle a bio-instigated command that has been completed.
1002  */
1003 static void
1004 aac_bio_complete(struct aac_command *cm)
1005 {
1006 	struct aac_blockread_response *brr;
1007 	struct aac_blockwrite_response *bwr;
1008 	struct bio *bp;
1009 	AAC_FSAStatus status;
1010 
1011 	/* fetch relevant status and then release the command */
1012 	bp = (struct bio *)cm->cm_private;
1013 	if (bp->bio_cmd == BIO_READ) {
1014 		brr = (struct aac_blockread_response *)&cm->cm_fib->data[0];
1015 		status = brr->Status;
1016 	} else {
1017 		bwr = (struct aac_blockwrite_response *)&cm->cm_fib->data[0];
1018 		status = bwr->Status;
1019 	}
1020 	aac_release_command(cm);
1021 
1022 	/* fix up the bio based on status */
1023 	if (status == ST_OK) {
1024 		bp->bio_resid = 0;
1025 	} else {
1026 		bp->bio_error = EIO;
1027 		bp->bio_flags |= BIO_ERROR;
1028 		/* pass an error string out to the disk layer */
1029 		bp->bio_driver1 = aac_describe_code(aac_command_status_table,
1030 						    status);
1031 	}
1032 	aac_biodone(bp);
1033 }
1034 
1035 /*
1036  * Submit a command to the controller, return when it completes.
1037  * XXX This is very dangerous!  If the card has gone out to lunch, we could
1038  *     be stuck here forever.  At the same time, signals are not caught
1039  *     because there is a risk that a signal could wakeup the tsleep before
1040  *     the card has a chance to complete the command.  The passed in timeout
1041  *     is ignored for the same reason.  Since there is no way to cancel a
1042  *     command in progress, we should probably create a 'dead' queue where
1043  *     commands go that have been interrupted/timed-out/etc, that keeps them
1044  *     out of the free pool.  That way, if the card is just slow, it won't
1045  *     spam the memory of a command that has been recycled.
1046  */
1047 static int
1048 aac_wait_command(struct aac_command *cm, int timeout)
1049 {
1050 	struct aac_softc *sc;
1051 	int error = 0;
1052 
1053 	debug_called(2);
1054 
1055 	sc = cm->cm_sc;
1056 
1057 	/* Put the command on the ready queue and get things going */
1058 	cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
1059 	aac_enqueue_ready(cm);
1060 	aac_startio(sc);
1061 	while (!(cm->cm_flags & AAC_CMD_COMPLETED) && (error != EWOULDBLOCK)) {
1062 		error = msleep(cm, &sc->aac_io_lock, PRIBIO, "aacwait", 0);
1063 	}
1064 	return(error);
1065 }
1066 
1067 /*
1068  *Command Buffer Management
1069  */
1070 
1071 /*
1072  * Allocate a command.
1073  */
1074 int
1075 aac_alloc_command(struct aac_softc *sc, struct aac_command **cmp)
1076 {
1077 	struct aac_command *cm;
1078 
1079 	debug_called(3);
1080 
1081 	if ((cm = aac_dequeue_free(sc)) == NULL) {
1082 		if (sc->total_fibs < sc->aac_max_fibs) {
1083 			sc->aifflags |= AAC_AIFFLAGS_ALLOCFIBS;
1084 			wakeup(sc->aifthread);
1085 		}
1086 		return (EBUSY);
1087 	}
1088 
1089 	*cmp = cm;
1090 	return(0);
1091 }
1092 
1093 /*
1094  * Release a command back to the freelist.
1095  */
1096 void
1097 aac_release_command(struct aac_command *cm)
1098 {
1099 	debug_called(3);
1100 
1101 	/* (re)initialise the command/FIB */
1102 	cm->cm_sgtable = NULL;
1103 	cm->cm_flags = 0;
1104 	cm->cm_complete = NULL;
1105 	cm->cm_private = NULL;
1106 	cm->cm_fib->Header.XferState = AAC_FIBSTATE_EMPTY;
1107 	cm->cm_fib->Header.StructType = AAC_FIBTYPE_TFIB;
1108 	cm->cm_fib->Header.Flags = 0;
1109 	cm->cm_fib->Header.SenderSize = sizeof(struct aac_fib);
1110 
1111 	/*
1112 	 * These are duplicated in aac_start to cover the case where an
1113 	 * intermediate stage may have destroyed them.  They're left
1114 	 * initialised here for debugging purposes only.
1115 	 */
1116 	cm->cm_fib->Header.ReceiverFibAddress = (u_int32_t)cm->cm_fibphys;
1117 	cm->cm_fib->Header.SenderData = 0;
1118 
1119 	aac_enqueue_free(cm);
1120 }
1121 
1122 /*
1123  * Map helper for command/FIB allocation.
1124  */
1125 static void
1126 aac_map_command_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1127 {
1128 	uint32_t	*fibphys;
1129 
1130 	fibphys = (uint32_t *)arg;
1131 
1132 	debug_called(3);
1133 
1134 	*fibphys = segs[0].ds_addr;
1135 }
1136 
1137 /*
1138  * Allocate and initialise commands/FIBs for this adapter.
1139  */
1140 static int
1141 aac_alloc_commands(struct aac_softc *sc)
1142 {
1143 	struct aac_command *cm;
1144 	struct aac_fibmap *fm;
1145 	uint32_t fibphys;
1146 	int i, error;
1147 
1148 	debug_called(2);
1149 
1150 	if (sc->total_fibs + AAC_FIB_COUNT > sc->aac_max_fibs)
1151 		return (ENOMEM);
1152 
1153 	fm = malloc(sizeof(struct aac_fibmap), M_AACBUF, M_NOWAIT|M_ZERO);
1154 	if (fm == NULL)
1155 		return (ENOMEM);
1156 
1157 	/* allocate the FIBs in DMAable memory and load them */
1158 	if (bus_dmamem_alloc(sc->aac_fib_dmat, (void **)&fm->aac_fibs,
1159 			     BUS_DMA_NOWAIT, &fm->aac_fibmap)) {
1160 		device_printf(sc->aac_dev,
1161 			      "Not enough contiguous memory available.\n");
1162 		free(fm, M_AACBUF);
1163 		return (ENOMEM);
1164 	}
1165 
1166 	/* Ignore errors since this doesn't bounce */
1167 	(void)bus_dmamap_load(sc->aac_fib_dmat, fm->aac_fibmap, fm->aac_fibs,
1168 			      AAC_FIB_COUNT * sizeof(struct aac_fib),
1169 			      aac_map_command_helper, &fibphys, 0);
1170 
1171 	/* initialise constant fields in the command structure */
1172 	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
1173 	bzero(fm->aac_fibs, AAC_FIB_COUNT * sizeof(struct aac_fib));
1174 	for (i = 0; i < AAC_FIB_COUNT; i++) {
1175 		cm = sc->aac_commands + sc->total_fibs;
1176 		fm->aac_commands = cm;
1177 		cm->cm_sc = sc;
1178 		cm->cm_fib = fm->aac_fibs + i;
1179 		cm->cm_fibphys = fibphys + (i * sizeof(struct aac_fib));
1180 		cm->cm_index = sc->total_fibs;
1181 
1182 		if ((error = bus_dmamap_create(sc->aac_buffer_dmat, 0,
1183 					       &cm->cm_datamap)) == 0)
1184 			aac_release_command(cm);
1185 		else
1186 			break;
1187 		sc->total_fibs++;
1188 	}
1189 
1190 	if (i > 0) {
1191 		TAILQ_INSERT_TAIL(&sc->aac_fibmap_tqh, fm, fm_link);
1192 		debug(1, "total_fibs= %d\n", sc->total_fibs);
1193 		AAC_LOCK_RELEASE(&sc->aac_io_lock);
1194 		return (0);
1195 	}
1196 
1197 	AAC_LOCK_RELEASE(&sc->aac_io_lock);
1198 	bus_dmamap_unload(sc->aac_fib_dmat, fm->aac_fibmap);
1199 	bus_dmamem_free(sc->aac_fib_dmat, fm->aac_fibs, fm->aac_fibmap);
1200 	free(fm, M_AACBUF);
1201 	return (ENOMEM);
1202 }
1203 
1204 /*
1205  * Free FIBs owned by this adapter.
1206  */
1207 static void
1208 aac_free_commands(struct aac_softc *sc)
1209 {
1210 	struct aac_fibmap *fm;
1211 	struct aac_command *cm;
1212 	int i;
1213 
1214 	debug_called(1);
1215 
1216 	while ((fm = TAILQ_FIRST(&sc->aac_fibmap_tqh)) != NULL) {
1217 
1218 		TAILQ_REMOVE(&sc->aac_fibmap_tqh, fm, fm_link);
1219 		/*
1220 		 * We check against total_fibs to handle partially
1221 		 * allocated blocks.
1222 		 */
1223 		for (i = 0; i < AAC_FIB_COUNT && sc->total_fibs--; i++) {
1224 			cm = fm->aac_commands + i;
1225 			bus_dmamap_destroy(sc->aac_buffer_dmat, cm->cm_datamap);
1226 		}
1227 		bus_dmamap_unload(sc->aac_fib_dmat, fm->aac_fibmap);
1228 		bus_dmamem_free(sc->aac_fib_dmat, fm->aac_fibs, fm->aac_fibmap);
1229 		free(fm, M_AACBUF);
1230 	}
1231 }
1232 
1233 /*
1234  * Command-mapping helper function - populate this command's s/g table.
1235  */
1236 static void
1237 aac_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1238 {
1239 	struct aac_softc *sc;
1240 	struct aac_command *cm;
1241 	struct aac_fib *fib;
1242 	int i;
1243 
1244 	debug_called(3);
1245 
1246 	cm = (struct aac_command *)arg;
1247 	sc = cm->cm_sc;
1248 	fib = cm->cm_fib;
1249 
1250 	/* copy into the FIB */
1251 	if (cm->cm_sgtable != NULL) {
1252 		if ((cm->cm_sc->flags & AAC_FLAGS_SG_64BIT) == 0) {
1253 			struct aac_sg_table *sg;
1254 			sg = cm->cm_sgtable;
1255 			sg->SgCount = nseg;
1256 			for (i = 0; i < nseg; i++) {
1257 				sg->SgEntry[i].SgAddress = segs[i].ds_addr;
1258 				sg->SgEntry[i].SgByteCount = segs[i].ds_len;
1259 			}
1260 			/* update the FIB size for the s/g count */
1261 			fib->Header.Size += nseg * sizeof(struct aac_sg_entry);
1262 		} else {
1263 			struct aac_sg_table64 *sg;
1264 			sg = (struct aac_sg_table64 *)cm->cm_sgtable;
1265 			sg->SgCount = nseg;
1266 			for (i = 0; i < nseg; i++) {
1267 				sg->SgEntry64[i].SgAddress = segs[i].ds_addr;
1268 				sg->SgEntry64[i].SgByteCount = segs[i].ds_len;
1269 			}
1270 			/* update the FIB size for the s/g count */
1271 			fib->Header.Size += nseg*sizeof(struct aac_sg_entry64);
1272 		}
1273 	}
1274 
1275 	/* Fix up the address values in the FIB.  Use the command array index
1276 	 * instead of a pointer since these fields are only 32 bits.  Shift
1277 	 * the SenderFibAddress over to make room for the fast response bit.
1278 	 */
1279 	cm->cm_fib->Header.SenderFibAddress = (cm->cm_index << 1);
1280 	cm->cm_fib->Header.ReceiverFibAddress = cm->cm_fibphys;
1281 
1282 	/* save a pointer to the command for speedy reverse-lookup */
1283 	cm->cm_fib->Header.SenderData = cm->cm_index;
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 	cm->cm_flags |= AAC_CMD_MAPPED;
1292 
1293 	/* put the FIB on the outbound queue */
1294 	if (aac_enqueue_fib(sc, cm->cm_queue, cm) == EBUSY) {
1295 		aac_unmap_command(cm);
1296 		aac_requeue_ready(cm);
1297 	}
1298 
1299 	return;
1300 }
1301 
1302 /*
1303  * Unmap a command from controller-visible space.
1304  */
1305 static void
1306 aac_unmap_command(struct aac_command *cm)
1307 {
1308 	struct aac_softc *sc;
1309 
1310 	debug_called(2);
1311 
1312 	sc = cm->cm_sc;
1313 
1314 	if (!(cm->cm_flags & AAC_CMD_MAPPED))
1315 		return;
1316 
1317 	if (cm->cm_datalen != 0) {
1318 		if (cm->cm_flags & AAC_CMD_DATAIN)
1319 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1320 					BUS_DMASYNC_POSTREAD);
1321 		if (cm->cm_flags & AAC_CMD_DATAOUT)
1322 			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1323 					BUS_DMASYNC_POSTWRITE);
1324 
1325 		bus_dmamap_unload(sc->aac_buffer_dmat, cm->cm_datamap);
1326 	}
1327 	cm->cm_flags &= ~AAC_CMD_MAPPED;
1328 }
1329 
1330 /*
1331  * Hardware Interface
1332  */
1333 
1334 /*
1335  * Initialise the adapter.
1336  */
1337 static void
1338 aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1339 {
1340 	struct aac_softc *sc;
1341 
1342 	debug_called(1);
1343 
1344 	sc = (struct aac_softc *)arg;
1345 
1346 	sc->aac_common_busaddr = segs[0].ds_addr;
1347 }
1348 
1349 static int
1350 aac_check_firmware(struct aac_softc *sc)
1351 {
1352 	u_int32_t major, minor, options;
1353 
1354 	debug_called(1);
1355 
1356 	/*
1357 	 * Retrieve the firmware version numbers.  Dell PERC2/QC cards with
1358 	 * firmware version 1.x are not compatible with this driver.
1359 	 */
1360 	if (sc->flags & AAC_FLAGS_PERC2QC) {
1361 		if (aac_sync_command(sc, AAC_MONKER_GETKERNVER, 0, 0, 0, 0,
1362 				     NULL)) {
1363 			device_printf(sc->aac_dev,
1364 				      "Error reading firmware version\n");
1365 			return (EIO);
1366 		}
1367 
1368 		/* These numbers are stored as ASCII! */
1369 		major = (AAC_GET_MAILBOX(sc, 1) & 0xff) - 0x30;
1370 		minor = (AAC_GET_MAILBOX(sc, 2) & 0xff) - 0x30;
1371 		if (major == 1) {
1372 			device_printf(sc->aac_dev,
1373 			    "Firmware version %d.%d is not supported.\n",
1374 			    major, minor);
1375 			return (EINVAL);
1376 		}
1377 	}
1378 
1379 	/*
1380 	 * Retrieve the capabilities/supported options word so we know what
1381 	 * work-arounds to enable.
1382 	 */
1383 	if (aac_sync_command(sc, AAC_MONKER_GETINFO, 0, 0, 0, 0, NULL)) {
1384 		device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
1385 		return (EIO);
1386 	}
1387 	options = AAC_GET_MAILBOX(sc, 1);
1388 	sc->supported_options = options;
1389 
1390 	if ((options & AAC_SUPPORTED_4GB_WINDOW) != 0 &&
1391 	    (sc->flags & AAC_FLAGS_NO4GB) == 0)
1392 		sc->flags |= AAC_FLAGS_4GB_WINDOW;
1393 	if (options & AAC_SUPPORTED_NONDASD)
1394 		sc->flags |= AAC_FLAGS_ENABLE_CAM;
1395 	if ((options & AAC_SUPPORTED_SGMAP_HOST64) != 0
1396 	     && (sizeof(bus_addr_t) > 4)) {
1397 		device_printf(sc->aac_dev, "Enabling 64-bit address support\n");
1398 		sc->flags |= AAC_FLAGS_SG_64BIT;
1399 	}
1400 
1401 	/* Check for broken hardware that does a lower number of commands */
1402 	if ((sc->flags & AAC_FLAGS_256FIBS) == 0)
1403 		sc->aac_max_fibs = AAC_MAX_FIBS;
1404 	else
1405 		sc->aac_max_fibs = 256;
1406 
1407 	return (0);
1408 }
1409 
1410 static int
1411 aac_init(struct aac_softc *sc)
1412 {
1413 	struct aac_adapter_init	*ip;
1414 	time_t then;
1415 	u_int32_t code, qoffset;
1416 	int error;
1417 
1418 	debug_called(1);
1419 
1420 	/*
1421 	 * First wait for the adapter to come ready.
1422 	 */
1423 	then = time_second;
1424 	do {
1425 		code = AAC_GET_FWSTATUS(sc);
1426 		if (code & AAC_SELF_TEST_FAILED) {
1427 			device_printf(sc->aac_dev, "FATAL: selftest failed\n");
1428 			return(ENXIO);
1429 		}
1430 		if (code & AAC_KERNEL_PANIC) {
1431 			device_printf(sc->aac_dev,
1432 				      "FATAL: controller kernel panic\n");
1433 			return(ENXIO);
1434 		}
1435 		if (time_second > (then + AAC_BOOT_TIMEOUT)) {
1436 			device_printf(sc->aac_dev,
1437 				      "FATAL: controller not coming ready, "
1438 					   "status %x\n", code);
1439 			return(ENXIO);
1440 		}
1441 	} while (!(code & AAC_UP_AND_RUNNING));
1442 
1443 	error = ENOMEM;
1444 	/*
1445 	 * Create DMA tag for mapping buffers into controller-addressable space.
1446 	 */
1447 	if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1448 			       1, 0, 			/* algnmnt, boundary */
1449 			       (sc->flags & AAC_FLAGS_SG_64BIT) ?
1450 			       BUS_SPACE_MAXADDR :
1451 			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1452 			       BUS_SPACE_MAXADDR, 	/* highaddr */
1453 			       NULL, NULL, 		/* filter, filterarg */
1454 			       MAXBSIZE,		/* maxsize */
1455 			       AAC_MAXSGENTRIES,	/* nsegments */
1456 			       MAXBSIZE,		/* maxsegsize */
1457 			       BUS_DMA_ALLOCNOW,	/* flags */
1458 			       busdma_lock_mutex,	/* lockfunc */
1459 			       &sc->aac_io_lock,	/* lockfuncarg */
1460 			       &sc->aac_buffer_dmat)) {
1461 		device_printf(sc->aac_dev, "can't allocate buffer DMA tag\n");
1462 		goto out;
1463 	}
1464 
1465 	/*
1466 	 * Create DMA tag for mapping FIBs into controller-addressable space..
1467 	 */
1468 	if (bus_dma_tag_create(sc->aac_parent_dmat,	/* parent */
1469 			       1, 0, 			/* algnmnt, boundary */
1470 			       (sc->flags & AAC_FLAGS_4GB_WINDOW) ?
1471 			       BUS_SPACE_MAXADDR_32BIT :
1472 			       0x7fffffff,		/* lowaddr */
1473 			       BUS_SPACE_MAXADDR, 	/* highaddr */
1474 			       NULL, NULL, 		/* filter, filterarg */
1475 			       AAC_FIB_COUNT *
1476 			       sizeof(struct aac_fib),  /* maxsize */
1477 			       1,			/* nsegments */
1478 			       AAC_FIB_COUNT *
1479 			       sizeof(struct aac_fib),	/* maxsegsize */
1480 			       BUS_DMA_ALLOCNOW,	/* flags */
1481 			       NULL, NULL,		/* No locking needed */
1482 			       &sc->aac_fib_dmat)) {
1483 		device_printf(sc->aac_dev, "can't allocate FIB DMA tag\n");;
1484 		goto out;
1485 	}
1486 
1487 	/*
1488 	 * Create DMA tag for the common structure and allocate it.
1489 	 */
1490 	if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1491 			       1, 0,			/* algnmnt, boundary */
1492 			       (sc->flags & AAC_FLAGS_4GB_WINDOW) ?
1493 			       BUS_SPACE_MAXADDR_32BIT :
1494 			       0x7fffffff,		/* lowaddr */
1495 			       BUS_SPACE_MAXADDR, 	/* highaddr */
1496 			       NULL, NULL, 		/* filter, filterarg */
1497 			       8192 + sizeof(struct aac_common), /* maxsize */
1498 			       1,			/* nsegments */
1499 			       BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1500 			       BUS_DMA_ALLOCNOW,	/* flags */
1501 			       NULL, NULL,		/* No locking needed */
1502 			       &sc->aac_common_dmat)) {
1503 		device_printf(sc->aac_dev,
1504 			      "can't allocate common structure DMA tag\n");
1505 		goto out;
1506 	}
1507 	if (bus_dmamem_alloc(sc->aac_common_dmat, (void **)&sc->aac_common,
1508 			     BUS_DMA_NOWAIT, &sc->aac_common_dmamap)) {
1509 		device_printf(sc->aac_dev, "can't allocate common structure\n");
1510 		goto out;
1511 	}
1512 
1513 	/*
1514 	 * Work around a bug in the 2120 and 2200 that cannot DMA commands
1515 	 * below address 8192 in physical memory.
1516 	 * XXX If the padding is not needed, can it be put to use instead
1517 	 * of ignored?
1518 	 */
1519 	(void)bus_dmamap_load(sc->aac_common_dmat, sc->aac_common_dmamap,
1520 			sc->aac_common, 8192 + sizeof(*sc->aac_common),
1521 			aac_common_map, sc, 0);
1522 
1523 	if (sc->aac_common_busaddr < 8192) {
1524 		(uint8_t *)sc->aac_common += 8192;
1525 		sc->aac_common_busaddr += 8192;
1526 	}
1527 	bzero(sc->aac_common, sizeof(*sc->aac_common));
1528 
1529 	/* Allocate some FIBs and associated command structs */
1530 	TAILQ_INIT(&sc->aac_fibmap_tqh);
1531 	sc->aac_commands = malloc(AAC_MAX_FIBS * sizeof(struct aac_command),
1532 				  M_AACBUF, M_WAITOK|M_ZERO);
1533 	while (sc->total_fibs < AAC_PREALLOCATE_FIBS) {
1534 		if (aac_alloc_commands(sc) != 0)
1535 			break;
1536 	}
1537 	if (sc->total_fibs == 0)
1538 		goto out;
1539 
1540 	/*
1541 	 * Fill in the init structure.  This tells the adapter about the
1542 	 * physical location of various important shared data structures.
1543 	 */
1544 	ip = &sc->aac_common->ac_init;
1545 	ip->InitStructRevision = AAC_INIT_STRUCT_REVISION;
1546 	ip->MiniPortRevision = AAC_INIT_STRUCT_MINIPORT_REVISION;
1547 
1548 	ip->AdapterFibsPhysicalAddress = sc->aac_common_busaddr +
1549 					 offsetof(struct aac_common, ac_fibs);
1550 	ip->AdapterFibsVirtualAddress = 0;
1551 	ip->AdapterFibsSize = AAC_ADAPTER_FIBS * sizeof(struct aac_fib);
1552 	ip->AdapterFibAlign = sizeof(struct aac_fib);
1553 
1554 	ip->PrintfBufferAddress = sc->aac_common_busaddr +
1555 				  offsetof(struct aac_common, ac_printf);
1556 	ip->PrintfBufferSize = AAC_PRINTF_BUFSIZE;
1557 
1558 	/*
1559 	 * The adapter assumes that pages are 4K in size, except on some
1560  	 * broken firmware versions that do the page->byte conversion twice,
1561 	 * therefore 'assuming' that this value is in 16MB units (2^24).
1562 	 * Round up since the granularity is so high.
1563 	 */
1564 	ip->HostPhysMemPages = ctob(physmem) / AAC_PAGE_SIZE;
1565 	if (sc->flags & AAC_FLAGS_BROKEN_MEMMAP) {
1566 		ip->HostPhysMemPages =
1567 		    (ip->HostPhysMemPages + AAC_PAGE_SIZE) / AAC_PAGE_SIZE;
1568 	}
1569 	ip->HostElapsedSeconds = time_second;	/* reset later if invalid */
1570 
1571 	/*
1572 	 * Initialise FIB queues.  Note that it appears that the layout of the
1573 	 * indexes and the segmentation of the entries may be mandated by the
1574 	 * adapter, which is only told about the base of the queue index fields.
1575 	 *
1576 	 * The initial values of the indices are assumed to inform the adapter
1577 	 * of the sizes of the respective queues, and theoretically it could
1578 	 * work out the entire layout of the queue structures from this.  We
1579 	 * take the easy route and just lay this area out like everyone else
1580 	 * does.
1581 	 *
1582 	 * The Linux driver uses a much more complex scheme whereby several
1583 	 * header records are kept for each queue.  We use a couple of generic
1584 	 * list manipulation functions which 'know' the size of each list by
1585 	 * virtue of a table.
1586 	 */
1587 	qoffset = offsetof(struct aac_common, ac_qbuf) + AAC_QUEUE_ALIGN;
1588 	qoffset &= ~(AAC_QUEUE_ALIGN - 1);
1589 	sc->aac_queues =
1590 	    (struct aac_queue_table *)((uintptr_t)sc->aac_common + qoffset);
1591 	ip->CommHeaderAddress = sc->aac_common_busaddr + qoffset;
1592 
1593 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1594 		AAC_HOST_NORM_CMD_ENTRIES;
1595 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1596 		AAC_HOST_NORM_CMD_ENTRIES;
1597 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1598 		AAC_HOST_HIGH_CMD_ENTRIES;
1599 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1600 		AAC_HOST_HIGH_CMD_ENTRIES;
1601 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1602 		AAC_ADAP_NORM_CMD_ENTRIES;
1603 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1604 		AAC_ADAP_NORM_CMD_ENTRIES;
1605 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1606 		AAC_ADAP_HIGH_CMD_ENTRIES;
1607 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1608 		AAC_ADAP_HIGH_CMD_ENTRIES;
1609 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1610 		AAC_HOST_NORM_RESP_ENTRIES;
1611 	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1612 		AAC_HOST_NORM_RESP_ENTRIES;
1613 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1614 		AAC_HOST_HIGH_RESP_ENTRIES;
1615 	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1616 		AAC_HOST_HIGH_RESP_ENTRIES;
1617 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1618 		AAC_ADAP_NORM_RESP_ENTRIES;
1619 	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1620 		AAC_ADAP_NORM_RESP_ENTRIES;
1621 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1622 		AAC_ADAP_HIGH_RESP_ENTRIES;
1623 	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1624 		AAC_ADAP_HIGH_RESP_ENTRIES;
1625 	sc->aac_qentries[AAC_HOST_NORM_CMD_QUEUE] =
1626 		&sc->aac_queues->qt_HostNormCmdQueue[0];
1627 	sc->aac_qentries[AAC_HOST_HIGH_CMD_QUEUE] =
1628 		&sc->aac_queues->qt_HostHighCmdQueue[0];
1629 	sc->aac_qentries[AAC_ADAP_NORM_CMD_QUEUE] =
1630 		&sc->aac_queues->qt_AdapNormCmdQueue[0];
1631 	sc->aac_qentries[AAC_ADAP_HIGH_CMD_QUEUE] =
1632 		&sc->aac_queues->qt_AdapHighCmdQueue[0];
1633 	sc->aac_qentries[AAC_HOST_NORM_RESP_QUEUE] =
1634 		&sc->aac_queues->qt_HostNormRespQueue[0];
1635 	sc->aac_qentries[AAC_HOST_HIGH_RESP_QUEUE] =
1636 		&sc->aac_queues->qt_HostHighRespQueue[0];
1637 	sc->aac_qentries[AAC_ADAP_NORM_RESP_QUEUE] =
1638 		&sc->aac_queues->qt_AdapNormRespQueue[0];
1639 	sc->aac_qentries[AAC_ADAP_HIGH_RESP_QUEUE] =
1640 		&sc->aac_queues->qt_AdapHighRespQueue[0];
1641 
1642 	/*
1643 	 * Do controller-type-specific initialisation
1644 	 */
1645 	switch (sc->aac_hwif) {
1646 	case AAC_HWIF_I960RX:
1647 		AAC_SETREG4(sc, AAC_RX_ODBR, ~0);
1648 		break;
1649 	}
1650 
1651 	/*
1652 	 * Give the init structure to the controller.
1653 	 */
1654 	if (aac_sync_command(sc, AAC_MONKER_INITSTRUCT,
1655 			     sc->aac_common_busaddr +
1656 			     offsetof(struct aac_common, ac_init), 0, 0, 0,
1657 			     NULL)) {
1658 		device_printf(sc->aac_dev,
1659 			      "error establishing init structure\n");
1660 		error = EIO;
1661 		goto out;
1662 	}
1663 
1664 	error = 0;
1665 out:
1666 	return(error);
1667 }
1668 
1669 /*
1670  * Send a synchronous command to the controller and wait for a result.
1671  */
1672 static int
1673 aac_sync_command(struct aac_softc *sc, u_int32_t command,
1674 		 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3,
1675 		 u_int32_t *sp)
1676 {
1677 	time_t then;
1678 	u_int32_t status;
1679 
1680 	debug_called(3);
1681 
1682 	/* populate the mailbox */
1683 	AAC_SET_MAILBOX(sc, command, arg0, arg1, arg2, arg3);
1684 
1685 	/* ensure the sync command doorbell flag is cleared */
1686 	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1687 
1688 	/* then set it to signal the adapter */
1689 	AAC_QNOTIFY(sc, AAC_DB_SYNC_COMMAND);
1690 
1691 	/* spin waiting for the command to complete */
1692 	then = time_second;
1693 	do {
1694 		if (time_second > (then + AAC_IMMEDIATE_TIMEOUT)) {
1695 			debug(1, "timed out");
1696 			return(EIO);
1697 		}
1698 	} while (!(AAC_GET_ISTATUS(sc) & AAC_DB_SYNC_COMMAND));
1699 
1700 	/* clear the completion flag */
1701 	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1702 
1703 	/* get the command status */
1704 	status = AAC_GET_MAILBOX(sc, 0);
1705 	if (sp != NULL)
1706 		*sp = status;
1707 	return(0);
1708 }
1709 
1710 /*
1711  * Grab the sync fib area.
1712  */
1713 int
1714 aac_alloc_sync_fib(struct aac_softc *sc, struct aac_fib **fib, int flags)
1715 {
1716 
1717 	/*
1718 	 * If the force flag is set, the system is shutting down, or in
1719 	 * trouble.  Ignore the mutex.
1720 	 */
1721 	if (!(flags & AAC_SYNC_LOCK_FORCE))
1722 		AAC_LOCK_ACQUIRE(&sc->aac_sync_lock);
1723 
1724 	*fib = &sc->aac_common->ac_sync_fib;
1725 
1726 	return (1);
1727 }
1728 
1729 /*
1730  * Release the sync fib area.
1731  */
1732 void
1733 aac_release_sync_fib(struct aac_softc *sc)
1734 {
1735 
1736 	AAC_LOCK_RELEASE(&sc->aac_sync_lock);
1737 }
1738 
1739 /*
1740  * Send a synchronous FIB to the controller and wait for a result.
1741  */
1742 int
1743 aac_sync_fib(struct aac_softc *sc, u_int32_t command, u_int32_t xferstate,
1744 		 struct aac_fib *fib, u_int16_t datasize)
1745 {
1746 	debug_called(3);
1747 
1748 	if (datasize > AAC_FIB_DATASIZE)
1749 		return(EINVAL);
1750 
1751 	/*
1752 	 * Set up the sync FIB
1753 	 */
1754 	fib->Header.XferState = AAC_FIBSTATE_HOSTOWNED |
1755 				AAC_FIBSTATE_INITIALISED |
1756 				AAC_FIBSTATE_EMPTY;
1757 	fib->Header.XferState |= xferstate;
1758 	fib->Header.Command = command;
1759 	fib->Header.StructType = AAC_FIBTYPE_TFIB;
1760 	fib->Header.Size = sizeof(struct aac_fib) + datasize;
1761 	fib->Header.SenderSize = sizeof(struct aac_fib);
1762 	fib->Header.SenderFibAddress = 0;	/* Not needed */
1763 	fib->Header.ReceiverFibAddress = sc->aac_common_busaddr +
1764 					 offsetof(struct aac_common,
1765 						  ac_sync_fib);
1766 
1767 	/*
1768 	 * Give the FIB to the controller, wait for a response.
1769 	 */
1770 	if (aac_sync_command(sc, AAC_MONKER_SYNCFIB,
1771 			     fib->Header.ReceiverFibAddress, 0, 0, 0, NULL)) {
1772 		debug(2, "IO error");
1773 		return(EIO);
1774 	}
1775 
1776 	return (0);
1777 }
1778 
1779 /*
1780  * Adapter-space FIB queue manipulation
1781  *
1782  * Note that the queue implementation here is a little funky; neither the PI or
1783  * CI will ever be zero.  This behaviour is a controller feature.
1784  */
1785 static struct {
1786 	int		size;
1787 	int		notify;
1788 } aac_qinfo[] = {
1789 	{AAC_HOST_NORM_CMD_ENTRIES, AAC_DB_COMMAND_NOT_FULL},
1790 	{AAC_HOST_HIGH_CMD_ENTRIES, 0},
1791 	{AAC_ADAP_NORM_CMD_ENTRIES, AAC_DB_COMMAND_READY},
1792 	{AAC_ADAP_HIGH_CMD_ENTRIES, 0},
1793 	{AAC_HOST_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_NOT_FULL},
1794 	{AAC_HOST_HIGH_RESP_ENTRIES, 0},
1795 	{AAC_ADAP_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_READY},
1796 	{AAC_ADAP_HIGH_RESP_ENTRIES, 0}
1797 };
1798 
1799 /*
1800  * Atomically insert an entry into the nominated queue, returns 0 on success or
1801  * EBUSY if the queue is full.
1802  *
1803  * Note: it would be more efficient to defer notifying the controller in
1804  *	 the case where we may be inserting several entries in rapid succession,
1805  *	 but implementing this usefully may be difficult (it would involve a
1806  *	 separate queue/notify interface).
1807  */
1808 static int
1809 aac_enqueue_fib(struct aac_softc *sc, int queue, struct aac_command *cm)
1810 {
1811 	u_int32_t pi, ci;
1812 	int error;
1813 	u_int32_t fib_size;
1814 	u_int32_t fib_addr;
1815 
1816 	debug_called(3);
1817 
1818 	fib_size = cm->cm_fib->Header.Size;
1819 	fib_addr = cm->cm_fib->Header.ReceiverFibAddress;
1820 
1821 	/* get the producer/consumer indices */
1822 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1823 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1824 
1825 	/* wrap the queue? */
1826 	if (pi >= aac_qinfo[queue].size)
1827 		pi = 0;
1828 
1829 	/* check for queue full */
1830 	if ((pi + 1) == ci) {
1831 		error = EBUSY;
1832 		goto out;
1833 	}
1834 
1835 	/* populate queue entry */
1836 	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1837 	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1838 
1839 	/* update producer index */
1840 	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1841 
1842 	/*
1843 	 * To avoid a race with its completion interrupt, place this command on
1844 	 * the busy queue prior to advertising it to the controller.
1845 	 */
1846 	aac_enqueue_busy(cm);
1847 
1848 	/* notify the adapter if we know how */
1849 	if (aac_qinfo[queue].notify != 0)
1850 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1851 
1852 	error = 0;
1853 
1854 out:
1855 	return(error);
1856 }
1857 
1858 /*
1859  * Atomically remove one entry from the nominated queue, returns 0 on
1860  * success or ENOENT if the queue is empty.
1861  */
1862 static int
1863 aac_dequeue_fib(struct aac_softc *sc, int queue, u_int32_t *fib_size,
1864 		struct aac_fib **fib_addr)
1865 {
1866 	u_int32_t pi, ci;
1867 	u_int32_t fib_index;
1868 	int error;
1869 	int notify;
1870 
1871 	debug_called(3);
1872 
1873 	/* get the producer/consumer indices */
1874 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1875 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1876 
1877 	/* check for queue empty */
1878 	if (ci == pi) {
1879 		error = ENOENT;
1880 		goto out;
1881 	}
1882 
1883 	/* wrap the pi so the following test works */
1884 	if (pi >= aac_qinfo[queue].size)
1885 		pi = 0;
1886 
1887 	notify = 0;
1888 	if (ci == pi + 1)
1889 		notify++;
1890 
1891 	/* wrap the queue? */
1892 	if (ci >= aac_qinfo[queue].size)
1893 		ci = 0;
1894 
1895 	/* fetch the entry */
1896 	*fib_size = (sc->aac_qentries[queue] + ci)->aq_fib_size;
1897 
1898 	switch (queue) {
1899 	case AAC_HOST_NORM_CMD_QUEUE:
1900 	case AAC_HOST_HIGH_CMD_QUEUE:
1901 		/*
1902 		 * The aq_fib_addr is only 32 bits wide so it can't be counted
1903 		 * on to hold an address.  For AIF's, the adapter assumes
1904 		 * that it's giving us an address into the array of AIF fibs.
1905 		 * Therefore, we have to convert it to an index.
1906 		 */
1907 		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr /
1908 			sizeof(struct aac_fib);
1909 		*fib_addr = &sc->aac_common->ac_fibs[fib_index];
1910 		break;
1911 
1912 	case AAC_HOST_NORM_RESP_QUEUE:
1913 	case AAC_HOST_HIGH_RESP_QUEUE:
1914 	{
1915 		struct aac_command *cm;
1916 
1917 		/*
1918 		 * As above, an index is used instead of an actual address.
1919 		 * Gotta shift the index to account for the fast response
1920 		 * bit.  No other correction is needed since this value was
1921 		 * originally provided by the driver via the SenderFibAddress
1922 		 * field.
1923 		 */
1924 		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr;
1925 		cm = sc->aac_commands + (fib_index >> 1);
1926 		*fib_addr = cm->cm_fib;
1927 
1928 		/*
1929 		 * Is this a fast response? If it is, update the fib fields in
1930 		 * local memory since the whole fib isn't DMA'd back up.
1931 		 */
1932 		if (fib_index & 0x01) {
1933 			(*fib_addr)->Header.XferState |= AAC_FIBSTATE_DONEADAP;
1934 			*((u_int32_t*)((*fib_addr)->data)) = AAC_ERROR_NORMAL;
1935 		}
1936 		break;
1937 	}
1938 	default:
1939 		panic("Invalid queue in aac_dequeue_fib()");
1940 		break;
1941 	}
1942 
1943 	/* update consumer index */
1944 	sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX] = ci + 1;
1945 
1946 	/* if we have made the queue un-full, notify the adapter */
1947 	if (notify && (aac_qinfo[queue].notify != 0))
1948 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1949 	error = 0;
1950 
1951 out:
1952 	return(error);
1953 }
1954 
1955 /*
1956  * Put our response to an Adapter Initialed Fib on the response queue
1957  */
1958 static int
1959 aac_enqueue_response(struct aac_softc *sc, int queue, struct aac_fib *fib)
1960 {
1961 	u_int32_t pi, ci;
1962 	int error;
1963 	u_int32_t fib_size;
1964 	u_int32_t fib_addr;
1965 
1966 	debug_called(1);
1967 
1968 	/* Tell the adapter where the FIB is */
1969 	fib_size = fib->Header.Size;
1970 	fib_addr = fib->Header.SenderFibAddress;
1971 	fib->Header.ReceiverFibAddress = fib_addr;
1972 
1973 	/* get the producer/consumer indices */
1974 	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1975 	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1976 
1977 	/* wrap the queue? */
1978 	if (pi >= aac_qinfo[queue].size)
1979 		pi = 0;
1980 
1981 	/* check for queue full */
1982 	if ((pi + 1) == ci) {
1983 		error = EBUSY;
1984 		goto out;
1985 	}
1986 
1987 	/* populate queue entry */
1988 	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1989 	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1990 
1991 	/* update producer index */
1992 	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1993 
1994 	/* notify the adapter if we know how */
1995 	if (aac_qinfo[queue].notify != 0)
1996 		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1997 
1998 	error = 0;
1999 
2000 out:
2001 	return(error);
2002 }
2003 
2004 /*
2005  * Check for commands that have been outstanding for a suspiciously long time,
2006  * and complain about them.
2007  */
2008 static void
2009 aac_timeout(struct aac_softc *sc)
2010 {
2011 	struct aac_command *cm;
2012 	time_t deadline;
2013 
2014 	/*
2015 	 * Traverse the busy command list, bitch about late commands once
2016 	 * only.
2017 	 */
2018 	deadline = time_second - AAC_CMD_TIMEOUT;
2019 	TAILQ_FOREACH(cm, &sc->aac_busy, cm_link) {
2020 		if ((cm->cm_timestamp  < deadline)
2021 			/* && !(cm->cm_flags & AAC_CMD_TIMEDOUT) */) {
2022 			cm->cm_flags |= AAC_CMD_TIMEDOUT;
2023 			device_printf(sc->aac_dev,
2024 				      "COMMAND %p TIMEOUT AFTER %d SECONDS\n",
2025 				      cm, (int)(time_second-cm->cm_timestamp));
2026 			AAC_PRINT_FIB(sc, cm->cm_fib);
2027 		}
2028 	}
2029 
2030 	return;
2031 }
2032 
2033 /*
2034  * Interface Function Vectors
2035  */
2036 
2037 /*
2038  * Read the current firmware status word.
2039  */
2040 static int
2041 aac_sa_get_fwstatus(struct aac_softc *sc)
2042 {
2043 	debug_called(3);
2044 
2045 	return(AAC_GETREG4(sc, AAC_SA_FWSTATUS));
2046 }
2047 
2048 static int
2049 aac_rx_get_fwstatus(struct aac_softc *sc)
2050 {
2051 	debug_called(3);
2052 
2053 	return(AAC_GETREG4(sc, AAC_RX_FWSTATUS));
2054 }
2055 
2056 static int
2057 aac_fa_get_fwstatus(struct aac_softc *sc)
2058 {
2059 	int val;
2060 
2061 	debug_called(3);
2062 
2063 	val = AAC_GETREG4(sc, AAC_FA_FWSTATUS);
2064 	return (val);
2065 }
2066 
2067 /*
2068  * Notify the controller of a change in a given queue
2069  */
2070 
2071 static void
2072 aac_sa_qnotify(struct aac_softc *sc, int qbit)
2073 {
2074 	debug_called(3);
2075 
2076 	AAC_SETREG2(sc, AAC_SA_DOORBELL1_SET, qbit);
2077 }
2078 
2079 static void
2080 aac_rx_qnotify(struct aac_softc *sc, int qbit)
2081 {
2082 	debug_called(3);
2083 
2084 	AAC_SETREG4(sc, AAC_RX_IDBR, qbit);
2085 }
2086 
2087 static void
2088 aac_fa_qnotify(struct aac_softc *sc, int qbit)
2089 {
2090 	debug_called(3);
2091 
2092 	AAC_SETREG2(sc, AAC_FA_DOORBELL1, qbit);
2093 	AAC_FA_HACK(sc);
2094 }
2095 
2096 /*
2097  * Get the interrupt reason bits
2098  */
2099 static int
2100 aac_sa_get_istatus(struct aac_softc *sc)
2101 {
2102 	debug_called(3);
2103 
2104 	return(AAC_GETREG2(sc, AAC_SA_DOORBELL0));
2105 }
2106 
2107 static int
2108 aac_rx_get_istatus(struct aac_softc *sc)
2109 {
2110 	debug_called(3);
2111 
2112 	return(AAC_GETREG4(sc, AAC_RX_ODBR));
2113 }
2114 
2115 static int
2116 aac_fa_get_istatus(struct aac_softc *sc)
2117 {
2118 	int val;
2119 
2120 	debug_called(3);
2121 
2122 	val = AAC_GETREG2(sc, AAC_FA_DOORBELL0);
2123 	return (val);
2124 }
2125 
2126 /*
2127  * Clear some interrupt reason bits
2128  */
2129 static void
2130 aac_sa_clear_istatus(struct aac_softc *sc, int mask)
2131 {
2132 	debug_called(3);
2133 
2134 	AAC_SETREG2(sc, AAC_SA_DOORBELL0_CLEAR, mask);
2135 }
2136 
2137 static void
2138 aac_rx_clear_istatus(struct aac_softc *sc, int mask)
2139 {
2140 	debug_called(3);
2141 
2142 	AAC_SETREG4(sc, AAC_RX_ODBR, mask);
2143 }
2144 
2145 static void
2146 aac_fa_clear_istatus(struct aac_softc *sc, int mask)
2147 {
2148 	debug_called(3);
2149 
2150 	AAC_SETREG2(sc, AAC_FA_DOORBELL0_CLEAR, mask);
2151 	AAC_FA_HACK(sc);
2152 }
2153 
2154 /*
2155  * Populate the mailbox and set the command word
2156  */
2157 static void
2158 aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
2159 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2160 {
2161 	debug_called(4);
2162 
2163 	AAC_SETREG4(sc, AAC_SA_MAILBOX, command);
2164 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 4, arg0);
2165 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 8, arg1);
2166 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 12, arg2);
2167 	AAC_SETREG4(sc, AAC_SA_MAILBOX + 16, arg3);
2168 }
2169 
2170 static void
2171 aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
2172 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2173 {
2174 	debug_called(4);
2175 
2176 	AAC_SETREG4(sc, AAC_RX_MAILBOX, command);
2177 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 4, arg0);
2178 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 8, arg1);
2179 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 12, arg2);
2180 	AAC_SETREG4(sc, AAC_RX_MAILBOX + 16, arg3);
2181 }
2182 
2183 static void
2184 aac_fa_set_mailbox(struct aac_softc *sc, u_int32_t command,
2185 		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2186 {
2187 	debug_called(4);
2188 
2189 	AAC_SETREG4(sc, AAC_FA_MAILBOX, command);
2190 	AAC_FA_HACK(sc);
2191 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 4, arg0);
2192 	AAC_FA_HACK(sc);
2193 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 8, arg1);
2194 	AAC_FA_HACK(sc);
2195 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 12, arg2);
2196 	AAC_FA_HACK(sc);
2197 	AAC_SETREG4(sc, AAC_FA_MAILBOX + 16, arg3);
2198 	AAC_FA_HACK(sc);
2199 }
2200 
2201 /*
2202  * Fetch the immediate command status word
2203  */
2204 static int
2205 aac_sa_get_mailbox(struct aac_softc *sc, int mb)
2206 {
2207 	debug_called(4);
2208 
2209 	return(AAC_GETREG4(sc, AAC_SA_MAILBOX + (mb * 4)));
2210 }
2211 
2212 static int
2213 aac_rx_get_mailbox(struct aac_softc *sc, int mb)
2214 {
2215 	debug_called(4);
2216 
2217 	return(AAC_GETREG4(sc, AAC_RX_MAILBOX + (mb * 4)));
2218 }
2219 
2220 static int
2221 aac_fa_get_mailbox(struct aac_softc *sc, int mb)
2222 {
2223 	int val;
2224 
2225 	debug_called(4);
2226 
2227 	val = AAC_GETREG4(sc, AAC_FA_MAILBOX + (mb * 4));
2228 	return (val);
2229 }
2230 
2231 /*
2232  * Set/clear interrupt masks
2233  */
2234 static void
2235 aac_sa_set_interrupts(struct aac_softc *sc, int enable)
2236 {
2237 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2238 
2239 	if (enable) {
2240 		AAC_SETREG2((sc), AAC_SA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2241 	} else {
2242 		AAC_SETREG2((sc), AAC_SA_MASK0_SET, ~0);
2243 	}
2244 }
2245 
2246 static void
2247 aac_rx_set_interrupts(struct aac_softc *sc, int enable)
2248 {
2249 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2250 
2251 	if (enable) {
2252 		AAC_SETREG4(sc, AAC_RX_OIMR, ~AAC_DB_INTERRUPTS);
2253 	} else {
2254 		AAC_SETREG4(sc, AAC_RX_OIMR, ~0);
2255 	}
2256 }
2257 
2258 static void
2259 aac_fa_set_interrupts(struct aac_softc *sc, int enable)
2260 {
2261 	debug(2, "%sable interrupts", enable ? "en" : "dis");
2262 
2263 	if (enable) {
2264 		AAC_SETREG2((sc), AAC_FA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2265 		AAC_FA_HACK(sc);
2266 	} else {
2267 		AAC_SETREG2((sc), AAC_FA_MASK0, ~0);
2268 		AAC_FA_HACK(sc);
2269 	}
2270 }
2271 
2272 /*
2273  * Debugging and Diagnostics
2274  */
2275 
2276 /*
2277  * Print some information about the controller.
2278  */
2279 static void
2280 aac_describe_controller(struct aac_softc *sc)
2281 {
2282 	struct aac_fib *fib;
2283 	struct aac_adapter_info	*info;
2284 
2285 	debug_called(2);
2286 
2287 	aac_alloc_sync_fib(sc, &fib, 0);
2288 
2289 	fib->data[0] = 0;
2290 	if (aac_sync_fib(sc, RequestAdapterInfo, 0, fib, 1)) {
2291 		device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
2292 		aac_release_sync_fib(sc);
2293 		return;
2294 	}
2295 	info = (struct aac_adapter_info *)&fib->data[0];
2296 
2297 	device_printf(sc->aac_dev, "%s %dMHz, %dMB cache memory, %s\n",
2298 		      aac_describe_code(aac_cpu_variant, info->CpuVariant),
2299 		      info->ClockSpeed, info->BufferMem / (1024 * 1024),
2300 		      aac_describe_code(aac_battery_platform,
2301 					info->batteryPlatform));
2302 
2303 	/* save the kernel revision structure for later use */
2304 	sc->aac_revision = info->KernelRevision;
2305 	device_printf(sc->aac_dev, "Kernel %d.%d-%d, Build %d, S/N %6X\n",
2306 		      info->KernelRevision.external.comp.major,
2307 		      info->KernelRevision.external.comp.minor,
2308 		      info->KernelRevision.external.comp.dash,
2309 		      info->KernelRevision.buildNumber,
2310 		      (u_int32_t)(info->SerialNumber & 0xffffff));
2311 
2312 	aac_release_sync_fib(sc);
2313 
2314 	if (1 || bootverbose) {
2315 		device_printf(sc->aac_dev, "Supported Options=%b\n",
2316 			      sc->supported_options,
2317 			      "\20"
2318 			      "\1SNAPSHOT"
2319 			      "\2CLUSTERS"
2320 			      "\3WCACHE"
2321 			      "\4DATA64"
2322 			      "\5HOSTTIME"
2323 			      "\6RAID50"
2324 			      "\7WINDOW4GB"
2325 			      "\10SCSIUPGD"
2326 			      "\11SOFTERR"
2327 			      "\12NORECOND"
2328 			      "\13SGMAP64"
2329 			      "\14ALARM"
2330 			      "\15NONDASD");
2331 	}
2332 }
2333 
2334 /*
2335  * Look up a text description of a numeric error code and return a pointer to
2336  * same.
2337  */
2338 static char *
2339 aac_describe_code(struct aac_code_lookup *table, u_int32_t code)
2340 {
2341 	int i;
2342 
2343 	for (i = 0; table[i].string != NULL; i++)
2344 		if (table[i].code == code)
2345 			return(table[i].string);
2346 	return(table[i + 1].string);
2347 }
2348 
2349 /*
2350  * Management Interface
2351  */
2352 
2353 static int
2354 aac_open(dev_t dev, int flags, int fmt, d_thread_t *td)
2355 {
2356 	struct aac_softc *sc;
2357 
2358 	debug_called(2);
2359 
2360 	sc = dev->si_drv1;
2361 
2362 	/* Check to make sure the device isn't already open */
2363 	if (sc->aac_state & AAC_STATE_OPEN) {
2364 		return EBUSY;
2365 	}
2366 	sc->aac_state |= AAC_STATE_OPEN;
2367 
2368 	return 0;
2369 }
2370 
2371 static int
2372 aac_close(dev_t dev, int flags, int fmt, d_thread_t *td)
2373 {
2374 	struct aac_softc *sc;
2375 
2376 	debug_called(2);
2377 
2378 	sc = dev->si_drv1;
2379 
2380 	/* Mark this unit as no longer open  */
2381 	sc->aac_state &= ~AAC_STATE_OPEN;
2382 
2383 	return 0;
2384 }
2385 
2386 static int
2387 aac_ioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, d_thread_t *td)
2388 {
2389 	union aac_statrequest *as;
2390 	struct aac_softc *sc;
2391 	int error = 0;
2392 	uint32_t cookie;
2393 
2394 	debug_called(2);
2395 
2396 	as = (union aac_statrequest *)arg;
2397 	sc = dev->si_drv1;
2398 
2399 	switch (cmd) {
2400 	case AACIO_STATS:
2401 		switch (as->as_item) {
2402 		case AACQ_FREE:
2403 		case AACQ_BIO:
2404 		case AACQ_READY:
2405 		case AACQ_BUSY:
2406 			bcopy(&sc->aac_qstat[as->as_item], &as->as_qstat,
2407 			      sizeof(struct aac_qstat));
2408 			break;
2409 		default:
2410 			error = ENOENT;
2411 			break;
2412 		}
2413 	break;
2414 
2415 	case FSACTL_SENDFIB:
2416 		arg = *(caddr_t*)arg;
2417 	case FSACTL_LNX_SENDFIB:
2418 		debug(1, "FSACTL_SENDFIB");
2419 		error = aac_ioctl_sendfib(sc, arg);
2420 		break;
2421 	case FSACTL_AIF_THREAD:
2422 	case FSACTL_LNX_AIF_THREAD:
2423 		debug(1, "FSACTL_AIF_THREAD");
2424 		error = EINVAL;
2425 		break;
2426 	case FSACTL_OPEN_GET_ADAPTER_FIB:
2427 		arg = *(caddr_t*)arg;
2428 	case FSACTL_LNX_OPEN_GET_ADAPTER_FIB:
2429 		debug(1, "FSACTL_OPEN_GET_ADAPTER_FIB");
2430 		/*
2431 		 * Pass the caller out an AdapterFibContext.
2432 		 *
2433 		 * Note that because we only support one opener, we
2434 		 * basically ignore this.  Set the caller's context to a magic
2435 		 * number just in case.
2436 		 *
2437 		 * The Linux code hands the driver a pointer into kernel space,
2438 		 * and then trusts it when the caller hands it back.  Aiee!
2439 		 * Here, we give it the proc pointer of the per-adapter aif
2440 		 * thread. It's only used as a sanity check in other calls.
2441 		 */
2442 		cookie = (uint32_t)(uintptr_t)sc->aifthread;
2443 		error = copyout(&cookie, arg, sizeof(cookie));
2444 		break;
2445 	case FSACTL_GET_NEXT_ADAPTER_FIB:
2446 		arg = *(caddr_t*)arg;
2447 	case FSACTL_LNX_GET_NEXT_ADAPTER_FIB:
2448 		debug(1, "FSACTL_GET_NEXT_ADAPTER_FIB");
2449 		error = aac_getnext_aif(sc, arg);
2450 		break;
2451 	case FSACTL_CLOSE_GET_ADAPTER_FIB:
2452 	case FSACTL_LNX_CLOSE_GET_ADAPTER_FIB:
2453 		debug(1, "FSACTL_CLOSE_GET_ADAPTER_FIB");
2454 		/* don't do anything here */
2455 		break;
2456 	case FSACTL_MINIPORT_REV_CHECK:
2457 		arg = *(caddr_t*)arg;
2458 	case FSACTL_LNX_MINIPORT_REV_CHECK:
2459 		debug(1, "FSACTL_MINIPORT_REV_CHECK");
2460 		error = aac_rev_check(sc, arg);
2461 		break;
2462 	case FSACTL_QUERY_DISK:
2463 		arg = *(caddr_t*)arg;
2464 	case FSACTL_LNX_QUERY_DISK:
2465 		debug(1, "FSACTL_QUERY_DISK");
2466 		error = aac_query_disk(sc, arg);
2467 			break;
2468 	case FSACTL_DELETE_DISK:
2469 	case FSACTL_LNX_DELETE_DISK:
2470 		/*
2471 		 * We don't trust the underland to tell us when to delete a
2472 		 * container, rather we rely on an AIF coming from the
2473 		 * controller
2474 		 */
2475 		error = 0;
2476 		break;
2477 	default:
2478 		debug(1, "unsupported cmd 0x%lx\n", cmd);
2479 		error = EINVAL;
2480 		break;
2481 	}
2482 	return(error);
2483 }
2484 
2485 static int
2486 aac_poll(dev_t dev, int poll_events, d_thread_t *td)
2487 {
2488 	struct aac_softc *sc;
2489 	int revents;
2490 
2491 	sc = dev->si_drv1;
2492 	revents = 0;
2493 
2494 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2495 	if ((poll_events & (POLLRDNORM | POLLIN)) != 0) {
2496 		if (sc->aac_aifq_tail != sc->aac_aifq_head)
2497 			revents |= poll_events & (POLLIN | POLLRDNORM);
2498 	}
2499 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2500 
2501 	if (revents == 0) {
2502 		if (poll_events & (POLLIN | POLLRDNORM))
2503 			selrecord(td, &sc->rcv_select);
2504 	}
2505 
2506 	return (revents);
2507 }
2508 
2509 /*
2510  * Send a FIB supplied from userspace
2511  */
2512 static int
2513 aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib)
2514 {
2515 	struct aac_command *cm;
2516 	int size, error;
2517 
2518 	debug_called(2);
2519 
2520 	cm = NULL;
2521 
2522 	/*
2523 	 * Get a command
2524 	 */
2525 	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
2526 	if (aac_alloc_command(sc, &cm)) {
2527 		error = EBUSY;
2528 		goto out;
2529 	}
2530 
2531 	/*
2532 	 * Fetch the FIB header, then re-copy to get data as well.
2533 	 */
2534 	if ((error = copyin(ufib, cm->cm_fib,
2535 			    sizeof(struct aac_fib_header))) != 0)
2536 		goto out;
2537 	size = cm->cm_fib->Header.Size + sizeof(struct aac_fib_header);
2538 	if (size > sizeof(struct aac_fib)) {
2539 		device_printf(sc->aac_dev, "incoming FIB oversized (%d > %zd)\n",
2540 			      size, sizeof(struct aac_fib));
2541 		size = sizeof(struct aac_fib);
2542 	}
2543 	if ((error = copyin(ufib, cm->cm_fib, size)) != 0)
2544 		goto out;
2545 	cm->cm_fib->Header.Size = size;
2546 	cm->cm_timestamp = time_second;
2547 
2548 	/*
2549 	 * Pass the FIB to the controller, wait for it to complete.
2550 	 */
2551 	if ((error = aac_wait_command(cm, 30)) != 0) {	/* XXX user timeout? */
2552 		device_printf(sc->aac_dev,
2553 			      "aac_wait_command return %d\n", error);
2554 		goto out;
2555 	}
2556 
2557 	/*
2558 	 * Copy the FIB and data back out to the caller.
2559 	 */
2560 	size = cm->cm_fib->Header.Size;
2561 	if (size > sizeof(struct aac_fib)) {
2562 		device_printf(sc->aac_dev, "outbound FIB oversized (%d > %zd)\n",
2563 			      size, sizeof(struct aac_fib));
2564 		size = sizeof(struct aac_fib);
2565 	}
2566 	error = copyout(cm->cm_fib, ufib, size);
2567 
2568 out:
2569 	if (cm != NULL) {
2570 		aac_release_command(cm);
2571 	}
2572 
2573 	AAC_LOCK_RELEASE(&sc->aac_io_lock);
2574 	return(error);
2575 }
2576 
2577 /*
2578  * Handle an AIF sent to us by the controller; queue it for later reference.
2579  * If the queue fills up, then drop the older entries.
2580  */
2581 static void
2582 aac_handle_aif(struct aac_softc *sc, struct aac_fib *fib)
2583 {
2584 	struct aac_aif_command *aif;
2585 	struct aac_container *co, *co_next;
2586 	struct aac_mntinfo *mi;
2587 	struct aac_mntinforesp *mir = NULL;
2588 	u_int16_t rsize;
2589 	int next, found;
2590 	int count = 0, added = 0, i = 0;
2591 
2592 	debug_called(2);
2593 
2594 	aif = (struct aac_aif_command*)&fib->data[0];
2595 	aac_print_aif(sc, aif);
2596 
2597 	/* Is it an event that we should care about? */
2598 	switch (aif->command) {
2599 	case AifCmdEventNotify:
2600 		switch (aif->data.EN.type) {
2601 		case AifEnAddContainer:
2602 		case AifEnDeleteContainer:
2603 			/*
2604 			 * A container was added or deleted, but the message
2605 			 * doesn't tell us anything else!  Re-enumerate the
2606 			 * containers and sort things out.
2607 			 */
2608 			aac_alloc_sync_fib(sc, &fib, 0);
2609 			mi = (struct aac_mntinfo *)&fib->data[0];
2610 			do {
2611 				/*
2612 				 * Ask the controller for its containers one at
2613 				 * a time.
2614 				 * XXX What if the controller's list changes
2615 				 * midway through this enumaration?
2616 				 * XXX This should be done async.
2617 				 */
2618 				bzero(mi, sizeof(struct aac_mntinfo));
2619 				mi->Command = VM_NameServe;
2620 				mi->MntType = FT_FILESYS;
2621 				mi->MntCount = i;
2622 				rsize = sizeof(mir);
2623 				if (aac_sync_fib(sc, ContainerCommand, 0, fib,
2624 						 sizeof(struct aac_mntinfo))) {
2625 					printf("Error probing container %d\n",
2626 					      i);
2627 					continue;
2628 				}
2629 				mir = (struct aac_mntinforesp *)&fib->data[0];
2630 				/* XXX Need to check if count changed */
2631 				count = mir->MntRespCount;
2632 				/*
2633 				 * Check the container against our list.
2634 				 * co->co_found was already set to 0 in a
2635 				 * previous run.
2636 				 */
2637 				if ((mir->Status == ST_OK) &&
2638 				    (mir->MntTable[0].VolType != CT_NONE)) {
2639 					found = 0;
2640 					TAILQ_FOREACH(co,
2641 						      &sc->aac_container_tqh,
2642 						      co_link) {
2643 						if (co->co_mntobj.ObjectId ==
2644 						    mir->MntTable[0].ObjectId) {
2645 							co->co_found = 1;
2646 							found = 1;
2647 							break;
2648 						}
2649 					}
2650 					/*
2651 					 * If the container matched, continue
2652 					 * in the list.
2653 					 */
2654 					if (found) {
2655 						i++;
2656 						continue;
2657 					}
2658 
2659 					/*
2660 					 * This is a new container.  Do all the
2661 					 * appropriate things to set it up.
2662 					 */
2663 					aac_add_container(sc, mir, 1);
2664 					added = 1;
2665 				}
2666 				i++;
2667 			} while ((i < count) && (i < AAC_MAX_CONTAINERS));
2668 			aac_release_sync_fib(sc);
2669 
2670 			/*
2671 			 * Go through our list of containers and see which ones
2672 			 * were not marked 'found'.  Since the controller didn't
2673 			 * list them they must have been deleted.  Do the
2674 			 * appropriate steps to destroy the device.  Also reset
2675 			 * the co->co_found field.
2676 			 */
2677 			co = TAILQ_FIRST(&sc->aac_container_tqh);
2678 			while (co != NULL) {
2679 				if (co->co_found == 0) {
2680 					device_delete_child(sc->aac_dev,
2681 							    co->co_disk);
2682 					co_next = TAILQ_NEXT(co, co_link);
2683 					AAC_LOCK_ACQUIRE(&sc->
2684 							aac_container_lock);
2685 					TAILQ_REMOVE(&sc->aac_container_tqh, co,
2686 						     co_link);
2687 					AAC_LOCK_RELEASE(&sc->
2688 							 aac_container_lock);
2689 					FREE(co, M_AACBUF);
2690 					co = co_next;
2691 				} else {
2692 					co->co_found = 0;
2693 					co = TAILQ_NEXT(co, co_link);
2694 				}
2695 			}
2696 
2697 			/* Attach the newly created containers */
2698 			if (added)
2699 				bus_generic_attach(sc->aac_dev);
2700 
2701 			break;
2702 
2703 		default:
2704 			break;
2705 		}
2706 
2707 	default:
2708 		break;
2709 	}
2710 
2711 	/* Copy the AIF data to the AIF queue for ioctl retrieval */
2712 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2713 	next = (sc->aac_aifq_head + 1) % AAC_AIFQ_LENGTH;
2714 	if (next != sc->aac_aifq_tail) {
2715 		bcopy(aif, &sc->aac_aifq[next], sizeof(struct aac_aif_command));
2716 		sc->aac_aifq_head = next;
2717 
2718 		/* On the off chance that someone is sleeping for an aif... */
2719 		if (sc->aac_state & AAC_STATE_AIF_SLEEPER)
2720 			wakeup(sc->aac_aifq);
2721 		/* Wakeup any poll()ers */
2722 		selwakeuppri(&sc->rcv_select, PRIBIO);
2723 	}
2724 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2725 
2726 	return;
2727 }
2728 
2729 /*
2730  * Return the Revision of the driver to userspace and check to see if the
2731  * userspace app is possibly compatible.  This is extremely bogus since
2732  * our driver doesn't follow Adaptec's versioning system.  Cheat by just
2733  * returning what the card reported.
2734  */
2735 static int
2736 aac_rev_check(struct aac_softc *sc, caddr_t udata)
2737 {
2738 	struct aac_rev_check rev_check;
2739 	struct aac_rev_check_resp rev_check_resp;
2740 	int error = 0;
2741 
2742 	debug_called(2);
2743 
2744 	/*
2745 	 * Copyin the revision struct from userspace
2746 	 */
2747 	if ((error = copyin(udata, (caddr_t)&rev_check,
2748 			sizeof(struct aac_rev_check))) != 0) {
2749 		return error;
2750 	}
2751 
2752 	debug(2, "Userland revision= %d\n",
2753 	      rev_check.callingRevision.buildNumber);
2754 
2755 	/*
2756 	 * Doctor up the response struct.
2757 	 */
2758 	rev_check_resp.possiblyCompatible = 1;
2759 	rev_check_resp.adapterSWRevision.external.ul =
2760 	    sc->aac_revision.external.ul;
2761 	rev_check_resp.adapterSWRevision.buildNumber =
2762 	    sc->aac_revision.buildNumber;
2763 
2764 	return(copyout((caddr_t)&rev_check_resp, udata,
2765 			sizeof(struct aac_rev_check_resp)));
2766 }
2767 
2768 /*
2769  * Pass the caller the next AIF in their queue
2770  */
2771 static int
2772 aac_getnext_aif(struct aac_softc *sc, caddr_t arg)
2773 {
2774 	struct get_adapter_fib_ioctl agf;
2775 	int error;
2776 
2777 	debug_called(2);
2778 
2779 	if ((error = copyin(arg, &agf, sizeof(agf))) == 0) {
2780 
2781 		/*
2782 		 * Check the magic number that we gave the caller.
2783 		 */
2784 		if (agf.AdapterFibContext != (int)(uintptr_t)sc->aifthread) {
2785 			error = EFAULT;
2786 		} else {
2787 			error = aac_return_aif(sc, agf.AifFib);
2788 			if ((error == EAGAIN) && (agf.Wait)) {
2789 				sc->aac_state |= AAC_STATE_AIF_SLEEPER;
2790 				while (error == EAGAIN) {
2791 					error = tsleep(sc->aac_aifq, PRIBIO |
2792 						       PCATCH, "aacaif", 0);
2793 					if (error == 0)
2794 						error = aac_return_aif(sc,
2795 						    agf.AifFib);
2796 				}
2797 				sc->aac_state &= ~AAC_STATE_AIF_SLEEPER;
2798 			}
2799 		}
2800 	}
2801 	return(error);
2802 }
2803 
2804 /*
2805  * Hand the next AIF off the top of the queue out to userspace.
2806  */
2807 static int
2808 aac_return_aif(struct aac_softc *sc, caddr_t uptr)
2809 {
2810 	int next, error;
2811 
2812 	debug_called(2);
2813 
2814 	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2815 	if (sc->aac_aifq_tail == sc->aac_aifq_head) {
2816 		AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2817 		return (EAGAIN);
2818 	}
2819 
2820 	next = (sc->aac_aifq_tail + 1) % AAC_AIFQ_LENGTH;
2821 	error = copyout(&sc->aac_aifq[next], uptr,
2822 			sizeof(struct aac_aif_command));
2823 	if (error)
2824 		device_printf(sc->aac_dev,
2825 		    "aac_return_aif: copyout returned %d\n", error);
2826 	else
2827 		sc->aac_aifq_tail = next;
2828 
2829 	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2830 	return(error);
2831 }
2832 
2833 /*
2834  * Give the userland some information about the container.  The AAC arch
2835  * expects the driver to be a SCSI passthrough type driver, so it expects
2836  * the containers to have b:t:l numbers.  Fake it.
2837  */
2838 static int
2839 aac_query_disk(struct aac_softc *sc, caddr_t uptr)
2840 {
2841 	struct aac_query_disk query_disk;
2842 	struct aac_container *co;
2843 	struct aac_disk	*disk;
2844 	int error, id;
2845 
2846 	debug_called(2);
2847 
2848 	disk = NULL;
2849 
2850 	error = copyin(uptr, (caddr_t)&query_disk,
2851 		       sizeof(struct aac_query_disk));
2852 	if (error)
2853 		return (error);
2854 
2855 	id = query_disk.ContainerNumber;
2856 	if (id == -1)
2857 		return (EINVAL);
2858 
2859 	AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
2860 	TAILQ_FOREACH(co, &sc->aac_container_tqh, co_link) {
2861 		if (co->co_mntobj.ObjectId == id)
2862 			break;
2863 		}
2864 
2865 	if (co == NULL) {
2866 			query_disk.Valid = 0;
2867 			query_disk.Locked = 0;
2868 			query_disk.Deleted = 1;		/* XXX is this right? */
2869 	} else {
2870 		disk = device_get_softc(co->co_disk);
2871 		query_disk.Valid = 1;
2872 		query_disk.Locked =
2873 		    (disk->ad_flags & AAC_DISK_OPEN) ? 1 : 0;
2874 		query_disk.Deleted = 0;
2875 		query_disk.Bus = device_get_unit(sc->aac_dev);
2876 		query_disk.Target = disk->unit;
2877 		query_disk.Lun = 0;
2878 		query_disk.UnMapped = 0;
2879 		sprintf(&query_disk.diskDeviceName[0], "%s%d",
2880 		        disk->ad_disk->d_name, disk->ad_disk->d_unit);
2881 	}
2882 	AAC_LOCK_RELEASE(&sc->aac_container_lock);
2883 
2884 	error = copyout((caddr_t)&query_disk, uptr,
2885 			sizeof(struct aac_query_disk));
2886 
2887 	return (error);
2888 }
2889 
2890 static void
2891 aac_get_bus_info(struct aac_softc *sc)
2892 {
2893 	struct aac_fib *fib;
2894 	struct aac_ctcfg *c_cmd;
2895 	struct aac_ctcfg_resp *c_resp;
2896 	struct aac_vmioctl *vmi;
2897 	struct aac_vmi_businf_resp *vmi_resp;
2898 	struct aac_getbusinf businfo;
2899 	struct aac_sim *caminf;
2900 	device_t child;
2901 	int i, found, error;
2902 
2903 	aac_alloc_sync_fib(sc, &fib, 0);
2904 	c_cmd = (struct aac_ctcfg *)&fib->data[0];
2905 	bzero(c_cmd, sizeof(struct aac_ctcfg));
2906 
2907 	c_cmd->Command = VM_ContainerConfig;
2908 	c_cmd->cmd = CT_GET_SCSI_METHOD;
2909 	c_cmd->param = 0;
2910 
2911 	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2912 	    sizeof(struct aac_ctcfg));
2913 	if (error) {
2914 		device_printf(sc->aac_dev, "Error %d sending "
2915 		    "VM_ContainerConfig command\n", error);
2916 		aac_release_sync_fib(sc);
2917 		return;
2918 	}
2919 
2920 	c_resp = (struct aac_ctcfg_resp *)&fib->data[0];
2921 	if (c_resp->Status != ST_OK) {
2922 		device_printf(sc->aac_dev, "VM_ContainerConfig returned 0x%x\n",
2923 		    c_resp->Status);
2924 		aac_release_sync_fib(sc);
2925 		return;
2926 	}
2927 
2928 	sc->scsi_method_id = c_resp->param;
2929 
2930 	vmi = (struct aac_vmioctl *)&fib->data[0];
2931 	bzero(vmi, sizeof(struct aac_vmioctl));
2932 
2933 	vmi->Command = VM_Ioctl;
2934 	vmi->ObjType = FT_DRIVE;
2935 	vmi->MethId = sc->scsi_method_id;
2936 	vmi->ObjId = 0;
2937 	vmi->IoctlCmd = GetBusInfo;
2938 
2939 	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2940 	    sizeof(struct aac_vmioctl));
2941 	if (error) {
2942 		device_printf(sc->aac_dev, "Error %d sending VMIoctl command\n",
2943 		    error);
2944 		aac_release_sync_fib(sc);
2945 		return;
2946 	}
2947 
2948 	vmi_resp = (struct aac_vmi_businf_resp *)&fib->data[0];
2949 	if (vmi_resp->Status != ST_OK) {
2950 		device_printf(sc->aac_dev, "VM_Ioctl returned %d\n",
2951 		    vmi_resp->Status);
2952 		aac_release_sync_fib(sc);
2953 		return;
2954 	}
2955 
2956 	bcopy(&vmi_resp->BusInf, &businfo, sizeof(struct aac_getbusinf));
2957 	aac_release_sync_fib(sc);
2958 
2959 	found = 0;
2960 	for (i = 0; i < businfo.BusCount; i++) {
2961 		if (businfo.BusValid[i] != AAC_BUS_VALID)
2962 			continue;
2963 
2964 		caminf = (struct aac_sim *)malloc( sizeof(struct aac_sim),
2965 		    M_AACBUF, M_NOWAIT | M_ZERO);
2966 		if (caminf == NULL)
2967 			continue;
2968 
2969 		child = device_add_child(sc->aac_dev, "aacp", -1);
2970 		if (child == NULL) {
2971 			device_printf(sc->aac_dev, "device_add_child failed\n");
2972 			continue;
2973 		}
2974 
2975 		caminf->TargetsPerBus = businfo.TargetsPerBus;
2976 		caminf->BusNumber = i;
2977 		caminf->InitiatorBusId = businfo.InitiatorBusId[i];
2978 		caminf->aac_sc = sc;
2979 		caminf->sim_dev = child;
2980 
2981 		device_set_ivars(child, caminf);
2982 		device_set_desc(child, "SCSI Passthrough Bus");
2983 		TAILQ_INSERT_TAIL(&sc->aac_sim_tqh, caminf, sim_link);
2984 
2985 		found = 1;
2986 	}
2987 
2988 	if (found)
2989 		bus_generic_attach(sc->aac_dev);
2990 
2991 	return;
2992 }
2993