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