Merge branch 'vendor/TCPDUMP' and update build for the update.
[dragonfly.git] / sys / dev / raid / mly / mly.c
1 /*-
2  * Copyright (c) 2000, 2001 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  *      $FreeBSD: src/sys/dev/mly/mly.c,v 1.3.2.3 2001/03/05 20:17:24 msmith Exp $
28  *      $DragonFly: src/sys/dev/raid/mly/mly.c,v 1.21 2008/05/18 20:30:23 pavalos Exp $
29  */
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/malloc.h>
34 #include <sys/kernel.h>
35 #include <sys/bus.h>
36 #include <sys/conf.h>
37 #include <sys/device.h>
38 #include <sys/ctype.h>
39 #include <sys/stat.h>
40 #include <sys/rman.h>
41 #include <sys/thread2.h>
42
43 #include <bus/cam/cam.h>
44 #include <bus/cam/cam_ccb.h>
45 #include <bus/cam/cam_periph.h>
46 #include <bus/cam/cam_sim.h>
47 #include <bus/cam/cam_xpt_sim.h>
48 #include <bus/cam/scsi/scsi_all.h>
49 #include <bus/cam/scsi/scsi_message.h>
50
51 #include <bus/pci/pcireg.h>
52 #include <bus/pci/pcivar.h>
53
54 #include "mlyreg.h"
55 #include "mlyio.h"
56 #include "mlyvar.h"
57 #include "mly_tables.h"
58
59 static int      mly_probe(device_t dev);
60 static int      mly_attach(device_t dev);
61 static int      mly_pci_attach(struct mly_softc *sc);
62 static int      mly_detach(device_t dev);
63 static int      mly_shutdown(device_t dev);
64 static void     mly_intr(void *arg);
65
66 static int      mly_sg_map(struct mly_softc *sc);
67 static void     mly_sg_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error);
68 static int      mly_mmbox_map(struct mly_softc *sc);
69 static void     mly_mmbox_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error);
70 static void     mly_free(struct mly_softc *sc);
71
72 static int      mly_get_controllerinfo(struct mly_softc *sc);
73 static void     mly_scan_devices(struct mly_softc *sc);
74 static void     mly_rescan_btl(struct mly_softc *sc, int bus, int target);
75 static void     mly_complete_rescan(struct mly_command *mc);
76 static int      mly_get_eventstatus(struct mly_softc *sc);
77 static int      mly_enable_mmbox(struct mly_softc *sc);
78 static int      mly_flush(struct mly_softc *sc);
79 static int      mly_ioctl(struct mly_softc *sc, struct mly_command_ioctl *ioctl, void **data, 
80                           size_t datasize, u_int8_t *status, void *sense_buffer, size_t *sense_length);
81 static void     mly_check_event(struct mly_softc *sc);
82 static void     mly_fetch_event(struct mly_softc *sc);
83 static void     mly_complete_event(struct mly_command *mc);
84 static void     mly_process_event(struct mly_softc *sc, struct mly_event *me);
85 static void     mly_periodic(void *data);
86
87 static int      mly_immediate_command(struct mly_command *mc);
88 static int      mly_start(struct mly_command *mc);
89 static void     mly_done(struct mly_softc *sc);
90 static void     mly_complete(void *context, int pending);
91
92 static int      mly_alloc_command(struct mly_softc *sc, struct mly_command **mcp);
93 static void     mly_release_command(struct mly_command *mc);
94 static void     mly_alloc_commands_map(void *arg, bus_dma_segment_t *segs, int nseg, int error);
95 static int      mly_alloc_commands(struct mly_softc *sc);
96 static void     mly_release_commands(struct mly_softc *sc);
97 static void     mly_map_command(struct mly_command *mc);
98 static void     mly_unmap_command(struct mly_command *mc);
99
100 static int      mly_cam_attach(struct mly_softc *sc);
101 static void     mly_cam_detach(struct mly_softc *sc);
102 static void     mly_cam_rescan_btl(struct mly_softc *sc, int bus, int target);
103 static void     mly_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb);
104 static void     mly_cam_action(struct cam_sim *sim, union ccb *ccb);
105 static int      mly_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio);
106 static void     mly_cam_poll(struct cam_sim *sim);
107 static void     mly_cam_complete(struct mly_command *mc);
108 static struct cam_periph *mly_find_periph(struct mly_softc *sc, int bus, int target);
109 static int      mly_name_device(struct mly_softc *sc, int bus, int target);
110
111 static int      mly_fwhandshake(struct mly_softc *sc);
112
113 static void     mly_describe_controller(struct mly_softc *sc);
114 #ifdef MLY_DEBUG
115 static void     mly_printstate(struct mly_softc *sc);
116 static void     mly_print_command(struct mly_command *mc);
117 static void     mly_print_packet(struct mly_command *mc);
118 static void     mly_panic(struct mly_softc *sc, char *reason);
119 #endif
120 void            mly_print_controller(int controller);
121 static int      mly_timeout(struct mly_softc *sc);
122
123
124 static d_open_t         mly_user_open;
125 static d_close_t        mly_user_close;
126 static d_ioctl_t        mly_user_ioctl;
127 static int      mly_user_command(struct mly_softc *sc, struct mly_user_command *uc);
128 static int      mly_user_health(struct mly_softc *sc, struct mly_user_health *uh);
129
130 #define MLY_CMD_TIMEOUT         20
131
132 static device_method_t mly_methods[] = {
133     /* Device interface */
134     DEVMETHOD(device_probe,     mly_probe),
135     DEVMETHOD(device_attach,    mly_attach),
136     DEVMETHOD(device_detach,    mly_detach),
137     DEVMETHOD(device_shutdown,  mly_shutdown),
138     { 0, 0 }
139 };
140
141 static driver_t mly_pci_driver = {
142         "mly",
143         mly_methods,
144         sizeof(struct mly_softc)
145 };
146
147 static devclass_t       mly_devclass;
148 DRIVER_MODULE(mly, pci, mly_pci_driver, mly_devclass, 0, 0);
149
150 #define MLY_CDEV_MAJOR  158
151
152 static struct dev_ops mly_ops = {
153     { "mly", MLY_CDEV_MAJOR, 0 },
154     .d_open =   mly_user_open,
155     .d_close =  mly_user_close,
156     .d_ioctl =  mly_user_ioctl,
157 };
158
159 /********************************************************************************
160  ********************************************************************************
161                                                                  Device Interface
162  ********************************************************************************
163  ********************************************************************************/
164
165 static struct mly_ident
166 {
167     u_int16_t           vendor;
168     u_int16_t           device;
169     u_int16_t           subvendor;
170     u_int16_t           subdevice;
171     int                 hwif;
172     char                *desc;
173 } mly_identifiers[] = {
174     {0x1069, 0xba56, 0x1069, 0x0040, MLY_HWIF_STRONGARM, "Mylex eXtremeRAID 2000"},
175     {0x1069, 0xba56, 0x1069, 0x0030, MLY_HWIF_STRONGARM, "Mylex eXtremeRAID 3000"},
176     {0x1069, 0x0050, 0x1069, 0x0050, MLY_HWIF_I960RX,    "Mylex AcceleRAID 352"},
177     {0x1069, 0x0050, 0x1069, 0x0052, MLY_HWIF_I960RX,    "Mylex AcceleRAID 170"},
178     {0x1069, 0x0050, 0x1069, 0x0054, MLY_HWIF_I960RX,    "Mylex AcceleRAID 160"},
179     {0, 0, 0, 0, 0, 0}
180 };
181
182 /********************************************************************************
183  * Compare the provided PCI device with the list we support.
184  */
185 static int
186 mly_probe(device_t dev)
187 {
188     struct mly_ident    *m;
189
190     debug_called(1);
191
192     for (m = mly_identifiers; m->vendor != 0; m++) {
193         if ((m->vendor == pci_get_vendor(dev)) &&
194             (m->device == pci_get_device(dev)) &&
195             ((m->subvendor == 0) || ((m->subvendor == pci_get_subvendor(dev)) &&
196                                      (m->subdevice == pci_get_subdevice(dev))))) {
197             
198             device_set_desc(dev, m->desc);
199             return(BUS_PROBE_DEFAULT);  /* allow room to be overridden */
200         }
201     }
202     return(ENXIO);
203 }
204
205 /********************************************************************************
206  * Initialise the controller and softc
207  */
208 static int
209 mly_attach(device_t dev)
210 {
211     struct mly_softc    *sc = device_get_softc(dev);
212     int                 error;
213
214     debug_called(1);
215
216     sc->mly_dev = dev;
217
218 #ifdef MLY_DEBUG
219     if (device_get_unit(sc->mly_dev) == 0)
220         mly_softc0 = sc;
221 #endif    
222
223     /*
224      * Do PCI-specific initialisation.
225      */
226     if ((error = mly_pci_attach(sc)) != 0)
227         goto out;
228
229     callout_init(&sc->mly_periodic);
230     callout_init(&sc->mly_timeout);
231
232     /*
233      * Initialise per-controller queues.
234      */
235     mly_initq_free(sc);
236     mly_initq_busy(sc);
237     mly_initq_complete(sc);
238
239     /*
240      * Initialise command-completion task.
241      */
242     TASK_INIT(&sc->mly_task_complete, 0, mly_complete, sc);
243
244     /* disable interrupts before we start talking to the controller */
245     MLY_MASK_INTERRUPTS(sc);
246
247     /* 
248      * Wait for the controller to come ready, handshake with the firmware if required.
249      * This is typically only necessary on platforms where the controller BIOS does not
250      * run.
251      */
252     if ((error = mly_fwhandshake(sc)))
253         goto out;
254
255     /*
256      * Allocate initial command buffers.
257      */
258     if ((error = mly_alloc_commands(sc)))
259         goto out;
260
261     /* 
262      * Obtain controller feature information
263      */
264     if ((error = mly_get_controllerinfo(sc)))
265         goto out;
266
267     /*
268      * Reallocate command buffers now we know how many we want.
269      */
270     mly_release_commands(sc);
271     if ((error = mly_alloc_commands(sc)))
272         goto out;
273
274     /*
275      * Get the current event counter for health purposes, populate the initial
276      * health status buffer.
277      */
278     if ((error = mly_get_eventstatus(sc)))
279         goto out;
280
281     /*
282      * Enable memory-mailbox mode.
283      */
284     if ((error = mly_enable_mmbox(sc)))
285         goto out;
286
287     /*
288      * Attach to CAM.
289      */
290     if ((error = mly_cam_attach(sc)))
291         goto out;
292
293     /* 
294      * Print a little information about the controller 
295      */
296     mly_describe_controller(sc);
297
298     /*
299      * Mark all attached devices for rescan.
300      */
301     mly_scan_devices(sc);
302
303     /*
304      * Instigate the first status poll immediately.  Rescan completions won't
305      * happen until interrupts are enabled, which should still be before
306      * the SCSI subsystem gets to us, courtesy of the "SCSI settling delay".
307      */
308     mly_periodic((void *)sc);
309
310     /*
311      * Create the control device.
312      */
313     dev_ops_add(&mly_ops, -1, device_get_unit(sc->mly_dev));
314     sc->mly_dev_t = make_dev(&mly_ops, device_get_unit(sc->mly_dev),
315                                 UID_ROOT, GID_OPERATOR, S_IRUSR | S_IWUSR, 
316                                 "mly%d", device_get_unit(sc->mly_dev));
317     sc->mly_dev_t->si_drv1 = sc;
318
319     /* enable interrupts now */
320     MLY_UNMASK_INTERRUPTS(sc);
321
322 #ifdef MLY_DEBUG
323     callout_reset(&sc->mly_timeout, MLY_CMD_TIMEOUT * hz,
324                   (timeout_t *)mly_timeout, sc);
325 #endif
326
327  out:
328     if (error != 0)
329         mly_free(sc);
330     return(error);
331 }
332
333 /********************************************************************************
334  * Perform PCI-specific initialisation.
335  */
336 static int
337 mly_pci_attach(struct mly_softc *sc)
338 {
339     int                 i, error;
340     u_int32_t           command;
341
342     debug_called(1);
343
344     /* assume failure is 'not configured' */
345     error = ENXIO;
346
347     /* 
348      * Verify that the adapter is correctly set up in PCI space.
349      * 
350      * XXX we shouldn't do this; the PCI code should.
351      */
352     command = pci_read_config(sc->mly_dev, PCIR_COMMAND, 2);
353     command |= PCIM_CMD_BUSMASTEREN;
354     pci_write_config(sc->mly_dev, PCIR_COMMAND, command, 2);
355     command = pci_read_config(sc->mly_dev, PCIR_COMMAND, 2);
356     if (!(command & PCIM_CMD_BUSMASTEREN)) {
357         mly_printf(sc, "can't enable busmaster feature\n");
358         goto fail;
359     }
360     if ((command & PCIM_CMD_MEMEN) == 0) {
361         mly_printf(sc, "memory window not available\n");
362         goto fail;
363     }
364
365     /*
366      * Allocate the PCI register window.
367      */
368     sc->mly_regs_rid = PCIR_BAR(0);     /* first base address register */
369     if ((sc->mly_regs_resource = bus_alloc_resource_any(sc->mly_dev, 
370             SYS_RES_MEMORY, &sc->mly_regs_rid, RF_ACTIVE)) == NULL) {
371         mly_printf(sc, "can't allocate register window\n");
372         goto fail;
373     }
374     sc->mly_btag = rman_get_bustag(sc->mly_regs_resource);
375     sc->mly_bhandle = rman_get_bushandle(sc->mly_regs_resource);
376
377     /* 
378      * Allocate and connect our interrupt.
379      */
380     sc->mly_irq_rid = 0;
381     if ((sc->mly_irq = bus_alloc_resource_any(sc->mly_dev, SYS_RES_IRQ, 
382                     &sc->mly_irq_rid, RF_SHAREABLE | RF_ACTIVE)) == NULL) {
383         mly_printf(sc, "can't allocate interrupt\n");
384         goto fail;
385     }
386     error = bus_setup_intr(sc->mly_dev, sc->mly_irq, 0,
387                            mly_intr, sc, &sc->mly_intr, NULL);
388     if (error) {
389         mly_printf(sc, "can't set up interrupt\n");
390         goto fail;
391     }
392
393     /* assume failure is 'out of memory' */
394     error = ENOMEM;
395
396     /*
397      * Allocate the parent bus DMA tag appropriate for our PCI interface.
398      * 
399      * Note that all of these controllers are 64-bit capable.
400      */
401     if (bus_dma_tag_create(NULL,                        /* parent */
402                            1, 0,                        /* alignment, boundary */
403                            BUS_SPACE_MAXADDR_32BIT,     /* lowaddr */
404                            BUS_SPACE_MAXADDR,           /* highaddr */
405                            NULL, NULL,                  /* filter, filterarg */
406                            MAXBSIZE, MLY_MAX_SGENTRIES, /* maxsize, nsegments */
407                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
408                            BUS_DMA_ALLOCNOW,            /* flags */
409                            &sc->mly_parent_dmat)) {
410         mly_printf(sc, "can't allocate parent DMA tag\n");
411         goto fail;
412     }
413
414     /*
415      * Create DMA tag for mapping buffers into controller-addressable space.
416      */
417     if (bus_dma_tag_create(sc->mly_parent_dmat,         /* parent */
418                            1, 0,                        /* alignment, boundary */
419                            BUS_SPACE_MAXADDR,           /* lowaddr */
420                            BUS_SPACE_MAXADDR,           /* highaddr */
421                            NULL, NULL,                  /* filter, filterarg */
422                            MAXBSIZE, MLY_MAX_SGENTRIES, /* maxsize, nsegments */
423                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
424                            0,                           /* flags */
425                            &sc->mly_buffer_dmat)) {
426         mly_printf(sc, "can't allocate buffer DMA tag\n");
427         goto fail;
428     }
429
430     /*
431      * Initialise the DMA tag for command packets.
432      */
433     if (bus_dma_tag_create(sc->mly_parent_dmat,         /* parent */
434                            1, 0,                        /* alignment, boundary */
435                            BUS_SPACE_MAXADDR,           /* lowaddr */
436                            BUS_SPACE_MAXADDR,           /* highaddr */
437                            NULL, NULL,                  /* filter, filterarg */
438                            sizeof(union mly_command_packet) * MLY_MAX_COMMANDS, 1,      /* maxsize, nsegments */
439                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
440                            BUS_DMA_ALLOCNOW,            /* flags */
441                            &sc->mly_packet_dmat)) {
442         mly_printf(sc, "can't allocate command packet DMA tag\n");
443         goto fail;
444     }
445
446     /* 
447      * Detect the hardware interface version 
448      */
449     for (i = 0; mly_identifiers[i].vendor != 0; i++) {
450         if ((mly_identifiers[i].vendor == pci_get_vendor(sc->mly_dev)) &&
451             (mly_identifiers[i].device == pci_get_device(sc->mly_dev))) {
452             sc->mly_hwif = mly_identifiers[i].hwif;
453             switch(sc->mly_hwif) {
454             case MLY_HWIF_I960RX:
455                 debug(1, "set hardware up for i960RX");
456                 sc->mly_doorbell_true = 0x00;
457                 sc->mly_command_mailbox =  MLY_I960RX_COMMAND_MAILBOX;
458                 sc->mly_status_mailbox =   MLY_I960RX_STATUS_MAILBOX;
459                 sc->mly_idbr =             MLY_I960RX_IDBR;
460                 sc->mly_odbr =             MLY_I960RX_ODBR;
461                 sc->mly_error_status =     MLY_I960RX_ERROR_STATUS;
462                 sc->mly_interrupt_status = MLY_I960RX_INTERRUPT_STATUS;
463                 sc->mly_interrupt_mask =   MLY_I960RX_INTERRUPT_MASK;
464                 break;
465             case MLY_HWIF_STRONGARM:
466                 debug(1, "set hardware up for StrongARM");
467                 sc->mly_doorbell_true = 0xff;           /* doorbell 'true' is 0 */
468                 sc->mly_command_mailbox =  MLY_STRONGARM_COMMAND_MAILBOX;
469                 sc->mly_status_mailbox =   MLY_STRONGARM_STATUS_MAILBOX;
470                 sc->mly_idbr =             MLY_STRONGARM_IDBR;
471                 sc->mly_odbr =             MLY_STRONGARM_ODBR;
472                 sc->mly_error_status =     MLY_STRONGARM_ERROR_STATUS;
473                 sc->mly_interrupt_status = MLY_STRONGARM_INTERRUPT_STATUS;
474                 sc->mly_interrupt_mask =   MLY_STRONGARM_INTERRUPT_MASK;
475                 break;
476             }
477             break;
478         }
479     }
480
481     /*
482      * Create the scatter/gather mappings.
483      */
484     if ((error = mly_sg_map(sc)))
485         goto fail;
486
487     /*
488      * Allocate and map the memory mailbox
489      */
490     if ((error = mly_mmbox_map(sc)))
491         goto fail;
492
493     error = 0;
494             
495 fail:
496     return(error);
497 }
498
499 /********************************************************************************
500  * Shut the controller down and detach all our resources.
501  */
502 static int
503 mly_detach(device_t dev)
504 {
505     int                 error;
506
507     if ((error = mly_shutdown(dev)) != 0)
508         return(error);
509     
510     mly_free(device_get_softc(dev));
511     return(0);
512 }
513
514 /********************************************************************************
515  * Bring the controller to a state where it can be safely left alone.
516  *
517  * Note that it should not be necessary to wait for any outstanding commands,
518  * as they should be completed prior to calling here.
519  *
520  * XXX this applies for I/O, but not status polls; we should beware of
521  *     the case where a status command is running while we detach.
522  */
523 static int
524 mly_shutdown(device_t dev)
525 {
526     struct mly_softc    *sc = device_get_softc(dev);
527
528     debug_called(1);
529     
530     if (sc->mly_state & MLY_STATE_OPEN)
531         return(EBUSY);
532
533     /* kill the periodic event */
534     callout_stop(&sc->mly_periodic);
535
536     /* flush controller */
537     mly_printf(sc, "flushing cache...");
538     kprintf("%s\n", mly_flush(sc) ? "failed" : "done");
539
540     MLY_MASK_INTERRUPTS(sc);
541
542     return(0);
543 }
544
545 /*******************************************************************************
546  * Take an interrupt, or be poked by other code to look for interrupt-worthy
547  * status.
548  */
549 static void
550 mly_intr(void *arg)
551 {
552     struct mly_softc    *sc = (struct mly_softc *)arg;
553
554     debug_called(2);
555
556     mly_done(sc);
557 };
558
559 /********************************************************************************
560  ********************************************************************************
561                                                 Bus-dependant Resource Management
562  ********************************************************************************
563  ********************************************************************************/
564
565 /********************************************************************************
566  * Allocate memory for the scatter/gather tables
567  */
568 static int
569 mly_sg_map(struct mly_softc *sc)
570 {
571     size_t      segsize;
572
573     debug_called(1);
574
575     /*
576      * Create a single tag describing a region large enough to hold all of
577      * the s/g lists we will need.
578      */
579     segsize = sizeof(struct mly_sg_entry) * MLY_MAX_COMMANDS *MLY_MAX_SGENTRIES;
580     if (bus_dma_tag_create(sc->mly_parent_dmat,         /* parent */
581                            1, 0,                        /* alignment,boundary */
582                            BUS_SPACE_MAXADDR,           /* lowaddr */
583                            BUS_SPACE_MAXADDR,           /* highaddr */
584                            NULL, NULL,                  /* filter, filterarg */
585                            segsize, 1,                  /* maxsize, nsegments */
586                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
587                            BUS_DMA_ALLOCNOW,            /* flags */
588                            &sc->mly_sg_dmat)) {
589         mly_printf(sc, "can't allocate scatter/gather DMA tag\n");
590         return(ENOMEM);
591     }
592
593     /*
594      * Allocate enough s/g maps for all commands and permanently map them into
595      * controller-visible space.
596      *  
597      * XXX this assumes we can get enough space for all the s/g maps in one 
598      * contiguous slab.
599      */
600     if (bus_dmamem_alloc(sc->mly_sg_dmat, (void **)&sc->mly_sg_table,
601                          BUS_DMA_NOWAIT, &sc->mly_sg_dmamap)) {
602         mly_printf(sc, "can't allocate s/g table\n");
603         return(ENOMEM);
604     }
605     if (bus_dmamap_load(sc->mly_sg_dmat, sc->mly_sg_dmamap, sc->mly_sg_table,
606                         segsize, mly_sg_map_helper, sc, BUS_DMA_NOWAIT) != 0)
607         return (ENOMEM);
608     return(0);
609 }
610
611 /********************************************************************************
612  * Save the physical address of the base of the s/g table.
613  */
614 static void
615 mly_sg_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
616 {
617     struct mly_softc    *sc = (struct mly_softc *)arg;
618
619     debug_called(1);
620
621     /* save base of s/g table's address in bus space */
622     sc->mly_sg_busaddr = segs->ds_addr;
623 }
624
625 /********************************************************************************
626  * Allocate memory for the memory-mailbox interface
627  */
628 static int
629 mly_mmbox_map(struct mly_softc *sc)
630 {
631
632     /*
633      * Create a DMA tag for a single contiguous region large enough for the
634      * memory mailbox structure.
635      */
636     if (bus_dma_tag_create(sc->mly_parent_dmat,         /* parent */
637                            1, 0,                        /* alignment,boundary */
638                            BUS_SPACE_MAXADDR,           /* lowaddr */
639                            BUS_SPACE_MAXADDR,           /* highaddr */
640                            NULL, NULL,                  /* filter, filterarg */
641                            sizeof(struct mly_mmbox), 1, /* maxsize, nsegments */
642                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
643                            BUS_DMA_ALLOCNOW,            /* flags */
644                            &sc->mly_mmbox_dmat)) {
645         mly_printf(sc, "can't allocate memory mailbox DMA tag\n");
646         return(ENOMEM);
647     }
648
649     /*
650      * Allocate the buffer
651      */
652     if (bus_dmamem_alloc(sc->mly_mmbox_dmat, (void **)&sc->mly_mmbox, BUS_DMA_NOWAIT, &sc->mly_mmbox_dmamap)) {
653         mly_printf(sc, "can't allocate memory mailbox\n");
654         return(ENOMEM);
655     }
656     if (bus_dmamap_load(sc->mly_mmbox_dmat, sc->mly_mmbox_dmamap, sc->mly_mmbox,
657                         sizeof(struct mly_mmbox), mly_mmbox_map_helper, sc, 
658                         BUS_DMA_NOWAIT) != 0)
659         return (ENOMEM);
660     bzero(sc->mly_mmbox, sizeof(*sc->mly_mmbox));
661     return(0);
662
663 }
664
665 /********************************************************************************
666  * Save the physical address of the memory mailbox 
667  */
668 static void
669 mly_mmbox_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
670 {
671     struct mly_softc    *sc = (struct mly_softc *)arg;
672
673     debug_called(1);
674
675     sc->mly_mmbox_busaddr = segs->ds_addr;
676 }
677
678 /********************************************************************************
679  * Free all of the resources associated with (sc)
680  *
681  * Should not be called if the controller is active.
682  */
683 static void
684 mly_free(struct mly_softc *sc)
685 {
686     
687     debug_called(1);
688
689     /* Remove the management device */
690     destroy_dev(sc->mly_dev_t);
691
692     /* detach from CAM */
693     mly_cam_detach(sc);
694
695     /* release command memory */
696     mly_release_commands(sc);
697     
698     /* throw away the controllerinfo structure */
699     if (sc->mly_controllerinfo != NULL)
700         kfree(sc->mly_controllerinfo, M_DEVBUF);
701
702     /* throw away the controllerparam structure */
703     if (sc->mly_controllerparam != NULL)
704         kfree(sc->mly_controllerparam, M_DEVBUF);
705
706     /* destroy data-transfer DMA tag */
707     if (sc->mly_buffer_dmat)
708         bus_dma_tag_destroy(sc->mly_buffer_dmat);
709
710     /* free and destroy DMA memory and tag for s/g lists */
711     if (sc->mly_sg_table) {
712         bus_dmamap_unload(sc->mly_sg_dmat, sc->mly_sg_dmamap);
713         bus_dmamem_free(sc->mly_sg_dmat, sc->mly_sg_table, sc->mly_sg_dmamap);
714     }
715     if (sc->mly_sg_dmat)
716         bus_dma_tag_destroy(sc->mly_sg_dmat);
717
718     /* free and destroy DMA memory and tag for memory mailbox */
719     if (sc->mly_mmbox) {
720         bus_dmamap_unload(sc->mly_mmbox_dmat, sc->mly_mmbox_dmamap);
721         bus_dmamem_free(sc->mly_mmbox_dmat, sc->mly_mmbox, sc->mly_mmbox_dmamap);
722     }
723     if (sc->mly_mmbox_dmat)
724         bus_dma_tag_destroy(sc->mly_mmbox_dmat);
725
726     /* disconnect the interrupt handler */
727     if (sc->mly_intr)
728         bus_teardown_intr(sc->mly_dev, sc->mly_irq, sc->mly_intr);
729     if (sc->mly_irq != NULL)
730         bus_release_resource(sc->mly_dev, SYS_RES_IRQ, sc->mly_irq_rid, sc->mly_irq);
731
732     /* destroy the parent DMA tag */
733     if (sc->mly_parent_dmat)
734         bus_dma_tag_destroy(sc->mly_parent_dmat);
735
736     /* release the register window mapping */
737     if (sc->mly_regs_resource != NULL)
738         bus_release_resource(sc->mly_dev, SYS_RES_MEMORY, sc->mly_regs_rid, sc->mly_regs_resource);
739 }
740
741 /********************************************************************************
742  ********************************************************************************
743                                                                  Command Wrappers
744  ********************************************************************************
745  ********************************************************************************/
746
747 /********************************************************************************
748  * Fill in the mly_controllerinfo and mly_controllerparam fields in the softc.
749  */
750 static int
751 mly_get_controllerinfo(struct mly_softc *sc)
752 {
753     struct mly_command_ioctl    mci;
754     u_int8_t                    status;
755     int                         error;
756
757     debug_called(1);
758
759     if (sc->mly_controllerinfo != NULL)
760         kfree(sc->mly_controllerinfo, M_DEVBUF);
761
762     /* build the getcontrollerinfo ioctl and send it */
763     bzero(&mci, sizeof(mci));
764     sc->mly_controllerinfo = NULL;
765     mci.sub_ioctl = MDACIOCTL_GETCONTROLLERINFO;
766     if ((error = mly_ioctl(sc, &mci, (void **)&sc->mly_controllerinfo, sizeof(*sc->mly_controllerinfo),
767                            &status, NULL, NULL)))
768         return(error);
769     if (status != 0)
770         return(EIO);
771
772     if (sc->mly_controllerparam != NULL)
773         kfree(sc->mly_controllerparam, M_DEVBUF);
774
775     /* build the getcontrollerparameter ioctl and send it */
776     bzero(&mci, sizeof(mci));
777     sc->mly_controllerparam = NULL;
778     mci.sub_ioctl = MDACIOCTL_GETCONTROLLERPARAMETER;
779     if ((error = mly_ioctl(sc, &mci, (void **)&sc->mly_controllerparam, sizeof(*sc->mly_controllerparam),
780                            &status, NULL, NULL)))
781         return(error);
782     if (status != 0)
783         return(EIO);
784
785     return(0);
786 }
787
788 /********************************************************************************
789  * Schedule all possible devices for a rescan.
790  *
791  */
792 static void
793 mly_scan_devices(struct mly_softc *sc)
794 {
795     int         bus, target;
796
797     debug_called(1);
798
799     /*
800      * Clear any previous BTL information.
801      */
802     bzero(&sc->mly_btl, sizeof(sc->mly_btl));
803
804     /*
805      * Mark all devices as requiring a rescan, and let the next
806      * periodic scan collect them. 
807      */
808     for (bus = 0; bus < sc->mly_cam_channels; bus++)
809         if (MLY_BUS_IS_VALID(sc, bus)) 
810             for (target = 0; target < MLY_MAX_TARGETS; target++)
811                 sc->mly_btl[bus][target].mb_flags = MLY_BTL_RESCAN;
812
813 }
814
815 /********************************************************************************
816  * Rescan a device, possibly as a consequence of getting an event which suggests
817  * that it may have changed.
818  *
819  * If we suffer resource starvation, we can abandon the rescan as we'll be
820  * retried.
821  */
822 static void
823 mly_rescan_btl(struct mly_softc *sc, int bus, int target)
824 {
825     struct mly_command          *mc;
826     struct mly_command_ioctl    *mci;
827
828     debug_called(1);
829
830     /* check that this bus is valid */
831     if (!MLY_BUS_IS_VALID(sc, bus))
832         return;
833
834     /* get a command */
835     if (mly_alloc_command(sc, &mc))
836         return;
837
838     /* set up the data buffer */
839     mc->mc_data = kmalloc(sizeof(union mly_devinfo), M_DEVBUF, M_INTWAIT | M_ZERO);
840     mc->mc_flags |= MLY_CMD_DATAIN;
841     mc->mc_complete = mly_complete_rescan;
842
843     /* 
844      * Build the ioctl.
845      */
846     mci = (struct mly_command_ioctl *)&mc->mc_packet->ioctl;
847     mci->opcode = MDACMD_IOCTL;
848     mci->addr.phys.controller = 0;
849     mci->timeout.value = 30;
850     mci->timeout.scale = MLY_TIMEOUT_SECONDS;
851     if (MLY_BUS_IS_VIRTUAL(sc, bus)) {
852         mc->mc_length = mci->data_size = sizeof(struct mly_ioctl_getlogdevinfovalid);
853         mci->sub_ioctl = MDACIOCTL_GETLOGDEVINFOVALID;
854         mci->addr.log.logdev = MLY_LOGDEV_ID(sc, bus, target);
855         debug(1, "logical device %d", mci->addr.log.logdev);
856     } else {
857         mc->mc_length = mci->data_size = sizeof(struct mly_ioctl_getphysdevinfovalid);
858         mci->sub_ioctl = MDACIOCTL_GETPHYSDEVINFOVALID;
859         mci->addr.phys.lun = 0;
860         mci->addr.phys.target = target;
861         mci->addr.phys.channel = bus;
862         debug(1, "physical device %d:%d", mci->addr.phys.channel, mci->addr.phys.target);
863     }
864     
865     /*
866      * Dispatch the command.  If we successfully send the command, clear the rescan
867      * bit.
868      */
869     if (mly_start(mc) != 0) {
870         mly_release_command(mc);
871     } else {
872         sc->mly_btl[bus][target].mb_flags &= ~MLY_BTL_RESCAN;   /* success */   
873     }
874 }
875
876 /********************************************************************************
877  * Handle the completion of a rescan operation
878  */
879 static void
880 mly_complete_rescan(struct mly_command *mc)
881 {
882     struct mly_softc                            *sc = mc->mc_sc;
883     struct mly_ioctl_getlogdevinfovalid         *ldi;
884     struct mly_ioctl_getphysdevinfovalid        *pdi;
885     struct mly_command_ioctl                    *mci;
886     struct mly_btl                              btl, *btlp;
887     int                                         bus, target, rescan;
888
889     debug_called(1);
890
891     /*
892      * Recover the bus and target from the command.  We need these even in
893      * the case where we don't have a useful response.
894      */
895     mci = (struct mly_command_ioctl *)&mc->mc_packet->ioctl;
896     if (mci->sub_ioctl == MDACIOCTL_GETLOGDEVINFOVALID) {
897         bus = MLY_LOGDEV_BUS(sc, mci->addr.log.logdev);
898         target = MLY_LOGDEV_TARGET(sc, mci->addr.log.logdev);
899     } else {
900         bus = mci->addr.phys.channel;
901         target = mci->addr.phys.target;
902     }
903     /* XXX validate bus/target? */
904     
905     /* the default result is 'no device' */
906     bzero(&btl, sizeof(btl));
907
908     /* if the rescan completed OK, we have possibly-new BTL data */
909     if (mc->mc_status == 0) {
910         if (mc->mc_length == sizeof(*ldi)) {
911             ldi = (struct mly_ioctl_getlogdevinfovalid *)mc->mc_data;
912             if ((MLY_LOGDEV_BUS(sc, ldi->logical_device_number) != bus) ||
913                 (MLY_LOGDEV_TARGET(sc, ldi->logical_device_number) != target)) {
914                 mly_printf(sc, "WARNING: BTL rescan for %d:%d returned data for %d:%d instead\n",
915                            bus, target, MLY_LOGDEV_BUS(sc, ldi->logical_device_number),
916                            MLY_LOGDEV_TARGET(sc, ldi->logical_device_number));
917                 /* XXX what can we do about this? */
918             }
919             btl.mb_flags = MLY_BTL_LOGICAL;
920             btl.mb_type = ldi->raid_level;
921             btl.mb_state = ldi->state;
922             debug(1, "BTL rescan for %d returns %s, %s", ldi->logical_device_number, 
923                   mly_describe_code(mly_table_device_type, ldi->raid_level),
924                   mly_describe_code(mly_table_device_state, ldi->state));
925         } else if (mc->mc_length == sizeof(*pdi)) {
926             pdi = (struct mly_ioctl_getphysdevinfovalid *)mc->mc_data;
927             if ((pdi->channel != bus) || (pdi->target != target)) {
928                 mly_printf(sc, "WARNING: BTL rescan for %d:%d returned data for %d:%d instead\n",
929                            bus, target, pdi->channel, pdi->target);
930                 /* XXX what can we do about this? */
931             }
932             btl.mb_flags = MLY_BTL_PHYSICAL;
933             btl.mb_type = MLY_DEVICE_TYPE_PHYSICAL;
934             btl.mb_state = pdi->state;
935             btl.mb_speed = pdi->speed;
936             btl.mb_width = pdi->width;
937             if (pdi->state != MLY_DEVICE_STATE_UNCONFIGURED)
938                 sc->mly_btl[bus][target].mb_flags |= MLY_BTL_PROTECTED;
939             debug(1, "BTL rescan for %d:%d returns %s", bus, target, 
940                   mly_describe_code(mly_table_device_state, pdi->state));
941         } else {
942             mly_printf(sc, "BTL rescan result invalid\n");
943         }
944     }
945
946     kfree(mc->mc_data, M_DEVBUF);
947     mly_release_command(mc);
948
949     /*
950      * Decide whether we need to rescan the device.
951      */
952     rescan = 0;
953
954     /* device type changes (usually between 'nothing' and 'something') */
955     btlp = &sc->mly_btl[bus][target];
956     if (btl.mb_flags != btlp->mb_flags) {
957         debug(1, "flags changed, rescanning");
958         rescan = 1;
959     }
960     
961     /* XXX other reasons? */
962
963     /*
964      * Update BTL information.
965      */
966     *btlp = btl;
967
968     /*
969      * Perform CAM rescan if required.
970      */
971     if (rescan)
972         mly_cam_rescan_btl(sc, bus, target);
973 }
974
975 /********************************************************************************
976  * Get the current health status and set the 'next event' counter to suit.
977  */
978 static int
979 mly_get_eventstatus(struct mly_softc *sc)
980 {
981     struct mly_command_ioctl    mci;
982     struct mly_health_status    *mh;
983     u_int8_t                    status;
984     int                         error;
985
986     /* build the gethealthstatus ioctl and send it */
987     bzero(&mci, sizeof(mci));
988     mh = NULL;
989     mci.sub_ioctl = MDACIOCTL_GETHEALTHSTATUS;
990
991     if ((error = mly_ioctl(sc, &mci, (void **)&mh, sizeof(*mh), &status, NULL, NULL)))
992         return(error);
993     if (status != 0)
994         return(EIO);
995
996     /* get the event counter */
997     sc->mly_event_change = mh->change_counter;
998     sc->mly_event_waiting = mh->next_event;
999     sc->mly_event_counter = mh->next_event;
1000
1001     /* save the health status into the memory mailbox */
1002     bcopy(mh, &sc->mly_mmbox->mmm_health.status, sizeof(*mh));
1003
1004     debug(1, "initial change counter %d, event counter %d", mh->change_counter, mh->next_event);
1005     
1006     kfree(mh, M_DEVBUF);
1007     return(0);
1008 }
1009
1010 /********************************************************************************
1011  * Enable the memory mailbox mode.
1012  */
1013 static int
1014 mly_enable_mmbox(struct mly_softc *sc)
1015 {
1016     struct mly_command_ioctl    mci;
1017     u_int8_t                    *sp, status;
1018     int                         error;
1019
1020     debug_called(1);
1021
1022     /* build the ioctl and send it */
1023     bzero(&mci, sizeof(mci));
1024     mci.sub_ioctl = MDACIOCTL_SETMEMORYMAILBOX;
1025     /* set buffer addresses */
1026     mci.param.setmemorymailbox.command_mailbox_physaddr = 
1027         sc->mly_mmbox_busaddr + offsetof(struct mly_mmbox, mmm_command);
1028     mci.param.setmemorymailbox.status_mailbox_physaddr = 
1029         sc->mly_mmbox_busaddr + offsetof(struct mly_mmbox, mmm_status);
1030     mci.param.setmemorymailbox.health_buffer_physaddr = 
1031         sc->mly_mmbox_busaddr + offsetof(struct mly_mmbox, mmm_health);
1032
1033     /* set buffer sizes - abuse of data_size field is revolting */
1034     sp = (u_int8_t *)&mci.data_size;
1035     sp[0] = ((sizeof(union mly_command_packet) * MLY_MMBOX_COMMANDS) / 1024);
1036     sp[1] = (sizeof(union mly_status_packet) * MLY_MMBOX_STATUS) / 1024;
1037     mci.param.setmemorymailbox.health_buffer_size = sizeof(union mly_health_region) / 1024;
1038
1039     debug(1, "memory mailbox at %p (0x%llx/%d 0x%llx/%d 0x%llx/%d", sc->mly_mmbox,
1040           mci.param.setmemorymailbox.command_mailbox_physaddr, sp[0],
1041           mci.param.setmemorymailbox.status_mailbox_physaddr, sp[1],
1042           mci.param.setmemorymailbox.health_buffer_physaddr, 
1043           mci.param.setmemorymailbox.health_buffer_size);
1044
1045     if ((error = mly_ioctl(sc, &mci, NULL, 0, &status, NULL, NULL)))
1046         return(error);
1047     if (status != 0)
1048         return(EIO);
1049     sc->mly_state |= MLY_STATE_MMBOX_ACTIVE;
1050     debug(1, "memory mailbox active");
1051     return(0);
1052 }
1053
1054 /********************************************************************************
1055  * Flush all pending I/O from the controller.
1056  */
1057 static int
1058 mly_flush(struct mly_softc *sc)
1059 {
1060     struct mly_command_ioctl    mci;
1061     u_int8_t                    status;
1062     int                         error;
1063
1064     debug_called(1);
1065
1066     /* build the ioctl */
1067     bzero(&mci, sizeof(mci));
1068     mci.sub_ioctl = MDACIOCTL_FLUSHDEVICEDATA;
1069     mci.param.deviceoperation.operation_device = MLY_OPDEVICE_PHYSICAL_CONTROLLER;
1070
1071     /* pass it off to the controller */
1072     if ((error = mly_ioctl(sc, &mci, NULL, 0, &status, NULL, NULL)))
1073         return(error);
1074
1075     return((status == 0) ? 0 : EIO);
1076 }
1077
1078 /********************************************************************************
1079  * Perform an ioctl command.
1080  *
1081  * If (data) is not NULL, the command requires data transfer.  If (*data) is NULL
1082  * the command requires data transfer from the controller, and we will allocate
1083  * a buffer for it.  If (*data) is not NULL, the command requires data transfer
1084  * to the controller.
1085  *
1086  * XXX passing in the whole ioctl structure is ugly.  Better ideas?
1087  *
1088  * XXX we don't even try to handle the case where datasize > 4k.  We should.
1089  */
1090 static int
1091 mly_ioctl(struct mly_softc *sc, struct mly_command_ioctl *ioctl, void **data, size_t datasize, 
1092           u_int8_t *status, void *sense_buffer, size_t *sense_length)
1093 {
1094     struct mly_command          *mc;
1095     struct mly_command_ioctl    *mci;
1096     int                         error;
1097
1098     debug_called(1);
1099
1100     mc = NULL;
1101     if (mly_alloc_command(sc, &mc)) {
1102         error = ENOMEM;
1103         goto out;
1104     }
1105
1106     /* copy the ioctl structure, but save some important fields and then fixup */
1107     mci = &mc->mc_packet->ioctl;
1108     ioctl->sense_buffer_address = mci->sense_buffer_address;
1109     ioctl->maximum_sense_size = mci->maximum_sense_size;
1110     *mci = *ioctl;
1111     mci->opcode = MDACMD_IOCTL;
1112     mci->timeout.value = 30;
1113     mci->timeout.scale = MLY_TIMEOUT_SECONDS;
1114     
1115     /* handle the data buffer */
1116     if (data != NULL) {
1117         if (*data == NULL) {
1118             /* allocate data buffer */
1119             mc->mc_data = kmalloc(datasize, M_DEVBUF, M_INTWAIT);
1120             mc->mc_flags |= MLY_CMD_DATAIN;
1121         } else {
1122             mc->mc_data = *data;
1123             mc->mc_flags |= MLY_CMD_DATAOUT;
1124         }
1125         mc->mc_length = datasize;
1126         mc->mc_packet->generic.data_size = datasize;
1127     }
1128     
1129     /* run the command */
1130     if ((error = mly_immediate_command(mc)))
1131         goto out;
1132     
1133     /* clean up and return any data */
1134     *status = mc->mc_status;
1135     if ((mc->mc_sense > 0) && (sense_buffer != NULL)) {
1136         bcopy(mc->mc_packet, sense_buffer, mc->mc_sense);
1137         *sense_length = mc->mc_sense;
1138         goto out;
1139     }
1140
1141     /* should we return a data pointer? */
1142     if ((data != NULL) && (*data == NULL))
1143         *data = mc->mc_data;
1144
1145     /* command completed OK */
1146     error = 0;
1147
1148 out:
1149     if (mc != NULL) {
1150         /* do we need to free a data buffer we allocated? */
1151         if (error && (mc->mc_data != NULL) && (*data == NULL))
1152             kfree(mc->mc_data, M_DEVBUF);
1153         mly_release_command(mc);
1154     }
1155     return(error);
1156 }
1157
1158 /********************************************************************************
1159  * Check for event(s) outstanding in the controller.
1160  */
1161 static void
1162 mly_check_event(struct mly_softc *sc)
1163 {
1164     
1165     /*
1166      * The controller may have updated the health status information,
1167      * so check for it here.  Note that the counters are all in host memory,
1168      * so this check is very cheap.  Also note that we depend on checking on
1169      * completion 
1170      */
1171     if (sc->mly_mmbox->mmm_health.status.change_counter != sc->mly_event_change) {
1172         sc->mly_event_change = sc->mly_mmbox->mmm_health.status.change_counter;
1173         debug(1, "event change %d, event status update, %d -> %d", sc->mly_event_change,
1174               sc->mly_event_waiting, sc->mly_mmbox->mmm_health.status.next_event);
1175         sc->mly_event_waiting = sc->mly_mmbox->mmm_health.status.next_event;
1176
1177         /* wake up anyone that might be interested in this */
1178         wakeup(&sc->mly_event_change);
1179     }
1180     if (sc->mly_event_counter != sc->mly_event_waiting)
1181     mly_fetch_event(sc);
1182 }
1183
1184 /********************************************************************************
1185  * Fetch one event from the controller.
1186  *
1187  * If we fail due to resource starvation, we'll be retried the next time a 
1188  * command completes.
1189  */
1190 static void
1191 mly_fetch_event(struct mly_softc *sc)
1192 {
1193     struct mly_command          *mc;
1194     struct mly_command_ioctl    *mci;
1195     u_int32_t                   event;
1196
1197     debug_called(1);
1198
1199     /* get a command */
1200     if (mly_alloc_command(sc, &mc))
1201         return;
1202
1203     /* set up the data buffer */
1204     mc->mc_data = kmalloc(sizeof(struct mly_event), M_DEVBUF, M_INTWAIT|M_ZERO);
1205     mc->mc_length = sizeof(struct mly_event);
1206     mc->mc_flags |= MLY_CMD_DATAIN;
1207     mc->mc_complete = mly_complete_event;
1208
1209     /*
1210      * Get an event number to fetch.  It's possible that we've raced with another
1211      * context for the last event, in which case there will be no more events.
1212      */
1213     crit_enter();
1214     if (sc->mly_event_counter == sc->mly_event_waiting) {
1215         mly_release_command(mc);
1216         crit_exit();
1217         return;
1218     }
1219     event = sc->mly_event_counter++;
1220     crit_exit();
1221
1222     /* 
1223      * Build the ioctl.
1224      *
1225      * At this point we are committed to sending this request, as it
1226      * will be the only one constructed for this particular event number.
1227      */
1228     mci = (struct mly_command_ioctl *)&mc->mc_packet->ioctl;
1229     mci->opcode = MDACMD_IOCTL;
1230     mci->data_size = sizeof(struct mly_event);
1231     mci->addr.phys.lun = (event >> 16) & 0xff;
1232     mci->addr.phys.target = (event >> 24) & 0xff;
1233     mci->addr.phys.channel = 0;
1234     mci->addr.phys.controller = 0;
1235     mci->timeout.value = 30;
1236     mci->timeout.scale = MLY_TIMEOUT_SECONDS;
1237     mci->sub_ioctl = MDACIOCTL_GETEVENT;
1238     mci->param.getevent.sequence_number_low = event & 0xffff;
1239
1240     debug(1, "fetch event %u", event);
1241
1242     /*
1243      * Submit the command.
1244      *
1245      * Note that failure of mly_start() will result in this event never being
1246      * fetched.
1247      */
1248     if (mly_start(mc) != 0) {
1249         mly_printf(sc, "couldn't fetch event %u\n", event);
1250         mly_release_command(mc);
1251     }
1252 }
1253
1254 /********************************************************************************
1255  * Handle the completion of an event poll.
1256  */
1257 static void
1258 mly_complete_event(struct mly_command *mc)
1259 {
1260     struct mly_softc    *sc = mc->mc_sc;
1261     struct mly_event    *me = (struct mly_event *)mc->mc_data;
1262
1263     debug_called(1);
1264
1265     /* 
1266      * If the event was successfully fetched, process it.
1267      */
1268     if (mc->mc_status == SCSI_STATUS_OK) {
1269         mly_process_event(sc, me);
1270         kfree(me, M_DEVBUF);
1271     }
1272     mly_release_command(mc);
1273
1274     /*
1275      * Check for another event.
1276      */
1277     mly_check_event(sc);
1278 }
1279
1280 /********************************************************************************
1281  * Process a controller event.
1282  */
1283 static void
1284 mly_process_event(struct mly_softc *sc, struct mly_event *me)
1285 {
1286     struct scsi_sense_data      *ssd = (struct scsi_sense_data *)&me->sense[0];
1287     char                        *fp, *tp;
1288     int                         bus, target, event, class, action;
1289
1290     /* 
1291      * Errors can be reported using vendor-unique sense data.  In this case, the
1292      * event code will be 0x1c (Request sense data present), the sense key will
1293      * be 0x09 (vendor specific), the MSB of the ASC will be set, and the 
1294      * actual event code will be a 16-bit value comprised of the ASCQ (low byte)
1295      * and low seven bits of the ASC (low seven bits of the high byte).
1296      */
1297     if ((me->code == 0x1c) && 
1298         ((ssd->flags & SSD_KEY) == SSD_KEY_Vendor_Specific) &&
1299         (ssd->add_sense_code & 0x80)) {
1300         event = ((int)(ssd->add_sense_code & ~0x80) << 8) + ssd->add_sense_code_qual;
1301     } else {
1302         event = me->code;
1303     }
1304
1305     /* look up event, get codes */
1306     fp = mly_describe_code(mly_table_event, event);
1307
1308     debug(1, "Event %d  code 0x%x", me->sequence_number, me->code);
1309
1310     /* quiet event? */
1311     class = fp[0];
1312     if (isupper(class) && bootverbose)
1313         class = tolower(class);
1314
1315     /* get action code, text string */
1316     action = fp[1];
1317     tp = &fp[2];
1318
1319     /*
1320      * Print some information about the event.
1321      *
1322      * This code uses a table derived from the corresponding portion of the Linux
1323      * driver, and thus the parser is very similar.
1324      */
1325     switch(class) {
1326     case 'p':           /* error on physical device */
1327         mly_printf(sc, "physical device %d:%d %s\n", me->channel, me->target, tp);
1328         if (action == 'r')
1329             sc->mly_btl[me->channel][me->target].mb_flags |= MLY_BTL_RESCAN;
1330         break;
1331     case 'l':           /* error on logical unit */
1332     case 'm':           /* message about logical unit */
1333         bus = MLY_LOGDEV_BUS(sc, me->lun);
1334         target = MLY_LOGDEV_TARGET(sc, me->lun);
1335         mly_name_device(sc, bus, target);
1336         mly_printf(sc, "logical device %d (%s) %s\n", me->lun, sc->mly_btl[bus][target].mb_name, tp);
1337         if (action == 'r')
1338             sc->mly_btl[bus][target].mb_flags |= MLY_BTL_RESCAN;
1339         break;
1340       break;
1341     case 's':           /* report of sense data */
1342         if (((ssd->flags & SSD_KEY) == SSD_KEY_NO_SENSE) ||
1343             (((ssd->flags & SSD_KEY) == SSD_KEY_NOT_READY) && 
1344              (ssd->add_sense_code == 0x04) && 
1345              ((ssd->add_sense_code_qual == 0x01) || (ssd->add_sense_code_qual == 0x02))))
1346             break;      /* ignore NO_SENSE or NOT_READY in one case */
1347
1348         mly_printf(sc, "physical device %d:%d %s\n", me->channel, me->target, tp);
1349         mly_printf(sc, "  sense key %d  asc %02x  ascq %02x\n", 
1350                       ssd->flags & SSD_KEY, ssd->add_sense_code, ssd->add_sense_code_qual);
1351         mly_printf(sc, "  info %4D  csi %4D\n", ssd->info, "", ssd->cmd_spec_info, "");
1352         if (action == 'r')
1353             sc->mly_btl[me->channel][me->target].mb_flags |= MLY_BTL_RESCAN;
1354         break;
1355     case 'e':
1356         mly_printf(sc, tp, me->target, me->lun);
1357         kprintf("\n");
1358         break;
1359     case 'c':
1360         mly_printf(sc, "controller %s\n", tp);
1361         break;
1362     case '?':
1363         mly_printf(sc, "%s - %d\n", tp, me->code);
1364         break;
1365     default:    /* probably a 'noisy' event being ignored */
1366         break;
1367     }
1368 }
1369
1370 /********************************************************************************
1371  * Perform periodic activities.
1372  */
1373 static void
1374 mly_periodic(void *data)
1375 {
1376     struct mly_softc    *sc = (struct mly_softc *)data;
1377     int                 bus, target;
1378
1379     debug_called(2);
1380
1381     /*
1382      * Scan devices.
1383      */
1384     for (bus = 0; bus < sc->mly_cam_channels; bus++) {
1385         if (MLY_BUS_IS_VALID(sc, bus)) {
1386             for (target = 0; target < MLY_MAX_TARGETS; target++) {
1387
1388                 /* ignore the controller in this scan */
1389                 if (target == sc->mly_controllerparam->initiator_id)
1390                     continue;
1391
1392                 /* perform device rescan? */
1393                 if (sc->mly_btl[bus][target].mb_flags & MLY_BTL_RESCAN)
1394                     mly_rescan_btl(sc, bus, target);
1395             }
1396         }
1397     }
1398     
1399     /* check for controller events */
1400     mly_check_event(sc);
1401
1402     /* reschedule ourselves */
1403     callout_reset(&sc->mly_periodic, MLY_PERIODIC_INTERVAL * hz, mly_periodic, sc);
1404 }
1405
1406 /********************************************************************************
1407  ********************************************************************************
1408                                                                Command Processing
1409  ********************************************************************************
1410  ********************************************************************************/
1411
1412 /********************************************************************************
1413  * Run a command and wait for it to complete.
1414  *
1415  */
1416 static int
1417 mly_immediate_command(struct mly_command *mc)
1418 {
1419     struct mly_softc    *sc = mc->mc_sc;
1420     int                 error;
1421
1422     debug_called(1);
1423
1424     /* spinning at splcam is ugly, but we're only used during controller init */
1425     crit_enter();
1426     if ((error = mly_start(mc))) {
1427         crit_exit();
1428         return(error);
1429     }
1430
1431     if (sc->mly_state & MLY_STATE_INTERRUPTS_ON) {
1432         /* sleep on the command */
1433         while(!(mc->mc_flags & MLY_CMD_COMPLETE)) {
1434             tsleep(mc, 0, "mlywait", 0);
1435         }
1436     } else {
1437         /* spin and collect status while we do */
1438         while(!(mc->mc_flags & MLY_CMD_COMPLETE)) {
1439             mly_done(mc->mc_sc);
1440         }
1441     }
1442     crit_exit();
1443     return(0);
1444 }
1445
1446 /********************************************************************************
1447  * Deliver a command to the controller.
1448  *
1449  * XXX it would be good to just queue commands that we can't submit immediately
1450  *     and send them later, but we probably want a wrapper for that so that
1451  *     we don't hang on a failed submission for an immediate command.
1452  */
1453 static int
1454 mly_start(struct mly_command *mc)
1455 {
1456     struct mly_softc            *sc = mc->mc_sc;
1457     union mly_command_packet    *pkt;
1458
1459     debug_called(2);
1460
1461     /* 
1462      * Set the command up for delivery to the controller. 
1463      */
1464     mly_map_command(mc);
1465     mc->mc_packet->generic.command_id = mc->mc_slot;
1466
1467 #ifdef MLY_DEBUG
1468     mc->mc_timestamp = time_second;
1469 #endif
1470
1471     crit_enter();
1472
1473     /*
1474      * Do we have to use the hardware mailbox?
1475      */
1476     if (!(sc->mly_state & MLY_STATE_MMBOX_ACTIVE)) {
1477         /*
1478          * Check to see if the controller is ready for us.
1479          */
1480         if (MLY_IDBR_TRUE(sc, MLY_HM_CMDSENT)) {
1481             crit_exit();
1482             return(EBUSY);
1483         }
1484         mc->mc_flags |= MLY_CMD_BUSY;
1485         
1486         /*
1487          * It's ready, send the command.
1488          */
1489         MLY_SET_MBOX(sc, sc->mly_command_mailbox, &mc->mc_packetphys);
1490         MLY_SET_REG(sc, sc->mly_idbr, MLY_HM_CMDSENT);
1491
1492     } else {    /* use memory-mailbox mode */
1493
1494         pkt = &sc->mly_mmbox->mmm_command[sc->mly_mmbox_command_index];
1495
1496         /* check to see if the next index is free yet */
1497         if (pkt->mmbox.flag != 0) {
1498             crit_exit();
1499             return(EBUSY);
1500         }
1501         mc->mc_flags |= MLY_CMD_BUSY;
1502         
1503         /* copy in new command */
1504         bcopy(mc->mc_packet->mmbox.data, pkt->mmbox.data, sizeof(pkt->mmbox.data));
1505         /* barrier to ensure completion of previous write before we write the flag */
1506         bus_space_barrier(sc->mly_btag, sc->mly_bhandle, 0, 0,
1507             BUS_SPACE_BARRIER_WRITE);
1508         /* copy flag last */
1509         pkt->mmbox.flag = mc->mc_packet->mmbox.flag;
1510         /* barrier to ensure completion of previous write before we notify the controller */
1511         bus_space_barrier(sc->mly_btag, sc->mly_bhandle, 0, 0,
1512             BUS_SPACE_BARRIER_WRITE);
1513
1514         /* signal controller, update index */
1515         MLY_SET_REG(sc, sc->mly_idbr, MLY_AM_CMDSENT);
1516         sc->mly_mmbox_command_index = (sc->mly_mmbox_command_index + 1) % MLY_MMBOX_COMMANDS;
1517     }
1518
1519     mly_enqueue_busy(mc);
1520     crit_exit();
1521     return(0);
1522 }
1523
1524 /********************************************************************************
1525  * Pick up command status from the controller, schedule a completion event
1526  */
1527 static void
1528 mly_done(struct mly_softc *sc) 
1529 {
1530     struct mly_command          *mc;
1531     union mly_status_packet     *sp;
1532     u_int16_t                   slot;
1533     int                         worked;
1534
1535     crit_enter();
1536     worked = 0;
1537
1538     /* pick up hardware-mailbox commands */
1539     if (MLY_ODBR_TRUE(sc, MLY_HM_STSREADY)) {
1540         slot = MLY_GET_REG2(sc, sc->mly_status_mailbox);
1541         if (slot < MLY_SLOT_MAX) {
1542             mc = &sc->mly_command[slot - MLY_SLOT_START];
1543             mc->mc_status = MLY_GET_REG(sc, sc->mly_status_mailbox + 2);
1544             mc->mc_sense = MLY_GET_REG(sc, sc->mly_status_mailbox + 3);
1545             mc->mc_resid = MLY_GET_REG4(sc, sc->mly_status_mailbox + 4);
1546             mly_remove_busy(mc);
1547             mc->mc_flags &= ~MLY_CMD_BUSY;
1548             mly_enqueue_complete(mc);
1549             worked = 1;
1550         } else {
1551             /* slot 0xffff may mean "extremely bogus command" */
1552             mly_printf(sc, "got HM completion for illegal slot %u\n", slot);
1553         }
1554         /* unconditionally acknowledge status */
1555         MLY_SET_REG(sc, sc->mly_odbr, MLY_HM_STSREADY);
1556         MLY_SET_REG(sc, sc->mly_idbr, MLY_HM_STSACK);
1557     }
1558
1559     /* pick up memory-mailbox commands */
1560     if (MLY_ODBR_TRUE(sc, MLY_AM_STSREADY)) {
1561         for (;;) {
1562             sp = &sc->mly_mmbox->mmm_status[sc->mly_mmbox_status_index];
1563
1564             /* check for more status */
1565             if (sp->mmbox.flag == 0)
1566                 break;
1567
1568             /* get slot number */
1569             slot = sp->status.command_id;
1570             if (slot < MLY_SLOT_MAX) {
1571                 mc = &sc->mly_command[slot - MLY_SLOT_START];
1572                 mc->mc_status = sp->status.status;
1573                 mc->mc_sense = sp->status.sense_length;
1574                 mc->mc_resid = sp->status.residue;
1575                 mly_remove_busy(mc);
1576                 mc->mc_flags &= ~MLY_CMD_BUSY;
1577                 mly_enqueue_complete(mc);
1578                 worked = 1;
1579             } else {
1580                 /* slot 0xffff may mean "extremely bogus command" */
1581                 mly_printf(sc, "got AM completion for illegal slot %u at %d\n", 
1582                            slot, sc->mly_mmbox_status_index);
1583             }
1584
1585             /* clear and move to next index */
1586             sp->mmbox.flag = 0;
1587             sc->mly_mmbox_status_index = (sc->mly_mmbox_status_index + 1) % MLY_MMBOX_STATUS;
1588         }
1589         /* acknowledge that we have collected status value(s) */
1590         MLY_SET_REG(sc, sc->mly_odbr, MLY_AM_STSREADY);
1591     }
1592
1593     crit_exit();
1594     if (worked) {
1595         if (sc->mly_state & MLY_STATE_INTERRUPTS_ON)
1596             taskqueue_enqueue(taskqueue_swi, &sc->mly_task_complete);
1597         else
1598             mly_complete(sc, 0);
1599     }
1600 }
1601
1602 /********************************************************************************
1603  * Process completed commands
1604  */
1605 static void
1606 mly_complete(void *context, int pending)
1607 {
1608     struct mly_softc    *sc = (struct mly_softc *)context;
1609     struct mly_command  *mc;
1610     void                (* mc_complete)(struct mly_command *mc);
1611
1612
1613     debug_called(2);
1614
1615     /* 
1616      * Spin pulling commands off the completed queue and processing them.
1617      */
1618     while ((mc = mly_dequeue_complete(sc)) != NULL) {
1619
1620         /*
1621          * Free controller resources, mark command complete.
1622          *
1623          * Note that as soon as we mark the command complete, it may be freed
1624          * out from under us, so we need to save the mc_complete field in
1625          * order to later avoid dereferencing mc.  (We would not expect to
1626          * have a polling/sleeping consumer with mc_complete != NULL).
1627          */
1628         mly_unmap_command(mc);
1629         mc_complete = mc->mc_complete;
1630         mc->mc_flags |= MLY_CMD_COMPLETE;
1631
1632         /* 
1633          * Call completion handler or wake up sleeping consumer.
1634          */
1635         if (mc_complete != NULL) {
1636             mc_complete(mc);
1637         } else {
1638             wakeup(mc);
1639         }
1640     }
1641     
1642     /*
1643      * XXX if we are deferring commands due to controller-busy status, we should
1644      *     retry submitting them here.
1645      */
1646 }
1647
1648 /********************************************************************************
1649  ********************************************************************************
1650                                                         Command Buffer Management
1651  ********************************************************************************
1652  ********************************************************************************/
1653
1654 /********************************************************************************
1655  * Allocate a command.
1656  */
1657 static int
1658 mly_alloc_command(struct mly_softc *sc, struct mly_command **mcp)
1659 {
1660     struct mly_command  *mc;
1661
1662     debug_called(3);
1663
1664     if ((mc = mly_dequeue_free(sc)) == NULL)
1665         return(ENOMEM);
1666
1667     *mcp = mc;
1668     return(0);
1669 }
1670
1671 /********************************************************************************
1672  * Release a command back to the freelist.
1673  */
1674 static void
1675 mly_release_command(struct mly_command *mc)
1676 {
1677     debug_called(3);
1678
1679     /*
1680      * Fill in parts of the command that may cause confusion if
1681      * a consumer doesn't when we are later allocated.
1682      */
1683     mc->mc_data = NULL;
1684     mc->mc_flags = 0;
1685     mc->mc_complete = NULL;
1686     mc->mc_private = NULL;
1687
1688     /*
1689      * By default, we set up to overwrite the command packet with
1690      * sense information.
1691      */
1692     mc->mc_packet->generic.sense_buffer_address = mc->mc_packetphys;
1693     mc->mc_packet->generic.maximum_sense_size = sizeof(union mly_command_packet);
1694
1695     mly_enqueue_free(mc);
1696 }
1697
1698 /********************************************************************************
1699  * Map helper for command allocation.
1700  */
1701 static void
1702 mly_alloc_commands_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1703 {
1704     struct mly_softc    *sc = (struct mly_softc *)arg;
1705
1706     debug_called(1);
1707
1708     sc->mly_packetphys = segs[0].ds_addr;
1709 }
1710
1711 /********************************************************************************
1712  * Allocate and initialise command and packet structures.
1713  *
1714  * If the controller supports fewer than MLY_MAX_COMMANDS commands, limit our
1715  * allocation to that number.  If we don't yet know how many commands the
1716  * controller supports, allocate a very small set (suitable for initialisation
1717  * purposes only).
1718  */
1719 static int
1720 mly_alloc_commands(struct mly_softc *sc)
1721 {
1722     struct mly_command          *mc;
1723     int                         i, ncmd;
1724  
1725     if (sc->mly_controllerinfo == NULL) {
1726         ncmd = 4;
1727     } else {
1728         ncmd = min(MLY_MAX_COMMANDS, sc->mly_controllerinfo->maximum_parallel_commands);
1729     }
1730
1731     /*
1732      * Allocate enough space for all the command packets in one chunk and
1733      * map them permanently into controller-visible space.
1734      */
1735     if (bus_dmamem_alloc(sc->mly_packet_dmat, (void **)&sc->mly_packet, 
1736                          BUS_DMA_NOWAIT, &sc->mly_packetmap)) {
1737         return(ENOMEM);
1738     }
1739     if (bus_dmamap_load(sc->mly_packet_dmat, sc->mly_packetmap, sc->mly_packet, 
1740                         ncmd * sizeof(union mly_command_packet), 
1741                         mly_alloc_commands_map, sc, BUS_DMA_NOWAIT) != 0)
1742         return (ENOMEM);
1743
1744     for (i = 0; i < ncmd; i++) {
1745         mc = &sc->mly_command[i];
1746         bzero(mc, sizeof(*mc));
1747         mc->mc_sc = sc;
1748         mc->mc_slot = MLY_SLOT_START + i;
1749         mc->mc_packet = sc->mly_packet + i;
1750         mc->mc_packetphys = sc->mly_packetphys + (i * sizeof(union mly_command_packet));
1751         if (!bus_dmamap_create(sc->mly_buffer_dmat, 0, &mc->mc_datamap))
1752             mly_release_command(mc);
1753     }
1754     return(0);
1755 }
1756
1757 /********************************************************************************
1758  * Free all the storage held by commands.
1759  *
1760  * Must be called with all commands on the free list.
1761  */
1762 static void
1763 mly_release_commands(struct mly_softc *sc)
1764 {
1765     struct mly_command  *mc;
1766
1767     /* throw away command buffer DMA maps */
1768     while (mly_alloc_command(sc, &mc) == 0)
1769         bus_dmamap_destroy(sc->mly_buffer_dmat, mc->mc_datamap);
1770
1771     /* release the packet storage */
1772     if (sc->mly_packet != NULL) {
1773         bus_dmamap_unload(sc->mly_packet_dmat, sc->mly_packetmap);
1774         bus_dmamem_free(sc->mly_packet_dmat, sc->mly_packet, sc->mly_packetmap);
1775         sc->mly_packet = NULL;
1776     }
1777 }
1778
1779
1780 /********************************************************************************
1781  * Command-mapping helper function - populate this command's s/g table
1782  * with the s/g entries for its data.
1783  */
1784 static void
1785 mly_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1786 {
1787     struct mly_command          *mc = (struct mly_command *)arg;
1788     struct mly_softc            *sc = mc->mc_sc;
1789     struct mly_command_generic  *gen = &(mc->mc_packet->generic);
1790     struct mly_sg_entry         *sg;
1791     int                         i, tabofs;
1792
1793     debug_called(2);
1794
1795     /* can we use the transfer structure directly? */
1796     if (nseg <= 2) {
1797         sg = &gen->transfer.direct.sg[0];
1798         gen->command_control.extended_sg_table = 0;
1799     } else {
1800         tabofs = ((mc->mc_slot - MLY_SLOT_START) * MLY_MAX_SGENTRIES);
1801         sg = sc->mly_sg_table + tabofs;
1802         gen->transfer.indirect.entries[0] = nseg;
1803         gen->transfer.indirect.table_physaddr[0] = sc->mly_sg_busaddr + (tabofs * sizeof(struct mly_sg_entry));
1804         gen->command_control.extended_sg_table = 1;
1805     }
1806
1807     /* copy the s/g table */
1808     for (i = 0; i < nseg; i++) {
1809         sg[i].physaddr = segs[i].ds_addr;
1810         sg[i].length = segs[i].ds_len;
1811     }
1812
1813 }
1814
1815 #if 0
1816 /********************************************************************************
1817  * Command-mapping helper function - save the cdb's physical address.
1818  *
1819  * We don't support 'large' SCSI commands at this time, so this is unused.
1820  */
1821 static void
1822 mly_map_command_cdb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1823 {
1824     struct mly_command                  *mc = (struct mly_command *)arg;
1825
1826     debug_called(2);
1827
1828     /* XXX can we safely assume that a CDB will never cross a page boundary? */
1829     if ((segs[0].ds_addr % PAGE_SIZE) > 
1830         ((segs[0].ds_addr + mc->mc_packet->scsi_large.cdb_length) % PAGE_SIZE))
1831         panic("cdb crosses page boundary");
1832
1833     /* fix up fields in the command packet */
1834     mc->mc_packet->scsi_large.cdb_physaddr = segs[0].ds_addr;
1835 }
1836 #endif
1837
1838 /********************************************************************************
1839  * Map a command into controller-visible space
1840  */
1841 static void
1842 mly_map_command(struct mly_command *mc)
1843 {
1844     struct mly_softc    *sc = mc->mc_sc;
1845
1846     debug_called(2);
1847
1848     /* don't map more than once */
1849     if (mc->mc_flags & MLY_CMD_MAPPED)
1850         return;
1851
1852     /* does the command have a data buffer? */
1853     if (mc->mc_data != NULL) {
1854         bus_dmamap_load(sc->mly_buffer_dmat, mc->mc_datamap, mc->mc_data, mc->mc_length, 
1855                         mly_map_command_sg, mc, 0);
1856         
1857         if (mc->mc_flags & MLY_CMD_DATAIN)
1858             bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_PREREAD);
1859         if (mc->mc_flags & MLY_CMD_DATAOUT)
1860             bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_PREWRITE);
1861     }
1862     mc->mc_flags |= MLY_CMD_MAPPED;
1863 }
1864
1865 /********************************************************************************
1866  * Unmap a command from controller-visible space
1867  */
1868 static void
1869 mly_unmap_command(struct mly_command *mc)
1870 {
1871     struct mly_softc    *sc = mc->mc_sc;
1872
1873     debug_called(2);
1874
1875     if (!(mc->mc_flags & MLY_CMD_MAPPED))
1876         return;
1877
1878     /* does the command have a data buffer? */
1879     if (mc->mc_data != NULL) {
1880         if (mc->mc_flags & MLY_CMD_DATAIN)
1881             bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_POSTREAD);
1882         if (mc->mc_flags & MLY_CMD_DATAOUT)
1883             bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_POSTWRITE);
1884
1885         bus_dmamap_unload(sc->mly_buffer_dmat, mc->mc_datamap);
1886     }
1887     mc->mc_flags &= ~MLY_CMD_MAPPED;
1888 }
1889
1890
1891 /********************************************************************************
1892  ********************************************************************************
1893                                                                     CAM interface
1894  ********************************************************************************
1895  ********************************************************************************/
1896
1897 /********************************************************************************
1898  * Attach the physical and virtual SCSI busses to CAM.
1899  *
1900  * Physical bus numbering starts from 0, virtual bus numbering from one greater
1901  * than the highest physical bus.  Physical busses are only registered if
1902  * the kernel environment variable "hw.mly.register_physical_channels" is set.
1903  *
1904  * When we refer to a "bus", we are referring to the bus number registered with
1905  * the SIM, wheras a "channel" is a channel number given to the adapter.  In order
1906  * to keep things simple, we map these 1:1, so "bus" and "channel" may be used
1907  * interchangeably.
1908  */
1909 static int
1910 mly_cam_attach(struct mly_softc *sc)
1911 {
1912     struct cam_devq     *devq;
1913     int                 chn, i;
1914
1915     debug_called(1);
1916
1917     /*
1918      * Allocate a devq for all our channels combined.
1919      */
1920     if ((devq = cam_simq_alloc(sc->mly_controllerinfo->maximum_parallel_commands)) == NULL) {
1921         mly_printf(sc, "can't allocate CAM SIM queue\n");
1922         return(ENOMEM);
1923     }
1924
1925     /*
1926      * If physical channel registration has been requested, register these first.
1927      * Note that we enable tagged command queueing for physical channels.
1928      */
1929     if (ktestenv("hw.mly.register_physical_channels")) {
1930         chn = 0;
1931         for (i = 0; i < sc->mly_controllerinfo->physical_channels_present; i++, chn++) {
1932
1933             if ((sc->mly_cam_sim[chn] = cam_sim_alloc(mly_cam_action, mly_cam_poll, "mly", sc,
1934                                                       device_get_unit(sc->mly_dev),
1935                                                       &sim_mplock,
1936                                                       sc->mly_controllerinfo->maximum_parallel_commands,
1937                                                       1, devq)) == NULL) {
1938                 return(ENOMEM);
1939             }
1940             if (xpt_bus_register(sc->mly_cam_sim[chn], chn)) {
1941                 mly_printf(sc, "CAM XPT phsyical channel registration failed\n");
1942                 return(ENXIO);
1943             }
1944             debug(1, "registered physical channel %d", chn);
1945         }
1946     }
1947
1948     /*
1949      * Register our virtual channels, with bus numbers matching channel numbers.
1950      */
1951     chn = sc->mly_controllerinfo->physical_channels_present;
1952     for (i = 0; i < sc->mly_controllerinfo->virtual_channels_present; i++, chn++) {
1953         if ((sc->mly_cam_sim[chn] = cam_sim_alloc(mly_cam_action, mly_cam_poll, "mly", sc,
1954                                                   device_get_unit(sc->mly_dev),
1955                                                   &sim_mplock,
1956                                                   sc->mly_controllerinfo->maximum_parallel_commands,
1957                                                   0, devq)) == NULL) {
1958             return(ENOMEM);
1959         }
1960         if (xpt_bus_register(sc->mly_cam_sim[chn], chn)) {
1961             mly_printf(sc, "CAM XPT virtual channel registration failed\n");
1962             return(ENXIO);
1963         }
1964         debug(1, "registered virtual channel %d", chn);
1965     }
1966
1967     /*
1968      * This is the total number of channels that (might have been) registered with
1969      * CAM.  Some may not have been; check the mly_cam_sim array to be certain.
1970      */
1971     sc->mly_cam_channels = sc->mly_controllerinfo->physical_channels_present +
1972         sc->mly_controllerinfo->virtual_channels_present;
1973
1974     return(0);
1975 }
1976
1977 /********************************************************************************
1978  * Detach from CAM
1979  */
1980 static void
1981 mly_cam_detach(struct mly_softc *sc)
1982 {
1983     int         i;
1984     
1985     debug_called(1);
1986
1987     for (i = 0; i < sc->mly_cam_channels; i++) {
1988         if (sc->mly_cam_sim[i] != NULL) {
1989             xpt_bus_deregister(cam_sim_path(sc->mly_cam_sim[i]));
1990             cam_sim_free(sc->mly_cam_sim[i]);
1991         }
1992     }
1993     if (sc->mly_cam_devq != NULL)
1994         cam_simq_release(sc->mly_cam_devq);
1995 }
1996
1997 /************************************************************************
1998  * Rescan a device.
1999  */ 
2000 static void
2001 mly_cam_rescan_btl(struct mly_softc *sc, int bus, int target)
2002 {
2003     union ccb   *ccb;
2004
2005     debug_called(1);
2006
2007     ccb = kmalloc(sizeof(union ccb), M_TEMP, M_WAITOK | M_ZERO);
2008     
2009     if (xpt_create_path(&sc->mly_cam_path, xpt_periph, 
2010                         cam_sim_path(sc->mly_cam_sim[bus]), target, 0) != CAM_REQ_CMP) {
2011         mly_printf(sc, "rescan failed (can't create path)\n");
2012         kfree(ccb, M_TEMP);
2013         return;
2014     }
2015     xpt_setup_ccb(&ccb->ccb_h, sc->mly_cam_path, 5/*priority (low)*/);
2016     ccb->ccb_h.func_code = XPT_SCAN_LUN;
2017     ccb->ccb_h.cbfcnp = mly_cam_rescan_callback;
2018     ccb->crcn.flags = CAM_FLAG_NONE;
2019     debug(1, "rescan target %d:%d", bus, target);
2020     xpt_action(ccb);
2021 }
2022
2023 static void
2024 mly_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2025 {
2026     kfree(ccb, M_TEMP);
2027 }
2028
2029 /********************************************************************************
2030  * Handle an action requested by CAM
2031  */
2032 static void
2033 mly_cam_action(struct cam_sim *sim, union ccb *ccb)
2034 {
2035     struct mly_softc    *sc = cam_sim_softc(sim);
2036
2037     debug_called(2);
2038
2039     switch (ccb->ccb_h.func_code) {
2040
2041         /* perform SCSI I/O */
2042     case XPT_SCSI_IO:
2043         if (!mly_cam_action_io(sim, (struct ccb_scsiio *)&ccb->csio))
2044             return;
2045         break;
2046
2047         /* perform geometry calculations */
2048     case XPT_CALC_GEOMETRY:
2049     {
2050         struct ccb_calc_geometry        *ccg = &ccb->ccg;
2051         u_int32_t                       secs_per_cylinder;
2052
2053         debug(2, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2054
2055         if (sc->mly_controllerparam->bios_geometry == MLY_BIOSGEOM_8G) {
2056             ccg->heads = 255;
2057             ccg->secs_per_track = 63;
2058         } else {                                /* MLY_BIOSGEOM_2G */
2059             ccg->heads = 128;
2060             ccg->secs_per_track = 32;
2061         }
2062         secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2063         ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2064         ccb->ccb_h.status = CAM_REQ_CMP;
2065         break;
2066     }
2067
2068         /* handle path attribute inquiry */
2069     case XPT_PATH_INQ:
2070     {
2071         struct ccb_pathinq      *cpi = &ccb->cpi;
2072
2073         debug(2, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2074
2075         cpi->version_num = 1;
2076         cpi->hba_inquiry = PI_TAG_ABLE;         /* XXX extra flags for physical channels? */
2077         cpi->target_sprt = 0;
2078         cpi->hba_misc = 0;
2079         cpi->max_target = MLY_MAX_TARGETS - 1;
2080         cpi->max_lun = MLY_MAX_LUNS - 1;
2081         cpi->initiator_id = sc->mly_controllerparam->initiator_id;
2082         strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2083         strncpy(cpi->hba_vid, "FreeBSD", HBA_IDLEN);
2084         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2085         cpi->unit_number = cam_sim_unit(sim);
2086         cpi->bus_id = cam_sim_bus(sim);
2087         cpi->base_transfer_speed = 132 * 1024;  /* XXX what to set this to? */
2088         cpi->transport = XPORT_SPI;
2089         cpi->transport_version = 2;
2090         cpi->protocol = PROTO_SCSI;
2091         cpi->protocol_version = SCSI_REV_2;
2092         ccb->ccb_h.status = CAM_REQ_CMP;
2093         break;
2094     }
2095
2096     case XPT_GET_TRAN_SETTINGS:
2097     {
2098         struct ccb_trans_settings       *cts = &ccb->cts;
2099         int                             bus, target;
2100         struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
2101         struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
2102
2103         cts->protocol = PROTO_SCSI;
2104         cts->protocol_version = SCSI_REV_2;
2105         cts->transport = XPORT_SPI;
2106         cts->transport_version = 2;
2107
2108         scsi->flags = 0;
2109         scsi->valid = 0;
2110         spi->flags = 0;
2111         spi->valid = 0;
2112
2113         bus = cam_sim_bus(sim);
2114         target = cts->ccb_h.target_id;
2115         debug(2, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2116         /* logical device? */
2117         if (sc->mly_btl[bus][target].mb_flags & MLY_BTL_LOGICAL) {
2118             /* nothing special for these */
2119         /* physical device? */
2120         } else if (sc->mly_btl[bus][target].mb_flags & MLY_BTL_PHYSICAL) {
2121             /* allow CAM to try tagged transactions */
2122             scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
2123             scsi->valid |= CTS_SCSI_VALID_TQ;
2124
2125             /* convert speed (MHz) to usec */
2126             if (sc->mly_btl[bus][target].mb_speed == 0) {
2127                 spi->sync_period = 1000000 / 5;
2128             } else {
2129                 spi->sync_period = 1000000 / sc->mly_btl[bus][target].mb_speed;
2130             }
2131
2132             /* convert bus width to CAM internal encoding */
2133             switch (sc->mly_btl[bus][target].mb_width) {
2134             case 32:
2135                 spi->bus_width = MSG_EXT_WDTR_BUS_32_BIT;
2136                 break;
2137             case 16:
2138                 spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
2139                 break;
2140             case 8:
2141             default:
2142                 spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
2143                 break;
2144             }
2145             spi->valid |= CTS_SPI_VALID_SYNC_RATE | CTS_SPI_VALID_BUS_WIDTH;
2146
2147             /* not a device, bail out */
2148         } else {
2149             cts->ccb_h.status = CAM_REQ_CMP_ERR;
2150             break;
2151         }
2152
2153         /* disconnect always OK */
2154         spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
2155         spi->valid |= CTS_SPI_VALID_DISC;
2156
2157         cts->ccb_h.status = CAM_REQ_CMP;
2158         break;
2159     }
2160
2161     default:            /* we can't do this */
2162         debug(2, "unsupported func_code = 0x%x", ccb->ccb_h.func_code);
2163         ccb->ccb_h.status = CAM_REQ_INVALID;
2164         break;
2165     }
2166
2167     xpt_done(ccb);
2168 }
2169
2170 /********************************************************************************
2171  * Handle an I/O operation requested by CAM
2172  */
2173 static int
2174 mly_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
2175 {
2176     struct mly_softc                    *sc = cam_sim_softc(sim);
2177     struct mly_command                  *mc;
2178     struct mly_command_scsi_small       *ss;
2179     int                                 bus, target;
2180     int                                 error;
2181
2182     bus = cam_sim_bus(sim);
2183     target = csio->ccb_h.target_id;
2184
2185     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
2186
2187     /* validate bus number */
2188     if (!MLY_BUS_IS_VALID(sc, bus)) {
2189         debug(0, " invalid bus %d", bus);
2190         csio->ccb_h.status = CAM_REQ_CMP_ERR;
2191     }
2192
2193     /*  check for I/O attempt to a protected device */
2194     if (sc->mly_btl[bus][target].mb_flags & MLY_BTL_PROTECTED) {
2195         debug(2, "  device protected");
2196         csio->ccb_h.status = CAM_REQ_CMP_ERR;
2197     }
2198
2199     /* check for I/O attempt to nonexistent device */
2200     if (!(sc->mly_btl[bus][target].mb_flags & (MLY_BTL_LOGICAL | MLY_BTL_PHYSICAL))) {
2201         debug(2, "  device %d:%d does not exist", bus, target);
2202         csio->ccb_h.status = CAM_REQ_CMP_ERR;
2203     }
2204
2205     /* XXX increase if/when we support large SCSI commands */
2206     if (csio->cdb_len > MLY_CMD_SCSI_SMALL_CDB) {
2207         debug(0, "  command too large (%d > %d)", csio->cdb_len, MLY_CMD_SCSI_SMALL_CDB);
2208         csio->ccb_h.status = CAM_REQ_CMP_ERR;
2209     }
2210
2211     /* check that the CDB pointer is not to a physical address */
2212     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
2213         debug(0, "  CDB pointer is to physical address");
2214         csio->ccb_h.status = CAM_REQ_CMP_ERR;
2215     }
2216
2217     /* if there is data transfer, it must be to/from a virtual address */
2218     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2219         if (csio->ccb_h.flags & CAM_DATA_PHYS) {                /* we can't map it */
2220             debug(0, "  data pointer is to physical address");
2221             csio->ccb_h.status = CAM_REQ_CMP_ERR;
2222         }
2223         if (csio->ccb_h.flags & CAM_SCATTER_VALID) {    /* we want to do the s/g setup */
2224             debug(0, "  data has premature s/g setup");
2225             csio->ccb_h.status = CAM_REQ_CMP_ERR;
2226         }
2227     }
2228
2229     /* abandon aborted ccbs or those that have failed validation */
2230     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2231         debug(2, "abandoning CCB due to abort/validation failure");
2232         return(EINVAL);
2233     }
2234
2235     /*
2236      * Get a command, or push the ccb back to CAM and freeze the queue.
2237      */
2238     if ((error = mly_alloc_command(sc, &mc))) {
2239         crit_enter();
2240         xpt_freeze_simq(sim, 1);
2241         csio->ccb_h.status |= CAM_REQUEUE_REQ;
2242         sc->mly_qfrzn_cnt++;
2243         crit_exit();
2244         return(error);
2245     }
2246     
2247     /* build the command */
2248     mc->mc_data = csio->data_ptr;
2249     mc->mc_length = csio->dxfer_len;
2250     mc->mc_complete = mly_cam_complete;
2251     mc->mc_private = csio;
2252
2253     /* save the bus number in the ccb for later recovery XXX should be a better way */
2254      csio->ccb_h.sim_priv.entries[0].field = bus;
2255
2256     /* build the packet for the controller */
2257     ss = &mc->mc_packet->scsi_small;
2258     ss->opcode = MDACMD_SCSI;
2259     if (csio->ccb_h.flags & CAM_DIS_DISCONNECT)
2260         ss->command_control.disable_disconnect = 1;
2261     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT)
2262         ss->command_control.data_direction = MLY_CCB_WRITE;
2263     ss->data_size = csio->dxfer_len;
2264     ss->addr.phys.lun = csio->ccb_h.target_lun;
2265     ss->addr.phys.target = csio->ccb_h.target_id;
2266     ss->addr.phys.channel = bus;
2267     if (csio->ccb_h.timeout < (60 * 1000)) {
2268         ss->timeout.value = csio->ccb_h.timeout / 1000;
2269         ss->timeout.scale = MLY_TIMEOUT_SECONDS;
2270     } else if (csio->ccb_h.timeout < (60 * 60 * 1000)) {
2271         ss->timeout.value = csio->ccb_h.timeout / (60 * 1000);
2272         ss->timeout.scale = MLY_TIMEOUT_MINUTES;
2273     } else {
2274         ss->timeout.value = csio->ccb_h.timeout / (60 * 60 * 1000);     /* overflow? */
2275         ss->timeout.scale = MLY_TIMEOUT_HOURS;
2276     }
2277     ss->maximum_sense_size = csio->sense_len;
2278     ss->cdb_length = csio->cdb_len;
2279     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2280         bcopy(csio->cdb_io.cdb_ptr, ss->cdb, csio->cdb_len);
2281     } else {
2282         bcopy(csio->cdb_io.cdb_bytes, ss->cdb, csio->cdb_len);
2283     }
2284
2285     /* give the command to the controller */
2286     if ((error = mly_start(mc))) {
2287         crit_enter();
2288         xpt_freeze_simq(sim, 1);
2289         csio->ccb_h.status |= CAM_REQUEUE_REQ;
2290         sc->mly_qfrzn_cnt++;
2291         crit_exit();
2292         return(error);
2293     }
2294
2295     return(0);
2296 }
2297
2298 /********************************************************************************
2299  * Check for possibly-completed commands.
2300  */
2301 static void
2302 mly_cam_poll(struct cam_sim *sim)
2303 {
2304     struct mly_softc    *sc = cam_sim_softc(sim);
2305
2306     debug_called(2);
2307
2308     mly_done(sc);
2309 }
2310
2311 /********************************************************************************
2312  * Handle completion of a command - pass results back through the CCB
2313  */
2314 static void
2315 mly_cam_complete(struct mly_command *mc)
2316 {
2317     struct mly_softc            *sc = mc->mc_sc;
2318     struct ccb_scsiio           *csio = (struct ccb_scsiio *)mc->mc_private;
2319     struct scsi_inquiry_data    *inq = (struct scsi_inquiry_data *)csio->data_ptr;
2320     struct mly_btl              *btl;
2321     u_int8_t                    cmd;
2322     int                         bus, target;
2323
2324     debug_called(2);
2325
2326     csio->scsi_status = mc->mc_status;
2327     switch(mc->mc_status) {
2328     case SCSI_STATUS_OK:
2329         /*
2330          * In order to report logical device type and status, we overwrite
2331          * the result of the INQUIRY command to logical devices.
2332          */
2333         bus = csio->ccb_h.sim_priv.entries[0].field;
2334         target = csio->ccb_h.target_id;
2335         /* XXX validate bus/target? */
2336         if (sc->mly_btl[bus][target].mb_flags & MLY_BTL_LOGICAL) {
2337             if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2338                 cmd = *csio->cdb_io.cdb_ptr;
2339             } else {
2340                 cmd = csio->cdb_io.cdb_bytes[0];
2341             }
2342             if (cmd == INQUIRY) {
2343                 btl = &sc->mly_btl[bus][target];
2344                 padstr(inq->vendor, mly_describe_code(mly_table_device_type, btl->mb_type), 8);
2345                 padstr(inq->product, mly_describe_code(mly_table_device_state, btl->mb_state), 16);
2346                 padstr(inq->revision, "", 4);
2347             }
2348         }
2349
2350         debug(2, "SCSI_STATUS_OK");
2351         csio->ccb_h.status = CAM_REQ_CMP;
2352         break;
2353
2354     case SCSI_STATUS_CHECK_COND:
2355         debug(1, "SCSI_STATUS_CHECK_COND  sense %d  resid %d", mc->mc_sense, mc->mc_resid);
2356         csio->ccb_h.status = CAM_SCSI_STATUS_ERROR;
2357         bzero(&csio->sense_data, SSD_FULL_SIZE);
2358         bcopy(mc->mc_packet, &csio->sense_data, mc->mc_sense);
2359         csio->sense_len = mc->mc_sense;
2360         csio->ccb_h.status |= CAM_AUTOSNS_VALID;
2361         csio->resid = mc->mc_resid;     /* XXX this is a signed value... */
2362         break;
2363
2364     case SCSI_STATUS_BUSY:
2365         debug(1, "SCSI_STATUS_BUSY");
2366         csio->ccb_h.status = CAM_SCSI_BUSY;
2367         break;
2368
2369     default:
2370         debug(1, "unknown status 0x%x", csio->scsi_status);
2371         csio->ccb_h.status = CAM_REQ_CMP_ERR;
2372         break;
2373     }
2374
2375     crit_enter();
2376     if (sc->mly_qfrzn_cnt) {
2377         csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2378         sc->mly_qfrzn_cnt--;
2379     }
2380     crit_exit();
2381
2382     xpt_done((union ccb *)csio);
2383     mly_release_command(mc);
2384 }
2385
2386 /********************************************************************************
2387  * Find a peripheral attahed at (bus),(target)
2388  */
2389 static struct cam_periph *
2390 mly_find_periph(struct mly_softc *sc, int bus, int target)
2391 {
2392     struct cam_periph   *periph;
2393     struct cam_path     *path;
2394     int                 status;
2395
2396     status = xpt_create_path(&path, NULL, cam_sim_path(sc->mly_cam_sim[bus]), target, 0);
2397     if (status == CAM_REQ_CMP) {
2398         periph = cam_periph_find(path, NULL);
2399         xpt_free_path(path);
2400     } else {
2401         periph = NULL;
2402     }
2403     return(periph);
2404 }
2405
2406 /********************************************************************************
2407  * Name the device at (bus)(target)
2408  */
2409 static int
2410 mly_name_device(struct mly_softc *sc, int bus, int target)
2411 {
2412     struct cam_periph   *periph;
2413
2414     if ((periph = mly_find_periph(sc, bus, target)) != NULL) {
2415         ksprintf(sc->mly_btl[bus][target].mb_name, "%s%d", periph->periph_name, periph->unit_number);
2416         return(0);
2417     }
2418     sc->mly_btl[bus][target].mb_name[0] = 0;
2419     return(ENOENT);
2420 }
2421
2422 /********************************************************************************
2423  ********************************************************************************
2424                                                                  Hardware Control
2425  ********************************************************************************
2426  ********************************************************************************/
2427
2428 /********************************************************************************
2429  * Handshake with the firmware while the card is being initialised.
2430  */
2431 static int
2432 mly_fwhandshake(struct mly_softc *sc) 
2433 {
2434     u_int8_t    error, param0, param1;
2435     int         spinup = 0;
2436
2437     debug_called(1);
2438
2439     /* set HM_STSACK and let the firmware initialise */
2440     MLY_SET_REG(sc, sc->mly_idbr, MLY_HM_STSACK);
2441     DELAY(1000);        /* too short? */
2442
2443     /* if HM_STSACK is still true, the controller is initialising */
2444     if (!MLY_IDBR_TRUE(sc, MLY_HM_STSACK))
2445         return(0);
2446     mly_printf(sc, "controller initialisation started\n");
2447
2448     /* spin waiting for initialisation to finish, or for a message to be delivered */
2449     while (MLY_IDBR_TRUE(sc, MLY_HM_STSACK)) {
2450         /* check for a message */
2451         if (MLY_ERROR_VALID(sc)) {
2452             error = MLY_GET_REG(sc, sc->mly_error_status) & ~MLY_MSG_EMPTY;
2453             param0 = MLY_GET_REG(sc, sc->mly_command_mailbox);
2454             param1 = MLY_GET_REG(sc, sc->mly_command_mailbox + 1);
2455
2456             switch(error) {
2457             case MLY_MSG_SPINUP:
2458                 if (!spinup) {
2459                     mly_printf(sc, "drive spinup in progress\n");
2460                     spinup = 1;                 /* only print this once (should print drive being spun?) */
2461                 }
2462                 break;
2463             case MLY_MSG_RACE_RECOVERY_FAIL:
2464                 mly_printf(sc, "mirror race recovery failed, one or more drives offline\n");
2465                 break;
2466             case MLY_MSG_RACE_IN_PROGRESS:
2467                 mly_printf(sc, "mirror race recovery in progress\n");
2468                 break;
2469             case MLY_MSG_RACE_ON_CRITICAL:
2470                 mly_printf(sc, "mirror race recovery on a critical drive\n");
2471                 break;
2472             case MLY_MSG_PARITY_ERROR:
2473                 mly_printf(sc, "FATAL MEMORY PARITY ERROR\n");
2474                 return(ENXIO);
2475             default:
2476                 mly_printf(sc, "unknown initialisation code 0x%x\n", error);
2477             }
2478         }
2479     }
2480     return(0);
2481 }
2482
2483 /********************************************************************************
2484  ********************************************************************************
2485                                                         Debugging and Diagnostics
2486  ********************************************************************************
2487  ********************************************************************************/
2488
2489 /********************************************************************************
2490  * Print some information about the controller.
2491  */
2492 static void
2493 mly_describe_controller(struct mly_softc *sc)
2494 {
2495     struct mly_ioctl_getcontrollerinfo  *mi = sc->mly_controllerinfo;
2496
2497     mly_printf(sc, "%16s, %d channel%s, firmware %d.%02d-%d-%02d (%02d%02d%02d%02d), %dMB RAM\n", 
2498                mi->controller_name, mi->physical_channels_present, (mi->physical_channels_present) > 1 ? "s" : "",
2499                mi->fw_major, mi->fw_minor, mi->fw_turn, mi->fw_build,   /* XXX turn encoding? */
2500                mi->fw_century, mi->fw_year, mi->fw_month, mi->fw_day,
2501                mi->memory_size);
2502
2503     if (bootverbose) {
2504         mly_printf(sc, "%s %s (%x), %dMHz %d-bit %.16s\n", 
2505                    mly_describe_code(mly_table_oemname, mi->oem_information), 
2506                    mly_describe_code(mly_table_controllertype, mi->controller_type), mi->controller_type,
2507                    mi->interface_speed, mi->interface_width, mi->interface_name);
2508         mly_printf(sc, "%dMB %dMHz %d-bit %s%s%s, cache %dMB\n",
2509                    mi->memory_size, mi->memory_speed, mi->memory_width, 
2510                    mly_describe_code(mly_table_memorytype, mi->memory_type),
2511                    mi->memory_parity ? "+parity": "",mi->memory_ecc ? "+ECC": "",
2512                    mi->cache_size);
2513         mly_printf(sc, "CPU: %s @ %dMHZ\n", 
2514                    mly_describe_code(mly_table_cputype, mi->cpu[0].type), mi->cpu[0].speed);
2515         if (mi->l2cache_size != 0)
2516             mly_printf(sc, "%dKB L2 cache\n", mi->l2cache_size);
2517         if (mi->exmemory_size != 0)
2518             mly_printf(sc, "%dMB %dMHz %d-bit private %s%s%s\n",
2519                        mi->exmemory_size, mi->exmemory_speed, mi->exmemory_width,
2520                        mly_describe_code(mly_table_memorytype, mi->exmemory_type),
2521                        mi->exmemory_parity ? "+parity": "",mi->exmemory_ecc ? "+ECC": "");
2522         mly_printf(sc, "battery backup %s\n", mi->bbu_present ? "present" : "not installed");
2523         mly_printf(sc, "maximum data transfer %d blocks, maximum sg entries/command %d\n",
2524                    mi->maximum_block_count, mi->maximum_sg_entries);
2525         mly_printf(sc, "logical devices present/critical/offline %d/%d/%d\n",
2526                    mi->logical_devices_present, mi->logical_devices_critical, mi->logical_devices_offline);
2527         mly_printf(sc, "physical devices present %d\n",
2528                    mi->physical_devices_present);
2529         mly_printf(sc, "physical disks present/offline %d/%d\n",
2530                    mi->physical_disks_present, mi->physical_disks_offline);
2531         mly_printf(sc, "%d physical channel%s, %d virtual channel%s of %d possible\n",
2532                    mi->physical_channels_present, mi->physical_channels_present == 1 ? "" : "s",
2533                    mi->virtual_channels_present, mi->virtual_channels_present == 1 ? "" : "s",
2534                    mi->virtual_channels_possible);
2535         mly_printf(sc, "%d parallel commands supported\n", mi->maximum_parallel_commands);
2536         mly_printf(sc, "%dMB flash ROM, %d of %d maximum cycles\n",
2537                    mi->flash_size, mi->flash_age, mi->flash_maximum_age);
2538     }
2539 }
2540
2541 #ifdef MLY_DEBUG
2542 /********************************************************************************
2543  * Print some controller state
2544  */
2545 static void
2546 mly_printstate(struct mly_softc *sc)
2547 {
2548     mly_printf(sc, "IDBR %02x  ODBR %02x  ERROR %02x  (%x %x %x)\n",
2549                   MLY_GET_REG(sc, sc->mly_idbr),
2550                   MLY_GET_REG(sc, sc->mly_odbr),
2551                   MLY_GET_REG(sc, sc->mly_error_status),
2552                   sc->mly_idbr,
2553                   sc->mly_odbr,
2554                   sc->mly_error_status);
2555     mly_printf(sc, "IMASK %02x  ISTATUS %02x\n",
2556                   MLY_GET_REG(sc, sc->mly_interrupt_mask),
2557                   MLY_GET_REG(sc, sc->mly_interrupt_status));
2558     mly_printf(sc, "COMMAND %02x %02x %02x %02x %02x %02x %02x %02x\n",
2559                   MLY_GET_REG(sc, sc->mly_command_mailbox),
2560                   MLY_GET_REG(sc, sc->mly_command_mailbox + 1),
2561                   MLY_GET_REG(sc, sc->mly_command_mailbox + 2),
2562                   MLY_GET_REG(sc, sc->mly_command_mailbox + 3),
2563                   MLY_GET_REG(sc, sc->mly_command_mailbox + 4),
2564                   MLY_GET_REG(sc, sc->mly_command_mailbox + 5),
2565                   MLY_GET_REG(sc, sc->mly_command_mailbox + 6),
2566                   MLY_GET_REG(sc, sc->mly_command_mailbox + 7));
2567     mly_printf(sc, "STATUS  %02x %02x %02x %02x %02x %02x %02x %02x\n",
2568                   MLY_GET_REG(sc, sc->mly_status_mailbox),
2569                   MLY_GET_REG(sc, sc->mly_status_mailbox + 1),
2570                   MLY_GET_REG(sc, sc->mly_status_mailbox + 2),
2571                   MLY_GET_REG(sc, sc->mly_status_mailbox + 3),
2572                   MLY_GET_REG(sc, sc->mly_status_mailbox + 4),
2573                   MLY_GET_REG(sc, sc->mly_status_mailbox + 5),
2574                   MLY_GET_REG(sc, sc->mly_status_mailbox + 6),
2575                   MLY_GET_REG(sc, sc->mly_status_mailbox + 7));
2576     mly_printf(sc, "        %04x        %08x\n",
2577                   MLY_GET_REG2(sc, sc->mly_status_mailbox),
2578                   MLY_GET_REG4(sc, sc->mly_status_mailbox + 4));
2579 }
2580
2581 struct mly_softc        *mly_softc0 = NULL;
2582 void
2583 mly_printstate0(void)
2584 {
2585     if (mly_softc0 != NULL)
2586         mly_printstate(mly_softc0);
2587 }
2588
2589 /********************************************************************************
2590  * Print a command
2591  */
2592 static void
2593 mly_print_command(struct mly_command *mc)
2594 {
2595     struct mly_softc    *sc = mc->mc_sc;
2596     
2597     mly_printf(sc, "COMMAND @ %p\n", mc);
2598     mly_printf(sc, "  slot      %d\n", mc->mc_slot);
2599     mly_printf(sc, "  status    0x%x\n", mc->mc_status);
2600     mly_printf(sc, "  sense len %d\n", mc->mc_sense);
2601     mly_printf(sc, "  resid     %d\n", mc->mc_resid);
2602     mly_printf(sc, "  packet    %p/0x%llx\n", mc->mc_packet, mc->mc_packetphys);
2603     if (mc->mc_packet != NULL)
2604         mly_print_packet(mc);
2605     mly_printf(sc, "  data      %p/%d\n", mc->mc_data, mc->mc_length);
2606     mly_printf(sc, "  flags     %b\n", mc->mc_flags, "\20\1busy\2complete\3slotted\4mapped\5datain\6dataout\n");
2607     mly_printf(sc, "  complete  %p\n", mc->mc_complete);
2608     mly_printf(sc, "  private   %p\n", mc->mc_private);
2609 }
2610
2611 /********************************************************************************
2612  * Print a command packet
2613  */
2614 static void
2615 mly_print_packet(struct mly_command *mc)
2616 {
2617     struct mly_softc                    *sc = mc->mc_sc;
2618     struct mly_command_generic          *ge = (struct mly_command_generic *)mc->mc_packet;
2619     struct mly_command_scsi_small       *ss = (struct mly_command_scsi_small *)mc->mc_packet;
2620     struct mly_command_scsi_large       *sl = (struct mly_command_scsi_large *)mc->mc_packet;
2621     struct mly_command_ioctl            *io = (struct mly_command_ioctl *)mc->mc_packet;
2622     int                                 transfer;
2623
2624     mly_printf(sc, "   command_id           %d\n", ge->command_id);
2625     mly_printf(sc, "   opcode               %d\n", ge->opcode);
2626     mly_printf(sc, "   command_control      fua %d  dpo %d  est %d  dd %s  nas %d ddis %d\n",
2627                   ge->command_control.force_unit_access,
2628                   ge->command_control.disable_page_out,
2629                   ge->command_control.extended_sg_table,
2630                   (ge->command_control.data_direction == MLY_CCB_WRITE) ? "WRITE" : "READ",
2631                   ge->command_control.no_auto_sense,
2632                   ge->command_control.disable_disconnect);
2633     mly_printf(sc, "   data_size            %d\n", ge->data_size);
2634     mly_printf(sc, "   sense_buffer_address 0x%llx\n", ge->sense_buffer_address);
2635     mly_printf(sc, "   lun                  %d\n", ge->addr.phys.lun);
2636     mly_printf(sc, "   target               %d\n", ge->addr.phys.target);
2637     mly_printf(sc, "   channel              %d\n", ge->addr.phys.channel);
2638     mly_printf(sc, "   logical device       %d\n", ge->addr.log.logdev);
2639     mly_printf(sc, "   controller           %d\n", ge->addr.phys.controller);
2640     mly_printf(sc, "   timeout              %d %s\n", 
2641                   ge->timeout.value,
2642                   (ge->timeout.scale == MLY_TIMEOUT_SECONDS) ? "seconds" : 
2643                   ((ge->timeout.scale == MLY_TIMEOUT_MINUTES) ? "minutes" : "hours"));
2644     mly_printf(sc, "   maximum_sense_size   %d\n", ge->maximum_sense_size);
2645     switch(ge->opcode) {
2646     case MDACMD_SCSIPT:
2647     case MDACMD_SCSI:
2648         mly_printf(sc, "   cdb length           %d\n", ss->cdb_length);
2649         mly_printf(sc, "   cdb                  %*D\n", ss->cdb_length, ss->cdb, " ");
2650         transfer = 1;
2651         break;
2652     case MDACMD_SCSILC:
2653     case MDACMD_SCSILCPT:
2654         mly_printf(sc, "   cdb length           %d\n", sl->cdb_length);
2655         mly_printf(sc, "   cdb                  0x%llx\n", sl->cdb_physaddr);
2656         transfer = 1;
2657         break;
2658     case MDACMD_IOCTL:
2659         mly_printf(sc, "   sub_ioctl            0x%x\n", io->sub_ioctl);
2660         switch(io->sub_ioctl) {
2661         case MDACIOCTL_SETMEMORYMAILBOX:
2662             mly_printf(sc, "   health_buffer_size   %d\n", 
2663                           io->param.setmemorymailbox.health_buffer_size);
2664             mly_printf(sc, "   health_buffer_phys   0x%llx\n",
2665                           io->param.setmemorymailbox.health_buffer_physaddr);
2666             mly_printf(sc, "   command_mailbox      0x%llx\n",
2667                           io->param.setmemorymailbox.command_mailbox_physaddr);
2668             mly_printf(sc, "   status_mailbox       0x%llx\n",
2669                           io->param.setmemorymailbox.status_mailbox_physaddr);
2670             transfer = 0;
2671             break;
2672
2673         case MDACIOCTL_SETREALTIMECLOCK:
2674         case MDACIOCTL_GETHEALTHSTATUS:
2675         case MDACIOCTL_GETCONTROLLERINFO:
2676         case MDACIOCTL_GETLOGDEVINFOVALID:
2677         case MDACIOCTL_GETPHYSDEVINFOVALID:
2678         case MDACIOCTL_GETPHYSDEVSTATISTICS:
2679         case MDACIOCTL_GETLOGDEVSTATISTICS:
2680         case MDACIOCTL_GETCONTROLLERSTATISTICS:
2681         case MDACIOCTL_GETBDT_FOR_SYSDRIVE:         
2682         case MDACIOCTL_CREATENEWCONF:
2683         case MDACIOCTL_ADDNEWCONF:
2684         case MDACIOCTL_GETDEVCONFINFO:
2685         case MDACIOCTL_GETFREESPACELIST:
2686         case MDACIOCTL_MORE:
2687         case MDACIOCTL_SETPHYSDEVPARAMETER:
2688         case MDACIOCTL_GETPHYSDEVPARAMETER:
2689         case MDACIOCTL_GETLOGDEVPARAMETER:
2690         case MDACIOCTL_SETLOGDEVPARAMETER:
2691             mly_printf(sc, "   param                %10D\n", io->param.data.param, " ");
2692             transfer = 1;
2693             break;
2694
2695         case MDACIOCTL_GETEVENT:
2696             mly_printf(sc, "   event                %d\n", 
2697                        io->param.getevent.sequence_number_low + ((u_int32_t)io->addr.log.logdev << 16));
2698             transfer = 1;
2699             break;
2700
2701         case MDACIOCTL_SETRAIDDEVSTATE:
2702             mly_printf(sc, "   state                %d\n", io->param.setraiddevstate.state);
2703             transfer = 0;
2704             break;
2705
2706         case MDACIOCTL_XLATEPHYSDEVTORAIDDEV:
2707             mly_printf(sc, "   raid_device          %d\n", io->param.xlatephysdevtoraiddev.raid_device);
2708             mly_printf(sc, "   controller           %d\n", io->param.xlatephysdevtoraiddev.controller);
2709             mly_printf(sc, "   channel              %d\n", io->param.xlatephysdevtoraiddev.channel);
2710             mly_printf(sc, "   target               %d\n", io->param.xlatephysdevtoraiddev.target);
2711             mly_printf(sc, "   lun                  %d\n", io->param.xlatephysdevtoraiddev.lun);
2712             transfer = 0;
2713             break;
2714
2715         case MDACIOCTL_GETGROUPCONFINFO:
2716             mly_printf(sc, "   group                %d\n", io->param.getgroupconfinfo.group);
2717             transfer = 1;
2718             break;
2719
2720         case MDACIOCTL_GET_SUBSYSTEM_DATA:
2721         case MDACIOCTL_SET_SUBSYSTEM_DATA:
2722         case MDACIOCTL_STARTDISOCVERY:
2723         case MDACIOCTL_INITPHYSDEVSTART:
2724         case MDACIOCTL_INITPHYSDEVSTOP:
2725         case MDACIOCTL_INITRAIDDEVSTART:
2726         case MDACIOCTL_INITRAIDDEVSTOP:
2727         case MDACIOCTL_REBUILDRAIDDEVSTART:
2728         case MDACIOCTL_REBUILDRAIDDEVSTOP:
2729         case MDACIOCTL_MAKECONSISTENTDATASTART:
2730         case MDACIOCTL_MAKECONSISTENTDATASTOP:
2731         case MDACIOCTL_CONSISTENCYCHECKSTART:
2732         case MDACIOCTL_CONSISTENCYCHECKSTOP:
2733         case MDACIOCTL_RESETDEVICE:
2734         case MDACIOCTL_FLUSHDEVICEDATA:
2735         case MDACIOCTL_PAUSEDEVICE:
2736         case MDACIOCTL_UNPAUSEDEVICE:
2737         case MDACIOCTL_LOCATEDEVICE:
2738         case MDACIOCTL_SETMASTERSLAVEMODE:
2739         case MDACIOCTL_DELETERAIDDEV:
2740         case MDACIOCTL_REPLACEINTERNALDEV:
2741         case MDACIOCTL_CLEARCONF:
2742         case MDACIOCTL_GETCONTROLLERPARAMETER:
2743         case MDACIOCTL_SETCONTRLLERPARAMETER:
2744         case MDACIOCTL_CLEARCONFSUSPMODE:
2745         case MDACIOCTL_STOREIMAGE:
2746         case MDACIOCTL_READIMAGE:
2747         case MDACIOCTL_FLASHIMAGES:
2748         case MDACIOCTL_RENAMERAIDDEV:
2749         default:                        /* no idea what to print */
2750             transfer = 0;
2751             break;
2752         }
2753         break;
2754
2755     case MDACMD_IOCTLCHECK:
2756     case MDACMD_MEMCOPY:
2757     default:
2758         transfer = 0;
2759         break;  /* print nothing */
2760     }
2761     if (transfer) {
2762         if (ge->command_control.extended_sg_table) {
2763             mly_printf(sc, "   sg table             0x%llx/%d\n",
2764                           ge->transfer.indirect.table_physaddr[0], ge->transfer.indirect.entries[0]);
2765         } else {
2766             mly_printf(sc, "   0000                 0x%llx/%lld\n",
2767                           ge->transfer.direct.sg[0].physaddr, ge->transfer.direct.sg[0].length);
2768             mly_printf(sc, "   0001                 0x%llx/%lld\n",
2769                           ge->transfer.direct.sg[1].physaddr, ge->transfer.direct.sg[1].length);
2770         }
2771     }
2772 }
2773
2774 /********************************************************************************
2775  * Panic in a slightly informative fashion
2776  */
2777 static void
2778 mly_panic(struct mly_softc *sc, char *reason)
2779 {
2780     mly_printstate(sc);
2781     panic(reason);
2782 }
2783
2784 /********************************************************************************
2785  * Print queue statistics, callable from DDB.
2786  */
2787 void
2788 mly_print_controller(int controller)
2789 {
2790     struct mly_softc    *sc;
2791     
2792     if ((sc = devclass_get_softc(devclass_find("mly"), controller)) == NULL) {
2793         kprintf("mly: controller %d invalid\n", controller);
2794     } else {
2795         device_printf(sc->mly_dev, "queue    curr max\n");
2796         device_printf(sc->mly_dev, "free     %04d/%04d\n", 
2797                       sc->mly_qstat[MLYQ_FREE].q_length, sc->mly_qstat[MLYQ_FREE].q_max);
2798         device_printf(sc->mly_dev, "busy     %04d/%04d\n", 
2799                       sc->mly_qstat[MLYQ_BUSY].q_length, sc->mly_qstat[MLYQ_BUSY].q_max);
2800         device_printf(sc->mly_dev, "complete %04d/%04d\n", 
2801                       sc->mly_qstat[MLYQ_COMPLETE].q_length, sc->mly_qstat[MLYQ_COMPLETE].q_max);
2802     }
2803 }
2804 #endif
2805
2806
2807 /********************************************************************************
2808  ********************************************************************************
2809                                                          Control device interface
2810  ********************************************************************************
2811  ********************************************************************************/
2812
2813 /********************************************************************************
2814  * Accept an open operation on the control device.
2815  */
2816 static int
2817 mly_user_open(struct dev_open_args *ap)
2818 {
2819     cdev_t dev = ap->a_head.a_dev;
2820     int                 unit = minor(dev);
2821     struct mly_softc    *sc = devclass_get_softc(devclass_find("mly"), unit);
2822
2823     sc->mly_state |= MLY_STATE_OPEN;
2824     return(0);
2825 }
2826
2827 /********************************************************************************
2828  * Accept the last close on the control device.
2829  */
2830 static int
2831 mly_user_close(struct dev_close_args *ap)
2832 {
2833     cdev_t dev = ap->a_head.a_dev;
2834     int                 unit = minor(dev);
2835     struct mly_softc    *sc = devclass_get_softc(devclass_find("mly"), unit);
2836
2837     sc->mly_state &= ~MLY_STATE_OPEN;
2838     return (0);
2839 }
2840
2841 /********************************************************************************
2842  * Handle controller-specific control operations.
2843  */
2844 static int
2845 mly_user_ioctl(struct dev_ioctl_args *ap)
2846 {
2847     cdev_t dev = ap->a_head.a_dev;
2848     struct mly_softc            *sc = (struct mly_softc *)dev->si_drv1;
2849     struct mly_user_command     *uc = (struct mly_user_command *)ap->a_data;
2850     struct mly_user_health      *uh = (struct mly_user_health *)ap->a_data;
2851     
2852     switch(ap->a_cmd) {
2853     case MLYIO_COMMAND:
2854         return(mly_user_command(sc, uc));
2855     case MLYIO_HEALTH:
2856         return(mly_user_health(sc, uh));
2857     default:
2858         return(ENOIOCTL);
2859     }
2860 }
2861
2862 /********************************************************************************
2863  * Execute a command passed in from userspace.
2864  *
2865  * The control structure contains the actual command for the controller, as well
2866  * as the user-space data pointer and data size, and an optional sense buffer
2867  * size/pointer.  On completion, the data size is adjusted to the command
2868  * residual, and the sense buffer size to the size of the returned sense data.
2869  * 
2870  */
2871 static int
2872 mly_user_command(struct mly_softc *sc, struct mly_user_command *uc)
2873 {
2874     struct mly_command  *mc;
2875     int                 error;
2876
2877     /* allocate a command */
2878     if (mly_alloc_command(sc, &mc)) {
2879         error = ENOMEM;
2880         goto out;               /* XXX Linux version will wait for a command */
2881     }
2882
2883     /* handle data size/direction */
2884     mc->mc_length = (uc->DataTransferLength >= 0) ? uc->DataTransferLength : -uc->DataTransferLength;
2885     if (mc->mc_length > 0)
2886         mc->mc_data = kmalloc(mc->mc_length, M_DEVBUF, M_INTWAIT);
2887     if (uc->DataTransferLength > 0) {
2888         mc->mc_flags |= MLY_CMD_DATAIN;
2889         bzero(mc->mc_data, mc->mc_length);
2890     }
2891     if (uc->DataTransferLength < 0) {
2892         mc->mc_flags |= MLY_CMD_DATAOUT;
2893         if ((error = copyin(uc->DataTransferBuffer, mc->mc_data, mc->mc_length)) != 0)
2894             goto out;
2895     }
2896
2897     /* copy the controller command */
2898     bcopy(&uc->CommandMailbox, mc->mc_packet, sizeof(uc->CommandMailbox));
2899
2900     /* clear command completion handler so that we get woken up */
2901     mc->mc_complete = NULL;
2902
2903     /* execute the command */
2904     if ((error = mly_start(mc)) != 0)
2905         goto out;
2906     crit_enter();
2907     while (!(mc->mc_flags & MLY_CMD_COMPLETE))
2908         tsleep(mc, 0, "mlyioctl", 0);
2909     crit_exit();
2910
2911     /* return the data to userspace */
2912     if (uc->DataTransferLength > 0)
2913         if ((error = copyout(mc->mc_data, uc->DataTransferBuffer, mc->mc_length)) != 0)
2914             goto out;
2915     
2916     /* return the sense buffer to userspace */
2917     if ((uc->RequestSenseLength > 0) && (mc->mc_sense > 0)) {
2918         if ((error = copyout(mc->mc_packet, uc->RequestSenseBuffer, 
2919                              min(uc->RequestSenseLength, mc->mc_sense))) != 0)
2920             goto out;
2921     }
2922     
2923     /* return command results to userspace (caller will copy out) */
2924     uc->DataTransferLength = mc->mc_resid;
2925     uc->RequestSenseLength = min(uc->RequestSenseLength, mc->mc_sense);
2926     uc->CommandStatus = mc->mc_status;
2927     error = 0;
2928
2929  out:
2930     if (mc->mc_data != NULL)
2931         kfree(mc->mc_data, M_DEVBUF);
2932     if (mc != NULL)
2933         mly_release_command(mc);
2934     return(error);
2935 }
2936
2937 /********************************************************************************
2938  * Return health status to userspace.  If the health change index in the user
2939  * structure does not match that currently exported by the controller, we
2940  * return the current status immediately.  Otherwise, we block until either
2941  * interrupted or new status is delivered.
2942  */
2943 static int
2944 mly_user_health(struct mly_softc *sc, struct mly_user_health *uh)
2945 {
2946     struct mly_health_status            mh;
2947     int                                 error;
2948     
2949     /* fetch the current health status from userspace */
2950     if ((error = copyin(uh->HealthStatusBuffer, &mh, sizeof(mh))) != 0)
2951         return(error);
2952
2953     /* spin waiting for a status update */
2954     crit_enter();
2955     error = EWOULDBLOCK;
2956     while ((error != 0) && (sc->mly_event_change == mh.change_counter))
2957         error = tsleep(&sc->mly_event_change, PCATCH, "mlyhealth", 0);
2958     crit_exit();
2959     
2960     /* copy the controller's health status buffer out (there is a race here if it changes again) */
2961     error = copyout(&sc->mly_mmbox->mmm_health.status, uh->HealthStatusBuffer, 
2962                     sizeof(uh->HealthStatusBuffer));
2963     return(error);
2964 }
2965
2966 static int
2967 mly_timeout(struct mly_softc *sc)
2968 {
2969         struct mly_command *mc;
2970         int deadline;
2971
2972         deadline = time_second - MLY_CMD_TIMEOUT;
2973         TAILQ_FOREACH(mc, &sc->mly_busy, mc_link) {
2974                 if ((mc->mc_timestamp < deadline)) {
2975                         device_printf(sc->mly_dev,
2976                             "COMMAND %p TIMEOUT AFTER %d SECONDS\n", mc,
2977                             (int)(time_second - mc->mc_timestamp));
2978                 }
2979         }
2980
2981         callout_reset(&sc->mly_timeout, MLY_CMD_TIMEOUT * hz,
2982                       (timeout_t *)mly_timeout, sc);
2983
2984         return (0);
2985 }