aac.c revision 81254
11541Srgrimes/*-
21541Srgrimes * Copyright (c) 2000 Michael Smith
31541Srgrimes * Copyright (c) 2001 Scott Long
41541Srgrimes * Copyright (c) 2000 BSDi
51541Srgrimes * Copyright (c) 2001 Adaptec, Inc.
61541Srgrimes * All rights reserved.
71541Srgrimes *
81541Srgrimes * Redistribution and use in source and binary forms, with or without
91541Srgrimes * modification, are permitted provided that the following conditions
101541Srgrimes * are met:
111541Srgrimes * 1. Redistributions of source code must retain the above copyright
121541Srgrimes *    notice, this list of conditions and the following disclaimer.
131541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141541Srgrimes *    notice, this list of conditions and the following disclaimer in the
151541Srgrimes *    documentation and/or other materials provided with the distribution.
161541Srgrimes *
171541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
181541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
211541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271541Srgrimes * SUCH DAMAGE.
281541Srgrimes *
291541Srgrimes *	$FreeBSD: head/sys/dev/aac/aac.c 81254 2001-08-07 16:48:28Z scottl $
301541Srgrimes */
311541Srgrimes
321541Srgrimes/*
331541Srgrimes * Driver for the Adaptec 'FSA' family of PCI/SCSI RAID adapters.
341541Srgrimes */
351541Srgrimes
361541Srgrimes#include "opt_aac.h"
371541Srgrimes
381541Srgrimes/* include <stddef.h> */
398747Sdg#include <sys/param.h>
401541Srgrimes#include <sys/systm.h>
411541Srgrimes#include <sys/malloc.h>
421541Srgrimes#include <sys/kernel.h>
431541Srgrimes#include <sys/sysctl.h>
441541Srgrimes
451541Srgrimes#include <dev/aac/aac_compat.h>
461541Srgrimes
471541Srgrimes#include <sys/bus.h>
481541Srgrimes#include <sys/conf.h>
491541Srgrimes#include <sys/devicestat.h>
501541Srgrimes#include <sys/disk.h>
511541Srgrimes#include <sys/file.h>
521541Srgrimes#include <sys/signalvar.h>
531541Srgrimes#include <sys/time.h>
541541Srgrimes
551541Srgrimes#include <machine/bus_memio.h>
561541Srgrimes#include <machine/bus.h>
571541Srgrimes#include <machine/resource.h>
581541Srgrimes
592729Sdfr#include <dev/aac/aacreg.h>
602729Sdfr#include <dev/aac/aac_ioctl.h>
612729Sdfr#include <dev/aac/aacvar.h>
622729Sdfr#include <dev/aac/aac_tables.h>
632729Sdfr
642729Sdfrdevclass_t	aac_devclass;
651541Srgrimes
661541Srgrimesstatic void	aac_startup(void *arg);
671541Srgrimes
681541Srgrimes/* Command Processing */
691541Srgrimesstatic void	aac_startio(struct aac_softc *sc);
701541Srgrimesstatic void	aac_timeout(struct aac_softc *sc);
711541Srgrimesstatic int	aac_start(struct aac_command *cm);
721541Srgrimesstatic void	aac_complete(void *context, int pending);
731541Srgrimesstatic int	aac_bio_command(struct aac_softc *sc, struct aac_command **cmp);
741541Srgrimesstatic void	aac_bio_complete(struct aac_command *cm);
751541Srgrimesstatic int	aac_wait_command(struct aac_command *cm, int timeout);
761541Srgrimesstatic void	aac_host_command(struct aac_softc *sc);
771541Srgrimesstatic void	aac_host_response(struct aac_softc *sc);
781541Srgrimes
791541Srgrimes/* Command Buffer Management */
801541Srgrimesstatic int	aac_alloc_command(struct aac_softc *sc,
811541Srgrimes				  struct aac_command **cmp);
821541Srgrimesstatic void	aac_release_command(struct aac_command *cm);
831541Srgrimesstatic void	aac_map_command_helper(void *arg, bus_dma_segment_t *segs,
845455Sdg				       int nseg, int error);
856577Sguidostatic int	aac_alloc_commands(struct aac_softc *sc);
865530Sdgstatic void	aac_free_commands(struct aac_softc *sc);
878747Sdgstatic void	aac_map_command(struct aac_command *cm);
885455Sdgstatic void	aac_unmap_command(struct aac_command *cm);
898747Sdg
908747Sdg/* Hardware Interface */
918747Sdgstatic void	aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg,
928747Sdg			       int error);
938747Sdgstatic int	aac_init(struct aac_softc *sc);
948747Sdgstatic int	aac_sync_command(struct aac_softc *sc, u_int32_t command,
958747Sdg				 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2,
968747Sdg				 u_int32_t arg3, u_int32_t *sp);
978747Sdgstatic int	aac_sync_fib(struct aac_softc *sc, u_int32_t command,
981541Srgrimes			     u_int32_t xferstate, void *data,
998747Sdg			     u_int16_t datasize, void *result,
1008747Sdg			     u_int16_t *resultsize);
1011541Srgrimesstatic int	aac_enqueue_fib(struct aac_softc *sc, int queue,
1021541Srgrimes				struct aac_command *cm);
1031541Srgrimesstatic int	aac_dequeue_fib(struct aac_softc *sc, int queue,
1041541Srgrimes				u_int32_t *fib_size, struct aac_fib **fib_addr);
1051541Srgrimes
1061541Srgrimes/* StrongARM interface */
1076492Sjoergstatic int	aac_sa_get_fwstatus(struct aac_softc *sc);
1081541Srgrimesstatic void	aac_sa_qnotify(struct aac_softc *sc, int qbit);
1096492Sjoergstatic int	aac_sa_get_istatus(struct aac_softc *sc);
1106492Sjoergstatic void	aac_sa_clear_istatus(struct aac_softc *sc, int mask);
1111541Srgrimesstatic void	aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
1126492Sjoerg				   u_int32_t arg0, u_int32_t arg1,
1136492Sjoerg				   u_int32_t arg2, u_int32_t arg3);
1141541Srgrimesstatic int	aac_sa_get_mailboxstatus(struct aac_softc *sc);
1156492Sjoergstatic void	aac_sa_set_interrupts(struct aac_softc *sc, int enable);
1166492Sjoerg
1171541Srgrimesstruct aac_interface aac_sa_interface = {
1186492Sjoerg    aac_sa_get_fwstatus,
1196492Sjoerg    aac_sa_qnotify,
1201541Srgrimes    aac_sa_get_istatus,
1216492Sjoerg    aac_sa_clear_istatus,
1221541Srgrimes    aac_sa_set_mailbox,
1231541Srgrimes    aac_sa_get_mailboxstatus,
1241541Srgrimes    aac_sa_set_interrupts
1251541Srgrimes};
1261541Srgrimes
1271541Srgrimes/* i960Rx interface */
1281541Srgrimesstatic int	aac_rx_get_fwstatus(struct aac_softc *sc);
1291541Srgrimesstatic void	aac_rx_qnotify(struct aac_softc *sc, int qbit);
1301541Srgrimesstatic int	aac_rx_get_istatus(struct aac_softc *sc);
1311541Srgrimesstatic void	aac_rx_clear_istatus(struct aac_softc *sc, int mask);
1321541Srgrimesstatic void	aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
1332729Sdfr				   u_int32_t arg0, u_int32_t arg1,
1342729Sdfr				   u_int32_t arg2, u_int32_t arg3);
1352729Sdfrstatic int	aac_rx_get_mailboxstatus(struct aac_softc *sc);
1362729Sdfrstatic void	aac_rx_set_interrupts(struct aac_softc *sc, int enable);
1372729Sdfr
1382729Sdfrstruct aac_interface aac_rx_interface = {
1392729Sdfr    aac_rx_get_fwstatus,
1402729Sdfr    aac_rx_qnotify,
1412729Sdfr    aac_rx_get_istatus,
1422729Sdfr    aac_rx_clear_istatus,
1432729Sdfr    aac_rx_set_mailbox,
1442729Sdfr    aac_rx_get_mailboxstatus,
1452729Sdfr    aac_rx_set_interrupts
1462729Sdfr};
1472729Sdfr
1482729Sdfr/* Debugging and Diagnostics */
1492729Sdfrstatic void	aac_describe_controller(struct aac_softc *sc);
1502729Sdfrstatic char	*aac_describe_code(struct aac_code_lookup *table,
1512729Sdfr				   u_int32_t code);
1522729Sdfr
1532729Sdfr/* Management Interface */
1542729Sdfrstatic d_open_t		aac_open;
1552729Sdfrstatic d_close_t	aac_close;
1562729Sdfrstatic d_ioctl_t	aac_ioctl;
1572729Sdfrstatic int		aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib);
1582729Sdfrstatic void		aac_handle_aif(struct aac_softc *sc,
1592729Sdfr				       struct aac_aif_command *aif);
1602729Sdfrstatic int		aac_rev_check(struct aac_softc *sc, caddr_t udata);
1612729Sdfrstatic int		aac_getnext_aif(struct aac_softc *sc, caddr_t arg);
1622729Sdfrstatic int		aac_return_aif(struct aac_softc *sc, caddr_t uptr);
1632729Sdfr
1642729Sdfr#define AAC_CDEV_MAJOR	150
1652729Sdfr
1662729Sdfrstatic struct cdevsw aac_cdevsw = {
1672729Sdfr    aac_open,		/* open */
1682729Sdfr    aac_close,		/* close */
1692729Sdfr    noread,		/* read */
1701541Srgrimes    nowrite,		/* write */
1711541Srgrimes    aac_ioctl,		/* ioctl */
1721541Srgrimes    nopoll,		/* poll */
1731541Srgrimes    nommap,		/* mmap */
1741541Srgrimes    nostrategy,		/* strategy */
1751541Srgrimes    "aac",		/* name */
1761541Srgrimes    AAC_CDEV_MAJOR,	/* major */
1771541Srgrimes    nodump,		/* dump */
1781541Srgrimes    nopsize,		/* psize */
1791541Srgrimes    0,			/* flags */
1801541Srgrimes};
1811541Srgrimes
1821541Srgrimes/* sysctl node */
1831541SrgrimesSYSCTL_NODE(_hw, OID_AUTO, aac, CTLFLAG_RD, 0, "AAC driver parameters");
1841541Srgrimes
1851541Srgrimes/******************************************************************************
1861541Srgrimes ******************************************************************************
1871541Srgrimes				Device Interface
1881541Srgrimes ******************************************************************************
1891541Srgrimes ******************************************************************************/
1901541Srgrimes
1911541Srgrimes/******************************************************************************
1921541Srgrimes * Initialise the controller and softc
1931541Srgrimes */
1941541Srgrimesint
1951541Srgrimesaac_attach(struct aac_softc *sc)
1961541Srgrimes{
1971541Srgrimes    int		error, unit;
1981541Srgrimes
1991541Srgrimes    debug_called(1);
2001541Srgrimes
2011541Srgrimes    /*
2021541Srgrimes     * Initialise per-controller queues.
2031541Srgrimes     */
2041541Srgrimes    aac_initq_free(sc);
2051541Srgrimes    aac_initq_ready(sc);
2061541Srgrimes    aac_initq_busy(sc);
2071541Srgrimes    aac_initq_complete(sc);
2081541Srgrimes    aac_initq_bio(sc);
209
210#if __FreeBSD_version >= 500005
211    /*
212     * Initialise command-completion task.
213     */
214    TASK_INIT(&sc->aac_task_complete, 0, aac_complete, sc);
215#endif
216
217    /* disable interrupts before we enable anything */
218    AAC_MASK_INTERRUPTS(sc);
219
220    /* mark controller as suspended until we get ourselves organised */
221    sc->aac_state |= AAC_STATE_SUSPEND;
222
223    /*
224     * Allocate command structures.
225     */
226    if ((error = aac_alloc_commands(sc)) != 0)
227	return(error);
228
229    /*
230     * Initialise the adapter.
231     */
232    if ((error = aac_init(sc)) != 0)
233	return(error);
234
235    /*
236     * Print a little information about the controller.
237     */
238    aac_describe_controller(sc);
239
240    /*
241     * Register to probe our containers later.
242     */
243    sc->aac_ich.ich_func = aac_startup;
244    sc->aac_ich.ich_arg = sc;
245    if (config_intrhook_establish(&sc->aac_ich) != 0) {
246        device_printf(sc->aac_dev, "can't establish configuration hook\n");
247        return(ENXIO);
248    }
249
250    /*
251     * Make the control device.
252     */
253    unit = device_get_unit(sc->aac_dev);
254    sc->aac_dev_t = make_dev(&aac_cdevsw, unit, UID_ROOT, GID_WHEEL, 0644,
255			     "aac%d", unit);
256    (void)make_dev_alias(sc->aac_dev_t, "afa%d", unit);
257    (void)make_dev_alias(sc->aac_dev_t, "hpn%d", unit);
258
259    sc->aac_dev_t->si_drv1 = sc;
260
261    return(0);
262}
263
264/******************************************************************************
265 * Probe for containers, create disks.
266 */
267static void
268aac_startup(void *arg)
269{
270    struct aac_softc		*sc = (struct aac_softc *)arg;
271    struct aac_mntinfo		mi;
272    struct aac_mntinforesponse	mir;
273    device_t			child;
274    u_int16_t			rsize;
275    int				i;
276
277    debug_called(1);
278
279    /* disconnect ourselves from the intrhook chain */
280    config_intrhook_disestablish(&sc->aac_ich);
281
282    /* loop over possible containers */
283    mi.Command = VM_NameServe;
284    mi.MntType = FT_FILESYS;
285    for (i = 0; i < AAC_MAX_CONTAINERS; i++) {
286	/* request information on this container */
287	mi.MntCount = i;
288	rsize = sizeof(mir);
289	if (aac_sync_fib(sc, ContainerCommand, 0, &mi,
290			 sizeof(struct aac_mntinfo), &mir, &rsize)) {
291	    debug(2, "error probing container %d", i);
292	    continue;
293	}
294	/* check response size */
295	if (rsize != sizeof(mir)) {
296	    debug(2, "container info response wrong size (%d should be %d)",
297		  rsize, sizeof(mir));
298	    continue;
299	}
300	/*
301	 * Check container volume type for validity.  Note that many of the
302	 * possible types may never show up.
303	 */
304	if ((mir.Status == ST_OK) && (mir.MntTable[0].VolType != CT_NONE)) {
305	    debug(1, "%d: id %x  name '%.16s'  size %u  type %d",
306		  i, mir.MntTable[0].ObjectId,
307		  mir.MntTable[0].FileSystemName, mir.MntTable[0].Capacity,
308		  mir.MntTable[0].VolType);
309
310	    if ((child = device_add_child(sc->aac_dev, NULL, -1)) == NULL) {
311		device_printf(sc->aac_dev, "device_add_child failed\n");
312	    } else {
313		device_set_ivars(child, &sc->aac_container[i]);
314	    }
315	    device_set_desc(child, aac_describe_code(aac_container_types,
316			    mir.MntTable[0].VolType));
317	    sc->aac_container[i].co_disk = child;
318	    sc->aac_container[i].co_mntobj = mir.MntTable[0];
319	}
320    }
321
322    /* poke the bus to actually attach the child devices */
323    if (bus_generic_attach(sc->aac_dev))
324	device_printf(sc->aac_dev, "bus_generic_attach failed\n");
325
326    /* mark the controller up */
327    sc->aac_state &= ~AAC_STATE_SUSPEND;
328
329    /* enable interrupts now */
330    AAC_UNMASK_INTERRUPTS(sc);
331
332    /* enable the timeout watchdog */
333    timeout((timeout_t*)aac_timeout, sc, AAC_PERIODIC_INTERVAL * hz);
334}
335
336/******************************************************************************
337 * Free all of the resources associated with (sc)
338 *
339 * Should not be called if the controller is active.
340 */
341void
342aac_free(struct aac_softc *sc)
343{
344    debug_called(1);
345
346    /* remove the control device */
347    if (sc->aac_dev_t != NULL)
348	destroy_dev(sc->aac_dev_t);
349
350    /* throw away any FIB buffers, discard the FIB DMA tag */
351    if (sc->aac_fibs != NULL)
352	aac_free_commands(sc);
353    if (sc->aac_fib_dmat)
354	bus_dma_tag_destroy(sc->aac_fib_dmat);
355
356    /* destroy the common area */
357    if (sc->aac_common) {
358	bus_dmamap_unload(sc->aac_common_dmat, sc->aac_common_dmamap);
359	bus_dmamem_free(sc->aac_common_dmat, sc->aac_common,
360			sc->aac_common_dmamap);
361    }
362    if (sc->aac_common_dmat)
363	bus_dma_tag_destroy(sc->aac_common_dmat);
364
365    /* disconnect the interrupt handler */
366    if (sc->aac_intr)
367	bus_teardown_intr(sc->aac_dev, sc->aac_irq, sc->aac_intr);
368    if (sc->aac_irq != NULL)
369	bus_release_resource(sc->aac_dev, SYS_RES_IRQ, sc->aac_irq_rid,
370			     sc->aac_irq);
371
372    /* destroy data-transfer DMA tag */
373    if (sc->aac_buffer_dmat)
374	bus_dma_tag_destroy(sc->aac_buffer_dmat);
375
376    /* destroy the parent DMA tag */
377    if (sc->aac_parent_dmat)
378	bus_dma_tag_destroy(sc->aac_parent_dmat);
379
380    /* release the register window mapping */
381    if (sc->aac_regs_resource != NULL)
382	bus_release_resource(sc->aac_dev, SYS_RES_MEMORY, sc->aac_regs_rid,
383			     sc->aac_regs_resource);
384}
385
386/******************************************************************************
387 * Disconnect from the controller completely, in preparation for unload.
388 */
389int
390aac_detach(device_t dev)
391{
392    struct aac_softc	*sc = device_get_softc(dev);
393    int			error;
394
395    debug_called(1);
396
397    if (sc->aac_state & AAC_STATE_OPEN)
398	return(EBUSY);
399
400    if ((error = aac_shutdown(dev)))
401	return(error);
402
403    aac_free(sc);
404
405    return(0);
406}
407
408/******************************************************************************
409 * Bring the controller down to a dormant state and detach all child devices.
410 *
411 * This function is called before detach or system shutdown.
412 *
413 * Note that we can assume that the bioq on the controller is empty, as we won't
414 * allow shutdown if any device is open.
415 */
416int
417aac_shutdown(device_t dev)
418{
419    struct aac_softc		*sc = device_get_softc(dev);
420    struct aac_close_command	cc;
421    int				s, i;
422
423    debug_called(1);
424
425    s = splbio();
426
427    sc->aac_state |= AAC_STATE_SUSPEND;
428
429    /*
430     * Send a Container shutdown followed by a HostShutdown FIB to the
431     * controller to convince it that we don't want to talk to it anymore.
432     * We've been closed and all I/O completed already
433     */
434    device_printf(sc->aac_dev, "shutting down controller...");
435
436    cc.Command = VM_CloseAll;
437    cc.ContainerId = 0xffffffff;
438    if (aac_sync_fib(sc, ContainerCommand, 0, &cc, sizeof(cc), NULL, NULL)) {
439	printf("FAILED.\n");
440    } else {
441	i = 0;
442	if (aac_sync_fib(sc, FsaHostShutdown, AAC_FIBSTATE_SHUTDOWN, &i,
443			 sizeof(i), NULL, NULL)) {
444	    printf("FAILED.\n");
445	} else {
446	    printf("done.\n");
447	}
448    }
449
450    AAC_MASK_INTERRUPTS(sc);
451
452    splx(s);
453    return(0);
454}
455
456/******************************************************************************
457 * Bring the controller to a quiescent state, ready for system suspend.
458 */
459int
460aac_suspend(device_t dev)
461{
462    struct aac_softc	*sc = device_get_softc(dev);
463    int			s;
464
465    debug_called(1);
466    s = splbio();
467
468    sc->aac_state |= AAC_STATE_SUSPEND;
469
470    AAC_MASK_INTERRUPTS(sc);
471    splx(s);
472    return(0);
473}
474
475/******************************************************************************
476 * Bring the controller back to a state ready for operation.
477 */
478int
479aac_resume(device_t dev)
480{
481    struct aac_softc	*sc = device_get_softc(dev);
482
483    debug_called(1);
484    sc->aac_state &= ~AAC_STATE_SUSPEND;
485    AAC_UNMASK_INTERRUPTS(sc);
486    return(0);
487}
488
489/******************************************************************************
490 * Take an interrupt.
491 */
492void
493aac_intr(void *arg)
494{
495    struct aac_softc	*sc = (struct aac_softc *)arg;
496    u_int16_t		reason;
497
498    debug_called(2);
499
500    reason = AAC_GET_ISTATUS(sc);
501
502    /* controller wants to talk to the log?  XXX should we defer this? */
503    if (reason & AAC_DB_PRINTF) {
504	if (sc->aac_common->ac_printf[0]) {
505	    device_printf(sc->aac_dev, "** %.*s", AAC_PRINTF_BUFSIZE,
506			  sc->aac_common->ac_printf);
507	    sc->aac_common->ac_printf[0] = 0;
508	}
509	AAC_CLEAR_ISTATUS(sc, AAC_DB_PRINTF);
510	AAC_QNOTIFY(sc, AAC_DB_PRINTF);
511    }
512
513    /* controller has a message for us? */
514    if (reason & AAC_DB_COMMAND_READY) {
515	AAC_CLEAR_ISTATUS(sc, AAC_DB_COMMAND_READY);
516	aac_host_command(sc);
517    }
518
519    /* controller has a response for us? */
520    if (reason & AAC_DB_RESPONSE_READY) {
521	AAC_CLEAR_ISTATUS(sc, AAC_DB_RESPONSE_READY);
522	aac_host_response(sc);
523    }
524
525    /*
526     * spurious interrupts that we don't use - reset the mask and clear the
527     * interrupts
528     */
529    if (reason & (AAC_DB_COMMAND_NOT_FULL | AAC_DB_RESPONSE_NOT_FULL)) {
530	AAC_UNMASK_INTERRUPTS(sc);
531	AAC_CLEAR_ISTATUS(sc, AAC_DB_COMMAND_NOT_FULL |
532			  AAC_DB_RESPONSE_NOT_FULL);
533    }
534};
535
536/******************************************************************************
537 ******************************************************************************
538				Command Processing
539 ******************************************************************************
540 ******************************************************************************/
541
542/******************************************************************************
543 * Start as much queued I/O as possible on the controller
544 */
545static void
546aac_startio(struct aac_softc *sc)
547{
548    struct aac_command	*cm;
549
550    debug_called(2);
551
552    for(;;) {
553	/* try to get a command that's been put off for lack of resources */
554	cm = aac_dequeue_ready(sc);
555
556	/* try to build a command off the bio queue (ignore error return) */
557	if (cm == NULL)
558	    aac_bio_command(sc, &cm);
559
560	/* nothing to do? */
561	if (cm == NULL)
562	    break;
563
564	/* try to give the command to the controller */
565	if (aac_start(cm) == EBUSY) {
566	    /* put it on the ready queue for later */
567	    aac_requeue_ready(cm);
568	    break;
569	}
570    }
571}
572
573/******************************************************************************
574 * Deliver a command to the controller; allocate controller resources at the
575 * last moment when possible.
576 */
577static int
578aac_start(struct aac_command *cm)
579{
580    struct aac_softc	*sc = cm->cm_sc;
581    int			error;
582
583    debug_called(2);
584
585    /* get the command mapped */
586    aac_map_command(cm);
587
588    /* fix up the address values in the FIB */
589    cm->cm_fib->Header.SenderFibAddress = (u_int32_t)cm->cm_fib;
590    cm->cm_fib->Header.ReceiverFibAddress = cm->cm_fibphys;
591
592    /* save a pointer to the command for speedy reverse-lookup */
593    cm->cm_fib->Header.SenderData = (u_int32_t)cm;	/* XXX 64-bit physical
594							 * address issue */
595
596    /* put the FIB on the outbound queue */
597    error = aac_enqueue_fib(sc, AAC_ADAP_NORM_CMD_QUEUE, cm);
598    return(error);
599}
600
601/******************************************************************************
602 * Handle notification of one or more FIBs coming from the controller.
603 */
604static void
605aac_host_command(struct aac_softc *sc)
606{
607    struct aac_fib	*fib;
608    u_int32_t		fib_size;
609
610    debug_called(1);
611
612    for (;;) {
613	if (aac_dequeue_fib(sc, AAC_HOST_NORM_CMD_QUEUE, &fib_size, &fib))
614	    break;	/* nothing to do */
615
616	switch(fib->Header.Command) {
617	case AifRequest:
618	    aac_handle_aif(sc, (struct aac_aif_command *)&fib->data[0]);
619	    break;
620	default:
621	    device_printf(sc->aac_dev, "unknown command from controller\n");
622	    AAC_PRINT_FIB(sc, fib);
623	    break;
624	}
625
626	/* XXX reply to FIBs requesting responses ?? */
627	/* XXX how do we return these FIBs to the controller? */
628    }
629}
630
631/******************************************************************************
632 * Handle notification of one or more FIBs completed by the controller
633 */
634static void
635aac_host_response(struct aac_softc *sc)
636{
637    struct aac_command	*cm;
638    struct aac_fib	*fib;
639    u_int32_t		fib_size;
640
641    debug_called(2);
642
643    for (;;) {
644	/* look for completed FIBs on our queue */
645	if (aac_dequeue_fib(sc, AAC_HOST_NORM_RESP_QUEUE, &fib_size, &fib))
646	    break;	/* nothing to do */
647
648	/* get the command, unmap and queue for later processing */
649	cm = (struct aac_command *)fib->Header.SenderData;
650	if (cm == NULL) {
651	    AAC_PRINT_FIB(sc, fib);
652	} else {
653	    aac_remove_busy(cm);
654	    aac_unmap_command(cm);		/* XXX defer? */
655	    aac_enqueue_complete(cm);
656	}
657    }
658
659    /* handle completion processing */
660#if __FreeBSD_version >= 500005
661    taskqueue_enqueue(taskqueue_swi, &sc->aac_task_complete);
662#else
663    aac_complete(sc, 0);
664#endif
665}
666
667/******************************************************************************
668 * Process completed commands.
669 */
670static void
671aac_complete(void *context, int pending)
672{
673    struct aac_softc	*sc = (struct aac_softc *)context;
674    struct aac_command	*cm;
675
676    debug_called(2);
677
678    /* pull completed commands off the queue */
679    for (;;) {
680	cm = aac_dequeue_complete(sc);
681	if (cm == NULL)
682	    break;
683	cm->cm_flags |= AAC_CMD_COMPLETED;
684
685	/* is there a completion handler? */
686	if (cm->cm_complete != NULL) {
687	    cm->cm_complete(cm);
688	} else {
689	    /* assume that someone is sleeping on this command */
690	    wakeup(cm);
691	}
692    }
693
694    /* see if we can start some more I/O */
695    aac_startio(sc);
696}
697
698/******************************************************************************
699 * Handle a bio submitted from a disk device.
700 */
701void
702aac_submit_bio(struct bio *bp)
703{
704    struct aac_disk	*ad = (struct aac_disk *)bp->bio_dev->si_drv1;
705    struct aac_softc	*sc = ad->ad_controller;
706
707    debug_called(2);
708
709    /* queue the BIO and try to get some work done */
710    aac_enqueue_bio(sc, bp);
711    aac_startio(sc);
712}
713
714/******************************************************************************
715 * Get a bio and build a command to go with it.
716 */
717static int
718aac_bio_command(struct aac_softc *sc, struct aac_command **cmp)
719{
720    struct aac_command		*cm;
721    struct aac_fib		*fib;
722    struct aac_blockread	*br;
723    struct aac_blockwrite	*bw;
724    struct aac_disk		*ad;
725    struct bio			*bp;
726
727    debug_called(2);
728
729    /* get the resources we will need */
730    cm = NULL;
731    if ((bp = aac_dequeue_bio(sc)) == NULL)
732	goto fail;
733    if (aac_alloc_command(sc, &cm))	/* get a command */
734	goto fail;
735
736    /* fill out the command */
737    cm->cm_data = (void *)bp->bio_data;
738    cm->cm_datalen = bp->bio_bcount;
739    cm->cm_complete = aac_bio_complete;
740    cm->cm_private = bp;
741    cm->cm_timestamp = time_second;
742
743    /* build the FIB */
744    fib = cm->cm_fib;
745    fib->Header.XferState =
746	AAC_FIBSTATE_HOSTOWNED   |
747	AAC_FIBSTATE_INITIALISED |
748	AAC_FIBSTATE_FROMHOST    |
749	AAC_FIBSTATE_REXPECTED   |
750	AAC_FIBSTATE_NORM;
751    fib->Header.Command = ContainerCommand;
752    fib->Header.Size = sizeof(struct aac_fib_header);
753
754    /* build the read/write request */
755    ad = (struct aac_disk *)bp->bio_dev->si_drv1;
756    if (BIO_IS_READ(bp)) {
757	br = (struct aac_blockread *)&fib->data[0];
758	br->Command = VM_CtBlockRead;
759	br->ContainerId = ad->ad_container->co_mntobj.ObjectId;
760	br->BlockNumber = bp->bio_pblkno;
761	br->ByteCount = bp->bio_bcount;
762	fib->Header.Size += sizeof(struct aac_blockread);
763	cm->cm_sgtable = &br->SgMap;
764	cm->cm_flags |= AAC_CMD_DATAIN;
765    } else {
766	bw = (struct aac_blockwrite *)&fib->data[0];
767	bw->Command = VM_CtBlockWrite;
768	bw->ContainerId = ad->ad_container->co_mntobj.ObjectId;
769	bw->BlockNumber = bp->bio_pblkno;
770	bw->ByteCount = bp->bio_bcount;
771	bw->Stable = CUNSTABLE;		/* XXX what's appropriate here? */
772	fib->Header.Size += sizeof(struct aac_blockwrite);
773	cm->cm_flags |= AAC_CMD_DATAOUT;
774	cm->cm_sgtable = &bw->SgMap;
775    }
776
777    *cmp = cm;
778    return(0);
779
780fail:
781    if (bp != NULL)
782	aac_enqueue_bio(sc, bp);
783    if (cm != NULL)
784	aac_release_command(cm);
785    return(ENOMEM);
786}
787
788/******************************************************************************
789 * Handle a bio-instigated command that has been completed.
790 */
791static void
792aac_bio_complete(struct aac_command *cm)
793{
794    struct aac_blockread_response	*brr;
795    struct aac_blockwrite_response	*bwr;
796    struct bio				*bp;
797    AAC_FSAStatus			status;
798
799    /* fetch relevant status and then release the command */
800    bp = (struct bio *)cm->cm_private;
801    if (BIO_IS_READ(bp)) {
802	brr = (struct aac_blockread_response *)&cm->cm_fib->data[0];
803	status = brr->Status;
804    } else {
805	bwr = (struct aac_blockwrite_response *)&cm->cm_fib->data[0];
806	status = bwr->Status;
807    }
808    aac_release_command(cm);
809
810    /* fix up the bio based on status */
811    if (status == ST_OK) {
812	bp->bio_resid = 0;
813    } else {
814	bp->bio_error = EIO;
815	bp->bio_flags |= BIO_ERROR;
816	/* pass an error string out to the disk layer */
817	bp->bio_driver1 = aac_describe_code(aac_command_status_table, status);
818    }
819    aac_biodone(bp);
820}
821
822/******************************************************************************
823 * Submit a command to the controller, return when it completes.
824 */
825static int
826aac_wait_command(struct aac_command *cm, int timeout)
827{
828    int s, error = 0;
829
830    debug_called(2);
831
832    /* Put the command on the ready queue and get things going */
833    aac_enqueue_ready(cm);
834    aac_startio(cm->cm_sc);
835    s = splbio();
836    while(!(cm->cm_flags & AAC_CMD_COMPLETED) && (error != EWOULDBLOCK)) {
837        error = tsleep(cm, PRIBIO, "aacwait", 0);
838    }
839    splx(s);
840    return(error);
841}
842
843/******************************************************************************
844 ******************************************************************************
845			Command Buffer Management
846 ******************************************************************************
847 ******************************************************************************/
848
849/******************************************************************************
850 * Allocate a command.
851 */
852static int
853aac_alloc_command(struct aac_softc *sc, struct aac_command **cmp)
854{
855    struct aac_command	*cm;
856
857    debug_called(3);
858
859    if ((cm = aac_dequeue_free(sc)) == NULL)
860	return(ENOMEM);
861
862    *cmp = cm;
863    return(0);
864}
865
866/******************************************************************************
867 * Release a command back to the freelist.
868 */
869static void
870aac_release_command(struct aac_command *cm)
871{
872    debug_called(3);
873
874    /* (re)initialise the command/FIB */
875    cm->cm_sgtable = NULL;
876    cm->cm_flags = 0;
877    cm->cm_complete = NULL;
878    cm->cm_private = NULL;
879    cm->cm_fib->Header.XferState = AAC_FIBSTATE_EMPTY;
880    cm->cm_fib->Header.StructType = AAC_FIBTYPE_TFIB;
881    cm->cm_fib->Header.Flags = 0;
882    cm->cm_fib->Header.SenderSize = sizeof(struct aac_fib);
883
884    /*
885     * These are duplicated in aac_start to cover the case where an
886     * intermediate stage may have destroyed them.  They're left
887     * initialised here for debugging purposes only.
888     */
889    cm->cm_fib->Header.SenderFibAddress = (u_int32_t)cm->cm_fib;
890    cm->cm_fib->Header.ReceiverFibAddress = cm->cm_fibphys;
891
892    aac_enqueue_free(cm);
893}
894
895/******************************************************************************
896 * Map helper for command/FIB allocation.
897 */
898static void
899aac_map_command_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
900{
901    struct aac_softc	*sc = (struct aac_softc *)arg;
902
903    debug_called(3);
904
905    sc->aac_fibphys = segs[0].ds_addr;
906}
907
908/******************************************************************************
909 * Allocate and initialise commands/FIBs for this adapter.
910 */
911static int
912aac_alloc_commands(struct aac_softc *sc)
913{
914    struct aac_command		*cm;
915    int				i;
916
917    debug_called(1);
918
919    /* allocate the FIBs in DMAable memory and load them */
920    if (bus_dmamem_alloc(sc->aac_fib_dmat, (void **)&sc->aac_fibs,
921			 BUS_DMA_NOWAIT, &sc->aac_fibmap)) {
922	return(ENOMEM);
923    }
924    bus_dmamap_load(sc->aac_fib_dmat, sc->aac_fibmap, sc->aac_fibs,
925		    AAC_FIB_COUNT * sizeof(struct aac_fib),
926		    aac_map_command_helper, sc, 0);
927
928    /* initialise constant fields in the command structure */
929    for (i = 0; i < AAC_FIB_COUNT; i++) {
930	cm = &sc->aac_command[i];
931	cm->cm_sc = sc;
932	cm->cm_fib = sc->aac_fibs + i;
933	cm->cm_fibphys = sc->aac_fibphys + (i * sizeof(struct aac_fib));
934
935	if (!bus_dmamap_create(sc->aac_buffer_dmat, 0, &cm->cm_datamap))
936	    aac_release_command(cm);
937    }
938    return(0);
939}
940
941/******************************************************************************
942 * Free FIBs owned by this adapter.
943 */
944static void
945aac_free_commands(struct aac_softc *sc)
946{
947    int			i;
948
949    debug_called(1);
950
951    for (i = 0; i < AAC_FIB_COUNT; i++)
952	bus_dmamap_destroy(sc->aac_buffer_dmat, sc->aac_command[i].cm_datamap);
953    bus_dmamap_unload(sc->aac_fib_dmat, sc->aac_fibmap);
954    bus_dmamem_free(sc->aac_fib_dmat, sc->aac_fibs, sc->aac_fibmap);
955}
956
957/******************************************************************************
958 * Command-mapping helper function - populate this command's s/g table.
959 */
960static void
961aac_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
962{
963    struct aac_command		*cm = (struct aac_command *)arg;
964    struct aac_fib		*fib = cm->cm_fib;
965    struct aac_sg_table		*sg;
966    int				i;
967
968    debug_called(3);
969
970    /* find the s/g table */
971    sg = cm->cm_sgtable;
972
973    /* copy into the FIB */
974    if (sg != NULL) {
975	sg->SgCount = nseg;
976	for (i = 0; i < nseg; i++) {
977	    sg->SgEntry[i].SgAddress = segs[i].ds_addr;
978	    sg->SgEntry[i].SgByteCount = segs[i].ds_len;
979	}
980	/* update the FIB size for the s/g count */
981	fib->Header.Size += nseg * sizeof(struct aac_sg_entry);
982    }
983
984}
985
986/******************************************************************************
987 * Map a command into controller-visible space.
988 */
989static void
990aac_map_command(struct aac_command *cm)
991{
992    struct aac_softc	*sc = cm->cm_sc;
993
994    debug_called(2);
995
996    /* don't map more than once */
997    if (cm->cm_flags & AAC_CMD_MAPPED)
998	return;
999
1000    if (cm->cm_datalen != 0) {
1001	bus_dmamap_load(sc->aac_buffer_dmat, cm->cm_datamap, cm->cm_data,
1002			cm->cm_datalen, aac_map_command_sg, cm, 0);
1003
1004	if (cm->cm_flags & AAC_CMD_DATAIN)
1005	    bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1006			    BUS_DMASYNC_PREREAD);
1007	if (cm->cm_flags & AAC_CMD_DATAOUT)
1008	    bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1009			    BUS_DMASYNC_PREWRITE);
1010    }
1011    cm->cm_flags |= AAC_CMD_MAPPED;
1012}
1013
1014/******************************************************************************
1015 * Unmap a command from controller-visible space.
1016 */
1017static void
1018aac_unmap_command(struct aac_command *cm)
1019{
1020    struct aac_softc	*sc = cm->cm_sc;
1021
1022    debug_called(2);
1023
1024    if (!(cm->cm_flags & AAC_CMD_MAPPED))
1025	return;
1026
1027    if (cm->cm_datalen != 0) {
1028	if (cm->cm_flags & AAC_CMD_DATAIN)
1029	    bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1030			    BUS_DMASYNC_POSTREAD);
1031	if (cm->cm_flags & AAC_CMD_DATAOUT)
1032	    bus_dmamap_sync(sc->aac_buffer_dmat, cm->cm_datamap,
1033			    BUS_DMASYNC_POSTWRITE);
1034
1035	bus_dmamap_unload(sc->aac_buffer_dmat, cm->cm_datamap);
1036    }
1037    cm->cm_flags &= ~AAC_CMD_MAPPED;
1038}
1039
1040/******************************************************************************
1041 ******************************************************************************
1042				Hardware Interface
1043 ******************************************************************************
1044 ******************************************************************************/
1045
1046/******************************************************************************
1047 * Initialise the adapter.
1048 */
1049static void
1050aac_common_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1051{
1052    struct aac_softc	*sc = (struct aac_softc *)arg;
1053
1054    debug_called(1);
1055
1056    sc->aac_common_busaddr = segs[0].ds_addr;
1057}
1058
1059static int
1060aac_init(struct aac_softc *sc)
1061{
1062    struct aac_adapter_init	*ip;
1063    time_t			then;
1064    u_int32_t			code;
1065    u_int8_t			*qaddr;
1066
1067    debug_called(1);
1068
1069    /*
1070     * First wait for the adapter to come ready.
1071     */
1072    then = time_second;
1073    do {
1074	code = AAC_GET_FWSTATUS(sc);
1075	if (code & AAC_SELF_TEST_FAILED) {
1076	    device_printf(sc->aac_dev, "FATAL: selftest failed\n");
1077	    return(ENXIO);
1078	}
1079	if (code & AAC_KERNEL_PANIC) {
1080	    device_printf(sc->aac_dev, "FATAL: controller kernel panic\n");
1081	    return(ENXIO);
1082	}
1083	if (time_second > (then + AAC_BOOT_TIMEOUT)) {
1084	    device_printf(sc->aac_dev, "FATAL: controller not coming ready, "
1085			  "status %x\n", code);
1086	    return(ENXIO);
1087	}
1088    } while (!(code & AAC_UP_AND_RUNNING));
1089
1090    /*
1091     * Create DMA tag for the common structure and allocate it.
1092     */
1093    if (bus_dma_tag_create(sc->aac_parent_dmat, 	/* parent */
1094			   1, 0, 			/* algnmnt, boundary */
1095			   BUS_SPACE_MAXADDR,		/* lowaddr */
1096			   BUS_SPACE_MAXADDR, 		/* highaddr */
1097			   NULL, NULL, 			/* filter, filterarg */
1098			   sizeof(struct aac_common), 1,/* maxsize, nsegments */
1099			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
1100			   0,				/* flags */
1101			   &sc->aac_common_dmat)) {
1102	device_printf(sc->aac_dev, "can't allocate common structure DMA tag\n");
1103	return(ENOMEM);
1104    }
1105    if (bus_dmamem_alloc(sc->aac_common_dmat, (void **)&sc->aac_common,
1106			 BUS_DMA_NOWAIT, &sc->aac_common_dmamap)) {
1107	device_printf(sc->aac_dev, "can't allocate common structure\n");
1108	return(ENOMEM);
1109    }
1110    bus_dmamap_load(sc->aac_common_dmat, sc->aac_common_dmamap, sc->aac_common,
1111		    sizeof(*sc->aac_common), aac_common_map, sc, 0);
1112    bzero(sc->aac_common, sizeof(*sc->aac_common));
1113
1114    /*
1115     * Fill in the init structure.  This tells the adapter about the physical
1116     * location of various important shared data structures.
1117     */
1118    ip = &sc->aac_common->ac_init;
1119    ip->InitStructRevision = AAC_INIT_STRUCT_REVISION;
1120
1121    ip->AdapterFibsPhysicalAddress = sc->aac_common_busaddr +
1122				     offsetof(struct aac_common, ac_fibs);
1123    ip->AdapterFibsVirtualAddress = &sc->aac_common->ac_fibs[0];
1124    ip->AdapterFibsSize = AAC_ADAPTER_FIBS * sizeof(struct aac_fib);
1125    ip->AdapterFibAlign = sizeof(struct aac_fib);
1126
1127    ip->PrintfBufferAddress = sc->aac_common_busaddr +
1128			      offsetof(struct aac_common, ac_printf);
1129    ip->PrintfBufferSize = AAC_PRINTF_BUFSIZE;
1130
1131    ip->HostPhysMemPages = 0;			/* not used? */
1132    ip->HostElapsedSeconds = time_second;	/* reset later if invalid */
1133
1134    /*
1135     * Initialise FIB queues.  Note that it appears that the layout of the
1136     * indexes and the segmentation of the entries may be mandated by the
1137     * adapter, which is only told about the base of the queue index fields.
1138     *
1139     * The initial values of the indices are assumed to inform the adapter
1140     * of the sizes of the respective queues, and theoretically it could work
1141     * out the entire layout of the queue structures from this.  We take the
1142     * easy route and just lay this area out like everyone else does.
1143     *
1144     * The Linux driver uses a much more complex scheme whereby several header
1145     * records are kept for each queue.  We use a couple of generic list
1146     * manipulation functions which 'know' the size of each list by virtue of a
1147     * table.
1148     */
1149    qaddr = &sc->aac_common->ac_qbuf[0] + AAC_QUEUE_ALIGN;
1150    qaddr -= (u_int32_t)qaddr % AAC_QUEUE_ALIGN;
1151    sc->aac_queues = (struct aac_queue_table *)qaddr;
1152    ip->CommHeaderAddress = sc->aac_common_busaddr + ((u_int32_t)sc->aac_queues
1153			    - (u_int32_t)sc->aac_common);
1154    bzero(sc->aac_queues, sizeof(struct aac_queue_table));
1155
1156    sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1157		AAC_HOST_NORM_CMD_ENTRIES;
1158    sc->aac_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1159		AAC_HOST_NORM_CMD_ENTRIES;
1160    sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1161		AAC_HOST_HIGH_CMD_ENTRIES;
1162    sc->aac_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1163		AAC_HOST_HIGH_CMD_ENTRIES;
1164    sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1165		AAC_ADAP_NORM_CMD_ENTRIES;
1166    sc->aac_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1167		AAC_ADAP_NORM_CMD_ENTRIES;
1168    sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
1169		AAC_ADAP_HIGH_CMD_ENTRIES;
1170    sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
1171		AAC_ADAP_HIGH_CMD_ENTRIES;
1172    sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX] =
1173		AAC_HOST_NORM_RESP_ENTRIES;
1174    sc->aac_queues->qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX] =
1175		AAC_HOST_NORM_RESP_ENTRIES;
1176    sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX] =
1177		AAC_HOST_HIGH_RESP_ENTRIES;
1178    sc->aac_queues->qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX] =
1179		AAC_HOST_HIGH_RESP_ENTRIES;
1180    sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX] =
1181		AAC_ADAP_NORM_RESP_ENTRIES;
1182    sc->aac_queues->qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX] =
1183		AAC_ADAP_NORM_RESP_ENTRIES;
1184    sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX] =
1185		AAC_ADAP_HIGH_RESP_ENTRIES;
1186    sc->aac_queues->qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX] =
1187		AAC_ADAP_HIGH_RESP_ENTRIES;
1188    sc->aac_qentries[AAC_HOST_NORM_CMD_QUEUE] =
1189		&sc->aac_queues->qt_HostNormCmdQueue[0];
1190    sc->aac_qentries[AAC_HOST_HIGH_CMD_QUEUE] =
1191		&sc->aac_queues->qt_HostHighCmdQueue[0];
1192    sc->aac_qentries[AAC_ADAP_NORM_CMD_QUEUE] =
1193		&sc->aac_queues->qt_AdapNormCmdQueue[0];
1194    sc->aac_qentries[AAC_ADAP_HIGH_CMD_QUEUE] =
1195		&sc->aac_queues->qt_AdapHighCmdQueue[0];
1196    sc->aac_qentries[AAC_HOST_NORM_RESP_QUEUE] =
1197		&sc->aac_queues->qt_HostNormRespQueue[0];
1198    sc->aac_qentries[AAC_HOST_HIGH_RESP_QUEUE] =
1199		&sc->aac_queues->qt_HostHighRespQueue[0];
1200    sc->aac_qentries[AAC_ADAP_NORM_RESP_QUEUE] =
1201		&sc->aac_queues->qt_AdapNormRespQueue[0];
1202    sc->aac_qentries[AAC_ADAP_HIGH_RESP_QUEUE] =
1203		&sc->aac_queues->qt_AdapHighRespQueue[0];
1204
1205    /*
1206     * Do controller-type-specific initialisation
1207     */
1208    switch (sc->aac_hwif) {
1209    case AAC_HWIF_I960RX:
1210	AAC_SETREG4(sc, AAC_RX_ODBR, ~0);
1211	break;
1212    }
1213
1214    /*
1215     * Give the init structure to the controller.
1216     */
1217    if (aac_sync_command(sc, AAC_MONKER_INITSTRUCT,
1218			 sc->aac_common_busaddr + offsetof(struct aac_common,
1219			 ac_init), 0, 0, 0, NULL)) {
1220	device_printf(sc->aac_dev, "error establishing init structure\n");
1221	return(EIO);
1222    }
1223
1224    return(0);
1225}
1226
1227/******************************************************************************
1228 * Send a synchronous command to the controller and wait for a result.
1229 */
1230static int
1231aac_sync_command(struct aac_softc *sc, u_int32_t command,
1232		 u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3,
1233		 u_int32_t *sp)
1234{
1235    time_t	then;
1236    u_int32_t	status;
1237
1238    debug_called(3);
1239
1240    /* populate the mailbox */
1241    AAC_SET_MAILBOX(sc, command, arg0, arg1, arg2, arg3);
1242
1243    /* ensure the sync command doorbell flag is cleared */
1244    AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1245
1246    /* then set it to signal the adapter */
1247    AAC_QNOTIFY(sc, AAC_DB_SYNC_COMMAND);
1248
1249    /* spin waiting for the command to complete */
1250    then = time_second;
1251    do {
1252	if (time_second > (then + AAC_IMMEDIATE_TIMEOUT)) {
1253	    debug(2, "timed out");
1254	    return(EIO);
1255	}
1256    } while (!(AAC_GET_ISTATUS(sc) & AAC_DB_SYNC_COMMAND));
1257
1258    /* clear the completion flag */
1259    AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);
1260
1261    /* get the command status */
1262    status = AAC_GET_MAILBOXSTATUS(sc);
1263    if (sp != NULL)
1264	*sp = status;
1265    return(0);
1266}
1267
1268/******************************************************************************
1269 * Send a synchronous FIB to the controller and wait for a result.
1270 */
1271static int
1272aac_sync_fib(struct aac_softc *sc, u_int32_t command, u_int32_t xferstate,
1273	     void *data, u_int16_t datasize,
1274	     void *result, u_int16_t *resultsize)
1275{
1276    struct aac_fib	*fib = &sc->aac_common->ac_sync_fib;
1277
1278    debug_called(3);
1279
1280    if (datasize > AAC_FIB_DATASIZE)
1281	return(EINVAL);
1282
1283    /*
1284     * Set up the sync FIB
1285     */
1286    fib->Header.XferState = AAC_FIBSTATE_HOSTOWNED | AAC_FIBSTATE_INITIALISED |
1287			    AAC_FIBSTATE_EMPTY;
1288    fib->Header.XferState |= xferstate;
1289    fib->Header.Command = command;
1290    fib->Header.StructType = AAC_FIBTYPE_TFIB;
1291    fib->Header.Size = sizeof(struct aac_fib) + datasize;
1292    fib->Header.SenderSize = sizeof(struct aac_fib);
1293    fib->Header.SenderFibAddress = (u_int32_t)fib;
1294    fib->Header.ReceiverFibAddress = sc->aac_common_busaddr +
1295				     offsetof(struct aac_common, ac_sync_fib);
1296
1297    /*
1298     * Copy in data.
1299     */
1300    if (data != NULL) {
1301	KASSERT(datasize <= sizeof(fib->data),
1302		("aac_sync_fib: datasize to large"));
1303	bcopy(data, fib->data, datasize);
1304	fib->Header.XferState |= AAC_FIBSTATE_FROMHOST | AAC_FIBSTATE_NORM;
1305    }
1306
1307    /*
1308     * Give the FIB to the controller, wait for a response.
1309     */
1310    if (aac_sync_command(sc, AAC_MONKER_SYNCFIB, fib->Header.ReceiverFibAddress,
1311			 0, 0, 0, NULL)) {
1312	debug(2, "IO error");
1313	return(EIO);
1314    }
1315
1316    /*
1317     * Copy out the result
1318     */
1319    if (result != NULL) {
1320	u_int copysize;
1321
1322	copysize = fib->Header.Size - sizeof(struct aac_fib_header);
1323	if (copysize > *resultsize)
1324		copysize = *resultsize;
1325	*resultsize = fib->Header.Size - sizeof(struct aac_fib_header);
1326	bcopy(fib->data, result, copysize);
1327    }
1328    return(0);
1329}
1330
1331/********************************************************************************
1332 * Adapter-space FIB queue manipulation
1333 *
1334 * Note that the queue implementation here is a little funky; neither the PI or
1335 * CI will ever be zero.  This behaviour is a controller feature.
1336 */
1337static struct {
1338    int		size;
1339    int		notify;
1340} aac_qinfo[] = {
1341    {AAC_HOST_NORM_CMD_ENTRIES, AAC_DB_COMMAND_NOT_FULL},
1342    {AAC_HOST_HIGH_CMD_ENTRIES, 0},
1343    {AAC_ADAP_NORM_CMD_ENTRIES, AAC_DB_COMMAND_READY},
1344    {AAC_ADAP_HIGH_CMD_ENTRIES, 0},
1345    {AAC_HOST_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_NOT_FULL},
1346    {AAC_HOST_HIGH_RESP_ENTRIES, 0},
1347    {AAC_ADAP_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_READY},
1348    {AAC_ADAP_HIGH_RESP_ENTRIES, 0}
1349};
1350
1351/*
1352 * Atomically insert an entry into the nominated queue, returns 0 on success or
1353 * EBUSY if the queue is full.
1354 *
1355 * Note: it would be more efficient to defer notifying the controller in
1356 *       the case where we may be inserting several entries in rapid succession,
1357 *       but implementing this usefully may be difficult (it would involve a
1358 *       separate queue/notify interface).
1359 */
1360static int
1361aac_enqueue_fib(struct aac_softc *sc, int queue, struct aac_command *cm)
1362{
1363    u_int32_t	pi, ci;
1364    int		s, error;
1365    u_int32_t	fib_size;
1366    u_int32_t	fib_addr;
1367
1368    fib_size = cm->cm_fib->Header.Size;
1369    fib_addr = cm->cm_fib->Header.ReceiverFibAddress;
1370
1371    debug_called(3);
1372
1373    s = splbio();
1374
1375    /* get the producer/consumer indices */
1376    pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1377    ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1378
1379    /* wrap the queue? */
1380    if (pi >= aac_qinfo[queue].size)
1381	pi = 0;
1382
1383    /* check for queue full */
1384    if ((pi + 1) == ci) {
1385	error = EBUSY;
1386	goto out;
1387    }
1388
1389    /* populate queue entry */
1390    (sc->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
1391    (sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;
1392
1393    /* update producer index */
1394    sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;
1395
1396    /*
1397     * To avoid a race with its completion interrupt, place this command on the
1398     * busy queue prior to advertising it to the controller.
1399     */
1400    aac_enqueue_busy(cm);
1401
1402    /* notify the adapter if we know how */
1403    if (aac_qinfo[queue].notify != 0)
1404	AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1405
1406    error = 0;
1407
1408out:
1409    splx(s);
1410    return(error);
1411}
1412
1413/*
1414 * Atomically remove one entry from the nominated queue, returns 0 on success or
1415 * ENOENT if the queue is empty.
1416 */
1417static int
1418aac_dequeue_fib(struct aac_softc *sc, int queue, u_int32_t *fib_size,
1419		struct aac_fib **fib_addr)
1420{
1421    u_int32_t	pi, ci;
1422    int		s, error;
1423    int		notify;
1424
1425    debug_called(3);
1426
1427    s = splbio();
1428
1429    /* get the producer/consumer indices */
1430    pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
1431    ci = sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];
1432
1433    /* check for queue empty */
1434    if (ci == pi) {
1435	error = ENOENT;
1436	goto out;
1437    }
1438
1439    notify = 0;
1440    if (ci == pi + 1)
1441	notify++;
1442
1443    /* wrap the queue? */
1444    if (ci >= aac_qinfo[queue].size)
1445	ci = 0;
1446
1447    /* fetch the entry */
1448    *fib_size = (sc->aac_qentries[queue] + ci)->aq_fib_size;
1449    *fib_addr = (struct aac_fib *)(sc->aac_qentries[queue] + ci)->aq_fib_addr;
1450
1451    /* update consumer index */
1452    sc->aac_queues->qt_qindex[queue][AAC_CONSUMER_INDEX] = ci + 1;
1453
1454    /* if we have made the queue un-full, notify the adapter */
1455    if (notify && (aac_qinfo[queue].notify != 0))
1456	AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
1457    error = 0;
1458
1459out:
1460    splx(s);
1461    return(error);
1462}
1463
1464/******************************************************************************
1465 * Check for commands that have been outstanding for a suspiciously long time,
1466 * and complain about them.
1467 */
1468static void
1469aac_timeout(struct aac_softc *sc)
1470{
1471    int		s;
1472    struct	aac_command *cm;
1473    time_t	deadline;
1474
1475#if 0
1476    /* simulate an interrupt to handle possibly-missed interrupts */
1477    /*
1478     * XXX This was done to work around another bug which has since been
1479     * fixed.  It is dangerous anyways because you don't want multiple
1480     * threads in the interrupt handler at the same time!  If calling
1481     * is deamed neccesary in the future, proper mutexes must be used.
1482     */
1483    s = splbio();
1484    aac_intr(sc);
1485    splx(s);
1486#endif
1487
1488    /* kick the I/O queue to restart it in the case of deadlock */
1489    aac_startio(sc);
1490
1491    /* traverse the busy command list, bitch about late commands once only */
1492    deadline = time_second - AAC_CMD_TIMEOUT;
1493    s = splbio();
1494    TAILQ_FOREACH(cm, &sc->aac_busy, cm_link) {
1495	if ((cm->cm_timestamp < deadline)
1496	    /*  && !(cm->cm_flags & AAC_CMD_TIMEDOUT) */) {
1497	    cm->cm_flags |= AAC_CMD_TIMEDOUT;
1498	    device_printf(sc->aac_dev, "COMMAND %p TIMEOUT AFTER %d SECONDS\n",
1499			  cm, (int)(time_second - cm->cm_timestamp));
1500	    AAC_PRINT_FIB(sc, cm->cm_fib);
1501	}
1502    }
1503    splx(s);
1504
1505    /* reset the timer for next time */
1506    timeout((timeout_t*)aac_timeout, sc, AAC_PERIODIC_INTERVAL * hz);
1507    return;
1508}
1509
1510/******************************************************************************
1511 ******************************************************************************
1512			Interface Function Vectors
1513 ******************************************************************************
1514 ******************************************************************************/
1515
1516/******************************************************************************
1517 * Read the current firmware status word.
1518 */
1519static int
1520aac_sa_get_fwstatus(struct aac_softc *sc)
1521{
1522    debug_called(3);
1523
1524    return(AAC_GETREG4(sc, AAC_SA_FWSTATUS));
1525}
1526
1527static int
1528aac_rx_get_fwstatus(struct aac_softc *sc)
1529{
1530    debug_called(3);
1531
1532    return(AAC_GETREG4(sc, AAC_RX_FWSTATUS));
1533}
1534
1535/******************************************************************************
1536 * Notify the controller of a change in a given queue
1537 */
1538
1539static void
1540aac_sa_qnotify(struct aac_softc *sc, int qbit)
1541{
1542    debug_called(3);
1543
1544    AAC_SETREG2(sc, AAC_SA_DOORBELL1_SET, qbit);
1545}
1546
1547static void
1548aac_rx_qnotify(struct aac_softc *sc, int qbit)
1549{
1550    debug_called(3);
1551
1552    AAC_SETREG4(sc, AAC_RX_IDBR, qbit);
1553}
1554
1555/******************************************************************************
1556 * Get the interrupt reason bits
1557 */
1558static int
1559aac_sa_get_istatus(struct aac_softc *sc)
1560{
1561    debug_called(3);
1562
1563    return(AAC_GETREG2(sc, AAC_SA_DOORBELL0));
1564}
1565
1566static int
1567aac_rx_get_istatus(struct aac_softc *sc)
1568{
1569    debug_called(3);
1570
1571    return(AAC_GETREG4(sc, AAC_RX_ODBR));
1572}
1573
1574/******************************************************************************
1575 * Clear some interrupt reason bits
1576 */
1577static void
1578aac_sa_clear_istatus(struct aac_softc *sc, int mask)
1579{
1580    debug_called(3);
1581
1582    AAC_SETREG2(sc, AAC_SA_DOORBELL0_CLEAR, mask);
1583}
1584
1585static void
1586aac_rx_clear_istatus(struct aac_softc *sc, int mask)
1587{
1588    debug_called(3);
1589
1590    AAC_SETREG4(sc, AAC_RX_ODBR, mask);
1591}
1592
1593/******************************************************************************
1594 * Populate the mailbox and set the command word
1595 */
1596static void
1597aac_sa_set_mailbox(struct aac_softc *sc, u_int32_t command,
1598		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
1599{
1600    debug_called(4);
1601
1602    AAC_SETREG4(sc, AAC_SA_MAILBOX, command);
1603    AAC_SETREG4(sc, AAC_SA_MAILBOX + 4, arg0);
1604    AAC_SETREG4(sc, AAC_SA_MAILBOX + 8, arg1);
1605    AAC_SETREG4(sc, AAC_SA_MAILBOX + 12, arg2);
1606    AAC_SETREG4(sc, AAC_SA_MAILBOX + 16, arg3);
1607}
1608
1609static void
1610aac_rx_set_mailbox(struct aac_softc *sc, u_int32_t command,
1611		u_int32_t arg0, u_int32_t arg1, u_int32_t arg2, u_int32_t arg3)
1612{
1613    debug_called(4);
1614
1615    AAC_SETREG4(sc, AAC_RX_MAILBOX, command);
1616    AAC_SETREG4(sc, AAC_RX_MAILBOX + 4, arg0);
1617    AAC_SETREG4(sc, AAC_RX_MAILBOX + 8, arg1);
1618    AAC_SETREG4(sc, AAC_RX_MAILBOX + 12, arg2);
1619    AAC_SETREG4(sc, AAC_RX_MAILBOX + 16, arg3);
1620}
1621
1622/******************************************************************************
1623 * Fetch the immediate command status word
1624 */
1625static int
1626aac_sa_get_mailboxstatus(struct aac_softc *sc)
1627{
1628    debug_called(4);
1629
1630    return(AAC_GETREG4(sc, AAC_SA_MAILBOX));
1631}
1632
1633static int
1634aac_rx_get_mailboxstatus(struct aac_softc *sc)
1635{
1636    debug_called(4);
1637
1638    return(AAC_GETREG4(sc, AAC_RX_MAILBOX));
1639}
1640
1641/******************************************************************************
1642 * Set/clear interrupt masks
1643 */
1644static void
1645aac_sa_set_interrupts(struct aac_softc *sc, int enable)
1646{
1647    debug(2, "%sable interrupts", enable ? "en" : "dis");
1648
1649    if (enable) {
1650	AAC_SETREG2((sc), AAC_SA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
1651    } else {
1652	AAC_SETREG2((sc), AAC_SA_MASK0_SET, ~0);
1653    }
1654}
1655
1656static void
1657aac_rx_set_interrupts(struct aac_softc *sc, int enable)
1658{
1659    debug(2, "%sable interrupts", enable ? "en" : "dis");
1660
1661    if (enable) {
1662	AAC_SETREG4(sc, AAC_RX_OIMR, ~AAC_DB_INTERRUPTS);
1663    } else {
1664	AAC_SETREG4(sc, AAC_RX_OIMR, ~0);
1665    }
1666}
1667
1668/******************************************************************************
1669 ******************************************************************************
1670			Debugging and Diagnostics
1671 ******************************************************************************
1672 ******************************************************************************/
1673
1674/******************************************************************************
1675 * Print some information about the controller.
1676 */
1677static void
1678aac_describe_controller(struct aac_softc *sc)
1679{
1680    u_int8_t			buf[AAC_FIB_DATASIZE];	/* XXX really a bit big
1681							 * for the stack */
1682    u_int16_t			bufsize;
1683    struct aac_adapter_info	*info;
1684    u_int8_t			arg;
1685
1686    debug_called(2);
1687
1688    arg = 0;
1689    bufsize = sizeof(buf);
1690    if (aac_sync_fib(sc, RequestAdapterInfo, 0, &arg, sizeof(arg), &buf,
1691		     &bufsize)) {
1692	device_printf(sc->aac_dev, "RequestAdapterInfo failed\n");
1693	return;
1694    }
1695    if (bufsize != sizeof(*info)) {
1696	device_printf(sc->aac_dev, "RequestAdapterInfo returned wrong data "
1697		      "size (%d != %d)\n", bufsize, sizeof(*info));
1698	/*return;*/
1699    }
1700    info = (struct aac_adapter_info *)&buf[0];
1701
1702    device_printf(sc->aac_dev, "%s %dMHz, %dMB total memory, %s (%d)\n",
1703		  aac_describe_code(aac_cpu_variant, info->CpuVariant),
1704		  info->ClockSpeed, info->TotalMem / (1024 * 1024),
1705		  aac_describe_code(aac_battery_platform,
1706		  info->batteryPlatform), info->batteryPlatform);
1707
1708    /* save the kernel revision structure for later use */
1709    sc->aac_revision = info->KernelRevision;
1710    device_printf(sc->aac_dev, "Kernel %d.%d-%d, S/N %llx\n",
1711		  info->KernelRevision.external.comp.major,
1712		  info->KernelRevision.external.comp.minor,
1713		  info->KernelRevision.external.comp.dash,
1714		  info->SerialNumber);	/* XXX format? */
1715}
1716
1717/******************************************************************************
1718 * Look up a text description of a numeric error code and return a pointer to
1719 * same.
1720 */
1721static char *
1722aac_describe_code(struct aac_code_lookup *table, u_int32_t code)
1723{
1724    int		i;
1725
1726    for (i = 0; table[i].string != NULL; i++)
1727	if (table[i].code == code)
1728	    return(table[i].string);
1729    return(table[i + 1].string);
1730}
1731
1732/*****************************************************************************
1733 *****************************************************************************
1734				Management Interface
1735 *****************************************************************************
1736 *****************************************************************************/
1737
1738static int
1739aac_open(dev_t dev, int flags, int fmt, struct proc *p)
1740{
1741    struct aac_softc	*sc = dev->si_drv1;
1742
1743    debug_called(2);
1744
1745    /* Check to make sure the device isn't already open */
1746    if (sc->aac_state & AAC_STATE_OPEN) {
1747        return EBUSY;
1748    }
1749    sc->aac_state |= AAC_STATE_OPEN;
1750
1751    return 0;
1752}
1753
1754static int
1755aac_close(dev_t dev, int flags, int fmt, struct proc *p)
1756{
1757    struct aac_softc	*sc = dev->si_drv1;
1758
1759    debug_called(2);
1760
1761    /* Mark this unit as no longer open  */
1762    sc->aac_state &= ~AAC_STATE_OPEN;
1763
1764    return 0;
1765}
1766
1767static int
1768aac_ioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, struct proc *p)
1769{
1770    union aac_statrequest	*as = (union aac_statrequest *)arg;
1771    struct aac_softc		*sc = dev->si_drv1;
1772    int				error = 0;
1773    int				i;
1774
1775    debug_called(2);
1776
1777    switch (cmd) {
1778    case AACIO_STATS:
1779	switch (as->as_item) {
1780	case AACQ_FREE:
1781	case AACQ_BIO:
1782	case AACQ_READY:
1783	case AACQ_BUSY:
1784	case AACQ_COMPLETE:
1785	    bcopy(&sc->aac_qstat[as->as_item], &as->as_qstat,
1786		  sizeof(struct aac_qstat));
1787	    break;
1788	default:
1789	    error = ENOENT;
1790	    break;
1791	}
1792	break;
1793
1794    case FSACTL_SENDFIB:
1795	arg = *(caddr_t *)arg;
1796    case FSACTL_LNX_SENDFIB:
1797	debug(1, "FSACTL_SENDFIB");
1798	error = aac_ioctl_sendfib(sc, arg);
1799	break;
1800    case FSACTL_AIF_THREAD:
1801    case FSACTL_LNX_AIF_THREAD:
1802	debug(1, "FSACTL_AIF_THREAD");
1803	error = EINVAL;
1804	break;
1805    case FSACTL_OPEN_GET_ADAPTER_FIB:
1806	arg = *(caddr_t *)arg;
1807    case FSACTL_LNX_OPEN_GET_ADAPTER_FIB:
1808	debug(1, "FSACTL_OPEN_GET_ADAPTER_FIB");
1809	/*
1810	 * Pass the caller out an AdapterFibContext.
1811	 *
1812	 * Note that because we only support one opener, we
1813	 * basically ignore this.  Set the caller's context to a magic
1814	 * number just in case.
1815	 *
1816	 * The Linux code hands the driver a pointer into kernel space,
1817	 * and then trusts it when the caller hands it back.  Aiee!
1818	 */
1819	i = AAC_AIF_SILLYMAGIC;
1820	error = copyout(&i, arg, sizeof(i));
1821	break;
1822    case FSACTL_GET_NEXT_ADAPTER_FIB:
1823	arg = *(caddr_t *)arg;
1824    case FSACTL_LNX_GET_NEXT_ADAPTER_FIB:
1825	debug(1, "FSACTL_GET_NEXT_ADAPTER_FIB");
1826	error = aac_getnext_aif(sc, arg);
1827	break;
1828    case FSACTL_CLOSE_GET_ADAPTER_FIB:
1829    case FSACTL_LNX_CLOSE_GET_ADAPTER_FIB:
1830	debug(1, "FSACTL_CLOSE_GET_ADAPTER_FIB");
1831	/* don't do anything here */
1832	break;
1833    case FSACTL_MINIPORT_REV_CHECK:
1834	arg = *(caddr_t *)arg;
1835    case FSACTL_LNX_MINIPORT_REV_CHECK:
1836	debug(1, "FSACTL_MINIPORT_REV_CHECK");
1837	error = aac_rev_check(sc, arg);
1838	break;
1839    default:
1840	device_printf(sc->aac_dev, "unsupported cmd 0x%lx\n", cmd);
1841	error = EINVAL;
1842	break;
1843    }
1844    return(error);
1845}
1846
1847/******************************************************************************
1848 * Send a FIB supplied from userspace
1849 */
1850static int
1851aac_ioctl_sendfib(struct aac_softc *sc, caddr_t ufib)
1852{
1853    struct aac_command 	*cm;
1854    int			size, error;
1855
1856    debug_called(2);
1857
1858    cm = NULL;
1859
1860    /*
1861     * Get a command
1862     */
1863    if (aac_alloc_command(sc, &cm)) {
1864	error = EBUSY;
1865	goto out;
1866    }
1867
1868    /*
1869     * Fetch the FIB header, then re-copy to get data as well.
1870     */
1871    if ((error = copyin(ufib, cm->cm_fib, sizeof(struct aac_fib_header))) != 0)
1872	goto out;
1873    size = cm->cm_fib->Header.Size + sizeof(struct aac_fib_header);
1874    if (size > sizeof(struct aac_fib)) {
1875	device_printf(sc->aac_dev, "incoming FIB oversized (%d > %d)\n", size,
1876		      sizeof(struct aac_fib));
1877	size = sizeof(struct aac_fib);
1878    }
1879    if ((error = copyin(ufib, cm->cm_fib, size)) != 0)
1880	goto out;
1881    cm->cm_fib->Header.Size = size;
1882    cm->cm_timestamp = time_second;
1883
1884    /*
1885     * Pass the FIB to the controller, wait for it to complete.
1886     */
1887    if ((error = aac_wait_command(cm, 30)) != 0)	/* XXX user timeout? */
1888	goto out;
1889
1890    /*
1891     * Copy the FIB and data back out to the caller.
1892     */
1893    size = cm->cm_fib->Header.Size;
1894    if (size > sizeof(struct aac_fib)) {
1895	device_printf(sc->aac_dev, "outbound FIB oversized (%d > %d)\n", size,
1896		      sizeof(struct aac_fib));
1897	size = sizeof(struct aac_fib);
1898    }
1899    error = copyout(cm->cm_fib, ufib, size);
1900
1901out:
1902    if (cm != NULL) {
1903	aac_release_command(cm);
1904    }
1905    return(error);
1906}
1907
1908/******************************************************************************
1909 * Handle an AIF sent to us by the controller; queue it for later reference.
1910 *
1911 * XXX what's the right thing to do here when the queue is full?  Drop the older
1912 * or newer entries?
1913 */
1914static void
1915aac_handle_aif(struct aac_softc *sc, struct aac_aif_command *aif)
1916{
1917    int		next, s;
1918
1919    debug_called(2);
1920
1921    s = splbio();
1922    next = (sc->aac_aifq_head + 1) % AAC_AIFQ_LENGTH;
1923    if (next != sc->aac_aifq_tail) {
1924	bcopy(aif, &sc->aac_aifq[next], sizeof(struct aac_aif_command));
1925	sc->aac_aifq_head = next;
1926	if (sc->aac_state & AAC_STATE_AIF_SLEEPER)
1927	    wakeup(sc->aac_aifq);
1928    }
1929    splx(s);
1930    aac_print_aif(sc, aif);
1931}
1932
1933/******************************************************************************
1934 ******************************************************************************
1935			Linux Management Interface
1936 ******************************************************************************
1937 ******************************************************************************/
1938
1939#ifdef AAC_COMPAT_LINUX
1940
1941#include <sys/proc.h>
1942#include <machine/../linux/linux.h>
1943#include <machine/../linux/linux_proto.h>
1944#include <compat/linux/linux_ioctl.h>
1945
1946#define AAC_LINUX_IOCTL_MIN  0x2000
1947#define AAC_LINUX_IOCTL_MAX  0x21ff
1948
1949static linux_ioctl_function_t aac_linux_ioctl;
1950static struct linux_ioctl_handler aac_handler = {aac_linux_ioctl,
1951						AAC_LINUX_IOCTL_MIN,
1952						AAC_LINUX_IOCTL_MAX};
1953
1954SYSINIT  (aac_register,   SI_SUB_KLD, SI_ORDER_MIDDLE,
1955	  linux_ioctl_register_handler, &aac_handler);
1956SYSUNINIT(aac_unregister, SI_SUB_KLD, SI_ORDER_MIDDLE,
1957	  linux_ioctl_unregister_handler, &aac_handler);
1958
1959MODULE_DEPEND(aac, linux, 1, 1, 1);
1960
1961static int
1962aac_linux_ioctl(struct proc *p, struct linux_ioctl_args *args)
1963{
1964    struct file		*fp = p->p_fd->fd_ofiles[args->fd];
1965    u_long		cmd = args->cmd;
1966
1967    /*
1968     * Pass the ioctl off to our standard handler.
1969     */
1970    return(fo_ioctl(fp, cmd, (caddr_t)args->arg, p));
1971}
1972
1973#endif
1974
1975/******************************************************************************
1976 * Return the Revision of the driver to userspace and check to see if the
1977 * userspace app is possibly compatible.  This is extremely bogus right now
1978 * because I have no idea how to handle the versioning of this driver.  It is
1979 * needed, though, to get aaccli working.
1980 */
1981static int
1982aac_rev_check(struct aac_softc *sc, caddr_t udata)
1983{
1984    struct aac_rev_check	rev_check;
1985    struct aac_rev_check_resp	rev_check_resp;
1986    int				error = 0;
1987
1988    debug_called(2);
1989
1990    /*
1991     * Copyin the revision struct from userspace
1992     */
1993    if ((error = copyin(udata, (caddr_t)&rev_check,
1994			sizeof(struct aac_rev_check))) != 0) {
1995	return error;
1996    }
1997
1998    debug(2, "Userland revision= %d\n", rev_check.callingRevision.buildNumber);
1999
2000    /*
2001     * Doctor up the response struct.
2002     */
2003    rev_check_resp.possiblyCompatible = 1;
2004    rev_check_resp.adapterSWRevision.external.ul = sc->aac_revision.external.ul;
2005    rev_check_resp.adapterSWRevision.buildNumber = sc->aac_revision.buildNumber;
2006
2007    return(copyout((caddr_t)&rev_check_resp, udata,
2008		   sizeof(struct aac_rev_check_resp)));
2009}
2010
2011/******************************************************************************
2012 * Pass the caller the next AIF in their queue
2013 */
2014static int
2015aac_getnext_aif(struct aac_softc *sc, caddr_t arg)
2016{
2017    struct get_adapter_fib_ioctl	agf;
2018    int					error, s;
2019
2020    debug_called(2);
2021
2022    if ((error = copyin(arg, &agf, sizeof(agf))) == 0) {
2023
2024	/*
2025	 * Check the magic number that we gave the caller.
2026	 */
2027	if (agf.AdapterFibContext != AAC_AIF_SILLYMAGIC) {
2028	    error = EFAULT;
2029	} else {
2030
2031	    s = splbio();
2032	    error = aac_return_aif(sc, agf.AifFib);
2033
2034	    if ((error == EAGAIN) && (agf.Wait)) {
2035		sc->aac_state |= AAC_STATE_AIF_SLEEPER;
2036		while (error == EAGAIN) {
2037		    error = tsleep(sc->aac_aifq, PRIBIO | PCATCH, "aacaif", 0);
2038		    if (error == 0)
2039			error = aac_return_aif(sc, agf.AifFib);
2040		}
2041		sc->aac_state &= ~AAC_STATE_AIF_SLEEPER;
2042	    }
2043	    splx(s);
2044	}
2045    }
2046    return(error);
2047}
2048
2049/******************************************************************************
2050 * Hand the next AIF off the top of the queue out to userspace.
2051 */
2052static int
2053aac_return_aif(struct aac_softc *sc, caddr_t uptr)
2054{
2055    int		error, s;
2056
2057    debug_called(2);
2058
2059    s = splbio();
2060    if (sc->aac_aifq_tail == sc->aac_aifq_head) {
2061	error = EAGAIN;
2062    } else {
2063	error = copyout(&sc->aac_aifq[sc->aac_aifq_tail], uptr,
2064			sizeof(struct aac_aif_command));
2065	if (!error)
2066	    sc->aac_aifq_tail = (sc->aac_aifq_tail + 1) % AAC_AIFQ_LENGTH;
2067    }
2068    splx(s);
2069    return(error);
2070}
2071