aac.c revision 117363
1/*-
2 * Copyright (c) 2000 Michael Smith
3 * Copyright (c) 2001 Scott Long
4 * Copyright (c) 2000 BSDi
5 * Copyright (c) 2001 Adaptec, Inc.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	$FreeBSD: head/sys/dev/aac/aac.c 117363 2003-07-09 21:16:23Z scottl $
30 */
31
32/*
33 * Driver for the Adaptec 'FSA' family of PCI/SCSI RAID adapters.
34 */
35
36#include "opt_aac.h"
37
38/* #include <stddef.h> */
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/malloc.h>
42#include <sys/kernel.h>
43#include <sys/kthread.h>
44#include <sys/sysctl.h>
45#include <sys/poll.h>
46#include <sys/ioccom.h>
47
48#include <sys/bus.h>
49#include <sys/conf.h>
50#include <sys/signalvar.h>
51#include <sys/time.h>
52#include <sys/eventhandler.h>
53
54#include <machine/bus_memio.h>
55#include <machine/bus.h>
56#include <machine/resource.h>
57
58#include <dev/aac/aacreg.h>
59#include <dev/aac/aac_ioctl.h>
60#include <dev/aac/aacvar.h>
61#include <dev/aac/aac_tables.h>
62
63static void	aac_startup(void *arg);
64static void	aac_add_container(struct aac_softc *sc,
65				  struct aac_mntinforesp *mir, int f);
66static void	aac_get_bus_info(struct aac_softc *sc);
67
68/* Command Processing */
69static void	aac_timeout(struct aac_softc *sc);
70static int	aac_map_command(struct aac_command *cm);
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, int timeout);
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
182#define AAC_CDEV_MAJOR	150
183
184static struct cdevsw aac_cdevsw = {
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	.d_maj =	AAC_CDEV_MAJOR,
191};
192
193MALLOC_DEFINE(M_AACBUF, "aacbuf", "Buffers for the AAC driver");
194
195/* sysctl node */
196SYSCTL_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 */
205int
206aac_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
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, 0);
319	mi = (struct aac_mntinfo *)&fib->data[0];
320
321	/* loop over possible containers */
322	do {
323		/* request information on this container */
324		bzero(mi, sizeof(struct aac_mntinfo));
325		mi->Command = VM_NameServe;
326		mi->MntType = FT_FILESYS;
327		mi->MntCount = i;
328		if (aac_sync_fib(sc, ContainerCommand, 0, fib,
329				 sizeof(struct aac_mntinfo))) {
330			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		AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
388		TAILQ_INSERT_TAIL(&sc->aac_container_tqh, co, co_link);
389		AAC_LOCK_RELEASE(&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, AAC_SYNC_LOCK_FORCE);
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
559	return(0);
560}
561
562/*
563 * Bring the controller to a quiescent state, ready for system suspend.
564 */
565int
566aac_suspend(device_t dev)
567{
568	struct aac_softc *sc;
569
570	debug_called(1);
571
572	sc = device_get_softc(dev);
573
574	sc->aac_state |= AAC_STATE_SUSPEND;
575
576	AAC_MASK_INTERRUPTS(sc);
577	return(0);
578}
579
580/*
581 * Bring the controller back to a state ready for operation.
582 */
583int
584aac_resume(device_t dev)
585{
586	struct aac_softc *sc;
587
588	debug_called(1);
589
590	sc = device_get_softc(dev);
591
592	sc->aac_state &= ~AAC_STATE_SUSPEND;
593	AAC_UNMASK_INTERRUPTS(sc);
594	return(0);
595}
596
597/*
598 * Take an interrupt.
599 */
600void
601aac_intr(void *arg)
602{
603	struct aac_softc *sc;
604	u_int32_t *resp_queue;
605	u_int16_t reason;
606
607	debug_called(2);
608
609	sc = (struct aac_softc *)arg;
610
611	/*
612	 * Optimize the common case of adapter response interrupts.
613	 * We must read from the card prior to processing the responses
614	 * to ensure the clear is flushed prior to accessing the queues.
615	 * Reading the queues from local memory might save us a PCI read.
616	 */
617	resp_queue = sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE];
618	if (resp_queue[AAC_PRODUCER_INDEX] != resp_queue[AAC_CONSUMER_INDEX])
619		reason = AAC_DB_RESPONSE_READY;
620	else
621		reason = AAC_GET_ISTATUS(sc);
622	AAC_CLEAR_ISTATUS(sc, reason);
623	(void)AAC_GET_ISTATUS(sc);
624
625	/* It's not ok to return here because of races with the previous step */
626	if (reason & AAC_DB_RESPONSE_READY)
627		/* handle completion processing */
628		taskqueue_enqueue(taskqueue_swi, &sc->aac_task_complete);
629
630	/* controller wants to talk to the log */
631	if (reason & AAC_DB_PRINTF) {
632		if (sc->aifflags & AAC_AIFFLAGS_RUNNING) {
633			sc->aifflags |= AAC_AIFFLAGS_PRINTF;
634		} else
635			aac_print_printf(sc);
636	}
637
638	/* controller has a message for us? */
639	if (reason & AAC_DB_COMMAND_READY) {
640		if (sc->aifflags & AAC_AIFFLAGS_RUNNING) {
641			sc->aifflags |= AAC_AIFFLAGS_AIF;
642		} else {
643			/*
644			 * XXX If the kthread is dead and we're at this point,
645			 * there are bigger problems than just figuring out
646			 * what to do with an AIF.
647			 */
648		}
649
650	}
651
652	if ((sc->aifflags & AAC_AIFFLAGS_PENDING) != 0)
653		/* XXX Should this be done with cv_signal? */
654		wakeup(sc->aifthread);
655}
656
657/*
658 * Command Processing
659 */
660
661/*
662 * Start as much queued I/O as possible on the controller
663 */
664void
665aac_startio(struct aac_softc *sc)
666{
667	struct aac_command *cm;
668
669	debug_called(2);
670
671	if (sc->flags & AAC_QUEUE_FRZN)
672		return;
673
674	for (;;) {
675		/*
676		 * Try to get a command that's been put off for lack of
677		 * resources
678		 */
679		cm = aac_dequeue_ready(sc);
680
681		/*
682		 * Try to build a command off the bio queue (ignore error
683		 * return)
684		 */
685		if (cm == NULL)
686			aac_bio_command(sc, &cm);
687
688		/* nothing to do? */
689		if (cm == NULL)
690			break;
691
692		/* try to give the command to the controller */
693		if (aac_map_command(cm) == EBUSY) {
694			/* put it on the ready queue for later */
695			aac_requeue_ready(cm);
696			break;
697		}
698	}
699}
700
701/*
702 * Deliver a command to the controller; allocate controller resources at the
703 * last moment when possible.
704 */
705static int
706aac_map_command(struct aac_command *cm)
707{
708	struct aac_softc *sc;
709	int error;
710
711	debug_called(2);
712
713	sc = cm->cm_sc;
714	error = 0;
715
716	/* don't map more than once */
717	if (cm->cm_flags & AAC_CMD_MAPPED)
718		return (0);
719
720	if (cm->cm_datalen != 0) {
721		error = bus_dmamap_load(sc->aac_buffer_dmat, cm->cm_datamap,
722					cm->cm_data, cm->cm_datalen,
723					aac_map_command_sg, cm, 0);
724		if (error == EINPROGRESS) {
725			debug(1, "freezing queue\n");
726			sc->flags |= AAC_QUEUE_FRZN;
727			error = 0;
728		}
729	}
730	return (error);
731}
732
733/*
734 * Handle notification of one or more FIBs coming from the controller.
735 */
736static void
737aac_command_thread(struct aac_softc *sc)
738{
739	struct aac_fib *fib;
740	u_int32_t fib_size;
741	int size;
742
743	debug_called(2);
744
745	sc->aifflags |= AAC_AIFFLAGS_RUNNING;
746
747	while (!(sc->aifflags & AAC_AIFFLAGS_EXIT)) {
748		if ((sc->aifflags & AAC_AIFFLAGS_PENDING) == 0)
749			tsleep(sc->aifthread, PRIBIO, "aifthd",
750			       AAC_PERIODIC_INTERVAL * hz);
751
752		if ((sc->aifflags & AAC_AIFFLAGS_PENDING) == 0)
753			aac_timeout(sc);
754
755		/* Check the hardware printf message buffer */
756		if ((sc->aifflags & AAC_AIFFLAGS_PRINTF) != 0) {
757			sc->aifflags &= ~AAC_AIFFLAGS_PRINTF;
758			aac_print_printf(sc);
759		}
760
761		/* See if any FIBs need to be allocated */
762		if ((sc->aifflags & AAC_AIFFLAGS_ALLOCFIBS) != 0) {
763			AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
764			aac_alloc_commands(sc);
765			sc->aifflags &= ~AAC_AIFFLAGS_ALLOCFIBS;
766			AAC_LOCK_RELEASE(&sc->aac_io_lock);
767		}
768
769		/* While we're here, check to see if any commands are stuck */
770		while (sc->aifflags & AAC_AIFFLAGS_AIF) {
771			if (aac_dequeue_fib(sc, AAC_HOST_NORM_CMD_QUEUE,
772					    &fib_size, &fib)) {
773				sc->aifflags &= ~AAC_AIFFLAGS_AIF;
774				break;	/* nothing to do */
775			}
776
777			AAC_PRINT_FIB(sc, fib);
778
779			switch (fib->Header.Command) {
780			case AifRequest:
781				aac_handle_aif(sc, fib);
782				break;
783			default:
784				device_printf(sc->aac_dev, "unknown command "
785					      "from controller\n");
786				break;
787			}
788
789			if ((fib->Header.XferState == 0) ||
790			    (fib->Header.StructType != AAC_FIBTYPE_TFIB))
791				break;
792
793			/* Return the AIF to the controller. */
794			if (fib->Header.XferState & AAC_FIBSTATE_FROMADAP) {
795				fib->Header.XferState |= AAC_FIBSTATE_DONEHOST;
796				*(AAC_FSAStatus*)fib->data = ST_OK;
797
798				/* XXX Compute the Size field? */
799				size = fib->Header.Size;
800				if (size > sizeof(struct aac_fib)) {
801					size = sizeof(struct aac_fib);
802					fib->Header.Size = size;
803				}
804				/*
805				 * Since we did not generate this command, it
806				 * cannot go through the normal
807				 * enqueue->startio chain.
808				 */
809				aac_enqueue_response(sc,
810						     AAC_ADAP_NORM_RESP_QUEUE,
811						     fib);
812			}
813		}
814	}
815	sc->aifflags &= ~AAC_AIFFLAGS_RUNNING;
816	wakeup(sc->aac_dev);
817
818	mtx_lock(&Giant);
819	kthread_exit(0);
820}
821
822/*
823 * Process completed commands.
824 */
825static void
826aac_complete(void *context, int pending)
827{
828	struct aac_softc *sc;
829	struct aac_command *cm;
830	struct aac_fib *fib;
831	u_int32_t fib_size;
832
833	debug_called(2);
834
835	sc = (struct aac_softc *)context;
836
837	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
838
839	/* pull completed commands off the queue */
840	for (;;) {
841		/* look for completed FIBs on our queue */
842		if (aac_dequeue_fib(sc, AAC_HOST_NORM_RESP_QUEUE, &fib_size,
843				    &fib))
844			break;	/* nothing to do */
845
846		/* get the command, unmap and queue for later processing */
847		cm = sc->aac_commands + fib->Header.SenderData;
848		if (cm == NULL) {
849			AAC_PRINT_FIB(sc, fib);
850			break;
851		}
852
853		aac_remove_busy(cm);
854		aac_unmap_command(cm);		/* XXX defer? */
855		cm->cm_flags |= AAC_CMD_COMPLETED;
856
857		/* is there a completion handler? */
858		if (cm->cm_complete != NULL) {
859			cm->cm_complete(cm);
860		} else {
861			/* assume that someone is sleeping on this command */
862			wakeup(cm);
863		}
864	}
865
866	/* see if we can start some more I/O */
867	sc->flags &= ~AAC_QUEUE_FRZN;
868	aac_startio(sc);
869
870	AAC_LOCK_RELEASE(&sc->aac_io_lock);
871}
872
873/*
874 * Handle a bio submitted from a disk device.
875 */
876void
877aac_submit_bio(struct bio *bp)
878{
879	struct aac_disk *ad;
880	struct aac_softc *sc;
881
882	debug_called(2);
883
884	ad = (struct aac_disk *)bp->bio_disk->d_drv1;
885	sc = ad->ad_controller;
886
887	/* queue the BIO and try to get some work done */
888	aac_enqueue_bio(sc, bp);
889	aac_startio(sc);
890}
891
892/*
893 * Get a bio and build a command to go with it.
894 */
895static int
896aac_bio_command(struct aac_softc *sc, struct aac_command **cmp)
897{
898	struct aac_command *cm;
899	struct aac_fib *fib;
900	struct aac_disk *ad;
901	struct bio *bp;
902
903	debug_called(2);
904
905	/* get the resources we will need */
906	cm = NULL;
907	if ((bp = aac_dequeue_bio(sc)) == NULL)
908		goto fail;
909	if (aac_alloc_command(sc, &cm))	/* get a command */
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
992fail:
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 */
1003static void
1004aac_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 */
1047static int
1048aac_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 */
1074int
1075aac_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 */
1096void
1097aac_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.SenderFibAddress = (u_int32_t)cm->cm_fib;
1117	cm->cm_fib->Header.ReceiverFibAddress = (u_int32_t)cm->cm_fibphys;
1118	cm->cm_fib->Header.SenderData = 0;
1119
1120	aac_enqueue_free(cm);
1121}
1122
1123/*
1124 * Map helper for command/FIB allocation.
1125 */
1126static void
1127aac_map_command_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1128{
1129	uint32_t	*fibphys;
1130
1131	fibphys = (uint32_t *)arg;
1132
1133	debug_called(3);
1134
1135	*fibphys = segs[0].ds_addr;
1136}
1137
1138/*
1139 * Allocate and initialise commands/FIBs for this adapter.
1140 */
1141static int
1142aac_alloc_commands(struct aac_softc *sc)
1143{
1144	struct aac_command *cm;
1145	struct aac_fibmap *fm;
1146	uint32_t fibphys;
1147	int i, error;
1148
1149	debug_called(2);
1150
1151	if (sc->total_fibs + AAC_FIB_COUNT > sc->aac_max_fibs)
1152		return (ENOMEM);
1153
1154	fm = malloc(sizeof(struct aac_fibmap), M_AACBUF, M_NOWAIT|M_ZERO);
1155	if (fm == NULL)
1156		return (ENOMEM);
1157
1158	/* allocate the FIBs in DMAable memory and load them */
1159	if (bus_dmamem_alloc(sc->aac_fib_dmat, (void **)&fm->aac_fibs,
1160			     BUS_DMA_NOWAIT, &fm->aac_fibmap)) {
1161		device_printf(sc->aac_dev,
1162			      "Not enough contiguous memory available.\n");
1163		free(fm, M_AACBUF);
1164		return (ENOMEM);
1165	}
1166
1167	/* Ignore errors since this doesn't bounce */
1168	(void)bus_dmamap_load(sc->aac_fib_dmat, fm->aac_fibmap, fm->aac_fibs,
1169			      AAC_FIB_COUNT * sizeof(struct aac_fib),
1170			      aac_map_command_helper, &fibphys, 0);
1171
1172	/* initialise constant fields in the command structure */
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		return (0);
1194	}
1195
1196	bus_dmamap_unload(sc->aac_fib_dmat, fm->aac_fibmap);
1197	bus_dmamem_free(sc->aac_fib_dmat, fm->aac_fibs, fm->aac_fibmap);
1198	free(fm, M_AACBUF);
1199	return (ENOMEM);
1200}
1201
1202/*
1203 * Free FIBs owned by this adapter.
1204 */
1205static void
1206aac_free_commands(struct aac_softc *sc)
1207{
1208	struct aac_fibmap *fm;
1209	struct aac_command *cm;
1210	int i;
1211
1212	debug_called(1);
1213
1214	while ((fm = TAILQ_FIRST(&sc->aac_fibmap_tqh)) != NULL) {
1215
1216		TAILQ_REMOVE(&sc->aac_fibmap_tqh, fm, fm_link);
1217		/*
1218		 * We check against total_fibs to handle partially
1219		 * allocated blocks.
1220		 */
1221		for (i = 0; i < AAC_FIB_COUNT && sc->total_fibs--; i++) {
1222			cm = fm->aac_commands + i;
1223			bus_dmamap_destroy(sc->aac_buffer_dmat, cm->cm_datamap);
1224		}
1225		bus_dmamap_unload(sc->aac_fib_dmat, fm->aac_fibmap);
1226		bus_dmamem_free(sc->aac_fib_dmat, fm->aac_fibs, fm->aac_fibmap);
1227		free(fm, M_AACBUF);
1228	}
1229}
1230
1231/*
1232 * Command-mapping helper function - populate this command's s/g table.
1233 */
1234static void
1235aac_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1236{
1237	struct aac_softc *sc;
1238	struct aac_command *cm;
1239	struct aac_fib *fib;
1240	int i;
1241
1242	debug_called(3);
1243
1244	cm = (struct aac_command *)arg;
1245	sc = cm->cm_sc;
1246	fib = cm->cm_fib;
1247
1248	/* copy into the FIB */
1249	if (cm->cm_sgtable != NULL) {
1250		if ((cm->cm_sc->flags & AAC_FLAGS_SG_64BIT) == 0) {
1251			struct aac_sg_table *sg;
1252			sg = cm->cm_sgtable;
1253			sg->SgCount = nseg;
1254			for (i = 0; i < nseg; i++) {
1255				sg->SgEntry[i].SgAddress = segs[i].ds_addr;
1256				sg->SgEntry[i].SgByteCount = segs[i].ds_len;
1257			}
1258			/* update the FIB size for the s/g count */
1259			fib->Header.Size += nseg * sizeof(struct aac_sg_entry);
1260		} else {
1261			struct aac_sg_table64 *sg;
1262			sg = (struct aac_sg_table64 *)cm->cm_sgtable;
1263			sg->SgCount = nseg;
1264			for (i = 0; i < nseg; i++) {
1265				sg->SgEntry64[i].SgAddress = segs[i].ds_addr;
1266				sg->SgEntry64[i].SgByteCount = segs[i].ds_len;
1267			}
1268			/* update the FIB size for the s/g count */
1269			fib->Header.Size += nseg*sizeof(struct aac_sg_entry64);
1270		}
1271	}
1272
1273	/* Fix up the address values in the FIB.  Use the command array index
1274	 * instead of a pointer since these fields are only 32 bits.  Shift
1275	 * the SenderFibAddress over to make room for the fast response bit.
1276	 */
1277	cm->cm_fib->Header.SenderFibAddress = (cm->cm_index << 1);
1278	cm->cm_fib->Header.ReceiverFibAddress = cm->cm_fibphys;
1279
1280	/* save a pointer to the command for speedy reverse-lookup */
1281	cm->cm_fib->Header.SenderData = cm->cm_index;
1282
1283	if (cm->cm_flags & AAC_CMD_DATAIN)
1284		bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1285				BUS_DMASYNC_PREREAD);
1286	if (cm->cm_flags & AAC_CMD_DATAOUT)
1287		bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1288				BUS_DMASYNC_PREWRITE);
1289	cm->cm_flags |= AAC_CMD_MAPPED;
1290
1291	/* put the FIB on the outbound queue */
1292	if (aac_enqueue_fib(sc, cm->cm_queue, cm) == EBUSY)
1293		aac_requeue_ready(cm);
1294
1295	return;
1296}
1297
1298/*
1299 * Unmap a command from controller-visible space.
1300 */
1301static void
1302aac_unmap_command(struct aac_command *cm)
1303{
1304	struct aac_softc *sc;
1305
1306	debug_called(2);
1307
1308	sc = cm->cm_sc;
1309
1310	if (!(cm->cm_flags & AAC_CMD_MAPPED))
1311		return;
1312
1313	if (cm->cm_datalen != 0) {
1314		if (cm->cm_flags & AAC_CMD_DATAIN)
1315			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1316					BUS_DMASYNC_POSTREAD);
1317		if (cm->cm_flags & AAC_CMD_DATAOUT)
1318			bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1319					BUS_DMASYNC_POSTWRITE);
1320
1321		bus_dmamap_unload(sc->aac_buffer_dmat, cm->cm_datamap);
1322	}
1323	cm->cm_flags &= ~AAC_CMD_MAPPED;
1324}
1325
1326/*
1327 * Hardware Interface
1328 */
1329
1330/*
1331 * Initialise the adapter.
1332 */
1333static void
1334aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1335{
1336	struct aac_softc *sc;
1337
1338	debug_called(1);
1339
1340	sc = (struct aac_softc *)arg;
1341
1342	sc->aac_common_busaddr = segs[0].ds_addr;
1343}
1344
1345static int
1346aac_check_firmware(struct aac_softc *sc)
1347{
1348	u_int32_t major, minor, options;
1349
1350	debug_called(1);
1351
1352	/*
1353	 * Retrieve the firmware version numbers.  Dell PERC2/QC cards with
1354	 * firmware version 1.x are not compatible with this driver.
1355	 */
1356	if (sc->flags & AAC_FLAGS_PERC2QC) {
1357		if (aac_sync_command(sc, AAC_MONKER_GETKERNVER, 0, 0, 0, 0,
1358				     NULL)) {
1359			device_printf(sc->aac_dev,
1360				      "Error reading firmware version\n");
1361			return (EIO);
1362		}
1363
1364		/* These numbers are stored as ASCII! */
1365		major = (AAC_GET_MAILBOX(sc, 1) & 0xff) - 0x30;
1366		minor = (AAC_GET_MAILBOX(sc, 2) & 0xff) - 0x30;
1367		if (major == 1) {
1368			device_printf(sc->aac_dev,
1369			    "Firmware version %d.%d is not supported.\n",
1370			    major, minor);
1371			return (EINVAL);
1372		}
1373	}
1374
1375	/*
1376	 * Retrieve the capabilities/supported options word so we know what
1377	 * work-arounds to enable.
1378	 */
1379	if (aac_sync_command(sc, AAC_MONKER_GETINFO, 0, 0, 0, 0, NULL)) {
1380		device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
1381		return (EIO);
1382	}
1383	options = AAC_GET_MAILBOX(sc, 1);
1384	sc->supported_options = options;
1385
1386	if ((options & AAC_SUPPORTED_4GB_WINDOW) != 0 &&
1387	    (sc->flags & AAC_FLAGS_NO4GB) == 0)
1388		sc->flags |= AAC_FLAGS_4GB_WINDOW;
1389	if (options & AAC_SUPPORTED_NONDASD)
1390		sc->flags |= AAC_FLAGS_ENABLE_CAM;
1391	if ((options & AAC_SUPPORTED_SGMAP_HOST64) != 0
1392	     && (sizeof(bus_addr_t) > 4)) {
1393		device_printf(sc->aac_dev, "Enabling 64-bit address support\n");
1394		sc->flags |= AAC_FLAGS_SG_64BIT;
1395	}
1396
1397	/* Check for broken hardware that does a lower number of commands */
1398	if ((sc->flags & AAC_FLAGS_256FIBS) == 0)
1399		sc->aac_max_fibs = AAC_MAX_FIBS;
1400	else
1401		sc->aac_max_fibs = 256;
1402
1403	return (0);
1404}
1405
1406static int
1407aac_init(struct aac_softc *sc)
1408{
1409	struct aac_adapter_init	*ip;
1410	time_t then;
1411	u_int32_t code;
1412	u_int8_t *qaddr;
1413	int error;
1414
1415	debug_called(1);
1416
1417	/*
1418	 * First wait for the adapter to come ready.
1419	 */
1420	then = time_second;
1421	do {
1422		code = AAC_GET_FWSTATUS(sc);
1423		if (code & AAC_SELF_TEST_FAILED) {
1424			device_printf(sc->aac_dev, "FATAL: selftest failed\n");
1425			return(ENXIO);
1426		}
1427		if (code & AAC_KERNEL_PANIC) {
1428			device_printf(sc->aac_dev,
1429				      "FATAL: controller kernel panic\n");
1430			return(ENXIO);
1431		}
1432		if (time_second > (then + AAC_BOOT_TIMEOUT)) {
1433			device_printf(sc->aac_dev,
1434				      "FATAL: controller not coming ready, "
1435					   "status %x\n", code);
1436			return(ENXIO);
1437		}
1438	} while (!(code & AAC_UP_AND_RUNNING));
1439
1440	error = ENOMEM;
1441	/*
1442	 * Create DMA tag for mapping buffers into controller-addressable space.
1443	 */
1444	if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1445			       1, 0, 			/* algnmnt, boundary */
1446			       (sc->flags & AAC_FLAGS_SG_64BIT) ?
1447			       BUS_SPACE_MAXADDR :
1448			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1449			       BUS_SPACE_MAXADDR, 	/* highaddr */
1450			       NULL, NULL, 		/* filter, filterarg */
1451			       MAXBSIZE,		/* maxsize */
1452			       AAC_MAXSGENTRIES,	/* nsegments */
1453			       MAXBSIZE,		/* maxsegsize */
1454			       BUS_DMA_ALLOCNOW,	/* flags */
1455			       busdma_lock_mutex,	/* lockfunc */
1456			       &sc->aac_io_lock,	/* lockfuncarg */
1457			       &sc->aac_buffer_dmat)) {
1458		device_printf(sc->aac_dev, "can't allocate buffer DMA tag\n");
1459		goto out;
1460	}
1461
1462	/*
1463	 * Create DMA tag for mapping FIBs into controller-addressable space..
1464	 */
1465	if (bus_dma_tag_create(sc->aac_parent_dmat,	/* parent */
1466			       1, 0, 			/* algnmnt, boundary */
1467			       (sc->flags & AAC_FLAGS_4GB_WINDOW) ?
1468			       BUS_SPACE_MAXADDR_32BIT :
1469			       0x7fffffff,		/* lowaddr */
1470			       BUS_SPACE_MAXADDR, 	/* highaddr */
1471			       NULL, NULL, 		/* filter, filterarg */
1472			       AAC_FIB_COUNT *
1473			       sizeof(struct aac_fib),  /* maxsize */
1474			       1,			/* nsegments */
1475			       AAC_FIB_COUNT *
1476			       sizeof(struct aac_fib),	/* maxsegsize */
1477			       BUS_DMA_ALLOCNOW,	/* flags */
1478			       NULL, NULL,		/* No locking needed */
1479			       &sc->aac_fib_dmat)) {
1480		device_printf(sc->aac_dev, "can't allocate FIB DMA tag\n");;
1481		goto out;
1482	}
1483
1484	/*
1485	 * Create DMA tag for the common structure and allocate it.
1486	 */
1487	if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1488			       1, 0,			/* algnmnt, boundary */
1489			       (sc->flags & AAC_FLAGS_4GB_WINDOW) ?
1490			       BUS_SPACE_MAXADDR_32BIT :
1491			       0x7fffffff,		/* lowaddr */
1492			       BUS_SPACE_MAXADDR, 	/* highaddr */
1493			       NULL, NULL, 		/* filter, filterarg */
1494			       8192 + sizeof(struct aac_common), /* maxsize */
1495			       1,			/* nsegments */
1496			       BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1497			       BUS_DMA_ALLOCNOW,	/* flags */
1498			       NULL, NULL,		/* No locking needed */
1499			       &sc->aac_common_dmat)) {
1500		device_printf(sc->aac_dev,
1501			      "can't allocate common structure DMA tag\n");
1502		goto out;
1503	}
1504	if (bus_dmamem_alloc(sc->aac_common_dmat, (void **)&sc->aac_common,
1505			     BUS_DMA_NOWAIT, &sc->aac_common_dmamap)) {
1506		device_printf(sc->aac_dev, "can't allocate common structure\n");
1507		goto out;
1508	}
1509
1510	/*
1511	 * Work around a bug in the 2120 and 2200 that cannot DMA commands
1512	 * below address 8192 in physical memory.
1513	 * XXX If the padding is not needed, can it be put to use instead
1514	 * of ignored?
1515	 */
1516	(void)bus_dmamap_load(sc->aac_common_dmat, sc->aac_common_dmamap,
1517			sc->aac_common, 8192 + sizeof(*sc->aac_common),
1518			aac_common_map, sc, 0);
1519
1520	if (sc->aac_common_busaddr < 8192) {
1521		(uint8_t *)sc->aac_common += 8192;
1522		sc->aac_common_busaddr += 8192;
1523	}
1524	bzero(sc->aac_common, sizeof(*sc->aac_common));
1525
1526	/* Allocate some FIBs and associated command structs */
1527	TAILQ_INIT(&sc->aac_fibmap_tqh);
1528	sc->aac_commands = malloc(AAC_MAX_FIBS * sizeof(struct aac_command),
1529				  M_AACBUF, M_WAITOK|M_ZERO);
1530	while (sc->total_fibs < AAC_PREALLOCATE_FIBS) {
1531		if (aac_alloc_commands(sc) != 0)
1532			break;
1533	}
1534	if (sc->total_fibs == 0)
1535		goto out;
1536
1537	/*
1538	 * Fill in the init structure.  This tells the adapter about the
1539	 * physical location of various important shared data structures.
1540	 */
1541	ip = &sc->aac_common->ac_init;
1542	ip->InitStructRevision = AAC_INIT_STRUCT_REVISION;
1543	ip->MiniPortRevision = AAC_INIT_STRUCT_MINIPORT_REVISION;
1544
1545	ip->AdapterFibsPhysicalAddress = sc->aac_common_busaddr +
1546					 offsetof(struct aac_common, ac_fibs);
1547	ip->AdapterFibsVirtualAddress = 0;
1548	ip->AdapterFibsSize = AAC_ADAPTER_FIBS * sizeof(struct aac_fib);
1549	ip->AdapterFibAlign = sizeof(struct aac_fib);
1550
1551	ip->PrintfBufferAddress = sc->aac_common_busaddr +
1552				  offsetof(struct aac_common, ac_printf);
1553	ip->PrintfBufferSize = AAC_PRINTF_BUFSIZE;
1554
1555	/*
1556	 * The adapter assumes that pages are 4K in size, except on some
1557 	 * broken firmware versions that do the page->byte conversion twice,
1558	 * therefore 'assuming' that this value is in 16MB units (2^24).
1559	 * Round up since the granularity is so high.
1560	 */
1561	ip->HostPhysMemPages = ctob(physmem) / AAC_PAGE_SIZE;
1562	if (sc->flags & AAC_FLAGS_BROKEN_MEMMAP) {
1563		ip->HostPhysMemPages =
1564		    (ip->HostPhysMemPages + AAC_PAGE_SIZE) / AAC_PAGE_SIZE;
1565	}
1566	ip->HostElapsedSeconds = time_second;	/* reset later if invalid */
1567
1568	/*
1569	 * Initialise FIB queues.  Note that it appears that the layout of the
1570	 * indexes and the segmentation of the entries may be mandated by the
1571	 * adapter, which is only told about the base of the queue index fields.
1572	 *
1573	 * The initial values of the indices are assumed to inform the adapter
1574	 * of the sizes of the respective queues, and theoretically it could
1575	 * work out the entire layout of the queue structures from this.  We
1576	 * take the easy route and just lay this area out like everyone else
1577	 * does.
1578	 *
1579	 * The Linux driver uses a much more complex scheme whereby several
1580	 * header records are kept for each queue.  We use a couple of generic
1581	 * list manipulation functions which 'know' the size of each list by
1582	 * virtue of a table.
1583	 */
1584	qaddr = &sc->aac_common->ac_qbuf[0] + AAC_QUEUE_ALIGN;
1585	qaddr -= (u_int32_t)qaddr % AAC_QUEUE_ALIGN;
1586	sc->aac_queues = (struct aac_queue_table *)qaddr;
1587	ip->CommHeaderAddress = sc->aac_common_busaddr +
1588				((u_int32_t)sc->aac_queues -
1589				(u_int32_t)sc->aac_common);
1590
1591	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1592		AAC_HOST_NORM_CMD_ENTRIES;
1593	sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1594		AAC_HOST_NORM_CMD_ENTRIES;
1595	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1596		AAC_HOST_HIGH_CMD_ENTRIES;
1597	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1598		AAC_HOST_HIGH_CMD_ENTRIES;
1599	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1600		AAC_ADAP_NORM_CMD_ENTRIES;
1601	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1602		AAC_ADAP_NORM_CMD_ENTRIES;
1603	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1604		AAC_ADAP_HIGH_CMD_ENTRIES;
1605	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1606		AAC_ADAP_HIGH_CMD_ENTRIES;
1607	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1608		AAC_HOST_NORM_RESP_ENTRIES;
1609	sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1610		AAC_HOST_NORM_RESP_ENTRIES;
1611	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1612		AAC_HOST_HIGH_RESP_ENTRIES;
1613	sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1614		AAC_HOST_HIGH_RESP_ENTRIES;
1615	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1616		AAC_ADAP_NORM_RESP_ENTRIES;
1617	sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1618		AAC_ADAP_NORM_RESP_ENTRIES;
1619	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX]=
1620		AAC_ADAP_HIGH_RESP_ENTRIES;
1621	sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX]=
1622		AAC_ADAP_HIGH_RESP_ENTRIES;
1623	sc->aac_qentries[AAC_HOST_NORM_CMD_QUEUE] =
1624		&sc->aac_queues->qt_HostNormCmdQueue[0];
1625	sc->aac_qentries[AAC_HOST_HIGH_CMD_QUEUE] =
1626		&sc->aac_queues->qt_HostHighCmdQueue[0];
1627	sc->aac_qentries[AAC_ADAP_NORM_CMD_QUEUE] =
1628		&sc->aac_queues->qt_AdapNormCmdQueue[0];
1629	sc->aac_qentries[AAC_ADAP_HIGH_CMD_QUEUE] =
1630		&sc->aac_queues->qt_AdapHighCmdQueue[0];
1631	sc->aac_qentries[AAC_HOST_NORM_RESP_QUEUE] =
1632		&sc->aac_queues->qt_HostNormRespQueue[0];
1633	sc->aac_qentries[AAC_HOST_HIGH_RESP_QUEUE] =
1634		&sc->aac_queues->qt_HostHighRespQueue[0];
1635	sc->aac_qentries[AAC_ADAP_NORM_RESP_QUEUE] =
1636		&sc->aac_queues->qt_AdapNormRespQueue[0];
1637	sc->aac_qentries[AAC_ADAP_HIGH_RESP_QUEUE] =
1638		&sc->aac_queues->qt_AdapHighRespQueue[0];
1639
1640	/*
1641	 * Do controller-type-specific initialisation
1642	 */
1643	switch (sc->aac_hwif) {
1644	case AAC_HWIF_I960RX:
1645		AAC_SETREG4(sc, AAC_RX_ODBR, ~0);
1646		break;
1647	}
1648
1649	/*
1650	 * Give the init structure to the controller.
1651	 */
1652	if (aac_sync_command(sc, AAC_MONKER_INITSTRUCT,
1653			     sc->aac_common_busaddr +
1654			     offsetof(struct aac_common, ac_init), 0, 0, 0,
1655			     NULL)) {
1656		device_printf(sc->aac_dev,
1657			      "error establishing init structure\n");
1658		error = EIO;
1659		goto out;
1660	}
1661
1662	error = 0;
1663out:
1664	return(error);
1665}
1666
1667/*
1668 * Send a synchronous command to the controller and wait for a result.
1669 */
1670static int
1671aac_sync_command(struct aac_softc *sc, u_int32_t command,
1672		 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3,
1673		 u_int32_t *sp)
1674{
1675	time_t then;
1676	u_int32_t status;
1677
1678	debug_called(3);
1679
1680	/* populate the mailbox */
1681	AAC_SET_MAILBOX(sc, command, arg0, arg1, arg2, arg3);
1682
1683	/* ensure the sync command doorbell flag is cleared */
1684	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1685
1686	/* then set it to signal the adapter */
1687	AAC_QNOTIFY(sc, AAC_DB_SYNC_COMMAND);
1688
1689	/* spin waiting for the command to complete */
1690	then = time_second;
1691	do {
1692		if (time_second > (then + AAC_IMMEDIATE_TIMEOUT)) {
1693			debug(1, "timed out");
1694			return(EIO);
1695		}
1696	} while (!(AAC_GET_ISTATUS(sc) & AAC_DB_SYNC_COMMAND));
1697
1698	/* clear the completion flag */
1699	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1700
1701	/* get the command status */
1702	status = AAC_GET_MAILBOX(sc, 0);
1703	if (sp != NULL)
1704		*sp = status;
1705	return(0);
1706}
1707
1708/*
1709 * Grab the sync fib area.
1710 */
1711int
1712aac_alloc_sync_fib(struct aac_softc *sc, struct aac_fib **fib, int flags)
1713{
1714
1715	/*
1716	 * If the force flag is set, the system is shutting down, or in
1717	 * trouble.  Ignore the mutex.
1718	 */
1719	if (!(flags & AAC_SYNC_LOCK_FORCE))
1720		AAC_LOCK_ACQUIRE(&sc->aac_sync_lock);
1721
1722	*fib = &sc->aac_common->ac_sync_fib;
1723
1724	return (1);
1725}
1726
1727/*
1728 * Release the sync fib area.
1729 */
1730void
1731aac_release_sync_fib(struct aac_softc *sc)
1732{
1733
1734	AAC_LOCK_RELEASE(&sc->aac_sync_lock);
1735}
1736
1737/*
1738 * Send a synchronous FIB to the controller and wait for a result.
1739 */
1740int
1741aac_sync_fib(struct aac_softc *sc, u_int32_t command, u_int32_t xferstate,
1742		 struct aac_fib *fib, u_int16_t datasize)
1743{
1744	debug_called(3);
1745
1746	if (datasize > AAC_FIB_DATASIZE)
1747		return(EINVAL);
1748
1749	/*
1750	 * Set up the sync FIB
1751	 */
1752	fib->Header.XferState = AAC_FIBSTATE_HOSTOWNED |
1753				AAC_FIBSTATE_INITIALISED |
1754				AAC_FIBSTATE_EMPTY;
1755	fib->Header.XferState |= xferstate;
1756	fib->Header.Command = command;
1757	fib->Header.StructType = AAC_FIBTYPE_TFIB;
1758	fib->Header.Size = sizeof(struct aac_fib) + datasize;
1759	fib->Header.SenderSize = sizeof(struct aac_fib);
1760	fib->Header.SenderFibAddress = (u_int32_t)fib;
1761	fib->Header.ReceiverFibAddress = sc->aac_common_busaddr +
1762					 offsetof(struct aac_common,
1763						  ac_sync_fib);
1764
1765	/*
1766	 * Give the FIB to the controller, wait for a response.
1767	 */
1768	if (aac_sync_command(sc, AAC_MONKER_SYNCFIB,
1769			     fib->Header.ReceiverFibAddress, 0, 0, 0, NULL)) {
1770		debug(2, "IO error");
1771		return(EIO);
1772	}
1773
1774	return (0);
1775}
1776
1777/*
1778 * Adapter-space FIB queue manipulation
1779 *
1780 * Note that the queue implementation here is a little funky; neither the PI or
1781 * CI will ever be zero.  This behaviour is a controller feature.
1782 */
1783static struct {
1784	int		size;
1785	int		notify;
1786} aac_qinfo[] = {
1787	{AAC_HOST_NORM_CMD_ENTRIES, AAC_DB_COMMAND_NOT_FULL},
1788	{AAC_HOST_HIGH_CMD_ENTRIES, 0},
1789	{AAC_ADAP_NORM_CMD_ENTRIES, AAC_DB_COMMAND_READY},
1790	{AAC_ADAP_HIGH_CMD_ENTRIES, 0},
1791	{AAC_HOST_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_NOT_FULL},
1792	{AAC_HOST_HIGH_RESP_ENTRIES, 0},
1793	{AAC_ADAP_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_READY},
1794	{AAC_ADAP_HIGH_RESP_ENTRIES, 0}
1795};
1796
1797/*
1798 * Atomically insert an entry into the nominated queue, returns 0 on success or
1799 * EBUSY if the queue is full.
1800 *
1801 * Note: it would be more efficient to defer notifying the controller in
1802 *	 the case where we may be inserting several entries in rapid succession,
1803 *	 but implementing this usefully may be difficult (it would involve a
1804 *	 separate queue/notify interface).
1805 */
1806static int
1807aac_enqueue_fib(struct aac_softc *sc, int queue, struct aac_command *cm)
1808{
1809	u_int32_t pi, ci;
1810	int error;
1811	u_int32_t fib_size;
1812	u_int32_t fib_addr;
1813
1814	debug_called(3);
1815
1816	fib_size = cm->cm_fib->Header.Size;
1817	fib_addr = cm->cm_fib->Header.ReceiverFibAddress;
1818
1819	/* get the producer/consumer indices */
1820	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1821	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1822
1823	/* wrap the queue? */
1824	if (pi >= aac_qinfo[queue].size)
1825		pi = 0;
1826
1827	/* check for queue full */
1828	if ((pi + 1) == ci) {
1829		error = EBUSY;
1830		goto out;
1831	}
1832
1833	/* populate queue entry */
1834	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1835	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1836
1837	/* update producer index */
1838	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1839
1840	/*
1841	 * To avoid a race with its completion interrupt, place this command on
1842	 * the busy queue prior to advertising it to the controller.
1843	 */
1844	aac_enqueue_busy(cm);
1845
1846	/* notify the adapter if we know how */
1847	if (aac_qinfo[queue].notify != 0)
1848		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1849
1850	error = 0;
1851
1852out:
1853	return(error);
1854}
1855
1856/*
1857 * Atomically remove one entry from the nominated queue, returns 0 on
1858 * success or ENOENT if the queue is empty.
1859 */
1860static int
1861aac_dequeue_fib(struct aac_softc *sc, int queue, u_int32_t *fib_size,
1862		struct aac_fib **fib_addr)
1863{
1864	u_int32_t pi, ci;
1865	u_int32_t fib_index;
1866	int error;
1867	int notify;
1868
1869	debug_called(3);
1870
1871	/* get the producer/consumer indices */
1872	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1873	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1874
1875	/* check for queue empty */
1876	if (ci == pi) {
1877		error = ENOENT;
1878		goto out;
1879	}
1880
1881	notify = 0;
1882	if (ci == pi + 1)
1883		notify++;
1884
1885	/* wrap the queue? */
1886	if (ci >= aac_qinfo[queue].size)
1887		ci = 0;
1888
1889	/* fetch the entry */
1890	*fib_size = (sc->aac_qentries[queue] + ci)->aq_fib_size;
1891
1892	switch (queue) {
1893	case AAC_HOST_NORM_CMD_QUEUE:
1894	case AAC_HOST_HIGH_CMD_QUEUE:
1895		/*
1896		 * The aq_fib_addr is only 32 bits wide so it can't be counted
1897		 * on to hold an address.  For AIF's, the adapter assumes
1898		 * that it's giving us an address into the array of AIF fibs.
1899		 * Therefore, we have to convert it to an index.
1900		 */
1901		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr /
1902			sizeof(struct aac_fib);
1903		*fib_addr = &sc->aac_common->ac_fibs[fib_index];
1904		break;
1905
1906	case AAC_HOST_NORM_RESP_QUEUE:
1907	case AAC_HOST_HIGH_RESP_QUEUE:
1908	{
1909		struct aac_command *cm;
1910
1911		/*
1912		 * As above, an index is used instead of an actual address.
1913		 * Gotta shift the index to account for the fast response
1914		 * bit.  No other correction is needed since this value was
1915		 * originally provided by the driver via the SenderFibAddress
1916		 * field.
1917		 */
1918		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr;
1919		cm = sc->aac_commands + (fib_index >> 1);
1920		*fib_addr = cm->cm_fib;
1921
1922		/*
1923		 * Is this a fast response? If it is, update the fib fields in
1924		 * local memory since the whole fib isn't DMA'd back up.
1925		 */
1926		if (fib_index & 0x01) {
1927			(*fib_addr)->Header.XferState |= AAC_FIBSTATE_DONEADAP;
1928			*((u_int32_t*)((*fib_addr)->data)) = AAC_ERROR_NORMAL;
1929		}
1930		break;
1931	}
1932	default:
1933		panic("Invalid queue in aac_dequeue_fib()");
1934		break;
1935	}
1936
1937	/* update consumer index */
1938	sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX] = ci + 1;
1939
1940	/* if we have made the queue un-full, notify the adapter */
1941	if (notify && (aac_qinfo[queue].notify != 0))
1942		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1943	error = 0;
1944
1945out:
1946	return(error);
1947}
1948
1949/*
1950 * Put our response to an Adapter Initialed Fib on the response queue
1951 */
1952static int
1953aac_enqueue_response(struct aac_softc *sc, int queue, struct aac_fib *fib)
1954{
1955	u_int32_t pi, ci;
1956	int error;
1957	u_int32_t fib_size;
1958	u_int32_t fib_addr;
1959
1960	debug_called(1);
1961
1962	/* Tell the adapter where the FIB is */
1963	fib_size = fib->Header.Size;
1964	fib_addr = fib->Header.SenderFibAddress;
1965	fib->Header.ReceiverFibAddress = fib_addr;
1966
1967	/* get the producer/consumer indices */
1968	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1969	ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1970
1971	/* wrap the queue? */
1972	if (pi >= aac_qinfo[queue].size)
1973		pi = 0;
1974
1975	/* check for queue full */
1976	if ((pi + 1) == ci) {
1977		error = EBUSY;
1978		goto out;
1979	}
1980
1981	/* populate queue entry */
1982	(sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1983	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1984
1985	/* update producer index */
1986	sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1987
1988	/* notify the adapter if we know how */
1989	if (aac_qinfo[queue].notify != 0)
1990		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1991
1992	error = 0;
1993
1994out:
1995	return(error);
1996}
1997
1998/*
1999 * Check for commands that have been outstanding for a suspiciously long time,
2000 * and complain about them.
2001 */
2002static void
2003aac_timeout(struct aac_softc *sc)
2004{
2005	struct aac_command *cm;
2006	time_t deadline;
2007
2008	/*
2009	 * Traverse the busy command list, bitch about late commands once
2010	 * only.
2011	 */
2012	deadline = time_second - AAC_CMD_TIMEOUT;
2013	TAILQ_FOREACH(cm, &sc->aac_busy, cm_link) {
2014		if ((cm->cm_timestamp  < deadline)
2015			/* && !(cm->cm_flags & AAC_CMD_TIMEDOUT) */) {
2016			cm->cm_flags |= AAC_CMD_TIMEDOUT;
2017			device_printf(sc->aac_dev,
2018				      "COMMAND %p TIMEOUT AFTER %d SECONDS\n",
2019				      cm, (int)(time_second-cm->cm_timestamp));
2020			AAC_PRINT_FIB(sc, cm->cm_fib);
2021		}
2022	}
2023
2024	return;
2025}
2026
2027/*
2028 * Interface Function Vectors
2029 */
2030
2031/*
2032 * Read the current firmware status word.
2033 */
2034static int
2035aac_sa_get_fwstatus(struct aac_softc *sc)
2036{
2037	debug_called(3);
2038
2039	return(AAC_GETREG4(sc, AAC_SA_FWSTATUS));
2040}
2041
2042static int
2043aac_rx_get_fwstatus(struct aac_softc *sc)
2044{
2045	debug_called(3);
2046
2047	return(AAC_GETREG4(sc, AAC_RX_FWSTATUS));
2048}
2049
2050static int
2051aac_fa_get_fwstatus(struct aac_softc *sc)
2052{
2053	int val;
2054
2055	debug_called(3);
2056
2057	val = AAC_GETREG4(sc, AAC_FA_FWSTATUS);
2058	return (val);
2059}
2060
2061/*
2062 * Notify the controller of a change in a given queue
2063 */
2064
2065static void
2066aac_sa_qnotify(struct aac_softc *sc, int qbit)
2067{
2068	debug_called(3);
2069
2070	AAC_SETREG2(sc, AAC_SA_DOORBELL1_SET, qbit);
2071}
2072
2073static void
2074aac_rx_qnotify(struct aac_softc *sc, int qbit)
2075{
2076	debug_called(3);
2077
2078	AAC_SETREG4(sc, AAC_RX_IDBR, qbit);
2079}
2080
2081static void
2082aac_fa_qnotify(struct aac_softc *sc, int qbit)
2083{
2084	debug_called(3);
2085
2086	AAC_SETREG2(sc, AAC_FA_DOORBELL1, qbit);
2087	AAC_FA_HACK(sc);
2088}
2089
2090/*
2091 * Get the interrupt reason bits
2092 */
2093static int
2094aac_sa_get_istatus(struct aac_softc *sc)
2095{
2096	debug_called(3);
2097
2098	return(AAC_GETREG2(sc, AAC_SA_DOORBELL0));
2099}
2100
2101static int
2102aac_rx_get_istatus(struct aac_softc *sc)
2103{
2104	debug_called(3);
2105
2106	return(AAC_GETREG4(sc, AAC_RX_ODBR));
2107}
2108
2109static int
2110aac_fa_get_istatus(struct aac_softc *sc)
2111{
2112	int val;
2113
2114	debug_called(3);
2115
2116	val = AAC_GETREG2(sc, AAC_FA_DOORBELL0);
2117	return (val);
2118}
2119
2120/*
2121 * Clear some interrupt reason bits
2122 */
2123static void
2124aac_sa_clear_istatus(struct aac_softc *sc, int mask)
2125{
2126	debug_called(3);
2127
2128	AAC_SETREG2(sc, AAC_SA_DOORBELL0_CLEAR, mask);
2129}
2130
2131static void
2132aac_rx_clear_istatus(struct aac_softc *sc, int mask)
2133{
2134	debug_called(3);
2135
2136	AAC_SETREG4(sc, AAC_RX_ODBR, mask);
2137}
2138
2139static void
2140aac_fa_clear_istatus(struct aac_softc *sc, int mask)
2141{
2142	debug_called(3);
2143
2144	AAC_SETREG2(sc, AAC_FA_DOORBELL0_CLEAR, mask);
2145	AAC_FA_HACK(sc);
2146}
2147
2148/*
2149 * Populate the mailbox and set the command word
2150 */
2151static void
2152aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
2153		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2154{
2155	debug_called(4);
2156
2157	AAC_SETREG4(sc, AAC_SA_MAILBOX, command);
2158	AAC_SETREG4(sc, AAC_SA_MAILBOX + 4, arg0);
2159	AAC_SETREG4(sc, AAC_SA_MAILBOX + 8, arg1);
2160	AAC_SETREG4(sc, AAC_SA_MAILBOX + 12, arg2);
2161	AAC_SETREG4(sc, AAC_SA_MAILBOX + 16, arg3);
2162}
2163
2164static void
2165aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
2166		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2167{
2168	debug_called(4);
2169
2170	AAC_SETREG4(sc, AAC_RX_MAILBOX, command);
2171	AAC_SETREG4(sc, AAC_RX_MAILBOX + 4, arg0);
2172	AAC_SETREG4(sc, AAC_RX_MAILBOX + 8, arg1);
2173	AAC_SETREG4(sc, AAC_RX_MAILBOX + 12, arg2);
2174	AAC_SETREG4(sc, AAC_RX_MAILBOX + 16, arg3);
2175}
2176
2177static void
2178aac_fa_set_mailbox(struct aac_softc *sc, u_int32_t command,
2179		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
2180{
2181	debug_called(4);
2182
2183	AAC_SETREG4(sc, AAC_FA_MAILBOX, command);
2184	AAC_FA_HACK(sc);
2185	AAC_SETREG4(sc, AAC_FA_MAILBOX + 4, arg0);
2186	AAC_FA_HACK(sc);
2187	AAC_SETREG4(sc, AAC_FA_MAILBOX + 8, arg1);
2188	AAC_FA_HACK(sc);
2189	AAC_SETREG4(sc, AAC_FA_MAILBOX + 12, arg2);
2190	AAC_FA_HACK(sc);
2191	AAC_SETREG4(sc, AAC_FA_MAILBOX + 16, arg3);
2192	AAC_FA_HACK(sc);
2193}
2194
2195/*
2196 * Fetch the immediate command status word
2197 */
2198static int
2199aac_sa_get_mailbox(struct aac_softc *sc, int mb)
2200{
2201	debug_called(4);
2202
2203	return(AAC_GETREG4(sc, AAC_SA_MAILBOX + (mb * 4)));
2204}
2205
2206static int
2207aac_rx_get_mailbox(struct aac_softc *sc, int mb)
2208{
2209	debug_called(4);
2210
2211	return(AAC_GETREG4(sc, AAC_RX_MAILBOX + (mb * 4)));
2212}
2213
2214static int
2215aac_fa_get_mailbox(struct aac_softc *sc, int mb)
2216{
2217	int val;
2218
2219	debug_called(4);
2220
2221	val = AAC_GETREG4(sc, AAC_FA_MAILBOX + (mb * 4));
2222	return (val);
2223}
2224
2225/*
2226 * Set/clear interrupt masks
2227 */
2228static void
2229aac_sa_set_interrupts(struct aac_softc *sc, int enable)
2230{
2231	debug(2, "%sable interrupts", enable ? "en" : "dis");
2232
2233	if (enable) {
2234		AAC_SETREG2((sc), AAC_SA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2235	} else {
2236		AAC_SETREG2((sc), AAC_SA_MASK0_SET, ~0);
2237	}
2238}
2239
2240static void
2241aac_rx_set_interrupts(struct aac_softc *sc, int enable)
2242{
2243	debug(2, "%sable interrupts", enable ? "en" : "dis");
2244
2245	if (enable) {
2246		AAC_SETREG4(sc, AAC_RX_OIMR, ~AAC_DB_INTERRUPTS);
2247	} else {
2248		AAC_SETREG4(sc, AAC_RX_OIMR, ~0);
2249	}
2250}
2251
2252static void
2253aac_fa_set_interrupts(struct aac_softc *sc, int enable)
2254{
2255	debug(2, "%sable interrupts", enable ? "en" : "dis");
2256
2257	if (enable) {
2258		AAC_SETREG2((sc), AAC_FA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
2259		AAC_FA_HACK(sc);
2260	} else {
2261		AAC_SETREG2((sc), AAC_FA_MASK0, ~0);
2262		AAC_FA_HACK(sc);
2263	}
2264}
2265
2266/*
2267 * Debugging and Diagnostics
2268 */
2269
2270/*
2271 * Print some information about the controller.
2272 */
2273static void
2274aac_describe_controller(struct aac_softc *sc)
2275{
2276	struct aac_fib *fib;
2277	struct aac_adapter_info	*info;
2278
2279	debug_called(2);
2280
2281	aac_alloc_sync_fib(sc, &fib, 0);
2282
2283	fib->data[0] = 0;
2284	if (aac_sync_fib(sc, RequestAdapterInfo, 0, fib, 1)) {
2285		device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
2286		aac_release_sync_fib(sc);
2287		return;
2288	}
2289	info = (struct aac_adapter_info *)&fib->data[0];
2290
2291	device_printf(sc->aac_dev, "%s %dMHz, %dMB cache memory, %s\n",
2292		      aac_describe_code(aac_cpu_variant, info->CpuVariant),
2293		      info->ClockSpeed, info->BufferMem / (1024 * 1024),
2294		      aac_describe_code(aac_battery_platform,
2295					info->batteryPlatform));
2296
2297	/* save the kernel revision structure for later use */
2298	sc->aac_revision = info->KernelRevision;
2299	device_printf(sc->aac_dev, "Kernel %d.%d-%d, Build %d, S/N %6X\n",
2300		      info->KernelRevision.external.comp.major,
2301		      info->KernelRevision.external.comp.minor,
2302		      info->KernelRevision.external.comp.dash,
2303		      info->KernelRevision.buildNumber,
2304		      (u_int32_t)(info->SerialNumber & 0xffffff));
2305
2306	aac_release_sync_fib(sc);
2307
2308	if (1 || bootverbose) {
2309		device_printf(sc->aac_dev, "Supported Options=%b\n",
2310			      sc->supported_options,
2311			      "\20"
2312			      "\1SNAPSHOT"
2313			      "\2CLUSTERS"
2314			      "\3WCACHE"
2315			      "\4DATA64"
2316			      "\5HOSTTIME"
2317			      "\6RAID50"
2318			      "\7WINDOW4GB"
2319			      "\10SCSIUPGD"
2320			      "\11SOFTERR"
2321			      "\12NORECOND"
2322			      "\13SGMAP64"
2323			      "\14ALARM"
2324			      "\15NONDASD");
2325	}
2326}
2327
2328/*
2329 * Look up a text description of a numeric error code and return a pointer to
2330 * same.
2331 */
2332static char *
2333aac_describe_code(struct aac_code_lookup *table, u_int32_t code)
2334{
2335	int i;
2336
2337	for (i = 0; table[i].string != NULL; i++)
2338		if (table[i].code == code)
2339			return(table[i].string);
2340	return(table[i + 1].string);
2341}
2342
2343/*
2344 * Management Interface
2345 */
2346
2347static int
2348aac_open(dev_t dev, int flags, int fmt, d_thread_t *td)
2349{
2350	struct aac_softc *sc;
2351
2352	debug_called(2);
2353
2354	sc = dev->si_drv1;
2355
2356	/* Check to make sure the device isn't already open */
2357	if (sc->aac_state & AAC_STATE_OPEN) {
2358		return EBUSY;
2359	}
2360	sc->aac_state |= AAC_STATE_OPEN;
2361
2362	return 0;
2363}
2364
2365static int
2366aac_close(dev_t dev, int flags, int fmt, d_thread_t *td)
2367{
2368	struct aac_softc *sc;
2369
2370	debug_called(2);
2371
2372	sc = dev->si_drv1;
2373
2374	/* Mark this unit as no longer open  */
2375	sc->aac_state &= ~AAC_STATE_OPEN;
2376
2377	return 0;
2378}
2379
2380static int
2381aac_ioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, d_thread_t *td)
2382{
2383	union aac_statrequest *as;
2384	struct aac_softc *sc;
2385	int error = 0;
2386	int i;
2387
2388	debug_called(2);
2389
2390	as = (union aac_statrequest *)arg;
2391	sc = dev->si_drv1;
2392
2393	switch (cmd) {
2394	case AACIO_STATS:
2395		switch (as->as_item) {
2396		case AACQ_FREE:
2397		case AACQ_BIO:
2398		case AACQ_READY:
2399		case AACQ_BUSY:
2400		case AACQ_COMPLETE:
2401			bcopy(&sc->aac_qstat[as->as_item], &as->as_qstat,
2402			      sizeof(struct aac_qstat));
2403			break;
2404		default:
2405			error = ENOENT;
2406			break;
2407		}
2408	break;
2409
2410	case FSACTL_SENDFIB:
2411		arg = *(caddr_t*)arg;
2412	case FSACTL_LNX_SENDFIB:
2413		debug(1, "FSACTL_SENDFIB");
2414		error = aac_ioctl_sendfib(sc, arg);
2415		break;
2416	case FSACTL_AIF_THREAD:
2417	case FSACTL_LNX_AIF_THREAD:
2418		debug(1, "FSACTL_AIF_THREAD");
2419		error = EINVAL;
2420		break;
2421	case FSACTL_OPEN_GET_ADAPTER_FIB:
2422		arg = *(caddr_t*)arg;
2423	case FSACTL_LNX_OPEN_GET_ADAPTER_FIB:
2424		debug(1, "FSACTL_OPEN_GET_ADAPTER_FIB");
2425		/*
2426		 * Pass the caller out an AdapterFibContext.
2427		 *
2428		 * Note that because we only support one opener, we
2429		 * basically ignore this.  Set the caller's context to a magic
2430		 * number just in case.
2431		 *
2432		 * The Linux code hands the driver a pointer into kernel space,
2433		 * and then trusts it when the caller hands it back.  Aiee!
2434		 * Here, we give it the proc pointer of the per-adapter aif
2435		 * thread. It's only used as a sanity check in other calls.
2436		 */
2437		i = (int)sc->aifthread;
2438		error = copyout(&i, arg, sizeof(i));
2439		break;
2440	case FSACTL_GET_NEXT_ADAPTER_FIB:
2441		arg = *(caddr_t*)arg;
2442	case FSACTL_LNX_GET_NEXT_ADAPTER_FIB:
2443		debug(1, "FSACTL_GET_NEXT_ADAPTER_FIB");
2444		error = aac_getnext_aif(sc, arg);
2445		break;
2446	case FSACTL_CLOSE_GET_ADAPTER_FIB:
2447	case FSACTL_LNX_CLOSE_GET_ADAPTER_FIB:
2448		debug(1, "FSACTL_CLOSE_GET_ADAPTER_FIB");
2449		/* don't do anything here */
2450		break;
2451	case FSACTL_MINIPORT_REV_CHECK:
2452		arg = *(caddr_t*)arg;
2453	case FSACTL_LNX_MINIPORT_REV_CHECK:
2454		debug(1, "FSACTL_MINIPORT_REV_CHECK");
2455		error = aac_rev_check(sc, arg);
2456		break;
2457	case FSACTL_QUERY_DISK:
2458		arg = *(caddr_t*)arg;
2459	case FSACTL_LNX_QUERY_DISK:
2460		debug(1, "FSACTL_QUERY_DISK");
2461		error = aac_query_disk(sc, arg);
2462			break;
2463	case FSACTL_DELETE_DISK:
2464	case FSACTL_LNX_DELETE_DISK:
2465		/*
2466		 * We don't trust the underland to tell us when to delete a
2467		 * container, rather we rely on an AIF coming from the
2468		 * controller
2469		 */
2470		error = 0;
2471		break;
2472	default:
2473		debug(1, "unsupported cmd 0x%lx\n", cmd);
2474		error = EINVAL;
2475		break;
2476	}
2477	return(error);
2478}
2479
2480static int
2481aac_poll(dev_t dev, int poll_events, d_thread_t *td)
2482{
2483	struct aac_softc *sc;
2484	int revents;
2485
2486	sc = dev->si_drv1;
2487	revents = 0;
2488
2489	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2490	if ((poll_events & (POLLRDNORM | POLLIN)) != 0) {
2491		if (sc->aac_aifq_tail != sc->aac_aifq_head)
2492			revents |= poll_events & (POLLIN | POLLRDNORM);
2493	}
2494	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2495
2496	if (revents == 0) {
2497		if (poll_events & (POLLIN | POLLRDNORM))
2498			selrecord(td, &sc->rcv_select);
2499	}
2500
2501	return (revents);
2502}
2503
2504/*
2505 * Send a FIB supplied from userspace
2506 */
2507static int
2508aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib)
2509{
2510	struct aac_command *cm;
2511	int size, error;
2512
2513	debug_called(2);
2514
2515	cm = NULL;
2516
2517	/*
2518	 * Get a command
2519	 */
2520	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
2521	if (aac_alloc_command(sc, &cm)) {
2522		error = EBUSY;
2523		goto out;
2524	}
2525
2526	/*
2527	 * Fetch the FIB header, then re-copy to get data as well.
2528	 */
2529	if ((error = copyin(ufib, cm->cm_fib,
2530			    sizeof(struct aac_fib_header))) != 0)
2531		goto out;
2532	size = cm->cm_fib->Header.Size + sizeof(struct aac_fib_header);
2533	if (size > sizeof(struct aac_fib)) {
2534		device_printf(sc->aac_dev, "incoming FIB oversized (%d > %d)\n",
2535			      size, sizeof(struct aac_fib));
2536		size = sizeof(struct aac_fib);
2537	}
2538	if ((error = copyin(ufib, cm->cm_fib, size)) != 0)
2539		goto out;
2540	cm->cm_fib->Header.Size = size;
2541	cm->cm_timestamp = time_second;
2542
2543	/*
2544	 * Pass the FIB to the controller, wait for it to complete.
2545	 */
2546	if ((error = aac_wait_command(cm, 30)) != 0) {	/* XXX user timeout? */
2547		device_printf(sc->aac_dev,
2548			      "aac_wait_command return %d\n", error);
2549		goto out;
2550	}
2551
2552	/*
2553	 * Copy the FIB and data back out to the caller.
2554	 */
2555	size = cm->cm_fib->Header.Size;
2556	if (size > sizeof(struct aac_fib)) {
2557		device_printf(sc->aac_dev, "outbound FIB oversized (%d > %d)\n",
2558			      size, sizeof(struct aac_fib));
2559		size = sizeof(struct aac_fib);
2560	}
2561	error = copyout(cm->cm_fib, ufib, size);
2562
2563out:
2564	if (cm != NULL) {
2565		aac_release_command(cm);
2566	}
2567
2568	AAC_LOCK_RELEASE(&sc->aac_io_lock);
2569	return(error);
2570}
2571
2572/*
2573 * Handle an AIF sent to us by the controller; queue it for later reference.
2574 * If the queue fills up, then drop the older entries.
2575 */
2576static void
2577aac_handle_aif(struct aac_softc *sc, struct aac_fib *fib)
2578{
2579	struct aac_aif_command *aif;
2580	struct aac_container *co, *co_next;
2581	struct aac_mntinfo *mi;
2582	struct aac_mntinforesp *mir = NULL;
2583	u_int16_t rsize;
2584	int next, found;
2585	int count = 0, added = 0, i = 0;
2586
2587	debug_called(2);
2588
2589	aif = (struct aac_aif_command*)&fib->data[0];
2590	aac_print_aif(sc, aif);
2591
2592	/* Is it an event that we should care about? */
2593	switch (aif->command) {
2594	case AifCmdEventNotify:
2595		switch (aif->data.EN.type) {
2596		case AifEnAddContainer:
2597		case AifEnDeleteContainer:
2598			/*
2599			 * A container was added or deleted, but the message
2600			 * doesn't tell us anything else!  Re-enumerate the
2601			 * containers and sort things out.
2602			 */
2603			aac_alloc_sync_fib(sc, &fib, 0);
2604			mi = (struct aac_mntinfo *)&fib->data[0];
2605			do {
2606				/*
2607				 * Ask the controller for its containers one at
2608				 * a time.
2609				 * XXX What if the controller's list changes
2610				 * midway through this enumaration?
2611				 * XXX This should be done async.
2612				 */
2613				bzero(mi, sizeof(struct aac_mntinfo));
2614				mi->Command = VM_NameServe;
2615				mi->MntType = FT_FILESYS;
2616				mi->MntCount = i;
2617				rsize = sizeof(mir);
2618				if (aac_sync_fib(sc, ContainerCommand, 0, fib,
2619						 sizeof(struct aac_mntinfo))) {
2620					printf("Error probing container %d\n",
2621					      i);
2622					continue;
2623				}
2624				mir = (struct aac_mntinforesp *)&fib->data[0];
2625				/* XXX Need to check if count changed */
2626				count = mir->MntRespCount;
2627				/*
2628				 * Check the container against our list.
2629				 * co->co_found was already set to 0 in a
2630				 * previous run.
2631				 */
2632				if ((mir->Status == ST_OK) &&
2633				    (mir->MntTable[0].VolType != CT_NONE)) {
2634					found = 0;
2635					TAILQ_FOREACH(co,
2636						      &sc->aac_container_tqh,
2637						      co_link) {
2638						if (co->co_mntobj.ObjectId ==
2639						    mir->MntTable[0].ObjectId) {
2640							co->co_found = 1;
2641							found = 1;
2642							break;
2643						}
2644					}
2645					/*
2646					 * If the container matched, continue
2647					 * in the list.
2648					 */
2649					if (found) {
2650						i++;
2651						continue;
2652					}
2653
2654					/*
2655					 * This is a new container.  Do all the
2656					 * appropriate things to set it up.
2657					 */
2658					aac_add_container(sc, mir, 1);
2659					added = 1;
2660				}
2661				i++;
2662			} while ((i < count) && (i < AAC_MAX_CONTAINERS));
2663			aac_release_sync_fib(sc);
2664
2665			/*
2666			 * Go through our list of containers and see which ones
2667			 * were not marked 'found'.  Since the controller didn't
2668			 * list them they must have been deleted.  Do the
2669			 * appropriate steps to destroy the device.  Also reset
2670			 * the co->co_found field.
2671			 */
2672			co = TAILQ_FIRST(&sc->aac_container_tqh);
2673			while (co != NULL) {
2674				if (co->co_found == 0) {
2675					device_delete_child(sc->aac_dev,
2676							    co->co_disk);
2677					co_next = TAILQ_NEXT(co, co_link);
2678					AAC_LOCK_ACQUIRE(&sc->
2679							aac_container_lock);
2680					TAILQ_REMOVE(&sc->aac_container_tqh, co,
2681						     co_link);
2682					AAC_LOCK_RELEASE(&sc->
2683							 aac_container_lock);
2684					FREE(co, M_AACBUF);
2685					co = co_next;
2686				} else {
2687					co->co_found = 0;
2688					co = TAILQ_NEXT(co, co_link);
2689				}
2690			}
2691
2692			/* Attach the newly created containers */
2693			if (added)
2694				bus_generic_attach(sc->aac_dev);
2695
2696			break;
2697
2698		default:
2699			break;
2700		}
2701
2702	default:
2703		break;
2704	}
2705
2706	/* Copy the AIF data to the AIF queue for ioctl retrieval */
2707	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2708	next = (sc->aac_aifq_head + 1) % AAC_AIFQ_LENGTH;
2709	if (next != sc->aac_aifq_tail) {
2710		bcopy(aif, &sc->aac_aifq[next], sizeof(struct aac_aif_command));
2711		sc->aac_aifq_head = next;
2712
2713		/* On the off chance that someone is sleeping for an aif... */
2714		if (sc->aac_state & AAC_STATE_AIF_SLEEPER)
2715			wakeup(sc->aac_aifq);
2716		/* Wakeup any poll()ers */
2717		selwakeup(&sc->rcv_select);
2718	}
2719	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2720
2721	return;
2722}
2723
2724/*
2725 * Return the Revision of the driver to userspace and check to see if the
2726 * userspace app is possibly compatible.  This is extremely bogus since
2727 * our driver doesn't follow Adaptec's versioning system.  Cheat by just
2728 * returning what the card reported.
2729 */
2730static int
2731aac_rev_check(struct aac_softc *sc, caddr_t udata)
2732{
2733	struct aac_rev_check rev_check;
2734	struct aac_rev_check_resp rev_check_resp;
2735	int error = 0;
2736
2737	debug_called(2);
2738
2739	/*
2740	 * Copyin the revision struct from userspace
2741	 */
2742	if ((error = copyin(udata, (caddr_t)&rev_check,
2743			sizeof(struct aac_rev_check))) != 0) {
2744		return error;
2745	}
2746
2747	debug(2, "Userland revision= %d\n",
2748	      rev_check.callingRevision.buildNumber);
2749
2750	/*
2751	 * Doctor up the response struct.
2752	 */
2753	rev_check_resp.possiblyCompatible = 1;
2754	rev_check_resp.adapterSWRevision.external.ul =
2755	    sc->aac_revision.external.ul;
2756	rev_check_resp.adapterSWRevision.buildNumber =
2757	    sc->aac_revision.buildNumber;
2758
2759	return(copyout((caddr_t)&rev_check_resp, udata,
2760			sizeof(struct aac_rev_check_resp)));
2761}
2762
2763/*
2764 * Pass the caller the next AIF in their queue
2765 */
2766static int
2767aac_getnext_aif(struct aac_softc *sc, caddr_t arg)
2768{
2769	struct get_adapter_fib_ioctl agf;
2770	int error;
2771
2772	debug_called(2);
2773
2774	if ((error = copyin(arg, &agf, sizeof(agf))) == 0) {
2775
2776		/*
2777		 * Check the magic number that we gave the caller.
2778		 */
2779		if (agf.AdapterFibContext != (int)sc->aifthread) {
2780			error = EFAULT;
2781		} else {
2782			error = aac_return_aif(sc, agf.AifFib);
2783			if ((error == EAGAIN) && (agf.Wait)) {
2784				sc->aac_state |= AAC_STATE_AIF_SLEEPER;
2785				while (error == EAGAIN) {
2786					error = tsleep(sc->aac_aifq, PRIBIO |
2787						       PCATCH, "aacaif", 0);
2788					if (error == 0)
2789						error = aac_return_aif(sc,
2790						    agf.AifFib);
2791				}
2792				sc->aac_state &= ~AAC_STATE_AIF_SLEEPER;
2793			}
2794		}
2795	}
2796	return(error);
2797}
2798
2799/*
2800 * Hand the next AIF off the top of the queue out to userspace.
2801 */
2802static int
2803aac_return_aif(struct aac_softc *sc, caddr_t uptr)
2804{
2805	int error;
2806
2807	debug_called(2);
2808
2809	AAC_LOCK_ACQUIRE(&sc->aac_aifq_lock);
2810	if (sc->aac_aifq_tail == sc->aac_aifq_head) {
2811		error = EAGAIN;
2812	} else {
2813		error = copyout(&sc->aac_aifq[sc->aac_aifq_tail], uptr,
2814				sizeof(struct aac_aif_command));
2815		if (error)
2816			device_printf(sc->aac_dev,
2817			    "aac_return_aif: copyout returned %d\n", error);
2818		if (!error)
2819			sc->aac_aifq_tail = (sc->aac_aifq_tail + 1) %
2820					    AAC_AIFQ_LENGTH;
2821	}
2822	AAC_LOCK_RELEASE(&sc->aac_aifq_lock);
2823	return(error);
2824}
2825
2826/*
2827 * Give the userland some information about the container.  The AAC arch
2828 * expects the driver to be a SCSI passthrough type driver, so it expects
2829 * the containers to have b:t:l numbers.  Fake it.
2830 */
2831static int
2832aac_query_disk(struct aac_softc *sc, caddr_t uptr)
2833{
2834	struct aac_query_disk query_disk;
2835	struct aac_container *co;
2836	struct aac_disk	*disk;
2837	int error, id;
2838
2839	debug_called(2);
2840
2841	disk = NULL;
2842
2843	error = copyin(uptr, (caddr_t)&query_disk,
2844		       sizeof(struct aac_query_disk));
2845	if (error)
2846		return (error);
2847
2848	id = query_disk.ContainerNumber;
2849	if (id == -1)
2850		return (EINVAL);
2851
2852	AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
2853	TAILQ_FOREACH(co, &sc->aac_container_tqh, co_link) {
2854		if (co->co_mntobj.ObjectId == id)
2855			break;
2856		}
2857
2858	if (co == NULL) {
2859			query_disk.Valid = 0;
2860			query_disk.Locked = 0;
2861			query_disk.Deleted = 1;		/* XXX is this right? */
2862	} else {
2863		disk = device_get_softc(co->co_disk);
2864		query_disk.Valid = 1;
2865		query_disk.Locked =
2866		    (disk->ad_flags & AAC_DISK_OPEN) ? 1 : 0;
2867		query_disk.Deleted = 0;
2868		query_disk.Bus = device_get_unit(sc->aac_dev);
2869		query_disk.Target = disk->unit;
2870		query_disk.Lun = 0;
2871		query_disk.UnMapped = 0;
2872		sprintf(&query_disk.diskDeviceName[0], "%s%d",
2873		        disk->ad_disk.d_name, disk->ad_disk.d_unit);
2874	}
2875	AAC_LOCK_RELEASE(&sc->aac_container_lock);
2876
2877	error = copyout((caddr_t)&query_disk, uptr,
2878			sizeof(struct aac_query_disk));
2879
2880	return (error);
2881}
2882
2883static void
2884aac_get_bus_info(struct aac_softc *sc)
2885{
2886	struct aac_fib *fib;
2887	struct aac_ctcfg *c_cmd;
2888	struct aac_ctcfg_resp *c_resp;
2889	struct aac_vmioctl *vmi;
2890	struct aac_vmi_businf_resp *vmi_resp;
2891	struct aac_getbusinf businfo;
2892	struct aac_sim *caminf;
2893	device_t child;
2894	int i, found, error;
2895
2896	aac_alloc_sync_fib(sc, &fib, 0);
2897	c_cmd = (struct aac_ctcfg *)&fib->data[0];
2898	bzero(c_cmd, sizeof(struct aac_ctcfg));
2899
2900	c_cmd->Command = VM_ContainerConfig;
2901	c_cmd->cmd = CT_GET_SCSI_METHOD;
2902	c_cmd->param = 0;
2903
2904	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2905	    sizeof(struct aac_ctcfg));
2906	if (error) {
2907		device_printf(sc->aac_dev, "Error %d sending "
2908		    "VM_ContainerConfig command\n", error);
2909		aac_release_sync_fib(sc);
2910		return;
2911	}
2912
2913	c_resp = (struct aac_ctcfg_resp *)&fib->data[0];
2914	if (c_resp->Status != ST_OK) {
2915		device_printf(sc->aac_dev, "VM_ContainerConfig returned 0x%x\n",
2916		    c_resp->Status);
2917		aac_release_sync_fib(sc);
2918		return;
2919	}
2920
2921	sc->scsi_method_id = c_resp->param;
2922
2923	vmi = (struct aac_vmioctl *)&fib->data[0];
2924	bzero(vmi, sizeof(struct aac_vmioctl));
2925
2926	vmi->Command = VM_Ioctl;
2927	vmi->ObjType = FT_DRIVE;
2928	vmi->MethId = sc->scsi_method_id;
2929	vmi->ObjId = 0;
2930	vmi->IoctlCmd = GetBusInfo;
2931
2932	error = aac_sync_fib(sc, ContainerCommand, 0, fib,
2933	    sizeof(struct aac_vmioctl));
2934	if (error) {
2935		device_printf(sc->aac_dev, "Error %d sending VMIoctl command\n",
2936		    error);
2937		aac_release_sync_fib(sc);
2938		return;
2939	}
2940
2941	vmi_resp = (struct aac_vmi_businf_resp *)&fib->data[0];
2942	if (vmi_resp->Status != ST_OK) {
2943		device_printf(sc->aac_dev, "VM_Ioctl returned %d\n",
2944		    vmi_resp->Status);
2945		aac_release_sync_fib(sc);
2946		return;
2947	}
2948
2949	bcopy(&vmi_resp->BusInf, &businfo, sizeof(struct aac_getbusinf));
2950	aac_release_sync_fib(sc);
2951
2952	found = 0;
2953	for (i = 0; i < businfo.BusCount; i++) {
2954		if (businfo.BusValid[i] != AAC_BUS_VALID)
2955			continue;
2956
2957		caminf = (struct aac_sim *)malloc( sizeof(struct aac_sim),
2958		    M_AACBUF, M_NOWAIT | M_ZERO);
2959		if (caminf == NULL)
2960			continue;
2961
2962		child = device_add_child(sc->aac_dev, "aacp", -1);
2963		if (child == NULL) {
2964			device_printf(sc->aac_dev, "device_add_child failed\n");
2965			continue;
2966		}
2967
2968		caminf->TargetsPerBus = businfo.TargetsPerBus;
2969		caminf->BusNumber = i;
2970		caminf->InitiatorBusId = businfo.InitiatorBusId[i];
2971		caminf->aac_sc = sc;
2972		caminf->sim_dev = child;
2973
2974		device_set_ivars(child, caminf);
2975		device_set_desc(child, "SCSI Passthrough Bus");
2976		TAILQ_INSERT_TAIL(&sc->aac_sim_tqh, caminf, sim_link);
2977
2978		found = 1;
2979	}
2980
2981	if (found)
2982		bus_generic_attach(sc->aac_dev);
2983
2984	return;
2985}
2986