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