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