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