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