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