amr(4): Remove unused code.
[dragonfly.git] / sys / dev / raid / amr / amr.c
1 /*-
2  * Copyright (c) 1999,2000 Michael Smith
3  * Copyright (c) 2000 BSDi
4  * Copyright (c) 2005 Scott Long
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*-
29  * Copyright (c) 2002 Eric Moore
30  * Copyright (c) 2002, 2004 LSI Logic Corporation
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. The party using or redistributing the source code and binary forms
42  *    agrees to the disclaimer below and the terms and conditions set forth
43  *    herein.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  *
57  * $FreeBSD: src/sys/dev/amr/amr.c,v 1.97 2012/04/20 20:27:31 jhb Exp $
58  */
59
60 /*
61  * Driver for the AMI MegaRaid family of controllers.
62  */
63
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/malloc.h>
67 #include <sys/kernel.h>
68 #include <sys/proc.h>
69 #include <sys/sysctl.h>
70 #include <sys/sysmsg.h>
71
72 #include <sys/bio.h>
73 #include <sys/bus.h>
74 #include <sys/conf.h>
75 #include <sys/stat.h>
76
77 #include <machine/cpu.h>
78 #include <sys/rman.h>
79
80 #include <bus/pci/pcireg.h>
81 #include <bus/pci/pcivar.h>
82
83 #include <dev/raid/amr/amrio.h>
84 #include <dev/raid/amr/amrreg.h>
85 #include <dev/raid/amr/amrvar.h>
86 #define AMR_DEFINE_TABLES
87 #include <dev/raid/amr/amr_tables.h>
88
89 SYSCTL_NODE(_hw, OID_AUTO, amr, CTLFLAG_RD, 0, "AMR driver parameters");
90
91 static d_open_t         amr_open;
92 static d_close_t        amr_close;
93 static d_ioctl_t        amr_ioctl;
94
95 static struct dev_ops amr_ops = {
96         { "amr", 0, 0 },
97         .d_open =       amr_open,
98         .d_close =      amr_close,
99         .d_ioctl =      amr_ioctl,
100 };
101
102 int linux_no_adapter = 0;
103 /*
104  * Initialisation, bus interface.
105  */
106 static void     amr_startup(void *arg);
107
108 /*
109  * Command wrappers
110  */
111 static int      amr_query_controller(struct amr_softc *sc);
112 static void     *amr_enquiry(struct amr_softc *sc, size_t bufsize, 
113                              u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual, int *status);
114 static void     amr_completeio(struct amr_command *ac);
115 static int      amr_support_ext_cdb(struct amr_softc *sc);
116
117 /*
118  * Command buffer allocation.
119  */
120 static void     amr_alloccmd_cluster(struct amr_softc *sc);
121 static void     amr_freecmd_cluster(struct amr_command_cluster *acc);
122
123 /*
124  * Command processing.
125  */
126 static int      amr_bio_command(struct amr_softc *sc, struct amr_command **acp);
127 static int      amr_wait_command(struct amr_command *ac);
128 static int      amr_mapcmd(struct amr_command *ac);
129 static void     amr_unmapcmd(struct amr_command *ac);
130 static int      amr_start(struct amr_command *ac);
131 static void     amr_complete(void *context, ac_qhead_t *head);
132 static void     amr_setup_sg(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
133 static void     amr_setup_data(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
134 static void     amr_setup_ccb(void *arg, bus_dma_segment_t *segs, int nsegments, int error);
135 static void     amr_abort_load(struct amr_command *ac);
136
137 #if 0
138 /*
139  * Status monitoring
140  */
141 static void     amr_periodic(void *data);
142 #endif
143
144 /*
145  * Interface-specific shims
146  */
147 static int      amr_quartz_submit_command(struct amr_command *ac);
148 static int      amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
149 static int      amr_quartz_poll_command(struct amr_command *ac);
150 static int      amr_quartz_poll_command1(struct amr_softc *sc, struct amr_command *ac);
151
152 static int      amr_std_submit_command(struct amr_command *ac);
153 static int      amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
154 static int      amr_std_poll_command(struct amr_command *ac);
155 static void     amr_std_attach_mailbox(struct amr_softc *sc);
156
157 #ifdef AMR_BOARD_INIT
158 static int      amr_quartz_init(struct amr_softc *sc);
159 static int      amr_std_init(struct amr_softc *sc);
160 #endif
161
162 /*
163  * Debugging
164  */
165 static void     amr_describe_controller(struct amr_softc *sc);
166 #ifdef AMR_DEBUG
167 #if 0
168 static void     amr_printcommand(struct amr_command *ac);
169 #endif
170 #endif
171
172 static void     amr_init_sysctl(struct amr_softc *sc);
173 static int      amr_linux_ioctl_int(struct cdev *dev, u_long cmd, caddr_t addr,
174                     int32_t flag, struct sysmsg *sm);
175
176 static MALLOC_DEFINE(M_AMR, "amr", "AMR memory");
177
178 /********************************************************************************
179  ********************************************************************************
180                                                                       Inline Glue
181  ********************************************************************************
182  ********************************************************************************/
183
184 /********************************************************************************
185  ********************************************************************************
186                                                                 Public Interfaces
187  ********************************************************************************
188  ********************************************************************************/
189
190 /********************************************************************************
191  * Initialise the controller and softc.
192  */
193 int
194 amr_attach(struct amr_softc *sc)
195 {
196     device_t child;
197
198     debug_called(1);
199
200     /*
201      * Initialise per-controller queues.
202      */
203     amr_init_qhead(&sc->amr_freecmds);
204     amr_init_qhead(&sc->amr_ready);
205     TAILQ_INIT(&sc->amr_cmd_clusters);
206     bioq_init(&sc->amr_bioq);
207
208     debug(2, "queue init done");
209
210     /*
211      * Configure for this controller type.
212      */
213     if (AMR_IS_QUARTZ(sc)) {
214         sc->amr_submit_command = amr_quartz_submit_command;
215         sc->amr_get_work       = amr_quartz_get_work;
216         sc->amr_poll_command   = amr_quartz_poll_command;
217         sc->amr_poll_command1  = amr_quartz_poll_command1;
218     } else {
219         sc->amr_submit_command = amr_std_submit_command;
220         sc->amr_get_work       = amr_std_get_work;
221         sc->amr_poll_command   = amr_std_poll_command;
222         amr_std_attach_mailbox(sc);
223     }
224
225 #ifdef AMR_BOARD_INIT
226     if ((AMR_IS_QUARTZ(sc) ? amr_quartz_init(sc) : amr_std_init(sc)))
227         return(ENXIO);
228 #endif
229
230     /*
231      * Allocate initial commands.
232      */
233     amr_alloccmd_cluster(sc);
234
235     /*
236      * Quiz controller for features and limits.
237      */
238     if (amr_query_controller(sc))
239         return(ENXIO);
240
241     debug(2, "controller query complete");
242
243     /*
244      * preallocate the remaining commands.
245      */
246     while (sc->amr_nextslot < sc->amr_maxio)
247         amr_alloccmd_cluster(sc);
248
249     /*
250      * Setup sysctls.
251      */
252     sysctl_ctx_init(&sc->amr_sysctl_ctx);
253     sc->amr_sysctl_tree = SYSCTL_ADD_NODE(&sc->amr_sysctl_ctx,
254         SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
255         device_get_nameunit(sc->amr_dev), CTLFLAG_RD, 0, "");
256     if (sc->amr_sysctl_tree == NULL) {
257         device_printf(sc->amr_dev, "can't add sysctl node\n");
258         return (EINVAL);
259     }
260     amr_init_sysctl(sc);
261
262     /*
263      * Attach our 'real' SCSI channels to CAM.
264      */
265     child = device_add_child(sc->amr_dev, "amrp", -1);
266     sc->amr_pass = child;
267     if (child != NULL) {
268         device_set_softc(child, sc);
269         device_set_desc(child, "SCSI Passthrough Bus");
270         bus_generic_attach(sc->amr_dev);
271     }
272
273     /*
274      * Create the control device.
275      */
276     sc->amr_dev_t = make_dev(&amr_ops, device_get_unit(sc->amr_dev), UID_ROOT, GID_OPERATOR,
277                              S_IRUSR | S_IWUSR, "amr%d", device_get_unit(sc->amr_dev));
278     sc->amr_dev_t->si_drv1 = sc;
279     linux_no_adapter++;
280     if (device_get_unit(sc->amr_dev) == 0)
281         make_dev_alias(sc->amr_dev_t, "megadev0");
282
283     /*
284      * Schedule ourselves to bring the controller up once interrupts are
285      * available.
286      */
287     bzero(&sc->amr_ich, sizeof(struct intr_config_hook));
288     sc->amr_ich.ich_func = amr_startup;
289     sc->amr_ich.ich_arg = sc;
290     if (config_intrhook_establish(&sc->amr_ich) != 0) {
291         device_printf(sc->amr_dev, "can't establish configuration hook\n");
292         return(ENOMEM);
293     }
294
295     /*
296      * Print a little information about the controller.
297      */
298     amr_describe_controller(sc);
299
300     debug(2, "attach complete");
301     return(0);
302 }
303
304 /********************************************************************************
305  * Locate disk resources and attach children to them.
306  */
307 static void
308 amr_startup(void *arg)
309 {
310     struct amr_softc    *sc = (struct amr_softc *)arg;
311     struct amr_logdrive *dr;
312     int                 i, error;
313     
314     debug_called(1);
315     callout_init(&sc->amr_timeout);
316
317     /* pull ourselves off the intrhook chain */
318     if (sc->amr_ich.ich_func)
319         config_intrhook_disestablish(&sc->amr_ich);
320     sc->amr_ich.ich_func = NULL;
321
322     /* get up-to-date drive information */
323     if (amr_query_controller(sc)) {
324         device_printf(sc->amr_dev, "can't scan controller for drives\n");
325         return;
326     }
327
328     /* iterate over available drives */
329     for (i = 0, dr = &sc->amr_drive[0]; (i < AMR_MAXLD) && (dr->al_size != 0xffffffff); i++, dr++) {
330         /* are we already attached to this drive? */
331         if (dr->al_disk == 0) {
332             /* generate geometry information */
333             if (dr->al_size > 0x200000) {       /* extended translation? */
334                 dr->al_heads = 255;
335                 dr->al_sectors = 63;
336             } else {
337                 dr->al_heads = 64;
338                 dr->al_sectors = 32;
339             }
340             dr->al_cylinders = dr->al_size / (dr->al_heads * dr->al_sectors);
341             
342             dr->al_disk = device_add_child(sc->amr_dev, NULL, -1);
343             if (dr->al_disk == 0)
344                 device_printf(sc->amr_dev, "device_add_child failed\n");
345             device_set_ivars(dr->al_disk, dr);
346         }
347     }
348     
349     if ((error = bus_generic_attach(sc->amr_dev)) != 0)
350         device_printf(sc->amr_dev, "bus_generic_attach returned %d\n", error);
351     
352     /* mark controller back up */
353     sc->amr_state &= ~AMR_STATE_SHUTDOWN;
354
355     /* interrupts will be enabled before we do anything more */
356     sc->amr_state |= AMR_STATE_INTEN;
357
358 #if 0
359     /*
360      * Start the timeout routine.
361      */
362     sc->amr_timeout = timeout(amr_periodic, sc, hz);
363 #endif
364
365     return;
366 }
367
368 static void
369 amr_init_sysctl(struct amr_softc *sc)
370 {
371
372     SYSCTL_ADD_INT(&sc->amr_sysctl_ctx,
373         SYSCTL_CHILDREN(sc->amr_sysctl_tree),
374         OID_AUTO, "allow_volume_configure", CTLFLAG_RW, &sc->amr_allow_vol_config, 0,
375         "");
376     SYSCTL_ADD_INT(&sc->amr_sysctl_ctx,
377         SYSCTL_CHILDREN(sc->amr_sysctl_tree),
378         OID_AUTO, "nextslot", CTLFLAG_RD, &sc->amr_nextslot, 0,
379         "");
380     SYSCTL_ADD_INT(&sc->amr_sysctl_ctx,
381         SYSCTL_CHILDREN(sc->amr_sysctl_tree),
382         OID_AUTO, "busyslots", CTLFLAG_RD, &sc->amr_busyslots, 0,
383         "");
384     SYSCTL_ADD_INT(&sc->amr_sysctl_ctx,
385         SYSCTL_CHILDREN(sc->amr_sysctl_tree),
386         OID_AUTO, "maxio", CTLFLAG_RD, &sc->amr_maxio, 0,
387         "");
388 }
389
390
391 /*******************************************************************************
392  * Free resources associated with a controller instance
393  */
394 void
395 amr_free(struct amr_softc *sc)
396 {
397     struct amr_command_cluster  *acc;
398
399     /* detach from CAM */
400     if (sc->amr_pass != NULL)
401         device_delete_child(sc->amr_dev, sc->amr_pass);
402
403     /* cancel status timeout */
404     callout_stop(&sc->amr_timeout);
405     
406     /* throw away any command buffers */
407     while ((acc = TAILQ_FIRST(&sc->amr_cmd_clusters)) != NULL) {
408         TAILQ_REMOVE(&sc->amr_cmd_clusters, acc, acc_link);
409         amr_freecmd_cluster(acc);
410     }
411
412     /* destroy control device */
413     if(sc->amr_dev_t != NULL)
414             destroy_dev(sc->amr_dev_t);
415     dev_ops_remove_minor(&amr_ops, device_get_unit(sc->amr_dev));
416
417 #if 0 /* XXX swildner */
418     if (mtx_initialized(&sc->amr_hw_lock))
419         mtx_destroy(&sc->amr_hw_lock);
420
421     if (mtx_initialized(&sc->amr_list_lock))
422         mtx_destroy(&sc->amr_list_lock);
423 #endif
424
425     if (sc->amr_sysctl_tree != NULL)
426             sysctl_ctx_free(&sc->amr_sysctl_ctx);
427
428     lockuninit(&sc->amr_hw_lock);
429     lockuninit(&sc->amr_list_lock);
430 }
431
432 /*******************************************************************************
433  * Receive a bio structure from a child device and queue it on a particular
434  * disk resource, then poke the disk resource to start as much work as it can.
435  */
436 int
437 amr_submit_bio(struct amr_softc *sc, struct bio *bio)
438 {
439     debug_called(2);
440
441     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
442     amr_enqueue_bio(sc, bio);
443     amr_startio(sc);
444     lockmgr(&sc->amr_list_lock, LK_RELEASE);
445     return(0);
446 }
447
448 /********************************************************************************
449  * Accept an open operation on the control device.
450  */
451 static int
452 amr_open(struct dev_open_args *ap)
453 {
454     cdev_t              dev = ap->a_head.a_dev;
455     int                 unit = minor(dev);
456     struct amr_softc    *sc = devclass_get_softc(devclass_find("amr"), unit);
457
458     debug_called(1);
459
460     sc->amr_state |= AMR_STATE_OPEN;
461     return(0);
462 }
463
464 /********************************************************************************
465  * Accept the last close on the control device.
466  */
467 static int
468 amr_close(struct dev_close_args *ap)
469 {
470     cdev_t              dev = ap->a_head.a_dev;
471     int                 unit = minor(dev);
472     struct amr_softc    *sc = devclass_get_softc(devclass_find("amr"), unit);
473
474     debug_called(1);
475
476     sc->amr_state &= ~AMR_STATE_OPEN;
477     return (0);
478 }
479
480 /********************************************************************************
481  * Handle controller-specific control operations.
482  */
483 static void
484 amr_rescan_drives(struct cdev *dev)
485 {
486     struct amr_softc    *sc = (struct amr_softc *)dev->si_drv1;
487     int                 i, error = 0;
488
489     sc->amr_state |= AMR_STATE_REMAP_LD;
490     while (sc->amr_busyslots) {
491         device_printf(sc->amr_dev, "idle controller\n");
492         amr_done(sc);
493     }
494
495     /* mark ourselves as in-shutdown */
496     sc->amr_state |= AMR_STATE_SHUTDOWN;
497
498     /* flush controller */
499     device_printf(sc->amr_dev, "flushing cache...");
500     kprintf("%s\n", amr_flush(sc) ? "failed" : "done");
501
502     /* delete all our child devices */
503     for(i = 0 ; i < AMR_MAXLD; i++) {
504         if(sc->amr_drive[i].al_disk != 0) {
505             if((error = device_delete_child(sc->amr_dev,
506                 sc->amr_drive[i].al_disk)) != 0)
507                 goto shutdown_out;
508
509              sc->amr_drive[i].al_disk = 0;
510         }
511     }
512
513 shutdown_out:
514     amr_startup(sc);
515 }
516
517 /*
518  * Bug-for-bug compatibility with Linux!
519  * Some apps will send commands with inlen and outlen set to 0,
520  * even though they expect data to be transfered to them from the
521  * card.  Linux accidentally allows this by allocating a 4KB
522  * buffer for the transfer anyways, but it then throws it away
523  * without copying it back to the app.
524  *
525  * The amr(4) firmware relies on this feature.  In fact, it assumes
526  * the buffer is always a power of 2 up to a max of 64k.  There is
527  * also at least one case where it assumes a buffer less than 16k is
528  * greater than 16k.  Force a minimum buffer size of 32k and round
529  * sizes between 32k and 64k up to 64k as a workaround.
530  */
531 static unsigned long
532 amr_ioctl_buffer_length(unsigned long len)
533 {
534
535     if (len <= 32 * 1024)
536         return (32 * 1024);
537     if (len <= 64 * 1024)
538         return (64 * 1024);
539     return (len);
540 }
541
542 int
543 amr_linux_ioctl_int(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag,
544     struct sysmsg *sm)
545 {
546     struct amr_softc            *sc = (struct amr_softc *)dev->si_drv1;
547     struct amr_command          *ac;
548     struct amr_mailbox          *mb;
549     struct amr_linux_ioctl      ali;
550     void                        *dp, *temp;
551     int                         error;
552     int                         adapter, len, ac_flags = 0;
553     int                         logical_drives_changed = 0;
554     u_int32_t                   linux_version = 0x02100000;
555     u_int8_t                    status;
556     struct amr_passthrough      *ap;    /* 60 bytes */
557
558     error = 0;
559     dp = NULL;
560     ac = NULL;
561     ap = NULL;
562
563     if ((error = copyin(addr, &ali, sizeof(ali))) != 0)
564         return (error);
565     switch (ali.ui.fcs.opcode) {
566     case 0x82:
567         switch(ali.ui.fcs.subopcode) {
568         case 'e':
569             copyout(&linux_version, (void *)(uintptr_t)ali.data,
570                 sizeof(linux_version));
571             error = 0;
572             break;
573
574         case 'm':
575             copyout(&linux_no_adapter, (void *)(uintptr_t)ali.data,
576                 sizeof(linux_no_adapter));
577             sm->sm_result.iresult = linux_no_adapter;
578             error = 0;
579             break;
580
581         default:
582             kprintf("Unknown subopcode\n");
583             error = ENOIOCTL;
584             break;
585         }
586     break;
587
588     case 0x80:
589     case 0x81:
590         if (ali.ui.fcs.opcode == 0x80)
591             len = max(ali.outlen, ali.inlen);
592         else
593             len = ali.ui.fcs.length;
594
595         adapter = (ali.ui.fcs.adapno) ^ 'm' << 8;
596
597         mb = (void *)&ali.mbox[0];
598
599         if ((ali.mbox[0] == FC_DEL_LOGDRV  && ali.mbox[2] == OP_DEL_LOGDRV) ||  /* delete */
600             (ali.mbox[0] == AMR_CMD_CONFIG && ali.mbox[2] == 0x0d)) {           /* create */
601             if (sc->amr_allow_vol_config == 0) {
602                 error = EPERM;
603                 break;
604             }
605             logical_drives_changed = 1;
606         }
607
608         if (ali.mbox[0] == AMR_CMD_PASS) {
609             lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
610             while ((ac = amr_alloccmd(sc)) == NULL)
611                 lksleep(sc, &sc->amr_list_lock, 0, "amrioc", hz);
612             lockmgr(&sc->amr_list_lock, LK_RELEASE);
613             ap = &ac->ac_ccb->ccb_pthru;
614
615             error = copyin((void *)(uintptr_t)mb->mb_physaddr, ap,
616                 sizeof(struct amr_passthrough));
617             if (error)
618                 break;
619
620             if (ap->ap_data_transfer_length)
621                 dp = kmalloc(ap->ap_data_transfer_length, M_AMR,
622                     M_WAITOK | M_ZERO);
623
624             if (ali.inlen) {
625                 error = copyin((void *)(uintptr_t)ap->ap_data_transfer_address,
626                     dp, ap->ap_data_transfer_length);
627                 if (error)
628                     break;
629             }
630
631             ac_flags = AMR_CMD_DATAIN|AMR_CMD_DATAOUT|AMR_CMD_CCB;
632             bzero(&ac->ac_mailbox, sizeof(ac->ac_mailbox));
633             ac->ac_mailbox.mb_command = AMR_CMD_PASS;
634             ac->ac_flags = ac_flags;
635
636             ac->ac_data = dp;
637             ac->ac_length = ap->ap_data_transfer_length;
638             temp = (void *)(uintptr_t)ap->ap_data_transfer_address;
639
640             lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
641             error = amr_wait_command(ac);
642             lockmgr(&sc->amr_list_lock, LK_RELEASE);
643             if (error)
644                 break;
645
646             status = ac->ac_status;
647             error = copyout(&status, &((struct amr_passthrough *)(uintptr_t)mb->mb_physaddr)->ap_scsi_status, sizeof(status));
648             if (error)
649                 break;
650
651             if (ali.outlen) {
652                 error = copyout(dp, temp, ap->ap_data_transfer_length);
653                 if (error)
654                     break;
655             }
656             error = copyout(ap->ap_request_sense_area, ((struct amr_passthrough *)(uintptr_t)mb->mb_physaddr)->ap_request_sense_area, ap->ap_request_sense_length);
657             if (error)
658                 break;
659
660             error = 0;
661             break;
662         } else if (ali.mbox[0] == AMR_CMD_PASS_64) {
663             kprintf("No AMR_CMD_PASS_64\n");
664             error = ENOIOCTL;
665             break;
666         } else if (ali.mbox[0] == AMR_CMD_EXTPASS) {
667             kprintf("No AMR_CMD_EXTPASS\n");
668             error = ENOIOCTL;
669             break;
670         } else {
671             len = amr_ioctl_buffer_length(imax(ali.inlen, ali.outlen));
672
673             dp = kmalloc(len, M_AMR, M_WAITOK | M_ZERO);
674
675             if (ali.inlen) {
676                 error = copyin((void *)(uintptr_t)mb->mb_physaddr, dp, len);
677                 if (error)
678                     break;
679             }
680
681             lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
682             while ((ac = amr_alloccmd(sc)) == NULL)
683                 lksleep(sc, &sc->amr_list_lock, 0, "amrioc", hz);
684
685             ac_flags = AMR_CMD_DATAIN|AMR_CMD_DATAOUT;
686             bzero(&ac->ac_mailbox, sizeof(ac->ac_mailbox));
687             bcopy(&ali.mbox[0], &ac->ac_mailbox, sizeof(ali.mbox));
688
689             ac->ac_length = len;
690             ac->ac_data = dp;
691             ac->ac_flags = ac_flags;
692
693             error = amr_wait_command(ac);
694             lockmgr(&sc->amr_list_lock, LK_RELEASE);
695             if (error)
696                 break;
697
698             status = ac->ac_status;
699             error = copyout(&status, &((struct amr_mailbox *)&((struct amr_linux_ioctl *)addr)->mbox[0])->mb_status, sizeof(status));
700             if (ali.outlen) {
701                 error = copyout(dp, (void *)(uintptr_t)mb->mb_physaddr, ali.outlen);
702                 if (error)
703                     break;
704             }
705
706             error = 0;
707             if (logical_drives_changed)
708                 amr_rescan_drives(dev);
709             break;
710         }
711         break;
712
713     default:
714         debug(1, "unknown linux ioctl 0x%lx", cmd);
715         kprintf("unknown linux ioctl 0x%lx\n", cmd);
716         error = ENOIOCTL;
717         break;
718     }
719
720     /*
721      * At this point, we know that there is a lock held and that these
722      * objects have been allocated.
723      */
724     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
725     if (ac != NULL)
726         amr_releasecmd(ac);
727     lockmgr(&sc->amr_list_lock, LK_RELEASE);
728     if (dp != NULL)
729         kfree(dp, M_AMR);
730     return(error);
731 }
732
733 static int
734 amr_ioctl(struct dev_ioctl_args *ap)
735 {
736     cdev_t                      dev = ap->a_head.a_dev;
737     caddr_t                     addr = ap->a_data;
738     u_long                      cmd = ap->a_cmd;
739     struct amr_softc            *sc = (struct amr_softc *)dev->si_drv1;
740     union {
741         void                    *_p;
742         struct amr_user_ioctl   *au;
743 #ifdef AMR_IO_COMMAND32
744         struct amr_user_ioctl32 *au32;
745 #endif
746         int                     *result;
747     } arg;
748     struct amr_command          *ac;
749     struct amr_mailbox_ioctl    *mbi;
750     void                        *dp, *au_buffer;
751     unsigned long               au_length, real_length;
752     unsigned char               *au_cmd;
753     int                         *au_statusp, au_direction;
754     int                         error;
755     struct amr_passthrough      *_ap;   /* 60 bytes */
756     int                         logical_drives_changed = 0;
757
758     debug_called(1);
759
760     arg._p = (void *)addr;
761
762     error = 0;
763     dp = NULL;
764     ac = NULL;
765     _ap = NULL;
766
767     switch(cmd) {
768
769     case AMR_IO_VERSION:
770         debug(1, "AMR_IO_VERSION");
771         *arg.result = AMR_IO_VERSION_NUMBER;
772         return(0);
773
774 #ifdef AMR_IO_COMMAND32
775     /*
776      * Accept ioctl-s from 32-bit binaries on non-32-bit
777      * platforms, such as AMD. LSI's MEGAMGR utility is
778      * the only example known today...  -mi
779      */
780     case AMR_IO_COMMAND32:
781         debug(1, "AMR_IO_COMMAND32 0x%x", arg.au32->au_cmd[0]);
782         au_cmd = arg.au32->au_cmd;
783         au_buffer = (void *)(u_int64_t)arg.au32->au_buffer;
784         au_length = arg.au32->au_length;
785         au_direction = arg.au32->au_direction;
786         au_statusp = &arg.au32->au_status;
787         break;
788 #endif
789
790     case AMR_IO_COMMAND:
791         debug(1, "AMR_IO_COMMAND  0x%x", arg.au->au_cmd[0]);
792         au_cmd = arg.au->au_cmd;
793         au_buffer = (void *)arg.au->au_buffer;
794         au_length = arg.au->au_length;
795         au_direction = arg.au->au_direction;
796         au_statusp = &arg.au->au_status;
797         break;
798
799     case 0xc0046d00:
800     case 0xc06e6d00:    /* Linux emulation */
801         {
802             devclass_t                  devclass;
803             struct amr_linux_ioctl      ali;
804             int                         adapter, error;
805
806             devclass = devclass_find("amr");
807             if (devclass == NULL)
808                 return (ENOENT);
809
810             error = copyin(addr, &ali, sizeof(ali));
811             if (error)
812                 return (error);
813             if (ali.ui.fcs.opcode == 0x82)
814                 adapter = 0;
815             else
816                 adapter = (ali.ui.fcs.adapno) ^ 'm' << 8;
817
818             sc = devclass_get_softc(devclass, adapter);
819             if (sc == NULL)
820                 return (ENOENT);
821
822             return (amr_linux_ioctl_int(sc->amr_dev_t, cmd, addr, 0, ap->a_sysmsg));
823         }
824     default:
825         debug(1, "unknown ioctl 0x%lx", cmd);
826         return(ENOIOCTL);
827     }
828
829     if ((au_cmd[0] == FC_DEL_LOGDRV && au_cmd[1] == OP_DEL_LOGDRV) ||   /* delete */
830         (au_cmd[0] == AMR_CMD_CONFIG && au_cmd[1] == 0x0d)) {           /* create */
831         if (sc->amr_allow_vol_config == 0) {
832             error = EPERM;
833             goto out;
834         }
835         logical_drives_changed = 1;
836     }
837
838     /* handle inbound data buffer */
839     real_length = amr_ioctl_buffer_length(au_length);
840     if (au_length != 0 && au_cmd[0] != 0x06) {
841         if ((dp = kmalloc(real_length, M_AMR, M_WAITOK|M_ZERO)) == NULL) {
842             error = ENOMEM;
843             goto out;
844         }
845         if ((error = copyin(au_buffer, dp, au_length)) != 0) {
846             kfree(dp, M_AMR);
847             return (error);
848         }
849         debug(2, "copyin %ld bytes from %p -> %p", au_length, au_buffer, dp);
850     }
851
852     /* Allocate this now before the mutex gets held */
853
854     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
855     while ((ac = amr_alloccmd(sc)) == NULL)
856         lksleep(sc, &sc->amr_list_lock, 0, "amrioc", hz);
857
858     /* handle SCSI passthrough command */
859     if (au_cmd[0] == AMR_CMD_PASS) {
860         int len;
861
862         _ap = &ac->ac_ccb->ccb_pthru;
863         bzero(_ap, sizeof(struct amr_passthrough));
864
865         /* copy cdb */
866         len = au_cmd[2];
867         _ap->ap_cdb_length = len;
868         bcopy(au_cmd + 3, _ap->ap_cdb, len);
869
870         /* build passthrough */
871         _ap->ap_timeout         = au_cmd[len + 3] & 0x07;
872         _ap->ap_ars             = (au_cmd[len + 3] & 0x08) ? 1 : 0;
873         _ap->ap_islogical       = (au_cmd[len + 3] & 0x80) ? 1 : 0;
874         _ap->ap_logical_drive_no = au_cmd[len + 4];
875         _ap->ap_channel         = au_cmd[len + 5];
876         _ap->ap_scsi_id         = au_cmd[len + 6];
877         _ap->ap_request_sense_length    = 14;
878         _ap->ap_data_transfer_length    = au_length;
879         /* XXX what about the request-sense area? does the caller want it? */
880
881         /* build command */
882         ac->ac_mailbox.mb_command = AMR_CMD_PASS;
883         ac->ac_flags = AMR_CMD_CCB;
884
885     } else {
886         /* direct command to controller */
887         mbi = (struct amr_mailbox_ioctl *)&ac->ac_mailbox;
888
889         /* copy pertinent mailbox items */
890         mbi->mb_command = au_cmd[0];
891         mbi->mb_channel = au_cmd[1];
892         mbi->mb_param = au_cmd[2];
893         mbi->mb_pad[0] = au_cmd[3];
894         mbi->mb_drive = au_cmd[4];
895         ac->ac_flags = 0;
896     }
897
898     /* build the command */
899     ac->ac_data = dp;
900     ac->ac_length = real_length;
901     ac->ac_flags |= AMR_CMD_DATAIN|AMR_CMD_DATAOUT;
902
903     /* run the command */
904     error = amr_wait_command(ac);
905     lockmgr(&sc->amr_list_lock, LK_RELEASE);
906     if (error)
907         goto out;
908
909     /* copy out data and set status */
910     if (au_length != 0) {
911         error = copyout(dp, au_buffer, au_length);
912     }
913     debug(2, "copyout %ld bytes from %p -> %p", au_length, dp, au_buffer);
914     if (dp != NULL)
915         debug(2, "%p status 0x%x", dp, ac->ac_status);
916     *au_statusp = ac->ac_status;
917
918 out:
919     /*
920      * At this point, we know that there is a lock held and that these
921      * objects have been allocated.
922      */
923     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
924     if (ac != NULL)
925         amr_releasecmd(ac);
926     lockmgr(&sc->amr_list_lock, LK_RELEASE);
927     if (dp != NULL)
928         kfree(dp, M_AMR);
929
930     if (logical_drives_changed)
931         amr_rescan_drives(dev);
932
933     return(error);
934 }
935
936 #if 0
937 /********************************************************************************
938  ********************************************************************************
939                                                                 Status Monitoring
940  ********************************************************************************
941  ********************************************************************************/
942
943 /********************************************************************************
944  * Perform a periodic check of the controller status
945  */
946 static void
947 amr_periodic(void *data)
948 {
949     struct amr_softc    *sc = (struct amr_softc *)data;
950
951     debug_called(2);
952
953     /* XXX perform periodic status checks here */
954
955     /* compensate for missed interrupts */
956     amr_done(sc);
957
958     /* reschedule */
959     callout_reset(&sc->amr_timeout, hz, amr_periodic, sc);
960 }
961 #endif
962
963 /********************************************************************************
964  ********************************************************************************
965                                                                  Command Wrappers
966  ********************************************************************************
967  ********************************************************************************/
968
969 /********************************************************************************
970  * Interrogate the controller for the operational parameters we require.
971  */
972 static int
973 amr_query_controller(struct amr_softc *sc)
974 {
975     struct amr_enquiry3 *aex;
976     struct amr_prodinfo *ap;
977     struct amr_enquiry  *ae;
978     int                 ldrv;
979     int                 status;
980
981     /*
982      * Greater than 10 byte cdb support
983      */
984     sc->support_ext_cdb = amr_support_ext_cdb(sc);
985
986     if(sc->support_ext_cdb) {
987         debug(2,"supports extended CDBs.");
988     }
989
990     /* 
991      * Try to issue an ENQUIRY3 command 
992      */
993     if ((aex = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_ENQ3, 
994                            AMR_CONFIG_ENQ3_SOLICITED_FULL, &status)) != NULL) {
995
996         /*
997          * Fetch current state of logical drives.
998          */
999         for (ldrv = 0; ldrv < aex->ae_numldrives; ldrv++) {
1000             sc->amr_drive[ldrv].al_size       = aex->ae_drivesize[ldrv];
1001             sc->amr_drive[ldrv].al_state      = aex->ae_drivestate[ldrv];
1002             sc->amr_drive[ldrv].al_properties = aex->ae_driveprop[ldrv];
1003             debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
1004                   sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
1005         }
1006         kfree(aex, M_AMR);
1007
1008         /*
1009          * Get product info for channel count.
1010          */
1011         if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0, &status)) == NULL) {
1012             device_printf(sc->amr_dev, "can't obtain product data from controller\n");
1013             return(1);
1014         }
1015         sc->amr_maxdrives = 40;
1016         sc->amr_maxchan = ap->ap_nschan;
1017         sc->amr_maxio = ap->ap_maxio;
1018         sc->amr_type |= AMR_TYPE_40LD;
1019         kfree(ap, M_AMR);
1020
1021         ap = amr_enquiry(sc, 0, FC_DEL_LOGDRV, OP_SUP_DEL_LOGDRV, 0, &status);
1022         if (ap != NULL)
1023             kfree(ap, M_AMR);
1024         if (!status) {
1025             sc->amr_ld_del_supported = 1;
1026             device_printf(sc->amr_dev, "delete logical drives supported by controller\n");
1027         }
1028     } else {
1029
1030         /* failed, try the 8LD ENQUIRY commands */
1031         if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0, &status)) == NULL) {
1032             if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0, &status)) == NULL) {
1033                 device_printf(sc->amr_dev, "can't obtain configuration data from controller\n");
1034                 return(1);
1035             }
1036             ae->ae_signature = 0;
1037         }
1038
1039         /*
1040          * Fetch current state of logical drives.
1041          */
1042         for (ldrv = 0; ldrv < ae->ae_ldrv.al_numdrives; ldrv++) {
1043             sc->amr_drive[ldrv].al_size       = ae->ae_ldrv.al_size[ldrv];
1044             sc->amr_drive[ldrv].al_state      = ae->ae_ldrv.al_state[ldrv];
1045             sc->amr_drive[ldrv].al_properties = ae->ae_ldrv.al_properties[ldrv];
1046             debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
1047                   sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
1048         }
1049
1050         sc->amr_maxdrives = 8;
1051         sc->amr_maxchan = ae->ae_adapter.aa_channels;
1052         sc->amr_maxio = ae->ae_adapter.aa_maxio;
1053         kfree(ae, M_AMR);
1054     }
1055
1056     /*
1057      * Mark remaining drives as unused.
1058      */
1059     for (; ldrv < AMR_MAXLD; ldrv++)
1060         sc->amr_drive[ldrv].al_size = 0xffffffff;
1061
1062     /* 
1063      * Cap the maximum number of outstanding I/Os.  AMI's Linux driver doesn't trust
1064      * the controller's reported value, and lockups have been seen when we do.
1065      */
1066     sc->amr_maxio = imin(sc->amr_maxio, AMR_LIMITCMD);
1067
1068     return(0);
1069 }
1070
1071 /********************************************************************************
1072  * Run a generic enquiry-style command.
1073  */
1074 static void *
1075 amr_enquiry(struct amr_softc *sc, size_t bufsize, u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual, int *status)
1076 {
1077     struct amr_command  *ac;
1078     void                *result;
1079     u_int8_t            *mbox;
1080     int                 error;
1081
1082     debug_called(1);
1083
1084     error = 1;
1085     result = NULL;
1086     
1087     /* get ourselves a command buffer */
1088     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1089     ac = amr_alloccmd(sc);
1090     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1091     if (ac == NULL)
1092         goto out;
1093     /* allocate the response structure */
1094     if ((result = kmalloc(bufsize, M_AMR, M_ZERO|M_NOWAIT)) == NULL)
1095         goto out;
1096     /* set command flags */
1097
1098     ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAIN;
1099     
1100     /* point the command at our data */
1101     ac->ac_data = result;
1102     ac->ac_length = bufsize;
1103     
1104     /* build the command proper */
1105     mbox = (u_int8_t *)&ac->ac_mailbox;         /* XXX want a real structure for this? */
1106     mbox[0] = cmd;
1107     mbox[2] = cmdsub;
1108     mbox[3] = cmdqual;
1109     *status = 0;
1110
1111     /* can't assume that interrupts are going to work here, so play it safe */
1112     if (sc->amr_poll_command(ac))
1113         goto out;
1114     error = ac->ac_status;
1115     *status = ac->ac_status;
1116     
1117  out:
1118     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1119     if (ac != NULL)
1120         amr_releasecmd(ac);
1121     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1122     if ((error != 0) && (result != NULL)) {
1123         kfree(result, M_AMR);
1124         result = NULL;
1125     }
1126     return(result);
1127 }
1128
1129 /********************************************************************************
1130  * Flush the controller's internal cache, return status.
1131  */
1132 int
1133 amr_flush(struct amr_softc *sc)
1134 {
1135     struct amr_command  *ac;
1136     int                 error;
1137
1138     /* get ourselves a command buffer */
1139     error = 1;
1140     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1141     ac = amr_alloccmd(sc);
1142     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1143     if (ac == NULL)
1144         goto out;
1145     /* set command flags */
1146     ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
1147     
1148     /* build the command proper */
1149     ac->ac_mailbox.mb_command = AMR_CMD_FLUSH;
1150
1151     /* we have to poll, as the system may be going down or otherwise damaged */
1152     if (sc->amr_poll_command(ac))
1153         goto out;
1154     error = ac->ac_status;
1155     
1156  out:
1157     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1158     if (ac != NULL)
1159         amr_releasecmd(ac);
1160     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1161     return(error);
1162 }
1163
1164 /********************************************************************************
1165  * Detect extented cdb >> greater than 10 byte cdb support
1166  * returns '1' means this support exist
1167  * returns '0' means this support doesn't exist
1168  */
1169 static int
1170 amr_support_ext_cdb(struct amr_softc *sc)
1171 {
1172     struct amr_command  *ac;
1173     u_int8_t            *mbox;
1174     int                 error;
1175
1176     /* get ourselves a command buffer */
1177     error = 0;
1178     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1179     ac = amr_alloccmd(sc);
1180     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1181     if (ac == NULL)
1182         goto out;
1183     /* set command flags */
1184     ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
1185
1186     /* build the command proper */
1187     mbox = (u_int8_t *)&ac->ac_mailbox;         /* XXX want a real structure for this? */
1188     mbox[0] = 0xA4;
1189     mbox[2] = 0x16;
1190
1191
1192     /* we have to poll, as the system may be going down or otherwise damaged */
1193     if (sc->amr_poll_command(ac))
1194         goto out;
1195     if( ac->ac_status == AMR_STATUS_SUCCESS ) {
1196             error = 1;
1197     }
1198
1199 out:
1200     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1201     if (ac != NULL)
1202         amr_releasecmd(ac);
1203     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1204     return(error);
1205 }
1206
1207 /********************************************************************************
1208  * Try to find I/O work for the controller from one or more of the work queues.
1209  *
1210  * We make the assumption that if the controller is not ready to take a command
1211  * at some given time, it will generate an interrupt at some later time when
1212  * it is.
1213  */
1214 void
1215 amr_startio(struct amr_softc *sc)
1216 {
1217     struct amr_command  *ac;
1218
1219     /* spin until something prevents us from doing any work */
1220     for (;;) {
1221
1222         /* Don't bother to queue commands no bounce buffers are available. */
1223         if (sc->amr_state & AMR_STATE_QUEUE_FRZN)
1224             break;
1225
1226         /* try to get a ready command */
1227         ac = amr_dequeue_ready(sc);
1228
1229         /* if that failed, build a command from a bio */
1230         if (ac == NULL)
1231             (void)amr_bio_command(sc, &ac);
1232
1233         /* if that failed, build a command from a ccb */
1234         if ((ac == NULL) && (sc->amr_cam_command != NULL))
1235             sc->amr_cam_command(sc, &ac);
1236
1237         /* if we don't have anything to do, give up */
1238         if (ac == NULL)
1239             break;
1240
1241         /* try to give the command to the controller; if this fails save it for later and give up */
1242         if (amr_start(ac)) {
1243             debug(2, "controller busy, command deferred");
1244             amr_requeue_ready(ac);      /* XXX schedule retry very soon? */
1245             break;
1246         }
1247     }
1248 }
1249
1250 /********************************************************************************
1251  * Handle completion of an I/O command.
1252  */
1253 static void
1254 amr_completeio(struct amr_command *ac)
1255 {
1256     struct amr_softc            *sc = ac->ac_sc;
1257     static struct timeval       lastfail;
1258     static int                  curfail;
1259     struct buf                  *bp = ac->ac_bio->bio_buf;
1260
1261     if (ac->ac_status != AMR_STATUS_SUCCESS) {  /* could be more verbose here? */
1262         bp->b_error = EIO;
1263         bp->b_flags |= B_ERROR;
1264
1265         if (ppsratecheck(&lastfail, &curfail, 1))
1266             device_printf(sc->amr_dev, "I/O error - 0x%x\n", ac->ac_status);
1267 /*      amr_printcommand(ac);*/
1268     }
1269     amrd_intr(ac->ac_bio);
1270     lockmgr(&ac->ac_sc->amr_list_lock, LK_EXCLUSIVE);
1271     amr_releasecmd(ac);
1272     lockmgr(&ac->ac_sc->amr_list_lock, LK_RELEASE);
1273 }
1274
1275 /********************************************************************************
1276  ********************************************************************************
1277                                                                Command Processing
1278  ********************************************************************************
1279  ********************************************************************************/
1280
1281 /********************************************************************************
1282  * Convert a bio off the top of the bio queue into a command.
1283  */
1284 static int
1285 amr_bio_command(struct amr_softc *sc, struct amr_command **acp)
1286 {
1287     struct amr_command  *ac;
1288     struct amrd_softc   *amrd;
1289     struct bio          *bio;
1290     struct buf          *bp;
1291     int                 error;
1292     int                 blkcount;
1293     int                 driveno;
1294     int                 cmd;
1295
1296     ac = NULL;
1297     error = 0;
1298
1299     /* get a command */
1300     if ((ac = amr_alloccmd(sc)) == NULL)
1301         return (ENOMEM);
1302
1303     /* get a bio to work on */
1304     if ((bio = amr_dequeue_bio(sc)) == NULL) {
1305         amr_releasecmd(ac);
1306         return (0);
1307     }
1308
1309     /* connect the bio to the command */
1310     bp = bio->bio_buf;
1311     ac->ac_complete = amr_completeio;
1312     ac->ac_bio = bio;
1313     ac->ac_data = bp->b_data;
1314     ac->ac_length = bp->b_bcount;
1315     cmd = 0;
1316     switch (bp->b_cmd) {
1317     case BUF_CMD_READ:
1318         ac->ac_flags |= AMR_CMD_DATAIN;
1319         if (AMR_IS_SG64(sc)) {
1320             cmd = AMR_CMD_LREAD64;
1321             ac->ac_flags |= AMR_CMD_SG64;
1322         } else
1323             cmd = AMR_CMD_LREAD;
1324         break;
1325     case BUF_CMD_WRITE:
1326         ac->ac_flags |= AMR_CMD_DATAOUT;
1327         if (AMR_IS_SG64(sc)) {
1328             cmd = AMR_CMD_LWRITE64;
1329             ac->ac_flags |= AMR_CMD_SG64;
1330         } else
1331             cmd = AMR_CMD_LWRITE;
1332         break;
1333     case BUF_CMD_FLUSH:
1334         ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
1335         cmd = AMR_CMD_FLUSH;
1336         break;
1337     default:
1338         panic("Invalid bio command");
1339     }
1340     amrd = (struct amrd_softc *)bio->bio_driver_info;
1341     driveno = amrd->amrd_drive - sc->amr_drive;
1342     blkcount = (bp->b_bcount + AMR_BLKSIZE - 1) / AMR_BLKSIZE;
1343
1344     ac->ac_mailbox.mb_command = cmd;
1345     if (bp->b_cmd & (BUF_CMD_READ|BUF_CMD_WRITE)) {
1346         ac->ac_mailbox.mb_blkcount = blkcount;
1347         ac->ac_mailbox.mb_lba = bio->bio_offset / AMR_BLKSIZE;
1348         if (((bio->bio_offset / AMR_BLKSIZE) + blkcount) > sc->amr_drive[driveno].al_size) {
1349             device_printf(sc->amr_dev,
1350                           "I/O beyond end of unit (%lld,%d > %lu)\n",
1351                           (long long)(bio->bio_offset / AMR_BLKSIZE), blkcount,
1352                           (u_long)sc->amr_drive[driveno].al_size);
1353         }
1354     }
1355     ac->ac_mailbox.mb_drive = driveno;
1356     if (sc->amr_state & AMR_STATE_REMAP_LD)
1357         ac->ac_mailbox.mb_drive |= 0x80;
1358
1359     /* we fill in the s/g related data when the command is mapped */
1360
1361
1362     *acp = ac;
1363     return(error);
1364 }
1365
1366 /********************************************************************************
1367  * Take a command, submit it to the controller and sleep until it completes
1368  * or fails.  Interrupts must be enabled, returns nonzero on error.
1369  */
1370 static int
1371 amr_wait_command(struct amr_command *ac)
1372 {
1373     int                 error = 0;
1374     struct amr_softc    *sc = ac->ac_sc;
1375
1376     debug_called(1);
1377
1378     ac->ac_complete = NULL;
1379     ac->ac_flags |= AMR_CMD_SLEEP;
1380     if ((error = amr_start(ac)) != 0) {
1381         return(error);
1382     }
1383     
1384     while ((ac->ac_flags & AMR_CMD_BUSY) && (error != EWOULDBLOCK)) {
1385         error = lksleep(ac,&sc->amr_list_lock, 0, "amrwcmd", 0);
1386     }
1387
1388     return(error);
1389 }
1390
1391 /********************************************************************************
1392  * Take a command, submit it to the controller and busy-wait for it to return.
1393  * Returns nonzero on error.  Can be safely called with interrupts enabled.
1394  */
1395 static int
1396 amr_std_poll_command(struct amr_command *ac)
1397 {
1398     struct amr_softc    *sc = ac->ac_sc;
1399     int                 error, count;
1400
1401     debug_called(2);
1402
1403     ac->ac_complete = NULL;
1404     if ((error = amr_start(ac)) != 0)
1405         return(error);
1406
1407     count = 0;
1408     do {
1409         /* 
1410          * Poll for completion, although the interrupt handler may beat us to it. 
1411          * Note that the timeout here is somewhat arbitrary.
1412          */
1413         amr_done(sc);
1414         DELAY(1000);
1415     } while ((ac->ac_flags & AMR_CMD_BUSY) && (count++ < 1000));
1416     if (!(ac->ac_flags & AMR_CMD_BUSY)) {
1417         error = 0;
1418     } else {
1419         /* XXX the slot is now marked permanently busy */
1420         error = EIO;
1421         device_printf(sc->amr_dev, "polled command timeout\n");
1422     }
1423     return(error);
1424 }
1425
1426 static void
1427 amr_setup_polled_dmamap(void *arg, bus_dma_segment_t *segs, int nsegs, int err)
1428 {
1429     struct amr_command *ac = arg;
1430     struct amr_softc *sc = ac->ac_sc;
1431     int mb_channel;
1432
1433     if (err) {
1434         device_printf(sc->amr_dev, "error %d in %s", err, __FUNCTION__);
1435         ac->ac_status = AMR_STATUS_ABORTED;
1436         return;
1437     }
1438
1439     amr_setup_sg(arg, segs, nsegs, err);
1440
1441     /* for AMR_CMD_CONFIG Read/Write the s/g count goes elsewhere */
1442     mb_channel = ((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_channel;
1443     if (ac->ac_mailbox.mb_command == AMR_CMD_CONFIG &&
1444         ((mb_channel == AMR_CONFIG_READ_NVRAM_CONFIG) ||
1445         (mb_channel == AMR_CONFIG_WRITE_NVRAM_CONFIG)))
1446         ((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_param = ac->ac_nsegments;
1447
1448     ac->ac_mailbox.mb_nsgelem = ac->ac_nsegments;
1449     ac->ac_mailbox.mb_physaddr = ac->ac_mb_physaddr;
1450     if (AC_IS_SG64(ac)) {
1451         ac->ac_sg64_hi = 0;
1452         ac->ac_sg64_lo = ac->ac_sgbusaddr;
1453     }
1454
1455     sc->amr_poll_command1(sc, ac);
1456 }
1457
1458 /********************************************************************************
1459  * Take a command, submit it to the controller and busy-wait for it to return.
1460  * Returns nonzero on error.  Can be safely called with interrupts enabled.
1461  */
1462 static int
1463 amr_quartz_poll_command(struct amr_command *ac)
1464 {
1465     struct amr_softc    *sc = ac->ac_sc;
1466     int                 error;
1467
1468     debug_called(2);
1469
1470     error = 0;
1471
1472     if (AC_IS_SG64(ac)) {
1473         ac->ac_tag = sc->amr_buffer64_dmat;
1474         ac->ac_datamap = ac->ac_dma64map;
1475     } else {
1476         ac->ac_tag = sc->amr_buffer_dmat;
1477         ac->ac_datamap = ac->ac_dmamap;
1478     }
1479
1480     /* now we have a slot, we can map the command (unmapped in amr_complete) */
1481     if (ac->ac_data != NULL && ac->ac_length != 0) {
1482         if (bus_dmamap_load(ac->ac_tag, ac->ac_datamap, ac->ac_data,
1483             ac->ac_length, amr_setup_polled_dmamap, ac, BUS_DMA_NOWAIT) != 0) {
1484             error = 1;
1485         }
1486     } else {
1487         error = amr_quartz_poll_command1(sc, ac);
1488     }
1489
1490     return (error);
1491 }
1492
1493 static int
1494 amr_quartz_poll_command1(struct amr_softc *sc, struct amr_command *ac)
1495 {
1496     int count, error;
1497
1498     lockmgr(&sc->amr_hw_lock, LK_EXCLUSIVE);
1499     if ((sc->amr_state & AMR_STATE_INTEN) == 0) {
1500         count=0;
1501         while (sc->amr_busyslots) {
1502             lksleep(sc, &sc->amr_hw_lock, PCATCH, "amrpoll", hz);
1503             if(count++>10) {
1504                 break;
1505             }
1506         }
1507
1508         if(sc->amr_busyslots) {
1509             device_printf(sc->amr_dev, "adapter is busy\n");
1510             lockmgr(&sc->amr_hw_lock, LK_RELEASE);
1511             if (ac->ac_data != NULL) {
1512                 bus_dmamap_unload(ac->ac_tag, ac->ac_datamap);
1513             }
1514             ac->ac_status=0;
1515             return(1);
1516         }
1517     }
1518
1519     bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, AMR_MBOX_CMDSIZE);
1520
1521     /* clear the poll/ack fields in the mailbox */
1522     sc->amr_mailbox->mb_ident = 0xFE;
1523     sc->amr_mailbox->mb_nstatus = 0xFF;
1524     sc->amr_mailbox->mb_status = 0xFF;
1525     sc->amr_mailbox->mb_poll = 0;
1526     sc->amr_mailbox->mb_ack = 0;
1527     sc->amr_mailbox->mb_busy = 1;
1528
1529     AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
1530
1531     while(sc->amr_mailbox->mb_nstatus == 0xFF)
1532         DELAY(1);
1533     while(sc->amr_mailbox->mb_status == 0xFF)
1534         DELAY(1);
1535     ac->ac_status=sc->amr_mailbox->mb_status;
1536     error = (ac->ac_status !=AMR_STATUS_SUCCESS) ? 1:0;
1537     while(sc->amr_mailbox->mb_poll != 0x77)
1538         DELAY(1);
1539     sc->amr_mailbox->mb_poll = 0;
1540     sc->amr_mailbox->mb_ack = 0x77;
1541
1542     /* acknowledge that we have the commands */
1543     AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_ACK);
1544     while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK)
1545         DELAY(1);
1546     lockmgr(&sc->amr_hw_lock, LK_RELEASE);
1547
1548     /* unmap the command's data buffer */
1549     if (ac->ac_flags & AMR_CMD_DATAIN) {
1550         bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, BUS_DMASYNC_POSTREAD);
1551     }
1552     if (ac->ac_flags & AMR_CMD_DATAOUT) {
1553         bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, BUS_DMASYNC_POSTWRITE);
1554     }
1555     bus_dmamap_unload(ac->ac_tag, ac->ac_datamap);
1556
1557     return(error);
1558 }
1559
1560 static __inline int
1561 amr_freeslot(struct amr_command *ac)
1562 {
1563     struct amr_softc *sc = ac->ac_sc;
1564     int                 slot;
1565
1566     debug_called(3);
1567
1568     slot = ac->ac_slot;
1569     if (sc->amr_busycmd[slot] == NULL)
1570         panic("amr: slot %d not busy?", slot);
1571
1572     sc->amr_busycmd[slot] = NULL;
1573     atomic_subtract_int(&sc->amr_busyslots, 1);
1574
1575     return (0);
1576 }
1577
1578 /********************************************************************************
1579  * Map/unmap (ac)'s data in the controller's addressable space as required.
1580  *
1581  * These functions may be safely called multiple times on a given command.
1582  */
1583 static void
1584 amr_setup_sg(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
1585 {
1586     struct amr_command  *ac = (struct amr_command *)arg;
1587     struct amr_sgentry  *sg;
1588     struct amr_sg64entry *sg64;
1589     int flags, i;
1590
1591     debug_called(3);
1592
1593     /* get base address of s/g table */
1594     sg = ac->ac_sg.sg32;
1595     sg64 = ac->ac_sg.sg64;
1596
1597     if (AC_IS_SG64(ac)) {
1598         ac->ac_nsegments = nsegments;
1599         ac->ac_mb_physaddr = 0xffffffff;
1600         for (i = 0; i < nsegments; i++, sg64++) {
1601             sg64->sg_addr = segs[i].ds_addr;
1602             sg64->sg_count = segs[i].ds_len;
1603         }
1604     } else {
1605         /* decide whether we need to populate the s/g table */
1606         if (nsegments < 2) {
1607             ac->ac_nsegments = 0;
1608             ac->ac_mb_physaddr = segs[0].ds_addr;
1609         } else {
1610             ac->ac_nsegments = nsegments;
1611             ac->ac_mb_physaddr = ac->ac_sgbusaddr;
1612             for (i = 0; i < nsegments; i++, sg++) {
1613                 sg->sg_addr = segs[i].ds_addr;
1614                 sg->sg_count = segs[i].ds_len;
1615             }
1616         }
1617     }
1618
1619     flags = 0;
1620     if (ac->ac_flags & AMR_CMD_DATAIN)
1621         flags |= BUS_DMASYNC_PREREAD;
1622     if (ac->ac_flags & AMR_CMD_DATAOUT)
1623         flags |= BUS_DMASYNC_PREWRITE;
1624     bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, flags);
1625     ac->ac_flags |= AMR_CMD_MAPPED;
1626 }
1627
1628 static void
1629 amr_setup_data(void *arg, bus_dma_segment_t *segs, int nsegs, int err)
1630 {
1631     struct amr_command *ac = arg;
1632     struct amr_softc *sc = ac->ac_sc;
1633     int mb_channel;
1634
1635     if (err) {
1636         device_printf(sc->amr_dev, "error %d in %s", err, __FUNCTION__);
1637         amr_abort_load(ac);
1638         return;
1639     }
1640
1641     amr_setup_sg(arg, segs, nsegs, err);
1642
1643     /* for AMR_CMD_CONFIG Read/Write the s/g count goes elsewhere */
1644     mb_channel = ((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_channel;
1645     if (ac->ac_mailbox.mb_command == AMR_CMD_CONFIG &&
1646         ((mb_channel == AMR_CONFIG_READ_NVRAM_CONFIG) ||
1647         (mb_channel == AMR_CONFIG_WRITE_NVRAM_CONFIG)))
1648         ((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_param = ac->ac_nsegments;
1649
1650     ac->ac_mailbox.mb_nsgelem = ac->ac_nsegments;
1651     ac->ac_mailbox.mb_physaddr = ac->ac_mb_physaddr;
1652     if (AC_IS_SG64(ac)) {
1653         ac->ac_sg64_hi = 0;
1654         ac->ac_sg64_lo = ac->ac_sgbusaddr;
1655     }
1656
1657     if (sc->amr_submit_command(ac) == EBUSY) {
1658         amr_freeslot(ac);
1659         amr_requeue_ready(ac);
1660     }
1661 }
1662
1663 static void
1664 amr_setup_ccb(void *arg, bus_dma_segment_t *segs, int nsegs, int err)
1665 {
1666     struct amr_command *ac = arg;
1667     struct amr_softc *sc = ac->ac_sc;
1668     struct amr_passthrough *ap = &ac->ac_ccb->ccb_pthru;
1669     struct amr_ext_passthrough *aep = &ac->ac_ccb->ccb_epthru;
1670
1671     if (err) {
1672         device_printf(sc->amr_dev, "error %d in %s", err, __FUNCTION__);
1673         amr_abort_load(ac);
1674         return;
1675     }
1676
1677     /* Set up the mailbox portion of the command to point at the ccb */
1678     ac->ac_mailbox.mb_nsgelem = 0;
1679     ac->ac_mailbox.mb_physaddr = ac->ac_ccb_busaddr;
1680
1681     amr_setup_sg(arg, segs, nsegs, err);
1682
1683     switch (ac->ac_mailbox.mb_command) {
1684     case AMR_CMD_EXTPASS:
1685         aep->ap_no_sg_elements = ac->ac_nsegments;
1686         aep->ap_data_transfer_address = ac->ac_mb_physaddr;
1687         break;
1688     case AMR_CMD_PASS:
1689         ap->ap_no_sg_elements = ac->ac_nsegments;
1690         ap->ap_data_transfer_address = ac->ac_mb_physaddr;
1691         break;
1692     default:
1693         panic("Unknown ccb command");
1694     }
1695
1696     if (sc->amr_submit_command(ac) == EBUSY) {
1697         amr_freeslot(ac);
1698         amr_requeue_ready(ac);
1699     }
1700 }
1701
1702 static int
1703 amr_mapcmd(struct amr_command *ac)
1704 {
1705     bus_dmamap_callback_t *cb;
1706     struct amr_softc    *sc = ac->ac_sc;
1707
1708     debug_called(3);
1709
1710     if (AC_IS_SG64(ac)) {
1711         ac->ac_tag = sc->amr_buffer64_dmat;
1712         ac->ac_datamap = ac->ac_dma64map;
1713     } else {
1714         ac->ac_tag = sc->amr_buffer_dmat;
1715         ac->ac_datamap = ac->ac_dmamap;
1716     }
1717
1718     if (ac->ac_flags & AMR_CMD_CCB)
1719         cb = amr_setup_ccb;
1720     else
1721         cb = amr_setup_data;
1722
1723     /* if the command involves data at all, and hasn't been mapped */
1724     if ((ac->ac_flags & AMR_CMD_MAPPED) == 0 && (ac->ac_data != NULL)) {
1725         /* map the data buffers into bus space and build the s/g list */
1726         if (bus_dmamap_load(ac->ac_tag, ac->ac_datamap, ac->ac_data,
1727              ac->ac_length, cb, ac, 0) == EINPROGRESS) {
1728             sc->amr_state |= AMR_STATE_QUEUE_FRZN;
1729         }
1730    } else {
1731         if (sc->amr_submit_command(ac) == EBUSY) {
1732             amr_freeslot(ac);
1733             amr_requeue_ready(ac);
1734         }
1735    }
1736
1737     return (0);
1738 }
1739
1740 static void
1741 amr_unmapcmd(struct amr_command *ac)
1742 {
1743     int                 flag;
1744
1745     debug_called(3);
1746
1747     /* if the command involved data at all and was mapped */
1748     if (ac->ac_flags & AMR_CMD_MAPPED) {
1749
1750         if (ac->ac_data != NULL) {
1751
1752             flag = 0;
1753             if (ac->ac_flags & AMR_CMD_DATAIN)
1754                 flag |= BUS_DMASYNC_POSTREAD;
1755             if (ac->ac_flags & AMR_CMD_DATAOUT)
1756                 flag |= BUS_DMASYNC_POSTWRITE;
1757
1758             bus_dmamap_sync(ac->ac_tag, ac->ac_datamap, flag);
1759             bus_dmamap_unload(ac->ac_tag, ac->ac_datamap);
1760         }
1761
1762         ac->ac_flags &= ~AMR_CMD_MAPPED;
1763     }
1764 }
1765
1766 static void
1767 amr_abort_load(struct amr_command *ac)
1768 {
1769     ac_qhead_t head;
1770     struct amr_softc *sc = ac->ac_sc;
1771
1772     KKASSERT(lockstatus(&sc->amr_list_lock, curthread) != 0);
1773
1774     ac->ac_status = AMR_STATUS_ABORTED;
1775     amr_init_qhead(&head);
1776     amr_enqueue_completed(ac, &head);
1777
1778     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1779     amr_complete(sc, &head);
1780     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1781 }
1782
1783 /********************************************************************************
1784  * Take a command and give it to the controller, returns 0 if successful, or
1785  * EBUSY if the command should be retried later.
1786  */
1787 static int
1788 amr_start(struct amr_command *ac)
1789 {
1790     struct amr_softc *sc;
1791     int error = 0;
1792     int slot;
1793
1794     debug_called(3);
1795
1796     /* mark command as busy so that polling consumer can tell */
1797     sc = ac->ac_sc;
1798     ac->ac_flags |= AMR_CMD_BUSY;
1799
1800     /* get a command slot (freed in amr_done) */
1801     slot = ac->ac_slot;
1802     if (sc->amr_busycmd[slot] != NULL)
1803         panic("amr: slot %d busy?", slot);
1804     sc->amr_busycmd[slot] = ac;
1805     atomic_add_int(&sc->amr_busyslots, 1);
1806
1807     /* Now we have a slot, we can map the command (unmapped in amr_complete). */
1808     if ((error = amr_mapcmd(ac)) == ENOMEM) {
1809         /*
1810          * Memroy resources are short, so free the slot and let this be tried
1811          * later.
1812          */
1813         amr_freeslot(ac);
1814     }
1815
1816     return (error);
1817 }
1818
1819 /********************************************************************************
1820  * Extract one or more completed commands from the controller (sc)
1821  *
1822  * Returns nonzero if any commands on the work queue were marked as completed.
1823  */
1824
1825 int
1826 amr_done(struct amr_softc *sc)
1827 {
1828     ac_qhead_t          head;
1829     struct amr_command  *ac;
1830     struct amr_mailbox  mbox;
1831     int                 i, idx, result;
1832     
1833     debug_called(3);
1834
1835     /* See if there's anything for us to do */
1836     result = 0;
1837     amr_init_qhead(&head);
1838
1839     /* loop collecting completed commands */
1840     for (;;) {
1841         /* poll for a completed command's identifier and status */
1842         if (sc->amr_get_work(sc, &mbox)) {
1843             result = 1;
1844             
1845             /* iterate over completed commands in this result */
1846             for (i = 0; i < mbox.mb_nstatus; i++) {
1847                 /* get pointer to busy command */
1848                 idx = mbox.mb_completed[i] - 1;
1849                 ac = sc->amr_busycmd[idx];
1850
1851                 /* really a busy command? */
1852                 if (ac != NULL) {
1853
1854                     /* pull the command from the busy index */
1855                     amr_freeslot(ac);
1856                 
1857                     /* save status for later use */
1858                     ac->ac_status = mbox.mb_status;
1859                     amr_enqueue_completed(ac, &head);
1860                     debug(3, "completed command with status %x", mbox.mb_status);
1861                 } else {
1862                     device_printf(sc->amr_dev, "bad slot %d completed\n", idx);
1863                 }
1864             }
1865         } else
1866             break;      /* no work */
1867     }
1868
1869     /* handle completion and timeouts */
1870     amr_complete(sc, &head);
1871
1872     return(result);
1873 }
1874
1875 /********************************************************************************
1876  * Do completion processing on done commands on (sc)
1877  */
1878
1879 static void
1880 amr_complete(void *context, ac_qhead_t *head)
1881 {
1882     struct amr_softc    *sc = (struct amr_softc *)context;
1883     struct amr_command  *ac;
1884
1885     debug_called(3);
1886
1887     /* pull completed commands off the queue */
1888     for (;;) {
1889         ac = amr_dequeue_completed(sc, head);
1890         if (ac == NULL)
1891             break;
1892
1893         /* unmap the command's data buffer */
1894         amr_unmapcmd(ac);
1895
1896         /* 
1897          * Is there a completion handler? 
1898          */
1899         if (ac->ac_complete != NULL) {
1900             /* unbusy the command */
1901             ac->ac_flags &= ~AMR_CMD_BUSY;
1902             ac->ac_complete(ac);
1903             
1904             /* 
1905              * Is someone sleeping on this one?
1906              */
1907         } else {
1908             lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1909             ac->ac_flags &= ~AMR_CMD_BUSY;
1910             if (ac->ac_flags & AMR_CMD_SLEEP) {
1911                 /* unbusy the command */
1912                 wakeup(ac);
1913             }
1914             lockmgr(&sc->amr_list_lock, LK_RELEASE);
1915         }
1916
1917         if(!sc->amr_busyslots) {
1918             wakeup(sc);
1919         }
1920     }
1921
1922     lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
1923     sc->amr_state &= ~AMR_STATE_QUEUE_FRZN;
1924     amr_startio(sc);
1925     lockmgr(&sc->amr_list_lock, LK_RELEASE);
1926 }
1927
1928 /********************************************************************************
1929  ********************************************************************************
1930                                                         Command Buffer Management
1931  ********************************************************************************
1932  ********************************************************************************/
1933
1934 /********************************************************************************
1935  * Get a new command buffer.
1936  *
1937  * This may return NULL in low-memory cases.
1938  *
1939  * If possible, we recycle a command buffer that's been used before.
1940  */
1941 struct amr_command *
1942 amr_alloccmd(struct amr_softc *sc)
1943 {
1944     struct amr_command  *ac;
1945
1946     debug_called(3);
1947
1948     ac = amr_dequeue_free(sc);
1949     if (ac == NULL) {
1950         sc->amr_state |= AMR_STATE_QUEUE_FRZN;
1951         return(NULL);
1952     }
1953
1954     /* clear out significant fields */
1955     ac->ac_status = 0;
1956     bzero(&ac->ac_mailbox, sizeof(struct amr_mailbox));
1957     ac->ac_flags = 0;
1958     ac->ac_bio = NULL;
1959     ac->ac_data = NULL;
1960     ac->ac_complete = NULL;
1961     ac->ac_retries = 0;
1962     ac->ac_tag = NULL;
1963     ac->ac_datamap = NULL;
1964     return(ac);
1965 }
1966
1967 /********************************************************************************
1968  * Release a command buffer for recycling.
1969  */
1970 void
1971 amr_releasecmd(struct amr_command *ac)
1972 {
1973     debug_called(3);
1974
1975     amr_enqueue_free(ac);
1976 }
1977
1978 /********************************************************************************
1979  * Allocate a new command cluster and initialise it.
1980  */
1981 static void
1982 amr_alloccmd_cluster(struct amr_softc *sc)
1983 {
1984     struct amr_command_cluster  *acc;
1985     struct amr_command          *ac;
1986     int                         i, nextslot;
1987
1988     /*
1989      * If we haven't found the real limit yet, let us have a couple of
1990      * commands in order to be able to probe.
1991      */
1992     if (sc->amr_maxio == 0)
1993         sc->amr_maxio = 2;
1994
1995     if (sc->amr_nextslot > sc->amr_maxio)
1996         return;
1997     acc = kmalloc(AMR_CMD_CLUSTERSIZE, M_AMR, M_NOWAIT | M_ZERO);
1998     if (acc != NULL) {
1999         nextslot = sc->amr_nextslot;
2000         lockmgr(&sc->amr_list_lock, LK_EXCLUSIVE);
2001         TAILQ_INSERT_TAIL(&sc->amr_cmd_clusters, acc, acc_link);
2002         lockmgr(&sc->amr_list_lock, LK_RELEASE);
2003         for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++) {
2004             ac = &acc->acc_command[i];
2005             ac->ac_sc = sc;
2006             ac->ac_slot = nextslot;
2007
2008             /*
2009              * The SG table for each slot is a fixed size and is assumed to
2010              * to hold 64-bit s/g objects when the driver is configured to do
2011              * 64-bit DMA.  32-bit DMA commands still use the same table, but
2012              * cast down to 32-bit objects.
2013              */
2014             if (AMR_IS_SG64(sc)) {
2015                 ac->ac_sgbusaddr = sc->amr_sgbusaddr +
2016                     (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sg64entry));
2017                 ac->ac_sg.sg64 = sc->amr_sg64table + (ac->ac_slot * AMR_NSEG);
2018             } else {
2019                 ac->ac_sgbusaddr = sc->amr_sgbusaddr +
2020                     (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
2021                 ac->ac_sg.sg32 = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
2022             }
2023
2024             ac->ac_ccb = sc->amr_ccb + ac->ac_slot;
2025             ac->ac_ccb_busaddr = sc->amr_ccb_busaddr +
2026                 (ac->ac_slot * sizeof(union amr_ccb));
2027
2028             if (bus_dmamap_create(sc->amr_buffer_dmat, 0, &ac->ac_dmamap))
2029                 break;
2030             if (AMR_IS_SG64(sc) &&
2031                 (bus_dmamap_create(sc->amr_buffer64_dmat, 0,&ac->ac_dma64map)))
2032                 break;
2033             amr_releasecmd(ac);
2034             if (++nextslot > sc->amr_maxio)
2035                 break;
2036         }
2037         sc->amr_nextslot = nextslot;
2038     }
2039 }
2040
2041 /********************************************************************************
2042  * Free a command cluster
2043  */
2044 static void
2045 amr_freecmd_cluster(struct amr_command_cluster *acc)
2046 {
2047     struct amr_softc    *sc = acc->acc_command[0].ac_sc;
2048     int                 i;
2049
2050     for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++) {
2051         if (acc->acc_command[i].ac_sc == NULL)
2052             break;
2053         bus_dmamap_destroy(sc->amr_buffer_dmat, acc->acc_command[i].ac_dmamap);
2054         if (AMR_IS_SG64(sc))
2055                 bus_dmamap_destroy(sc->amr_buffer64_dmat, acc->acc_command[i].ac_dma64map);
2056     }
2057     kfree(acc, M_AMR);
2058 }
2059
2060 /********************************************************************************
2061  ********************************************************************************
2062                                                          Interface-specific Shims
2063  ********************************************************************************
2064  ********************************************************************************/
2065
2066 /********************************************************************************
2067  * Tell the controller that the mailbox contains a valid command
2068  */
2069 static int
2070 amr_quartz_submit_command(struct amr_command *ac)
2071 {
2072     struct amr_softc    *sc = ac->ac_sc;
2073     static struct timeval lastfail;
2074     static int          curfail;
2075     int                 i = 0;
2076
2077     lockmgr(&sc->amr_hw_lock, LK_EXCLUSIVE);
2078     while (sc->amr_mailbox->mb_busy && (i++ < 10)) {
2079         DELAY(1);
2080         /* This is a no-op read that flushes pending mailbox updates */
2081         AMR_QGET_ODB(sc);
2082     }
2083     if (sc->amr_mailbox->mb_busy) {
2084         lockmgr(&sc->amr_hw_lock, LK_RELEASE);
2085         if (ac->ac_retries++ > 1000) {
2086             if (ppsratecheck(&lastfail, &curfail, 1))
2087                 device_printf(sc->amr_dev, "Too many retries on command %p.  "
2088                               "Controller is likely dead\n", ac);
2089             ac->ac_retries = 0;
2090         }
2091         return (EBUSY);
2092     }
2093
2094     /*
2095      * Save the slot number so that we can locate this command when complete.
2096      * Note that ident = 0 seems to be special, so we don't use it.
2097      */
2098     ac->ac_mailbox.mb_ident = ac->ac_slot + 1; /* will be coppied into mbox */
2099     bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, 14);
2100     sc->amr_mailbox->mb_busy = 1;
2101     sc->amr_mailbox->mb_poll = 0;
2102     sc->amr_mailbox->mb_ack  = 0;
2103     sc->amr_mailbox64->sg64_hi = ac->ac_sg64_hi;
2104     sc->amr_mailbox64->sg64_lo = ac->ac_sg64_lo;
2105
2106     AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
2107     lockmgr(&sc->amr_hw_lock, LK_RELEASE);
2108     return(0);
2109 }
2110
2111 static int
2112 amr_std_submit_command(struct amr_command *ac)
2113 {
2114     struct amr_softc    *sc = ac->ac_sc;
2115     static struct timeval lastfail;
2116     static int          curfail;
2117
2118     lockmgr(&sc->amr_hw_lock, LK_EXCLUSIVE);
2119     if (AMR_SGET_MBSTAT(sc) & AMR_SMBOX_BUSYFLAG) {
2120         lockmgr(&sc->amr_hw_lock, LK_RELEASE);
2121         if (ac->ac_retries++ > 1000) {
2122             if (ppsratecheck(&lastfail, &curfail, 1))
2123                 device_printf(sc->amr_dev, "Too many retries on command %p.  "
2124                               "Controller is likely dead\n", ac);
2125             ac->ac_retries = 0;
2126         }
2127         return (EBUSY);
2128     }
2129
2130     /*
2131      * Save the slot number so that we can locate this command when complete.
2132      * Note that ident = 0 seems to be special, so we don't use it.
2133      */
2134     ac->ac_mailbox.mb_ident = ac->ac_slot + 1; /* will be coppied into mbox */
2135     bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, 14);
2136     sc->amr_mailbox->mb_busy = 1;
2137     sc->amr_mailbox->mb_poll = 0;
2138     sc->amr_mailbox->mb_ack  = 0;
2139
2140     AMR_SPOST_COMMAND(sc);
2141     lockmgr(&sc->amr_hw_lock, LK_RELEASE);
2142     return(0);
2143 }
2144
2145 /********************************************************************************
2146  * Claim any work that the controller has completed; acknowledge completion,
2147  * save details of the completion in (mbsave)
2148  */
2149 static int
2150 amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
2151 {
2152     int         worked, i;
2153     u_int32_t   outd;
2154     u_int8_t    nstatus;
2155     u_int8_t    completed[46];
2156
2157     debug_called(3);
2158
2159     worked = 0;
2160
2161     /* work waiting for us? */
2162     if ((outd = AMR_QGET_ODB(sc)) == AMR_QODB_READY) {
2163
2164         /* acknowledge interrupt */
2165         AMR_QPUT_ODB(sc, AMR_QODB_READY);
2166
2167         while ((nstatus = sc->amr_mailbox->mb_nstatus) == 0xff)
2168             DELAY(1);
2169         sc->amr_mailbox->mb_nstatus = 0xff;
2170
2171         /* wait until fw wrote out all completions */
2172         for (i = 0; i < nstatus; i++) {
2173             while ((completed[i] = sc->amr_mailbox->mb_completed[i]) == 0xff)
2174                 DELAY(1);
2175             sc->amr_mailbox->mb_completed[i] = 0xff;
2176         }
2177
2178         /* Save information for later processing */
2179         mbsave->mb_nstatus = nstatus;
2180         mbsave->mb_status = sc->amr_mailbox->mb_status;
2181         sc->amr_mailbox->mb_status = 0xff;
2182
2183         for (i = 0; i < nstatus; i++)
2184             mbsave->mb_completed[i] = completed[i];
2185
2186         /* acknowledge that we have the commands */
2187         AMR_QPUT_IDB(sc, AMR_QIDB_ACK);
2188
2189 #if 0
2190 #ifndef AMR_QUARTZ_GOFASTER
2191         /*
2192          * This waits for the controller to notice that we've taken the
2193          * command from it.  It's very inefficient, and we shouldn't do it,
2194          * but if we remove this code, we stop completing commands under
2195          * load.
2196          *
2197          * Peter J says we shouldn't do this.  The documentation says we
2198          * should.  Who is right?
2199          */
2200         while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK)
2201             ;                           /* XXX aiee! what if it dies? */
2202 #endif
2203 #endif
2204
2205         worked = 1;                     /* got some work */
2206     }
2207
2208     return(worked);
2209 }
2210
2211 static int
2212 amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
2213 {
2214     int         worked;
2215     u_int8_t    istat;
2216
2217     debug_called(3);
2218
2219     worked = 0;
2220
2221     /* check for valid interrupt status */
2222     istat = AMR_SGET_ISTAT(sc);
2223     if ((istat & AMR_SINTR_VALID) != 0) {
2224         AMR_SPUT_ISTAT(sc, istat);      /* ack interrupt status */
2225
2226         /* save mailbox, which contains a list of completed commands */
2227         bcopy((void *)(uintptr_t)(volatile void *)sc->amr_mailbox, mbsave, sizeof(*mbsave));
2228
2229         AMR_SACK_INTERRUPT(sc);         /* acknowledge we have the mailbox */
2230         worked = 1;
2231     }
2232
2233     return(worked);
2234 }
2235
2236 /********************************************************************************
2237  * Notify the controller of the mailbox location.
2238  */
2239 static void
2240 amr_std_attach_mailbox(struct amr_softc *sc)
2241 {
2242
2243     /* program the mailbox physical address */
2244     AMR_SBYTE_SET(sc, AMR_SMBOX_0, sc->amr_mailboxphys         & 0xff);
2245     AMR_SBYTE_SET(sc, AMR_SMBOX_1, (sc->amr_mailboxphys >>  8) & 0xff);
2246     AMR_SBYTE_SET(sc, AMR_SMBOX_2, (sc->amr_mailboxphys >> 16) & 0xff);
2247     AMR_SBYTE_SET(sc, AMR_SMBOX_3, (sc->amr_mailboxphys >> 24) & 0xff);
2248     AMR_SBYTE_SET(sc, AMR_SMBOX_ENABLE, AMR_SMBOX_ADDR);
2249
2250     /* clear any outstanding interrupt and enable interrupts proper */
2251     AMR_SACK_INTERRUPT(sc);
2252     AMR_SENABLE_INTR(sc);
2253 }
2254
2255 #ifdef AMR_BOARD_INIT
2256 /********************************************************************************
2257  * Initialise the controller
2258  */
2259 static int
2260 amr_quartz_init(struct amr_softc *sc)
2261 {
2262     int         status, ostatus;
2263
2264     device_printf(sc->amr_dev, "initial init status %x\n", AMR_QGET_INITSTATUS(sc));
2265
2266     AMR_QRESET(sc);
2267
2268     ostatus = 0xff;
2269     while ((status = AMR_QGET_INITSTATUS(sc)) != AMR_QINIT_DONE) {
2270         if (status != ostatus) {
2271             device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_qinit, status));
2272             ostatus = status;
2273         }
2274         switch (status) {
2275         case AMR_QINIT_NOMEM:
2276             return(ENOMEM);
2277
2278         case AMR_QINIT_SCAN:
2279             /* XXX we could print channel/target here */
2280             break;
2281         }
2282     }
2283     return(0);
2284 }
2285
2286 static int
2287 amr_std_init(struct amr_softc *sc)
2288 {
2289     int         status, ostatus;
2290
2291     device_printf(sc->amr_dev, "initial init status %x\n", AMR_SGET_INITSTATUS(sc));
2292
2293     AMR_SRESET(sc);
2294  
2295     ostatus = 0xff;
2296     while ((status = AMR_SGET_INITSTATUS(sc)) != AMR_SINIT_DONE) {
2297         if (status != ostatus) {
2298             device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_sinit, status));
2299             ostatus = status;
2300         }
2301         switch (status) {
2302         case AMR_SINIT_NOMEM:
2303             return(ENOMEM);
2304
2305         case AMR_SINIT_INPROG:
2306             /* XXX we could print channel/target here? */
2307             break;
2308         }
2309     }
2310     return(0);
2311 }
2312 #endif
2313
2314 /********************************************************************************
2315  ********************************************************************************
2316                                                                         Debugging
2317  ********************************************************************************
2318  ********************************************************************************/
2319
2320 /********************************************************************************
2321  * Identify the controller and print some information about it.
2322  */
2323 static void
2324 amr_describe_controller(struct amr_softc *sc)
2325 {
2326     struct amr_prodinfo *ap;
2327     struct amr_enquiry  *ae;
2328     char                *prod;
2329     int                 status;
2330
2331     /*
2332      * Try to get 40LD product info, which tells us what the card is labelled as.
2333      */
2334     if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0, &status)) != NULL) {
2335         device_printf(sc->amr_dev, "<LSILogic %.80s> Firmware %.16s, BIOS %.16s, %dMB RAM\n",
2336                       ap->ap_product, ap->ap_firmware, ap->ap_bios,
2337                       ap->ap_memsize);
2338
2339         kfree(ap, M_AMR);
2340         return;
2341     }
2342
2343     /*
2344      * Try 8LD extended ENQUIRY to get controller signature, and use lookup table.
2345      */
2346     if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0, &status)) != NULL) {
2347         prod = amr_describe_code(amr_table_adaptertype, ae->ae_signature);
2348
2349     } else if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0, &status)) != NULL) {
2350
2351         /*
2352          * Try to work it out based on the PCI signatures.
2353          */
2354         switch (pci_get_device(sc->amr_dev)) {
2355         case 0x9010:
2356             prod = "Series 428";
2357             break;
2358         case 0x9060:
2359             prod = "Series 434";
2360             break;
2361         default:
2362             prod = "unknown controller";
2363             break;
2364         }
2365     } else {
2366         device_printf(sc->amr_dev, "<unsupported controller>\n");
2367         return;
2368     }
2369
2370     /*
2371      * HP NetRaid controllers have a special encoding of the firmware and
2372      * BIOS versions. The AMI version seems to have it as strings whereas
2373      * the HP version does it with a leading uppercase character and two
2374      * binary numbers.
2375      */
2376      
2377     if(ae->ae_adapter.aa_firmware[2] >= 'A' &&
2378        ae->ae_adapter.aa_firmware[2] <= 'Z' &&
2379        ae->ae_adapter.aa_firmware[1] <  ' ' &&
2380        ae->ae_adapter.aa_firmware[0] <  ' ' &&
2381        ae->ae_adapter.aa_bios[2] >= 'A'     &&
2382        ae->ae_adapter.aa_bios[2] <= 'Z'     &&
2383        ae->ae_adapter.aa_bios[1] <  ' '     &&
2384        ae->ae_adapter.aa_bios[0] <  ' ') {
2385
2386         /* this looks like we have an HP NetRaid version of the MegaRaid */
2387
2388         if(ae->ae_signature == AMR_SIG_438) {
2389                 /* the AMI 438 is a NetRaid 3si in HP-land */
2390                 prod = "HP NetRaid 3si";
2391         }
2392         
2393         device_printf(sc->amr_dev, "<%s> Firmware %c.%02d.%02d, BIOS %c.%02d.%02d, %dMB RAM\n",
2394                       prod, ae->ae_adapter.aa_firmware[2],
2395                       ae->ae_adapter.aa_firmware[1],
2396                       ae->ae_adapter.aa_firmware[0],
2397                       ae->ae_adapter.aa_bios[2],
2398                       ae->ae_adapter.aa_bios[1],
2399                       ae->ae_adapter.aa_bios[0],
2400                       ae->ae_adapter.aa_memorysize);            
2401     } else {
2402         device_printf(sc->amr_dev, "<%s> Firmware %.4s, BIOS %.4s, %dMB RAM\n", 
2403                       prod, ae->ae_adapter.aa_firmware, ae->ae_adapter.aa_bios,
2404                       ae->ae_adapter.aa_memorysize);
2405     }           
2406     kfree(ae, M_AMR);
2407 }
2408
2409 int
2410 amr_dump_blocks(struct amr_softc *sc, int unit, u_int32_t lba, void *data, int blks)
2411 {
2412     struct amr_command  *ac;
2413     int                 error = EIO;
2414
2415     debug_called(1);
2416
2417     sc->amr_state |= AMR_STATE_INTEN;
2418
2419     /* get ourselves a command buffer */
2420     if ((ac = amr_alloccmd(sc)) == NULL)
2421         goto out;
2422     /* set command flags */
2423     ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
2424     
2425     /* point the command at our data */
2426     ac->ac_data = data;
2427     ac->ac_length = blks * AMR_BLKSIZE;
2428     
2429     /* build the command proper */
2430     ac->ac_mailbox.mb_command   = AMR_CMD_LWRITE;
2431     ac->ac_mailbox.mb_blkcount  = blks;
2432     ac->ac_mailbox.mb_lba       = lba;
2433     ac->ac_mailbox.mb_drive     = unit;
2434
2435     /* can't assume that interrupts are going to work here, so play it safe */
2436     if (sc->amr_poll_command(ac))
2437         goto out;
2438     error = ac->ac_status;
2439     
2440  out:
2441     if (ac != NULL)
2442         amr_releasecmd(ac);
2443
2444     sc->amr_state &= ~AMR_STATE_INTEN;
2445     return (error);
2446 }
2447
2448
2449
2450 #ifdef AMR_DEBUG
2451 /********************************************************************************
2452  * Print the command (ac) in human-readable format
2453  */
2454 #if 0
2455 static void
2456 amr_printcommand(struct amr_command *ac)
2457 {
2458     struct amr_softc    *sc = ac->ac_sc;
2459     struct amr_sgentry  *sg;
2460     int                 i;
2461     
2462     device_printf(sc->amr_dev, "cmd %x  ident %d  drive %d\n",
2463                   ac->ac_mailbox.mb_command, ac->ac_mailbox.mb_ident, ac->ac_mailbox.mb_drive);
2464     device_printf(sc->amr_dev, "blkcount %d  lba %d\n", 
2465                   ac->ac_mailbox.mb_blkcount, ac->ac_mailbox.mb_lba);
2466     device_printf(sc->amr_dev, "virtaddr %p  length %lu\n", ac->ac_data, (unsigned long)ac->ac_length);
2467     device_printf(sc->amr_dev, "sg physaddr %08x  nsg %d\n",
2468                   ac->ac_mailbox.mb_physaddr, ac->ac_mailbox.mb_nsgelem);
2469     device_printf(sc->amr_dev, "ccb %p  bio %p\n", ac->ac_ccb_data, ac->ac_bio);
2470
2471     /* get base address of s/g table */
2472     sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
2473     for (i = 0; i < ac->ac_mailbox.mb_nsgelem; i++, sg++)
2474         device_printf(sc->amr_dev, "  %x/%d\n", sg->sg_addr, sg->sg_count);
2475 }
2476 #endif
2477 #endif