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