Initial import from FreeBSD RELENG_4:
[games.git] / sys / dev / raid / amr / amr.c
1 /*-
2  * Copyright (c) 1999,2000 Michael Smith
3  * Copyright (c) 2000 BSDi
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * Copyright (c) 2002 Eric Moore
28  * Copyright (c) 2002 LSI Logic Corporation
29  * All rights reserved.
30  *
31  * Redistribution and use in source and binary forms, with or without
32  * modification, are permitted provided that the following conditions
33  * are met:
34  * 1. Redistributions of source code must retain the above copyright
35  *    notice, this list of conditions and the following disclaimer.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  * 3. The party using or redistributing the source code and binary forms
40  *    agrees to the disclaimer below and the terms and conditions set forth
41  *    herein.
42  *
43  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  *
55  *      $FreeBSD: src/sys/dev/amr/amr.c,v 1.7.2.13 2003/01/15 13:41:18 emoore Exp $
56  */
57
58 /*
59  * Driver for the AMI MegaRaid family of controllers.
60  */
61
62 #include <sys/param.h>
63 #include <sys/systm.h>
64 #include <sys/malloc.h>
65 #include <sys/kernel.h>
66
67 #include <dev/amr/amr_compat.h>
68 #include <sys/bus.h>
69 #include <sys/conf.h>
70 #include <sys/devicestat.h>
71 #include <sys/disk.h>
72 #include <sys/stat.h>
73
74 #include <machine/bus_memio.h>
75 #include <machine/bus_pio.h>
76 #include <machine/bus.h>
77 #include <machine/resource.h>
78 #include <sys/rman.h>
79
80 #include <pci/pcireg.h>
81 #include <pci/pcivar.h>
82
83 #include <dev/amr/amrio.h>
84 #include <dev/amr/amrreg.h>
85 #include <dev/amr/amrvar.h>
86 #define AMR_DEFINE_TABLES
87 #include <dev/amr/amr_tables.h>
88
89 #define AMR_CDEV_MAJOR  132
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 cdevsw amr_cdevsw = {
96                 /* open */      amr_open,
97                 /* close */     amr_close,
98                 /* read */      noread,
99                 /* write */     nowrite,
100                 /* ioctl */     amr_ioctl,
101                 /* poll */      nopoll,
102                 /* mmap */      nommap,
103                 /* strategy */  nostrategy,
104                 /* name */      "amr",
105                 /* maj */       AMR_CDEV_MAJOR,
106                 /* dump */      nodump,
107                 /* psize */     nopsize,
108                 /* flags */     0,
109 };
110
111 /*
112  * Initialisation, bus interface.
113  */
114 static void     amr_startup(void *arg);
115
116 /*
117  * Command wrappers
118  */
119 static int      amr_query_controller(struct amr_softc *sc);
120 static void     *amr_enquiry(struct amr_softc *sc, size_t bufsize, 
121                              u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual);
122 static void     amr_completeio(struct amr_command *ac);
123 static int      amr_support_ext_cdb(struct amr_softc *sc);
124
125 /*
126  * Command buffer allocation.
127  */
128 static void     amr_alloccmd_cluster(struct amr_softc *sc);
129 static void     amr_freecmd_cluster(struct amr_command_cluster *acc);
130
131 /*
132  * Command processing.
133  */
134 static int      amr_bio_command(struct amr_softc *sc, struct amr_command **acp);
135 static int      amr_wait_command(struct amr_command *ac);
136 static int      amr_getslot(struct amr_command *ac);
137 static void     amr_mapcmd(struct amr_command *ac);
138 static void     amr_unmapcmd(struct amr_command *ac);
139 static int      amr_start(struct amr_command *ac);
140 static void     amr_complete(void *context, int pending);
141
142 /*
143  * Status monitoring
144  */
145 static void     amr_periodic(void *data);
146
147 /*
148  * Interface-specific shims
149  */
150 static int      amr_quartz_submit_command(struct amr_softc *sc);
151 static int      amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
152 static int      amr_quartz_poll_command(struct amr_command *ac);
153
154 static int      amr_std_submit_command(struct amr_softc *sc);
155 static int      amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave);
156 static int      amr_std_poll_command(struct amr_command *ac);
157 static void     amr_std_attach_mailbox(struct amr_softc *sc);
158
159 #ifdef AMR_BOARD_INIT
160 static int      amr_quartz_init(struct amr_softc *sc);
161 static int      amr_std_init(struct amr_softc *sc);
162 #endif
163
164 /*
165  * Debugging
166  */
167 static void     amr_describe_controller(struct amr_softc *sc);
168 #ifdef AMR_DEBUG
169 #if 0
170 static void     amr_printcommand(struct amr_command *ac);
171 #endif
172 #endif
173
174 /********************************************************************************
175  ********************************************************************************
176                                                                       Inline Glue
177  ********************************************************************************
178  ********************************************************************************/
179
180 /********************************************************************************
181  ********************************************************************************
182                                                                 Public Interfaces
183  ********************************************************************************
184  ********************************************************************************/
185
186 /********************************************************************************
187  * Initialise the controller and softc.
188  */
189 int
190 amr_attach(struct amr_softc *sc)
191 {
192
193     debug_called(1);
194
195     /*
196      * Initialise per-controller queues.
197      */
198     TAILQ_INIT(&sc->amr_completed);
199     TAILQ_INIT(&sc->amr_freecmds);
200     TAILQ_INIT(&sc->amr_cmd_clusters);
201     TAILQ_INIT(&sc->amr_ready);
202     bioq_init(&sc->amr_bioq);
203
204 #if __FreeBSD_version >= 500005
205     /*
206      * Initialise command-completion task.
207      */
208     TASK_INIT(&sc->amr_task_complete, 0, amr_complete, sc);
209 #endif
210
211     debug(2, "queue init done");
212
213     /*
214      * Configure for this controller type.
215      */
216     if (AMR_IS_QUARTZ(sc)) {
217         sc->amr_submit_command = amr_quartz_submit_command;
218         sc->amr_get_work       = amr_quartz_get_work;
219         sc->amr_poll_command   = amr_quartz_poll_command;
220     } else {
221         sc->amr_submit_command = amr_std_submit_command;
222         sc->amr_get_work       = amr_std_get_work;
223         sc->amr_poll_command   = amr_std_poll_command;
224         amr_std_attach_mailbox(sc);;
225     }
226
227 #ifdef AMR_BOARD_INIT
228     if ((AMR_IS_QUARTZ(sc) ? amr_quartz_init(sc) : amr_std_init(sc))))
229         return(ENXIO);
230 #endif
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      * Attach our 'real' SCSI channels to CAM.
242      */
243     if (amr_cam_attach(sc))
244         return(ENXIO);
245     debug(2, "CAM attach done");
246
247     /*
248      * Create the control device.
249      */
250     sc->amr_dev_t = make_dev(&amr_cdevsw, device_get_unit(sc->amr_dev), UID_ROOT, GID_OPERATOR,
251                              S_IRUSR | S_IWUSR, "amr%d", device_get_unit(sc->amr_dev));
252     sc->amr_dev_t->si_drv1 = sc;
253
254     /*
255      * Schedule ourselves to bring the controller up once interrupts are
256      * available.
257      */
258     bzero(&sc->amr_ich, sizeof(struct intr_config_hook));
259     sc->amr_ich.ich_func = amr_startup;
260     sc->amr_ich.ich_arg = sc;
261     if (config_intrhook_establish(&sc->amr_ich) != 0) {
262         device_printf(sc->amr_dev, "can't establish configuration hook\n");
263         return(ENOMEM);
264     }
265
266     /*
267      * Print a little information about the controller.
268      */
269     amr_describe_controller(sc);
270
271     debug(2, "attach complete");
272     return(0);
273 }
274
275 /********************************************************************************
276  * Locate disk resources and attach children to them.
277  */
278 static void
279 amr_startup(void *arg)
280 {
281     struct amr_softc    *sc = (struct amr_softc *)arg;
282     struct amr_logdrive *dr;
283     int                 i, error;
284     
285     debug_called(1);
286
287     /* pull ourselves off the intrhook chain */
288     config_intrhook_disestablish(&sc->amr_ich);
289
290     /* get up-to-date drive information */
291     if (amr_query_controller(sc)) {
292         device_printf(sc->amr_dev, "can't scan controller for drives\n");
293         return;
294     }
295
296     /* iterate over available drives */
297     for (i = 0, dr = &sc->amr_drive[0]; (i < AMR_MAXLD) && (dr->al_size != 0xffffffff); i++, dr++) {
298         /* are we already attached to this drive? */
299         if (dr->al_disk == 0) {
300             /* generate geometry information */
301             if (dr->al_size > 0x200000) {       /* extended translation? */
302                 dr->al_heads = 255;
303                 dr->al_sectors = 63;
304             } else {
305                 dr->al_heads = 64;
306                 dr->al_sectors = 32;
307             }
308             dr->al_cylinders = dr->al_size / (dr->al_heads * dr->al_sectors);
309             
310             dr->al_disk = device_add_child(sc->amr_dev, NULL, -1);
311             if (dr->al_disk == 0)
312                 device_printf(sc->amr_dev, "device_add_child failed\n");
313             device_set_ivars(dr->al_disk, dr);
314         }
315     }
316     
317     if ((error = bus_generic_attach(sc->amr_dev)) != 0)
318         device_printf(sc->amr_dev, "bus_generic_attach returned %d\n", error);
319     
320     /* mark controller back up */
321     sc->amr_state &= ~AMR_STATE_SHUTDOWN;
322
323     /* interrupts will be enabled before we do anything more */
324     sc->amr_state |= AMR_STATE_INTEN;
325
326     /*
327      * Start the timeout routine.
328      */
329 /*    sc->amr_timeout = timeout(amr_periodic, sc, hz);*/
330
331     return;
332 }
333
334 /*******************************************************************************
335  * Free resources associated with a controller instance
336  */
337 void
338 amr_free(struct amr_softc *sc)
339 {
340     struct amr_command_cluster  *acc;
341
342     /* detach from CAM */
343     amr_cam_detach(sc);
344
345     /* cancel status timeout */
346     untimeout(amr_periodic, sc, sc->amr_timeout);
347     
348     /* throw away any command buffers */
349     while ((acc = TAILQ_FIRST(&sc->amr_cmd_clusters)) != NULL) {
350         TAILQ_REMOVE(&sc->amr_cmd_clusters, acc, acc_link);
351         amr_freecmd_cluster(acc);
352     }
353
354     /* destroy control device */
355     if( sc->amr_dev_t != (dev_t)NULL)
356             destroy_dev(sc->amr_dev_t);
357 }
358
359 /*******************************************************************************
360  * Receive a bio structure from a child device and queue it on a particular
361  * disk resource, then poke the disk resource to start as much work as it can.
362  */
363 int
364 amr_submit_bio(struct amr_softc *sc, struct bio *bio)
365 {
366     debug_called(2);
367
368     amr_enqueue_bio(sc, bio);
369     amr_startio(sc);
370     return(0);
371 }
372
373 /********************************************************************************
374  * Accept an open operation on the control device.
375  */
376 static int
377 amr_open(dev_t dev, int flags, int fmt, d_thread_t *td)
378 {
379     int                 unit = minor(dev);
380     struct amr_softc    *sc = devclass_get_softc(devclass_find("amr"), unit);
381
382     debug_called(1);
383
384     sc->amr_state |= AMR_STATE_OPEN;
385     return(0);
386 }
387
388 /********************************************************************************
389  * Accept the last close on the control device.
390  */
391 static int
392 amr_close(dev_t dev, int flags, int fmt, d_thread_t *td)
393 {
394     int                 unit = minor(dev);
395     struct amr_softc    *sc = devclass_get_softc(devclass_find("amr"), unit);
396
397     debug_called(1);
398
399     sc->amr_state &= ~AMR_STATE_OPEN;
400     return (0);
401 }
402
403 /********************************************************************************
404  * Handle controller-specific control operations.
405  */
406 static int
407 amr_ioctl(dev_t dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *td)
408 {
409     struct amr_softc            *sc = (struct amr_softc *)dev->si_drv1;
410     int                         *arg = (int *)addr;
411     struct amr_user_ioctl       *au = (struct amr_user_ioctl *)addr;
412     struct amr_command          *ac;
413     struct amr_mailbox_ioctl    *mbi;
414     struct amr_passthrough      *ap;
415     void                        *dp;
416     int                         error;
417
418     debug_called(1);
419
420     error = 0;
421     dp = NULL;
422     ap = NULL;
423     ac = NULL;
424     switch(cmd) {
425
426     case AMR_IO_VERSION:
427         debug(1, "AMR_IO_VERSION");
428         *arg = AMR_IO_VERSION_NUMBER;
429         break;
430
431     case AMR_IO_COMMAND:
432         debug(1, "AMR_IO_COMMAND  0x%x", au->au_cmd[0]);
433         /* handle inbound data buffer */
434         if (au->au_length != 0) {
435             if ((dp = malloc(au->au_length, M_DEVBUF, M_WAITOK)) == NULL) {
436                 error = ENOMEM;
437                 break;
438             }
439             if ((error = copyin(au->au_buffer, dp, au->au_length)) != 0)
440                 break;
441             debug(2, "copyin %ld bytes from %p -> %p", au->au_length, au->au_buffer, dp);
442         }
443
444         if ((ac = amr_alloccmd(sc)) == NULL) {
445             error = ENOMEM;
446             break;
447         }
448
449         /* handle SCSI passthrough command */
450         if (au->au_cmd[0] == AMR_CMD_PASS) {
451             if ((ap = malloc(sizeof(*ap), M_DEVBUF, M_WAITOK | M_ZERO)) == NULL) {
452                 error = ENOMEM;
453                 break;
454             }
455
456             /* copy cdb */
457             ap->ap_cdb_length = au->au_cmd[2];
458             bcopy(&au->au_cmd[3], &ap->ap_cdb[0], ap->ap_cdb_length);
459
460             /* build passthrough */
461             ap->ap_timeout              = au->au_cmd[ap->ap_cdb_length + 3] & 0x07;
462             ap->ap_ars                  = (au->au_cmd[ap->ap_cdb_length + 3] & 0x08) ? 1 : 0;
463             ap->ap_islogical            = (au->au_cmd[ap->ap_cdb_length + 3] & 0x80) ? 1 : 0;
464             ap->ap_logical_drive_no     = au->au_cmd[ap->ap_cdb_length + 4];
465             ap->ap_channel              = au->au_cmd[ap->ap_cdb_length + 5];
466             ap->ap_scsi_id              = au->au_cmd[ap->ap_cdb_length + 6];
467             ap->ap_request_sense_length = 14;
468             ap->ap_data_transfer_length = au->au_length;
469             /* XXX what about the request-sense area? does the caller want it? */
470
471             /* build command */
472             ac->ac_data = ap;
473             ac->ac_length = sizeof(*ap);
474             ac->ac_flags |= AMR_CMD_DATAOUT;
475             ac->ac_ccb_data = dp;
476             ac->ac_ccb_length = au->au_length;
477             if (au->au_direction & AMR_IO_READ)
478                 ac->ac_flags |= AMR_CMD_CCB_DATAIN;
479             if (au->au_direction & AMR_IO_WRITE)
480                 ac->ac_flags |= AMR_CMD_CCB_DATAOUT;
481
482             ac->ac_mailbox.mb_command = AMR_CMD_PASS;
483
484         } else {
485             /* direct command to controller */
486             mbi = (struct amr_mailbox_ioctl *)&ac->ac_mailbox;
487
488             /* copy pertinent mailbox items */
489             mbi->mb_command = au->au_cmd[0];
490             mbi->mb_channel = au->au_cmd[1];
491             mbi->mb_param = au->au_cmd[2];
492             mbi->mb_pad[0] = au->au_cmd[3];
493             mbi->mb_drive = au->au_cmd[4];
494
495             /* build the command */
496             ac->ac_data = dp;
497             ac->ac_length = au->au_length;
498             if (au->au_direction & AMR_IO_READ)
499                 ac->ac_flags |= AMR_CMD_DATAIN;
500             if (au->au_direction & AMR_IO_WRITE)
501                 ac->ac_flags |= AMR_CMD_DATAOUT;
502         }
503
504         /* run the command */
505         if ((error = amr_wait_command(ac)) != 0)
506             break;
507
508         /* copy out data and set status */
509         if (au->au_length != 0)
510             error = copyout(dp, au->au_buffer, au->au_length);
511         debug(2, "copyout %ld bytes from %p -> %p", au->au_length, dp, au->au_buffer);
512         if (dp != NULL)
513             debug(2, "%16d", (int)dp);
514         au->au_status = ac->ac_status;
515         break;
516
517     default:
518         debug(1, "unknown ioctl 0x%lx", cmd);
519         error = ENOIOCTL;
520         break;
521     }
522
523     if (dp != NULL)
524         free(dp, M_DEVBUF);
525     if (ap != NULL)
526         free(ap, M_DEVBUF);
527     if (ac != NULL)
528         amr_releasecmd(ac);
529     return(error);
530 }
531
532 /********************************************************************************
533  ********************************************************************************
534                                                                 Status Monitoring
535  ********************************************************************************
536  ********************************************************************************/
537
538 /********************************************************************************
539  * Perform a periodic check of the controller status
540  */
541 static void
542 amr_periodic(void *data)
543 {
544     struct amr_softc    *sc = (struct amr_softc *)data;
545
546     debug_called(2);
547
548     /* XXX perform periodic status checks here */
549
550     /* compensate for missed interrupts */
551     amr_done(sc);
552
553     /* reschedule */
554     sc->amr_timeout = timeout(amr_periodic, sc, hz);
555 }
556
557 /********************************************************************************
558  ********************************************************************************
559                                                                  Command Wrappers
560  ********************************************************************************
561  ********************************************************************************/
562
563 /********************************************************************************
564  * Interrogate the controller for the operational parameters we require.
565  */
566 static int
567 amr_query_controller(struct amr_softc *sc)
568 {
569     struct amr_enquiry3 *aex;
570     struct amr_prodinfo *ap;
571     struct amr_enquiry  *ae;
572     int                 ldrv;
573
574     /* 
575      * If we haven't found the real limit yet, let us have a couple of commands in
576      * order to be able to probe.
577      */
578     if (sc->amr_maxio == 0)
579         sc->amr_maxio = 2;
580
581     /*
582      * Greater than 10 byte cdb support
583      */
584     sc->support_ext_cdb = amr_support_ext_cdb(sc);
585
586     if(sc->support_ext_cdb) {
587         debug(2,"supports extended CDBs.");
588     }
589
590     /* 
591      * Try to issue an ENQUIRY3 command 
592      */
593     if ((aex = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_ENQ3, 
594                            AMR_CONFIG_ENQ3_SOLICITED_FULL)) != NULL) {
595
596         /*
597          * Fetch current state of logical drives.
598          */
599         for (ldrv = 0; ldrv < aex->ae_numldrives; ldrv++) {
600             sc->amr_drive[ldrv].al_size       = aex->ae_drivesize[ldrv];
601             sc->amr_drive[ldrv].al_state      = aex->ae_drivestate[ldrv];
602             sc->amr_drive[ldrv].al_properties = aex->ae_driveprop[ldrv];
603             debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
604                   sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
605         }
606         free(aex, M_DEVBUF);
607
608         /*
609          * Get product info for channel count.
610          */
611         if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0)) == NULL) {
612             device_printf(sc->amr_dev, "can't obtain product data from controller\n");
613             return(1);
614         }
615         sc->amr_maxdrives = 40;
616         sc->amr_maxchan = ap->ap_nschan;
617         sc->amr_maxio = ap->ap_maxio;
618         sc->amr_type |= AMR_TYPE_40LD;
619         free(ap, M_DEVBUF);
620
621     } else {
622
623         /* failed, try the 8LD ENQUIRY commands */
624         if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0)) == NULL) {
625             if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0)) == NULL) {
626                 device_printf(sc->amr_dev, "can't obtain configuration data from controller\n");
627                 return(1);
628             }
629             ae->ae_signature = 0;
630         }
631
632         /*
633          * Fetch current state of logical drives.
634          */
635         for (ldrv = 0; ldrv < ae->ae_ldrv.al_numdrives; ldrv++) {
636             sc->amr_drive[ldrv].al_size       = ae->ae_ldrv.al_size[ldrv];
637             sc->amr_drive[ldrv].al_state      = ae->ae_ldrv.al_state[ldrv];
638             sc->amr_drive[ldrv].al_properties = ae->ae_ldrv.al_properties[ldrv];
639             debug(2, "  drive %d: %d state %x properties %x\n", ldrv, sc->amr_drive[ldrv].al_size,
640                   sc->amr_drive[ldrv].al_state, sc->amr_drive[ldrv].al_properties);
641         }
642
643         sc->amr_maxdrives = 8;
644         sc->amr_maxchan = ae->ae_adapter.aa_channels;
645         sc->amr_maxio = ae->ae_adapter.aa_maxio;
646         free(ae, M_DEVBUF);
647     }
648
649     /*
650      * Mark remaining drives as unused.
651      */
652     for (; ldrv < AMR_MAXLD; ldrv++)
653         sc->amr_drive[ldrv].al_size = 0xffffffff;
654
655     /* 
656      * Cap the maximum number of outstanding I/Os.  AMI's Linux driver doesn't trust
657      * the controller's reported value, and lockups have been seen when we do.
658      */
659     sc->amr_maxio = imin(sc->amr_maxio, AMR_LIMITCMD);
660
661     return(0);
662 }
663
664 /********************************************************************************
665  * Run a generic enquiry-style command.
666  */
667 static void *
668 amr_enquiry(struct amr_softc *sc, size_t bufsize, u_int8_t cmd, u_int8_t cmdsub, u_int8_t cmdqual)
669 {
670     struct amr_command  *ac;
671     void                *result;
672     u_int8_t            *mbox;
673     int                 error;
674
675     debug_called(1);
676
677     error = 1;
678     result = NULL;
679     
680     /* get ourselves a command buffer */
681     if ((ac = amr_alloccmd(sc)) == NULL)
682         goto out;
683     /* allocate the response structure */
684     if ((result = malloc(bufsize, M_DEVBUF, M_NOWAIT)) == NULL)
685         goto out;
686     /* set command flags */
687     ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
688     
689     /* point the command at our data */
690     ac->ac_data = result;
691     ac->ac_length = bufsize;
692     
693     /* build the command proper */
694     mbox = (u_int8_t *)&ac->ac_mailbox;         /* XXX want a real structure for this? */
695     mbox[0] = cmd;
696     mbox[2] = cmdsub;
697     mbox[3] = cmdqual;
698
699     /* can't assume that interrupts are going to work here, so play it safe */
700     if (sc->amr_poll_command(ac))
701         goto out;
702     error = ac->ac_status;
703     
704  out:
705     if (ac != NULL)
706         amr_releasecmd(ac);
707     if ((error != 0) && (result != NULL)) {
708         free(result, M_DEVBUF);
709         result = NULL;
710     }
711     return(result);
712 }
713
714 /********************************************************************************
715  * Flush the controller's internal cache, return status.
716  */
717 int
718 amr_flush(struct amr_softc *sc)
719 {
720     struct amr_command  *ac;
721     int                 error;
722
723     /* get ourselves a command buffer */
724     error = 1;
725     if ((ac = amr_alloccmd(sc)) == NULL)
726         goto out;
727     /* set command flags */
728     ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
729     
730     /* build the command proper */
731     ac->ac_mailbox.mb_command = AMR_CMD_FLUSH;
732
733     /* we have to poll, as the system may be going down or otherwise damaged */
734     if (sc->amr_poll_command(ac))
735         goto out;
736     error = ac->ac_status;
737     
738  out:
739     if (ac != NULL)
740         amr_releasecmd(ac);
741     return(error);
742 }
743
744 /********************************************************************************
745  * Detect extented cdb >> greater than 10 byte cdb support
746  * returns '1' means this support exist
747  * returns '0' means this support doesn't exist
748  */
749 static int
750 amr_support_ext_cdb(struct amr_softc *sc)
751 {
752     struct amr_command  *ac;
753     u_int8_t            *mbox;
754     int                 error;
755
756     /* get ourselves a command buffer */
757     error = 0;
758     if ((ac = amr_alloccmd(sc)) == NULL)
759         goto out;
760     /* set command flags */
761     ac->ac_flags |= AMR_CMD_PRIORITY | AMR_CMD_DATAOUT;
762
763     /* build the command proper */
764     mbox = (u_int8_t *)&ac->ac_mailbox;         /* XXX want a real structure for this? */
765     mbox[0] = 0xA4;
766     mbox[2] = 0x16;
767
768
769     /* we have to poll, as the system may be going down or otherwise damaged */
770     if (sc->amr_poll_command(ac))
771         goto out;
772     if( ac->ac_status == AMR_STATUS_SUCCESS ) {
773             error = 1;
774     }
775
776 out:
777     if (ac != NULL)
778         amr_releasecmd(ac);
779     return(error);
780 }
781
782 /********************************************************************************
783  * Try to find I/O work for the controller from one or more of the work queues.
784  *
785  * We make the assumption that if the controller is not ready to take a command
786  * at some given time, it will generate an interrupt at some later time when
787  * it is.
788  */
789 void
790 amr_startio(struct amr_softc *sc)
791 {
792     struct amr_command  *ac;
793
794     /* spin until something prevents us from doing any work */
795     for (;;) {
796
797         /* try to get a ready command */
798         ac = amr_dequeue_ready(sc);
799
800         /* if that failed, build a command from a bio */
801         if (ac == NULL)
802             (void)amr_bio_command(sc, &ac);
803
804         /* if that failed, build a command from a ccb */
805         if (ac == NULL)
806             (void)amr_cam_command(sc, &ac);
807
808         /* if we don't have anything to do, give up */
809         if (ac == NULL)
810             break;
811
812         /* try to give the command to the controller; if this fails save it for later and give up */
813         if (amr_start(ac)) {
814             debug(2, "controller busy, command deferred");
815             amr_requeue_ready(ac);      /* XXX schedule retry very soon? */
816             break;
817         }
818     }
819 }
820
821 /********************************************************************************
822  * Handle completion of an I/O command.
823  */
824 static void
825 amr_completeio(struct amr_command *ac)
826 {
827     struct amr_softc    *sc = ac->ac_sc;
828     
829     if (ac->ac_status != AMR_STATUS_SUCCESS) {  /* could be more verbose here? */
830         ac->ac_bio->bio_error = EIO;
831         ac->ac_bio->bio_flags |= BIO_ERROR;
832
833         device_printf(sc->amr_dev, "I/O error - 0x%x\n", ac->ac_status);
834 /*      amr_printcommand(ac);*/
835     }
836     amrd_intr(ac->ac_bio);
837     amr_releasecmd(ac);
838 }
839
840 /********************************************************************************
841  ********************************************************************************
842                                                                Command Processing
843  ********************************************************************************
844  ********************************************************************************/
845
846 /********************************************************************************
847  * Convert a bio off the top of the bio queue into a command.
848  */
849 static int
850 amr_bio_command(struct amr_softc *sc, struct amr_command **acp)
851 {
852     struct amr_command  *ac;
853     struct amrd_softc   *amrd;
854     struct bio          *bio;
855     int                 error;
856     int                 blkcount;
857     int                 driveno;
858     int                 cmd;
859
860     ac = NULL;
861     error = 0;
862
863     /* get a bio to work on */
864     if ((bio = amr_dequeue_bio(sc)) == NULL)
865         goto out;
866
867     /* get a command */
868     if ((ac = amr_alloccmd(sc)) == NULL) {
869         error = ENOMEM;
870         goto out;
871     }   
872         
873     /* connect the bio to the command */
874     ac->ac_complete = amr_completeio;
875     ac->ac_bio = bio;
876     ac->ac_data = bio->bio_data;
877     ac->ac_length = bio->bio_bcount;
878     if (BIO_IS_READ(bio)) {
879         ac->ac_flags |= AMR_CMD_DATAIN;
880         cmd = AMR_CMD_LREAD;
881     } else {
882         ac->ac_flags |= AMR_CMD_DATAOUT;
883         cmd = AMR_CMD_LWRITE;
884     }
885     amrd = (struct amrd_softc *)bio->bio_dev->si_drv1;
886     driveno = amrd->amrd_drive - sc->amr_drive;
887     blkcount = (bio->bio_bcount + AMR_BLKSIZE - 1) / AMR_BLKSIZE;
888
889     ac->ac_mailbox.mb_command = cmd;
890     ac->ac_mailbox.mb_blkcount = blkcount;
891     ac->ac_mailbox.mb_lba = bio->bio_pblkno;
892     ac->ac_mailbox.mb_drive = driveno;
893     /* we fill in the s/g related data when the command is mapped */
894
895     if ((bio->bio_pblkno + blkcount) > sc->amr_drive[driveno].al_size)
896         device_printf(sc->amr_dev, "I/O beyond end of unit (%lld,%d > %lu)\n", 
897                       (long long)bio->bio_pblkno, blkcount,
898                       (u_long)sc->amr_drive[driveno].al_size);
899
900 out:
901     if (error != 0) {
902         if (ac != NULL)
903             amr_releasecmd(ac);
904         if (bio != NULL)                        /* this breaks ordering... */
905             amr_enqueue_bio(sc, bio);
906     }
907     *acp = ac;
908     return(error);
909 }
910
911 /********************************************************************************
912  * Take a command, submit it to the controller and sleep until it completes
913  * or fails.  Interrupts must be enabled, returns nonzero on error.
914  */
915 static int
916 amr_wait_command(struct amr_command *ac)
917 {
918     int                 error, count;
919     
920     debug_called(1);
921
922     ac->ac_complete = NULL;
923     ac->ac_flags |= AMR_CMD_SLEEP;
924     if ((error = amr_start(ac)) != 0)
925         return(error);
926     
927     count = 0;
928     /* XXX better timeout? */
929     while ((ac->ac_flags & AMR_CMD_BUSY) && (count < 30)) {
930         tsleep(ac, PRIBIO | PCATCH, "amrwcmd", hz);
931     }
932     return(0);
933 }
934
935 /********************************************************************************
936  * Take a command, submit it to the controller and busy-wait for it to return.
937  * Returns nonzero on error.  Can be safely called with interrupts enabled.
938  */
939 static int
940 amr_std_poll_command(struct amr_command *ac)
941 {
942     struct amr_softc    *sc = ac->ac_sc;
943     int                 error, count;
944
945     debug_called(2);
946
947     ac->ac_complete = NULL;
948     if ((error = amr_start(ac)) != 0)
949         return(error);
950
951     count = 0;
952     do {
953         /* 
954          * Poll for completion, although the interrupt handler may beat us to it. 
955          * Note that the timeout here is somewhat arbitrary.
956          */
957         amr_done(sc);
958         DELAY(1000);
959     } while ((ac->ac_flags & AMR_CMD_BUSY) && (count++ < 1000));
960     if (!(ac->ac_flags & AMR_CMD_BUSY)) {
961         error = 0;
962     } else {
963         /* XXX the slot is now marked permanently busy */
964         error = EIO;
965         device_printf(sc->amr_dev, "polled command timeout\n");
966     }
967     return(error);
968 }
969
970 /********************************************************************************
971  * Take a command, submit it to the controller and busy-wait for it to return.
972  * Returns nonzero on error.  Can be safely called with interrupts enabled.
973  */
974 static int
975 amr_quartz_poll_command(struct amr_command *ac)
976 {
977     struct amr_softc    *sc = ac->ac_sc;
978     int                 s;
979     int                 error,count;
980
981     debug_called(2);
982
983     /* now we have a slot, we can map the command (unmapped in amr_complete) */
984     amr_mapcmd(ac);
985
986     s = splbio();
987
988     count=0;
989     while (sc->amr_busyslots){
990         tsleep(sc, PRIBIO | PCATCH, "amrpoll", hz);
991         if(count++>10) {
992             break;
993         }
994     }
995
996     if(sc->amr_busyslots) {
997         device_printf(sc->amr_dev, "adapter is busy\n");
998         splx(s);
999         amr_unmapcmd(ac);
1000         ac->ac_status=0;
1001         return(1);
1002     }
1003
1004     bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, AMR_MBOX_CMDSIZE);
1005
1006     /* clear the poll/ack fields in the mailbox */
1007     sc->amr_mailbox->mb_ident = 0xFE;
1008     sc->amr_mailbox->mb_nstatus = 0xFF;
1009     sc->amr_mailbox->mb_status = 0xFF;
1010     sc->amr_mailbox->mb_poll = 0;
1011     sc->amr_mailbox->mb_ack = 0;
1012     sc->amr_mailbox->mb_busy = 1;
1013
1014     AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
1015
1016     while(sc->amr_mailbox->mb_nstatus == 0xFF);
1017     while(sc->amr_mailbox->mb_status == 0xFF);
1018     ac->ac_status=sc->amr_mailbox->mb_status;
1019     error = (ac->ac_status !=AMR_STATUS_SUCCESS) ? 1:0;
1020     while(sc->amr_mailbox->mb_poll != 0x77);
1021     sc->amr_mailbox->mb_poll = 0;
1022     sc->amr_mailbox->mb_ack = 0x77;
1023
1024     /* acknowledge that we have the commands */
1025     AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_ACK);
1026     while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK);
1027
1028     splx(s);
1029
1030     /* unmap the command's data buffer */
1031     amr_unmapcmd(ac);
1032
1033     return(error);
1034 }
1035
1036 /********************************************************************************
1037  * Get a free command slot for a command if it doesn't already have one.
1038  *
1039  * May be safely called multiple times for a given command.
1040  */
1041 static int
1042 amr_getslot(struct amr_command *ac)
1043 {
1044     struct amr_softc    *sc = ac->ac_sc;
1045     int                 s, slot, limit, error;
1046
1047     debug_called(3);
1048
1049     /* if the command already has a slot, don't try to give it another one */
1050     if (ac->ac_slot != 0)
1051         return(0);
1052
1053     /* enforce slot usage limit */
1054     limit = (ac->ac_flags & AMR_CMD_PRIORITY) ? sc->amr_maxio : sc->amr_maxio - 4;
1055     if (sc->amr_busyslots > limit)
1056         return(EBUSY);
1057     
1058     /*
1059      * Allocate a slot.  XXX linear scan is slow
1060      */
1061     error = EBUSY;
1062     s = splbio();
1063     for (slot = 0; slot < sc->amr_maxio; slot++) {
1064         if (sc->amr_busycmd[slot] == NULL) {
1065             sc->amr_busycmd[slot] = ac;
1066             sc->amr_busyslots++;
1067             ac->ac_slot = slot;
1068             error = 0;
1069             break;
1070         }
1071     }
1072     splx(s);
1073
1074     return(error);
1075 }
1076
1077 /********************************************************************************
1078  * Map/unmap (ac)'s data in the controller's addressable space as required.
1079  *
1080  * These functions may be safely called multiple times on a given command.
1081  */
1082 static void
1083 amr_setup_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
1084 {
1085     struct amr_command  *ac = (struct amr_command *)arg;
1086     struct amr_softc    *sc = ac->ac_sc;
1087     struct amr_sgentry  *sg;
1088     int                 i;
1089     u_int8_t            *sgc;
1090
1091     debug_called(3);
1092
1093     /* get base address of s/g table */
1094     sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
1095
1096     /* save data physical address */
1097     ac->ac_dataphys = segs[0].ds_addr;
1098
1099     /* for AMR_CMD_CONFIG the s/g count goes elsewhere */
1100     if (ac->ac_mailbox.mb_command == AMR_CMD_CONFIG) {
1101         sgc = &(((struct amr_mailbox_ioctl *)&ac->ac_mailbox)->mb_param);
1102     } else {
1103         sgc = &ac->ac_mailbox.mb_nsgelem;
1104     }
1105
1106     /* decide whether we need to populate the s/g table */
1107     if (nsegments < 2) {
1108         *sgc = 0;
1109         ac->ac_mailbox.mb_nsgelem = 0;
1110         ac->ac_mailbox.mb_physaddr = ac->ac_dataphys;
1111     } else {
1112         ac->ac_mailbox.mb_nsgelem = nsegments;
1113         *sgc = nsegments;
1114         ac->ac_mailbox.mb_physaddr = sc->amr_sgbusaddr + (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
1115         for (i = 0; i < nsegments; i++, sg++) {
1116             sg->sg_addr = segs[i].ds_addr;
1117             sg->sg_count = segs[i].ds_len;
1118         }
1119     }
1120 }
1121
1122 static void
1123 amr_setup_ccbmap(void *arg, bus_dma_segment_t *segs, int nsegments, int error)
1124 {
1125     struct amr_command          *ac = (struct amr_command *)arg;
1126     struct amr_softc            *sc = ac->ac_sc;
1127     struct amr_sgentry          *sg;
1128     struct amr_passthrough      *ap = (struct amr_passthrough *)ac->ac_data;
1129     struct amr_ext_passthrough  *aep = (struct amr_ext_passthrough *)ac->ac_data;
1130     int                         i;
1131
1132     /* get base address of s/g table */
1133     sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
1134
1135     /* decide whether we need to populate the s/g table */
1136     if( ac->ac_mailbox.mb_command == AMR_CMD_EXTPASS ) {
1137         if (nsegments < 2) {
1138             aep->ap_no_sg_elements = 0;
1139             aep->ap_data_transfer_address =  segs[0].ds_addr;
1140         } else {
1141             /* save s/g table information in passthrough */
1142             aep->ap_no_sg_elements = nsegments;
1143             aep->ap_data_transfer_address = sc->amr_sgbusaddr + (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
1144             /* populate s/g table (overwrites previous call which mapped the passthrough) */
1145             for (i = 0; i < nsegments; i++, sg++) {
1146                 sg->sg_addr = segs[i].ds_addr;
1147                 sg->sg_count = segs[i].ds_len;
1148                 debug(3, " %d: 0x%x/%d", i, sg->sg_addr, sg->sg_count);
1149             }
1150         }
1151         debug(3, "slot %d  %d segments at 0x%x, passthrough at 0x%x", ac->ac_slot,
1152             aep->ap_no_sg_elements, aep->ap_data_transfer_address, ac->ac_dataphys);
1153     } else {
1154         if (nsegments < 2) {
1155             ap->ap_no_sg_elements = 0;
1156             ap->ap_data_transfer_address =  segs[0].ds_addr;
1157         } else {
1158             /* save s/g table information in passthrough */
1159             ap->ap_no_sg_elements = nsegments;
1160             ap->ap_data_transfer_address = sc->amr_sgbusaddr + (ac->ac_slot * AMR_NSEG * sizeof(struct amr_sgentry));
1161             /* populate s/g table (overwrites previous call which mapped the passthrough) */
1162             for (i = 0; i < nsegments; i++, sg++) {
1163                 sg->sg_addr = segs[i].ds_addr;
1164                 sg->sg_count = segs[i].ds_len;
1165                 debug(3, " %d: 0x%x/%d", i, sg->sg_addr, sg->sg_count);
1166             }
1167         }
1168         debug(3, "slot %d  %d segments at 0x%x, passthrough at 0x%x", ac->ac_slot,
1169             ap->ap_no_sg_elements, ap->ap_data_transfer_address, ac->ac_dataphys);
1170     }
1171 }
1172
1173 static void
1174 amr_mapcmd(struct amr_command *ac)
1175 {
1176     struct amr_softc    *sc = ac->ac_sc;
1177
1178     debug_called(3);
1179
1180     /* if the command involves data at all, and hasn't been mapped */
1181     if (!(ac->ac_flags & AMR_CMD_MAPPED)) {
1182
1183         if (ac->ac_data != NULL) {
1184             /* map the data buffers into bus space and build the s/g list */
1185             bus_dmamap_load(sc->amr_buffer_dmat, ac->ac_dmamap, ac->ac_data, ac->ac_length,
1186                             amr_setup_dmamap, ac, 0);
1187             if (ac->ac_flags & AMR_CMD_DATAIN)
1188                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_PREREAD);
1189             if (ac->ac_flags & AMR_CMD_DATAOUT)
1190                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_PREWRITE);
1191         }
1192
1193         if (ac->ac_ccb_data != NULL) {
1194             bus_dmamap_load(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, ac->ac_ccb_data, ac->ac_ccb_length,
1195                             amr_setup_ccbmap, ac, 0);
1196             if (ac->ac_flags & AMR_CMD_CCB_DATAIN)
1197                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_PREREAD);
1198             if (ac->ac_flags & AMR_CMD_CCB_DATAOUT)
1199                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_PREWRITE);
1200         }
1201         ac->ac_flags |= AMR_CMD_MAPPED;
1202     }
1203 }
1204
1205 static void
1206 amr_unmapcmd(struct amr_command *ac)
1207 {
1208     struct amr_softc    *sc = ac->ac_sc;
1209
1210     debug_called(3);
1211
1212     /* if the command involved data at all and was mapped */
1213     if (ac->ac_flags & AMR_CMD_MAPPED) {
1214
1215         if (ac->ac_data != NULL) {
1216             if (ac->ac_flags & AMR_CMD_DATAIN)
1217                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_POSTREAD);
1218             if (ac->ac_flags & AMR_CMD_DATAOUT)
1219                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_dmamap, BUS_DMASYNC_POSTWRITE);
1220             bus_dmamap_unload(sc->amr_buffer_dmat, ac->ac_dmamap);
1221         }
1222
1223         if (ac->ac_ccb_data != NULL) {
1224             if (ac->ac_flags & AMR_CMD_CCB_DATAIN)
1225                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_POSTREAD);
1226             if (ac->ac_flags & AMR_CMD_CCB_DATAOUT)
1227                 bus_dmamap_sync(sc->amr_buffer_dmat, ac->ac_ccb_dmamap, BUS_DMASYNC_POSTWRITE);
1228             bus_dmamap_unload(sc->amr_buffer_dmat, ac->ac_ccb_dmamap);
1229         }
1230         ac->ac_flags &= ~AMR_CMD_MAPPED;
1231     }
1232 }
1233
1234 /********************************************************************************
1235  * Take a command and give it to the controller, returns 0 if successful, or
1236  * EBUSY if the command should be retried later.
1237  */
1238 static int
1239 amr_start(struct amr_command *ac)
1240 {
1241     struct amr_softc    *sc = ac->ac_sc;
1242     int                 done, s, i;
1243
1244     debug_called(3);
1245
1246     /* mark command as busy so that polling consumer can tell */
1247     ac->ac_flags |= AMR_CMD_BUSY;
1248
1249     /* get a command slot (freed in amr_done) */
1250     if (amr_getslot(ac))
1251         return(EBUSY);
1252
1253     /* now we have a slot, we can map the command (unmapped in amr_complete) */
1254     amr_mapcmd(ac);
1255
1256     /* mark the new mailbox we are going to copy in as busy */
1257     ac->ac_mailbox.mb_busy = 1;
1258
1259     /* clear the poll/ack fields in the mailbox */
1260     sc->amr_mailbox->mb_poll = 0;
1261     sc->amr_mailbox->mb_ack = 0;
1262
1263     /* 
1264      * Save the slot number so that we can locate this command when complete.
1265      * Note that ident = 0 seems to be special, so we don't use it.
1266      */
1267     ac->ac_mailbox.mb_ident = ac->ac_slot + 1;
1268
1269     /* 
1270      * Spin waiting for the mailbox, give up after ~1 second.  We expect the
1271      * controller to be able to handle our I/O.
1272      *
1273      * XXX perhaps we should wait for less time, and count on the deferred command
1274      * handling to deal with retries?
1275      */
1276     debug(4, "wait for mailbox");
1277     for (i = 10000, done = 0; (i > 0) && !done; i--) {
1278         s = splbio();
1279         
1280         /* is the mailbox free? */
1281         if (sc->amr_mailbox->mb_busy == 0) {
1282             debug(4, "got mailbox");
1283             sc->amr_mailbox64->mb64_segment = 0;
1284             bcopy(&ac->ac_mailbox, (void *)(uintptr_t)(volatile void *)sc->amr_mailbox, AMR_MBOX_CMDSIZE);
1285             done = 1;
1286
1287             /* not free, spin waiting */
1288         } else {
1289             debug(4, "busy flag %x\n", sc->amr_mailbox->mb_busy);
1290             /* this is somewhat ugly */
1291             DELAY(100);
1292         }
1293         splx(s);        /* drop spl to allow completion interrupts */
1294     }
1295
1296     /*
1297      * Now give the command to the controller
1298      */
1299     if (done) {
1300         if (sc->amr_submit_command(sc)) {
1301             /* the controller wasn't ready to take the command, forget that we tried to post it */
1302             sc->amr_mailbox->mb_busy = 0;
1303             return(EBUSY);
1304         }
1305         debug(3, "posted command");
1306         return(0);
1307     }
1308     
1309     /*
1310      * The controller wouldn't take the command.  Return the command as busy
1311      * so that it is retried later.
1312      */
1313     return(EBUSY);
1314 }
1315
1316 /********************************************************************************
1317  * Extract one or more completed commands from the controller (sc)
1318  *
1319  * Returns nonzero if any commands on the work queue were marked as completed.
1320  */
1321 int
1322 amr_done(struct amr_softc *sc)
1323 {
1324     struct amr_command  *ac;
1325     struct amr_mailbox  mbox;
1326     int                 i, idx, result;
1327     
1328     debug_called(3);
1329
1330     /* See if there's anything for us to do */
1331     result = 0;
1332
1333     /* loop collecting completed commands */
1334     for (;;) {
1335         /* poll for a completed command's identifier and status */
1336         if (sc->amr_get_work(sc, &mbox)) {
1337             result = 1;
1338             
1339             /* iterate over completed commands in this result */
1340             for (i = 0; i < mbox.mb_nstatus; i++) {
1341                 /* get pointer to busy command */
1342                 idx = mbox.mb_completed[i] - 1;
1343                 ac = sc->amr_busycmd[idx];
1344
1345                 /* really a busy command? */
1346                 if (ac != NULL) {
1347
1348                     /* pull the command from the busy index */
1349                     sc->amr_busycmd[idx] = NULL;
1350                     sc->amr_busyslots--;
1351                 
1352                     /* save status for later use */
1353                     ac->ac_status = mbox.mb_status;
1354                     amr_enqueue_completed(ac);
1355                     debug(3, "completed command with status %x", mbox.mb_status);
1356                 } else {
1357                     device_printf(sc->amr_dev, "bad slot %d completed\n", idx);
1358                 }
1359             }
1360         } else {
1361             break;      /* no work */
1362         }
1363     }
1364     
1365     /* if we've completed any commands, try posting some more */
1366     if (result)
1367         amr_startio(sc);
1368     
1369     /* handle completion and timeouts */
1370 #if __FreeBSD_version >= 500005
1371     if (sc->amr_state & AMR_STATE_INTEN) 
1372         taskqueue_enqueue(taskqueue_swi, &sc->amr_task_complete);
1373     else
1374 #endif
1375         amr_complete(sc, 0);
1376     
1377     return(result);
1378 }
1379
1380 /********************************************************************************
1381  * Do completion processing on done commands on (sc)
1382  */
1383 static void
1384 amr_complete(void *context, int pending)
1385 {
1386     struct amr_softc    *sc = (struct amr_softc *)context;
1387     struct amr_command  *ac;
1388
1389     debug_called(3);
1390
1391     /* pull completed commands off the queue */
1392     for (;;) {
1393         ac = amr_dequeue_completed(sc);
1394         if (ac == NULL)
1395             break;
1396
1397         /* unmap the command's data buffer */
1398         amr_unmapcmd(ac);
1399
1400         /* unbusy the command */
1401         ac->ac_flags &= ~AMR_CMD_BUSY;
1402             
1403         /* 
1404          * Is there a completion handler? 
1405          */
1406         if (ac->ac_complete != NULL) {
1407             ac->ac_complete(ac);
1408             
1409             /* 
1410              * Is someone sleeping on this one?
1411              */
1412         } else if (ac->ac_flags & AMR_CMD_SLEEP) {
1413             wakeup(ac);
1414         }
1415
1416         if(!sc->amr_busyslots) {
1417             wakeup(sc);
1418         }
1419     }
1420 }
1421
1422 /********************************************************************************
1423  ********************************************************************************
1424                                                         Command Buffer Management
1425  ********************************************************************************
1426  ********************************************************************************/
1427
1428 /********************************************************************************
1429  * Get a new command buffer.
1430  *
1431  * This may return NULL in low-memory cases.
1432  *
1433  * If possible, we recycle a command buffer that's been used before.
1434  */
1435 struct amr_command *
1436 amr_alloccmd(struct amr_softc *sc)
1437 {
1438     struct amr_command  *ac;
1439
1440     debug_called(3);
1441
1442     ac = amr_dequeue_free(sc);
1443     if (ac == NULL) {
1444         amr_alloccmd_cluster(sc);
1445         ac = amr_dequeue_free(sc);
1446     }
1447     if (ac == NULL)
1448         return(NULL);
1449
1450     /* clear out significant fields */
1451     ac->ac_slot = 0;
1452     ac->ac_status = 0;
1453     bzero(&ac->ac_mailbox, sizeof(struct amr_mailbox));
1454     ac->ac_flags = 0;
1455     ac->ac_bio = NULL;
1456     ac->ac_data = NULL;
1457     ac->ac_ccb_data = NULL;
1458     ac->ac_complete = NULL;
1459     return(ac);
1460 }
1461
1462 /********************************************************************************
1463  * Release a command buffer for recycling.
1464  */
1465 void
1466 amr_releasecmd(struct amr_command *ac)
1467 {
1468     debug_called(3);
1469
1470     amr_enqueue_free(ac);
1471 }
1472
1473 /********************************************************************************
1474  * Allocate a new command cluster and initialise it.
1475  */
1476 static void
1477 amr_alloccmd_cluster(struct amr_softc *sc)
1478 {
1479     struct amr_command_cluster  *acc;
1480     struct amr_command          *ac;
1481     int                         s, i;
1482
1483     acc = malloc(AMR_CMD_CLUSTERSIZE, M_DEVBUF, M_NOWAIT);
1484     if (acc != NULL) {
1485         s = splbio();
1486         TAILQ_INSERT_TAIL(&sc->amr_cmd_clusters, acc, acc_link);
1487         splx(s);
1488         for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++) {
1489             ac = &acc->acc_command[i];
1490             bzero(ac, sizeof(*ac));
1491             ac->ac_sc = sc;
1492             if (!bus_dmamap_create(sc->amr_buffer_dmat, 0, &ac->ac_dmamap) &&
1493                 !bus_dmamap_create(sc->amr_buffer_dmat, 0, &ac->ac_ccb_dmamap))
1494                 amr_releasecmd(ac);
1495         }
1496     }
1497 }
1498
1499 /********************************************************************************
1500  * Free a command cluster
1501  */
1502 static void
1503 amr_freecmd_cluster(struct amr_command_cluster *acc)
1504 {
1505     struct amr_softc    *sc = acc->acc_command[0].ac_sc;
1506     int                 i;
1507
1508     for (i = 0; i < AMR_CMD_CLUSTERCOUNT; i++)
1509         bus_dmamap_destroy(sc->amr_buffer_dmat, acc->acc_command[i].ac_dmamap);
1510     free(acc, M_DEVBUF);
1511 }
1512
1513 /********************************************************************************
1514  ********************************************************************************
1515                                                          Interface-specific Shims
1516  ********************************************************************************
1517  ********************************************************************************/
1518
1519 /********************************************************************************
1520  * Tell the controller that the mailbox contains a valid command
1521  */
1522 static int
1523 amr_quartz_submit_command(struct amr_softc *sc)
1524 {
1525     debug_called(3);
1526
1527     if (AMR_QGET_IDB(sc) & AMR_QIDB_SUBMIT)
1528         return(EBUSY);
1529     AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_SUBMIT);
1530     return(0);
1531 }
1532
1533 static int
1534 amr_std_submit_command(struct amr_softc *sc)
1535 {
1536     debug_called(3);
1537
1538     if (AMR_SGET_MBSTAT(sc) & AMR_SMBOX_BUSYFLAG)
1539         return(EBUSY);
1540     AMR_SPOST_COMMAND(sc);
1541     return(0);
1542 }
1543
1544 /********************************************************************************
1545  * Claim any work that the controller has completed; acknowledge completion,
1546  * save details of the completion in (mbsave)
1547  */
1548 static int
1549 amr_quartz_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
1550 {
1551     int         s, worked;
1552     u_int32_t   outd;
1553
1554     debug_called(3);
1555
1556     worked = 0;
1557     s = splbio();
1558
1559     /* work waiting for us? */
1560     if ((outd = AMR_QGET_ODB(sc)) == AMR_QODB_READY) {
1561
1562         /* save mailbox, which contains a list of completed commands */
1563         bcopy((void *)(uintptr_t)(volatile void *)sc->amr_mailbox, mbsave, sizeof(*mbsave));
1564
1565         /* acknowledge interrupt */
1566         AMR_QPUT_ODB(sc, AMR_QODB_READY);
1567
1568         /* acknowledge that we have the commands */
1569         AMR_QPUT_IDB(sc, sc->amr_mailboxphys | AMR_QIDB_ACK);
1570
1571 #ifndef AMR_QUARTZ_GOFASTER
1572         /*
1573          * This waits for the controller to notice that we've taken the
1574          * command from it.  It's very inefficient, and we shouldn't do it,
1575          * but if we remove this code, we stop completing commands under
1576          * load.
1577          *
1578          * Peter J says we shouldn't do this.  The documentation says we
1579          * should.  Who is right?
1580          */
1581         while(AMR_QGET_IDB(sc) & AMR_QIDB_ACK)
1582             ;                           /* XXX aiee! what if it dies? */
1583 #endif
1584
1585         worked = 1;                     /* got some work */
1586     }
1587
1588     splx(s);
1589     return(worked);
1590 }
1591
1592 static int
1593 amr_std_get_work(struct amr_softc *sc, struct amr_mailbox *mbsave)
1594 {
1595     int         s, worked;
1596     u_int8_t    istat;
1597
1598     debug_called(3);
1599
1600     worked = 0;
1601     s = splbio();
1602
1603     /* check for valid interrupt status */
1604     istat = AMR_SGET_ISTAT(sc);
1605     if ((istat & AMR_SINTR_VALID) != 0) {
1606         AMR_SPUT_ISTAT(sc, istat);      /* ack interrupt status */
1607
1608         /* save mailbox, which contains a list of completed commands */
1609         bcopy((void *)(uintptr_t)(volatile void *)sc->amr_mailbox, mbsave, sizeof(*mbsave));
1610
1611         AMR_SACK_INTERRUPT(sc);         /* acknowledge we have the mailbox */
1612         worked = 1;
1613     }
1614
1615     splx(s);
1616     return(worked);
1617 }
1618
1619 /********************************************************************************
1620  * Notify the controller of the mailbox location.
1621  */
1622 static void
1623 amr_std_attach_mailbox(struct amr_softc *sc)
1624 {
1625
1626     /* program the mailbox physical address */
1627     AMR_SBYTE_SET(sc, AMR_SMBOX_0, sc->amr_mailboxphys         & 0xff);
1628     AMR_SBYTE_SET(sc, AMR_SMBOX_1, (sc->amr_mailboxphys >>  8) & 0xff);
1629     AMR_SBYTE_SET(sc, AMR_SMBOX_2, (sc->amr_mailboxphys >> 16) & 0xff);
1630     AMR_SBYTE_SET(sc, AMR_SMBOX_3, (sc->amr_mailboxphys >> 24) & 0xff);
1631     AMR_SBYTE_SET(sc, AMR_SMBOX_ENABLE, AMR_SMBOX_ADDR);
1632
1633     /* clear any outstanding interrupt and enable interrupts proper */
1634     AMR_SACK_INTERRUPT(sc);
1635     AMR_SENABLE_INTR(sc);
1636 }
1637
1638 #ifdef AMR_BOARD_INIT
1639 /********************************************************************************
1640  * Initialise the controller
1641  */
1642 static int
1643 amr_quartz_init(struct amr_softc *sc)
1644 {
1645     int         status, ostatus;
1646
1647     device_printf(sc->amr_dev, "initial init status %x\n", AMR_QGET_INITSTATUS(sc));
1648
1649     AMR_QRESET(sc);
1650
1651     ostatus = 0xff;
1652     while ((status = AMR_QGET_INITSTATUS(sc)) != AMR_QINIT_DONE) {
1653         if (status != ostatus) {
1654             device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_qinit, status));
1655             ostatus = status;
1656         }
1657         switch (status) {
1658         case AMR_QINIT_NOMEM:
1659             return(ENOMEM);
1660
1661         case AMR_QINIT_SCAN:
1662             /* XXX we could print channel/target here */
1663             break;
1664         }
1665     }
1666     return(0);
1667 }
1668
1669 static int
1670 amr_std_init(struct amr_softc *sc)
1671 {
1672     int         status, ostatus;
1673
1674     device_printf(sc->amr_dev, "initial init status %x\n", AMR_SGET_INITSTATUS(sc));
1675
1676     AMR_SRESET(sc);
1677  
1678     ostatus = 0xff;
1679     while ((status = AMR_SGET_INITSTATUS(sc)) != AMR_SINIT_DONE) {
1680         if (status != ostatus) {
1681             device_printf(sc->amr_dev, "(%x) %s\n", status, amr_describe_code(amr_table_sinit, status));
1682             ostatus = status;
1683         }
1684         switch (status) {
1685         case AMR_SINIT_NOMEM:
1686             return(ENOMEM);
1687
1688         case AMR_SINIT_INPROG:
1689             /* XXX we could print channel/target here? */
1690             break;
1691         }
1692     }
1693     return(0);
1694 }
1695 #endif
1696
1697 /********************************************************************************
1698  ********************************************************************************
1699                                                                         Debugging
1700  ********************************************************************************
1701  ********************************************************************************/
1702
1703 /********************************************************************************
1704  * Identify the controller and print some information about it.
1705  */
1706 static void
1707 amr_describe_controller(struct amr_softc *sc)
1708 {
1709     struct amr_prodinfo *ap;
1710     struct amr_enquiry  *ae;
1711     char                *prod;
1712
1713     /*
1714      * Try to get 40LD product info, which tells us what the card is labelled as.
1715      */
1716     if ((ap = amr_enquiry(sc, 2048, AMR_CMD_CONFIG, AMR_CONFIG_PRODUCT_INFO, 0)) != NULL) {
1717         device_printf(sc->amr_dev, "<LSILogic %.80s> Firmware %.16s, BIOS %.16s, %dMB RAM\n",
1718                       ap->ap_product, ap->ap_firmware, ap->ap_bios,
1719                       ap->ap_memsize);
1720
1721         free(ap, M_DEVBUF);
1722         return;
1723     }
1724
1725     /*
1726      * Try 8LD extended ENQUIRY to get controller signature, and use lookup table.
1727      */
1728     if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_EXT_ENQUIRY2, 0, 0)) != NULL) {
1729         prod = amr_describe_code(amr_table_adaptertype, ae->ae_signature);
1730
1731     } else if ((ae = (struct amr_enquiry *)amr_enquiry(sc, 2048, AMR_CMD_ENQUIRY, 0, 0)) != NULL) {
1732
1733         /*
1734          * Try to work it out based on the PCI signatures.
1735          */
1736         switch (pci_get_device(sc->amr_dev)) {
1737         case 0x9010:
1738             prod = "Series 428";
1739             break;
1740         case 0x9060:
1741             prod = "Series 434";
1742             break;
1743         default:
1744             prod = "unknown controller";
1745             break;
1746         }
1747     } else {
1748         prod = "unsupported controller";
1749     }
1750
1751     /*
1752      * HP NetRaid controllers have a special encoding of the firmware and
1753      * BIOS versions. The AMI version seems to have it as strings whereas
1754      * the HP version does it with a leading uppercase character and two
1755      * binary numbers.
1756      */
1757      
1758     if(ae->ae_adapter.aa_firmware[2] >= 'A' &&
1759        ae->ae_adapter.aa_firmware[2] <= 'Z' &&
1760        ae->ae_adapter.aa_firmware[1] <  ' ' &&
1761        ae->ae_adapter.aa_firmware[0] <  ' ' &&
1762        ae->ae_adapter.aa_bios[2] >= 'A'     &&
1763        ae->ae_adapter.aa_bios[2] <= 'Z'     &&
1764        ae->ae_adapter.aa_bios[1] <  ' '     &&
1765        ae->ae_adapter.aa_bios[0] <  ' ') {
1766
1767         /* this looks like we have an HP NetRaid version of the MegaRaid */
1768
1769         if(ae->ae_signature == AMR_SIG_438) {
1770                 /* the AMI 438 is a NetRaid 3si in HP-land */
1771                 prod = "HP NetRaid 3si";
1772         }
1773         
1774         device_printf(sc->amr_dev, "<%s> Firmware %c.%02d.%02d, BIOS %c.%02d.%02d, %dMB RAM\n",
1775                       prod, ae->ae_adapter.aa_firmware[2],
1776                       ae->ae_adapter.aa_firmware[1],
1777                       ae->ae_adapter.aa_firmware[0],
1778                       ae->ae_adapter.aa_bios[2],
1779                       ae->ae_adapter.aa_bios[1],
1780                       ae->ae_adapter.aa_bios[0],
1781                       ae->ae_adapter.aa_memorysize);            
1782     } else {
1783         device_printf(sc->amr_dev, "<%s> Firmware %.4s, BIOS %.4s, %dMB RAM\n", 
1784                       prod, ae->ae_adapter.aa_firmware, ae->ae_adapter.aa_bios,
1785                       ae->ae_adapter.aa_memorysize);
1786     }           
1787     free(ae, M_DEVBUF);
1788 }
1789
1790 #ifdef AMR_DEBUG
1791 /********************************************************************************
1792  * Print the command (ac) in human-readable format
1793  */
1794 #if 0
1795 static void
1796 amr_printcommand(struct amr_command *ac)
1797 {
1798     struct amr_softc    *sc = ac->ac_sc;
1799     struct amr_sgentry  *sg;
1800     int                 i;
1801     
1802     device_printf(sc->amr_dev, "cmd %x  ident %d  drive %d\n",
1803                   ac->ac_mailbox.mb_command, ac->ac_mailbox.mb_ident, ac->ac_mailbox.mb_drive);
1804     device_printf(sc->amr_dev, "blkcount %d  lba %d\n", 
1805                   ac->ac_mailbox.mb_blkcount, ac->ac_mailbox.mb_lba);
1806     device_printf(sc->amr_dev, "virtaddr %p  length %lu\n", ac->ac_data, (unsigned long)ac->ac_length);
1807     device_printf(sc->amr_dev, "sg physaddr %08x  nsg %d\n",
1808                   ac->ac_mailbox.mb_physaddr, ac->ac_mailbox.mb_nsgelem);
1809     device_printf(sc->amr_dev, "ccb %p  bio %p\n", ac->ac_ccb_data, ac->ac_bio);
1810
1811     /* get base address of s/g table */
1812     sg = sc->amr_sgtable + (ac->ac_slot * AMR_NSEG);
1813     for (i = 0; i < ac->ac_mailbox.mb_nsgelem; i++, sg++)
1814         device_printf(sc->amr_dev, "  %x/%d\n", sg->sg_addr, sg->sg_count);
1815 }
1816 #endif
1817 #endif