Initial import from FreeBSD RELENG_4:
[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  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/kernel.h>
34 #include <sys/bus.h>
35 #include <sys/conf.h>
36 #include <sys/ctype.h>
37 #include <sys/ioccom.h>
38 #include <sys/stat.h>
39
40 #include <machine/bus_memio.h>
41 #include <machine/bus.h>
42 #include <machine/resource.h>
43 #include <sys/rman.h>
44
45 #include <cam/scsi/scsi_all.h>
46
47 #include <dev/mly/mlyreg.h>
48 #include <dev/mly/mlyio.h>
49 #include <dev/mly/mlyvar.h>
50 #define MLY_DEFINE_TABLES
51 #include <dev/mly/mly_tables.h>
52
53 static int      mly_get_controllerinfo(struct mly_softc *sc);
54 static void     mly_scan_devices(struct mly_softc *sc);
55 static void     mly_rescan_btl(struct mly_softc *sc, int bus, int target);
56 static void     mly_complete_rescan(struct mly_command *mc);
57 static int      mly_get_eventstatus(struct mly_softc *sc);
58 static int      mly_enable_mmbox(struct mly_softc *sc);
59 static int      mly_flush(struct mly_softc *sc);
60 static int      mly_ioctl(struct mly_softc *sc, struct mly_command_ioctl *ioctl, void **data, 
61                           size_t datasize, u_int8_t *status, void *sense_buffer, size_t *sense_length);
62 static void     mly_fetch_event(struct mly_softc *sc);
63 static void     mly_complete_event(struct mly_command *mc);
64 static void     mly_process_event(struct mly_softc *sc, struct mly_event *me);
65 static void     mly_periodic(void *data);
66
67 static int      mly_immediate_command(struct mly_command *mc);
68 static int      mly_start(struct mly_command *mc);
69 static void     mly_complete(void *context, int pending);
70
71 static void     mly_alloc_commands_map(void *arg, bus_dma_segment_t *segs, int nseg, int error);
72 static int      mly_alloc_commands(struct mly_softc *sc);
73 static void     mly_map_command(struct mly_command *mc);
74 static void     mly_unmap_command(struct mly_command *mc);
75
76 static int      mly_fwhandshake(struct mly_softc *sc);
77
78 static void     mly_describe_controller(struct mly_softc *sc);
79 #ifdef MLY_DEBUG
80 static void     mly_printstate(struct mly_softc *sc);
81 static void     mly_print_command(struct mly_command *mc);
82 static void     mly_print_packet(struct mly_command *mc);
83 static void     mly_panic(struct mly_softc *sc, char *reason);
84 #endif
85 void            mly_print_controller(int controller);
86
87 static d_open_t         mly_user_open;
88 static d_close_t        mly_user_close;
89 static d_ioctl_t        mly_user_ioctl;
90 static int      mly_user_command(struct mly_softc *sc, struct mly_user_command *uc);
91 static int      mly_user_health(struct mly_softc *sc, struct mly_user_health *uh);
92
93 #define MLY_CDEV_MAJOR  158
94
95 static struct cdevsw mly_cdevsw = {
96     mly_user_open,
97     mly_user_close,
98     noread,
99     nowrite,
100     mly_user_ioctl,
101     nopoll,
102     nommap,
103     nostrategy,
104     "mly",
105     MLY_CDEV_MAJOR,
106     nodump,
107     nopsize,
108     0,
109     -1
110 };
111
112 /********************************************************************************
113  ********************************************************************************
114                                                                  Device Interface
115  ********************************************************************************
116  ********************************************************************************/
117
118 /********************************************************************************
119  * Initialise the controller and softc
120  */
121 int
122 mly_attach(struct mly_softc *sc)
123 {
124     int         error;
125
126     debug_called(1);
127
128     /*
129      * Initialise per-controller queues.
130      */
131     mly_initq_free(sc);
132     mly_initq_ready(sc);
133     mly_initq_busy(sc);
134     mly_initq_complete(sc);
135
136 #if __FreeBSD_version >= 500005
137     /*
138      * Initialise command-completion task.
139      */
140     TASK_INIT(&sc->mly_task_complete, 0, mly_complete, sc);
141 #endif
142
143     /* disable interrupts before we start talking to the controller */
144     MLY_MASK_INTERRUPTS(sc);
145
146     /* 
147      * Wait for the controller to come ready, handshake with the firmware if required.
148      * This is typically only necessary on platforms where the controller BIOS does not
149      * run.
150      */
151     if ((error = mly_fwhandshake(sc)))
152         return(error);
153
154     /*
155      * Allocate command buffers
156      */
157     if ((error = mly_alloc_commands(sc)))
158         return(error);
159
160     /* 
161      * Obtain controller feature information
162      */
163     if ((error = mly_get_controllerinfo(sc)))
164         return(error);
165
166     /*
167      * Get the current event counter for health purposes, populate the initial
168      * health status buffer.
169      */
170     if ((error = mly_get_eventstatus(sc)))
171         return(error);
172
173     /*
174      * Enable memory-mailbox mode
175      */
176     if ((error = mly_enable_mmbox(sc)))
177         return(error);
178
179     /*
180      * Attach to CAM.
181      */
182     if ((error = mly_cam_attach(sc)))
183         return(error);
184
185     /* 
186      * Print a little information about the controller 
187      */
188     mly_describe_controller(sc);
189
190     /*
191      * Mark all attached devices for rescan
192      */
193     mly_scan_devices(sc);
194
195     /*
196      * Instigate the first status poll immediately.  Rescan completions won't
197      * happen until interrupts are enabled, which should still be before
198      * the SCSI subsystem gets to us. (XXX assuming CAM and interrupt-driven
199      * discovery here...)
200      */
201     mly_periodic((void *)sc);
202
203     /*
204      * Create the control device.
205      */
206     sc->mly_dev_t = make_dev(&mly_cdevsw, device_get_unit(sc->mly_dev), UID_ROOT, GID_OPERATOR,
207                              S_IRUSR | S_IWUSR, "mly%d", device_get_unit(sc->mly_dev));
208     sc->mly_dev_t->si_drv1 = sc;
209
210     /* enable interrupts now */
211     MLY_UNMASK_INTERRUPTS(sc);
212
213     return(0);
214 }
215
216 /********************************************************************************
217  * Bring the controller to a state where it can be safely left alone.
218  */
219 void
220 mly_detach(struct mly_softc *sc)
221 {
222
223     debug_called(1);
224
225     /* kill the periodic event */
226     untimeout(mly_periodic, sc, sc->mly_periodic);
227
228     sc->mly_state |= MLY_STATE_SUSPEND;
229
230     /* flush controller */
231     mly_printf(sc, "flushing cache...");
232     printf("%s\n", mly_flush(sc) ? "failed" : "done");
233
234     MLY_MASK_INTERRUPTS(sc);
235 }
236
237 /********************************************************************************
238  ********************************************************************************
239                                                                  Command Wrappers
240  ********************************************************************************
241  ********************************************************************************/
242
243 /********************************************************************************
244  * Fill in the mly_controllerinfo and mly_controllerparam fields in the softc.
245  */
246 static int
247 mly_get_controllerinfo(struct mly_softc *sc)
248 {
249     struct mly_command_ioctl    mci;
250     u_int8_t                    status;
251     int                         error;
252
253     debug_called(1);
254
255     if (sc->mly_controllerinfo != NULL)
256         free(sc->mly_controllerinfo, M_DEVBUF);
257
258     /* build the getcontrollerinfo ioctl and send it */
259     bzero(&mci, sizeof(mci));
260     sc->mly_controllerinfo = NULL;
261     mci.sub_ioctl = MDACIOCTL_GETCONTROLLERINFO;
262     if ((error = mly_ioctl(sc, &mci, (void **)&sc->mly_controllerinfo, sizeof(*sc->mly_controllerinfo),
263                            &status, NULL, NULL)))
264         return(error);
265     if (status != 0)
266         return(EIO);
267
268     if (sc->mly_controllerparam != NULL)
269         free(sc->mly_controllerparam, M_DEVBUF);
270
271     /* build the getcontrollerparameter ioctl and send it */
272     bzero(&mci, sizeof(mci));
273     sc->mly_controllerparam = NULL;
274     mci.sub_ioctl = MDACIOCTL_GETCONTROLLERPARAMETER;
275     if ((error = mly_ioctl(sc, &mci, (void **)&sc->mly_controllerparam, sizeof(*sc->mly_controllerparam),
276                            &status, NULL, NULL)))
277         return(error);
278     if (status != 0)
279         return(EIO);
280
281     return(0);
282 }
283
284 /********************************************************************************
285  * Schedule all possible devices for a rescan.
286  *
287  */
288 static void
289 mly_scan_devices(struct mly_softc *sc)
290 {
291     int         bus, target, nchn;
292
293     debug_called(1);
294
295     /*
296      * Clear any previous BTL information.
297      */
298     bzero(&sc->mly_btl, sizeof(sc->mly_btl));
299
300     /*
301      * Mark all devices as requiring a rescan, and let the early periodic scan collect them.
302      */
303     nchn = sc->mly_controllerinfo->physical_channels_present +
304         sc->mly_controllerinfo->virtual_channels_present;
305     for (bus = 0; bus < nchn; bus++)
306         for (target = 0; target < MLY_MAX_TARGETS; target++)
307             sc->mly_btl[bus][target].mb_flags = MLY_BTL_RESCAN;
308
309 }
310
311 /********************************************************************************
312  * Rescan a device, possibly as a consequence of getting an event which suggests
313  * that it may have changed.
314  */
315 static void
316 mly_rescan_btl(struct mly_softc *sc, int bus, int target)
317 {
318     struct mly_command          *mc;
319     struct mly_command_ioctl    *mci;
320
321     debug_called(2);
322
323     /* get a command */
324     mc = NULL;
325     if (mly_alloc_command(sc, &mc))
326         return;                         /* we'll be retried soon */
327
328     /* set up the data buffer */
329     if ((mc->mc_data = malloc(sizeof(union mly_devinfo), M_DEVBUF, M_NOWAIT)) == NULL) {
330         mly_release_command(mc);
331         return;                         /* we'll get retried the next time a command completes */
332     }
333     bzero(mc->mc_data, sizeof(union mly_devinfo));
334     mc->mc_flags |= MLY_CMD_DATAIN;
335     mc->mc_complete = mly_complete_rescan;
336
337     sc->mly_btl[bus][target].mb_flags &= ~MLY_BTL_RESCAN;
338
339     /* 
340      * Build the ioctl.
341      *
342      * At this point we are committed to sending this request, as it
343      * will be the only one constructed for this particular update.
344      */
345     mci = (struct mly_command_ioctl *)&mc->mc_packet->ioctl;
346     mci->opcode = MDACMD_IOCTL;
347     mci->addr.phys.controller = 0;
348     mci->timeout.value = 30;
349     mci->timeout.scale = MLY_TIMEOUT_SECONDS;
350     if (bus >= sc->mly_controllerinfo->physical_channels_present) {
351         mc->mc_length = mci->data_size = sizeof(struct mly_ioctl_getlogdevinfovalid);
352         mci->sub_ioctl = MDACIOCTL_GETLOGDEVINFOVALID;
353         mci->addr.log.logdev = ((bus - sc->mly_controllerinfo->physical_channels_present) * MLY_MAX_TARGETS) 
354             + target;
355         debug(2, "logical device %d", mci->addr.log.logdev);
356     } else {
357         mc->mc_length = mci->data_size = sizeof(struct mly_ioctl_getphysdevinfovalid);
358         mci->sub_ioctl = MDACIOCTL_GETPHYSDEVINFOVALID;
359         mci->addr.phys.lun = 0;
360         mci->addr.phys.target = target;
361         mci->addr.phys.channel = bus;
362         debug(2, "physical device %d:%d", mci->addr.phys.channel, mci->addr.phys.target);
363     }
364     
365     /*
366      * Use the ready queue to get this command dispatched.
367      */
368     mly_enqueue_ready(mc);
369     mly_startio(sc);
370 }
371
372 /********************************************************************************
373  * Handle the completion of a rescan operation
374  */
375 static void
376 mly_complete_rescan(struct mly_command *mc)
377 {
378     struct mly_softc                            *sc = mc->mc_sc;
379     struct mly_ioctl_getlogdevinfovalid         *ldi;
380     struct mly_ioctl_getphysdevinfovalid        *pdi;
381     int                                         bus, target;
382
383     debug_called(2);
384
385     /* iff the command completed OK, we should use the result to update our data */
386     if (mc->mc_status == 0) {
387         if (mc->mc_length == sizeof(*ldi)) {
388             ldi = (struct mly_ioctl_getlogdevinfovalid *)mc->mc_data;
389             bus = MLY_LOGDEV_BUS(sc, ldi->logical_device_number);
390             target = MLY_LOGDEV_TARGET(ldi->logical_device_number);
391             sc->mly_btl[bus][target].mb_flags = MLY_BTL_LOGICAL;        /* clears all other flags */
392             sc->mly_btl[bus][target].mb_type = ldi->raid_level;
393             sc->mly_btl[bus][target].mb_state = ldi->state;
394             debug(2, "BTL rescan for %d returns %s, %s", ldi->logical_device_number, 
395                   mly_describe_code(mly_table_device_type, ldi->raid_level),
396                   mly_describe_code(mly_table_device_state, ldi->state));
397         } else if (mc->mc_length == sizeof(*pdi)) {
398             pdi = (struct mly_ioctl_getphysdevinfovalid *)mc->mc_data;
399             bus = pdi->channel;
400             target = pdi->target;
401             sc->mly_btl[bus][target].mb_flags = MLY_BTL_PHYSICAL;       /* clears all other flags */
402             sc->mly_btl[bus][target].mb_type = MLY_DEVICE_TYPE_PHYSICAL;
403             sc->mly_btl[bus][target].mb_state = pdi->state;
404             sc->mly_btl[bus][target].mb_speed = pdi->speed;
405             sc->mly_btl[bus][target].mb_width = pdi->width;
406             if (pdi->state != MLY_DEVICE_STATE_UNCONFIGURED)
407                 sc->mly_btl[bus][target].mb_flags |= MLY_BTL_PROTECTED;
408             debug(2, "BTL rescan for %d:%d returns %s", bus, target, 
409                   mly_describe_code(mly_table_device_state, pdi->state));
410         } else {
411             mly_printf(sc, "BTL rescan result corrupted\n");
412         }
413     } else {
414         /*
415          * A request sent for a device beyond the last device present will fail.
416          * We don't care about this, so we do nothing about it.
417          */
418     }
419     free(mc->mc_data, M_DEVBUF);
420     mly_release_command(mc);
421 }
422
423 /********************************************************************************
424  * Get the current health status and set the 'next event' counter to suit.
425  */
426 static int
427 mly_get_eventstatus(struct mly_softc *sc)
428 {
429     struct mly_command_ioctl    mci;
430     struct mly_health_status    *mh;
431     u_int8_t                    status;
432     int                         error;
433
434     /* build the gethealthstatus ioctl and send it */
435     bzero(&mci, sizeof(mci));
436     mh = NULL;
437     mci.sub_ioctl = MDACIOCTL_GETHEALTHSTATUS;
438
439     if ((error = mly_ioctl(sc, &mci, (void **)&mh, sizeof(*mh), &status, NULL, NULL)))
440         return(error);
441     if (status != 0)
442         return(EIO);
443
444     /* get the event counter */
445     sc->mly_event_change = mh->change_counter;
446     sc->mly_event_waiting = mh->next_event;
447     sc->mly_event_counter = mh->next_event;
448
449     /* save the health status into the memory mailbox */
450     bcopy(mh, &sc->mly_mmbox->mmm_health.status, sizeof(*mh));
451
452     debug(1, "initial change counter %d, event counter %d", mh->change_counter, mh->next_event);
453     
454     free(mh, M_DEVBUF);
455     return(0);
456 }
457
458 /********************************************************************************
459  * Enable the memory mailbox mode.
460  */
461 static int
462 mly_enable_mmbox(struct mly_softc *sc)
463 {
464     struct mly_command_ioctl    mci;
465     u_int8_t                    *sp, status;
466     int                         error;
467
468     debug_called(1);
469
470     /* build the ioctl and send it */
471     bzero(&mci, sizeof(mci));
472     mci.sub_ioctl = MDACIOCTL_SETMEMORYMAILBOX;
473     /* set buffer addresses */
474     mci.param.setmemorymailbox.command_mailbox_physaddr = 
475         sc->mly_mmbox_busaddr + offsetof(struct mly_mmbox, mmm_command);
476     mci.param.setmemorymailbox.status_mailbox_physaddr = 
477         sc->mly_mmbox_busaddr + offsetof(struct mly_mmbox, mmm_status);
478     mci.param.setmemorymailbox.health_buffer_physaddr = 
479         sc->mly_mmbox_busaddr + offsetof(struct mly_mmbox, mmm_health);
480
481     /* set buffer sizes - abuse of data_size field is revolting */
482     sp = (u_int8_t *)&mci.data_size;
483     sp[0] = ((sizeof(union mly_command_packet) * MLY_MMBOX_COMMANDS) / 1024);
484     sp[1] = (sizeof(union mly_status_packet) * MLY_MMBOX_STATUS) / 1024;
485     mci.param.setmemorymailbox.health_buffer_size = sizeof(union mly_health_region) / 1024;
486
487     debug(1, "memory mailbox at %p (0x%llx/%d 0x%llx/%d 0x%llx/%d", sc->mly_mmbox,
488           mci.param.setmemorymailbox.command_mailbox_physaddr, sp[0],
489           mci.param.setmemorymailbox.status_mailbox_physaddr, sp[1],
490           mci.param.setmemorymailbox.health_buffer_physaddr, 
491           mci.param.setmemorymailbox.health_buffer_size);
492
493     if ((error = mly_ioctl(sc, &mci, NULL, 0, &status, NULL, NULL)))
494         return(error);
495     if (status != 0)
496         return(EIO);
497     sc->mly_state |= MLY_STATE_MMBOX_ACTIVE;
498     debug(1, "memory mailbox active");
499     return(0);
500 }
501
502 /********************************************************************************
503  * Flush all pending I/O from the controller.
504  */
505 static int
506 mly_flush(struct mly_softc *sc)
507 {
508     struct mly_command_ioctl    mci;
509     u_int8_t                    status;
510     int                         error;
511
512     debug_called(1);
513
514     /* build the ioctl */
515     bzero(&mci, sizeof(mci));
516     mci.sub_ioctl = MDACIOCTL_FLUSHDEVICEDATA;
517     mci.param.deviceoperation.operation_device = MLY_OPDEVICE_PHYSICAL_CONTROLLER;
518
519     /* pass it off to the controller */
520     if ((error = mly_ioctl(sc, &mci, NULL, 0, &status, NULL, NULL)))
521         return(error);
522
523     return((status == 0) ? 0 : EIO);
524 }
525
526 /********************************************************************************
527  * Perform an ioctl command.
528  *
529  * If (data) is not NULL, the command requires data transfer.  If (*data) is NULL
530  * the command requires data transfer from the controller, and we will allocate
531  * a buffer for it.  If (*data) is not NULL, the command requires data transfer
532  * to the controller.
533  *
534  * XXX passing in the whole ioctl structure is ugly.  Better ideas?
535  *
536  * XXX we don't even try to handle the case where datasize > 4k.  We should.
537  */
538 static int
539 mly_ioctl(struct mly_softc *sc, struct mly_command_ioctl *ioctl, void **data, size_t datasize, 
540           u_int8_t *status, void *sense_buffer, size_t *sense_length)
541 {
542     struct mly_command          *mc;
543     struct mly_command_ioctl    *mci;
544     int                         error;
545
546     debug_called(1);
547
548     mc = NULL;
549     if (mly_alloc_command(sc, &mc)) {
550         error = ENOMEM;
551         goto out;
552     }
553
554     /* copy the ioctl structure, but save some important fields and then fixup */
555     mci = &mc->mc_packet->ioctl;
556     ioctl->sense_buffer_address = mci->sense_buffer_address;
557     ioctl->maximum_sense_size = mci->maximum_sense_size;
558     *mci = *ioctl;
559     mci->opcode = MDACMD_IOCTL;
560     mci->timeout.value = 30;
561     mci->timeout.scale = MLY_TIMEOUT_SECONDS;
562     
563     /* handle the data buffer */
564     if (data != NULL) {
565         if (*data == NULL) {
566             /* allocate data buffer */
567             if ((mc->mc_data = malloc(datasize, M_DEVBUF, M_NOWAIT)) == NULL) {
568                 error = ENOMEM;
569                 goto out;
570             }
571             mc->mc_flags |= MLY_CMD_DATAIN;
572         } else {
573             mc->mc_data = *data;
574             mc->mc_flags |= MLY_CMD_DATAOUT;
575         }
576         mc->mc_length = datasize;
577         mc->mc_packet->generic.data_size = datasize;
578     }
579     
580     /* run the command */
581     if ((error = mly_immediate_command(mc)))
582         goto out;
583     
584     /* clean up and return any data */
585     *status = mc->mc_status;
586     if ((mc->mc_sense > 0) && (sense_buffer != NULL)) {
587         bcopy(mc->mc_packet, sense_buffer, mc->mc_sense);
588         *sense_length = mc->mc_sense;
589         goto out;
590     }
591
592     /* should we return a data pointer? */
593     if ((data != NULL) && (*data == NULL))
594         *data = mc->mc_data;
595
596     /* command completed OK */
597     error = 0;
598
599 out:
600     if (mc != NULL) {
601         /* do we need to free a data buffer we allocated? */
602         if (error && (mc->mc_data != NULL) && (*data == NULL))
603             free(mc->mc_data, M_DEVBUF);
604         mly_release_command(mc);
605     }
606     return(error);
607 }
608
609 /********************************************************************************
610  * Fetch one event from the controller.
611  */
612 static void
613 mly_fetch_event(struct mly_softc *sc)
614 {
615     struct mly_command          *mc;
616     struct mly_command_ioctl    *mci;
617     int                         s;
618     u_int32_t                   event;
619
620     debug_called(2);
621
622     /* get a command */
623     mc = NULL;
624     if (mly_alloc_command(sc, &mc))
625         return;                         /* we'll get retried the next time a command completes */
626
627     /* set up the data buffer */
628     if ((mc->mc_data = malloc(sizeof(struct mly_event), M_DEVBUF, M_NOWAIT)) == NULL) {
629         mly_release_command(mc);
630         return;                         /* we'll get retried the next time a command completes */
631     }
632     bzero(mc->mc_data, sizeof(struct mly_event));
633     mc->mc_length = sizeof(struct mly_event);
634     mc->mc_flags |= MLY_CMD_DATAIN;
635     mc->mc_complete = mly_complete_event;
636
637     /*
638      * Get an event number to fetch.  It's possible that we've raced with another
639      * context for the last event, in which case there will be no more events.
640      */
641     s = splcam();
642     if (sc->mly_event_counter == sc->mly_event_waiting) {
643         mly_release_command(mc);
644         splx(s);
645         return;
646     }
647     event = sc->mly_event_counter++;
648     splx(s);
649
650     /* 
651      * Build the ioctl.
652      *
653      * At this point we are committed to sending this request, as it
654      * will be the only one constructed for this particular event number.
655      */
656     mci = (struct mly_command_ioctl *)&mc->mc_packet->ioctl;
657     mci->opcode = MDACMD_IOCTL;
658     mci->data_size = sizeof(struct mly_event);
659     mci->addr.phys.lun = (event >> 16) & 0xff;
660     mci->addr.phys.target = (event >> 24) & 0xff;
661     mci->addr.phys.channel = 0;
662     mci->addr.phys.controller = 0;
663     mci->timeout.value = 30;
664     mci->timeout.scale = MLY_TIMEOUT_SECONDS;
665     mci->sub_ioctl = MDACIOCTL_GETEVENT;
666     mci->param.getevent.sequence_number_low = event & 0xffff;
667
668     debug(2, "fetch event %u", event);
669
670     /*
671      * Use the ready queue to get this command dispatched.
672      */
673     mly_enqueue_ready(mc);
674     mly_startio(sc);
675 }
676
677 /********************************************************************************
678  * Handle the completion of an event poll.
679  *
680  * Note that we don't actually have to instigate another poll; the completion of
681  * this command will trigger that if there are any more events to poll for.
682  */
683 static void
684 mly_complete_event(struct mly_command *mc)
685 {
686     struct mly_softc    *sc = mc->mc_sc;
687     struct mly_event    *me = (struct mly_event *)mc->mc_data;
688
689     debug_called(2);
690
691     /* 
692      * If the event was successfully fetched, process it.
693      */
694     if (mc->mc_status == SCSI_STATUS_OK) {
695         mly_process_event(sc, me);
696         free(me, M_DEVBUF);
697     }
698     mly_release_command(mc);
699 }
700
701 /********************************************************************************
702  * Process a controller event.
703  */
704 static void
705 mly_process_event(struct mly_softc *sc, struct mly_event *me)
706 {
707     struct scsi_sense_data      *ssd = (struct scsi_sense_data *)&me->sense[0];
708     char                        *fp, *tp;
709     int                         bus, target, event, class, action;
710
711     /* 
712      * Errors can be reported using vendor-unique sense data.  In this case, the
713      * event code will be 0x1c (Request sense data present), the sense key will
714      * be 0x09 (vendor specific), the MSB of the ASC will be set, and the 
715      * actual event code will be a 16-bit value comprised of the ASCQ (low byte)
716      * and low seven bits of the ASC (low seven bits of the high byte).
717      */
718     if ((me->code == 0x1c) && 
719         ((ssd->flags & SSD_KEY) == SSD_KEY_Vendor_Specific) &&
720         (ssd->add_sense_code & 0x80)) {
721         event = ((int)(ssd->add_sense_code & ~0x80) << 8) + ssd->add_sense_code_qual;
722     } else {
723         event = me->code;
724     }
725
726     /* look up event, get codes */
727     fp = mly_describe_code(mly_table_event, event);
728
729     debug(2, "Event %d  code 0x%x", me->sequence_number, me->code);
730
731     /* quiet event? */
732     class = fp[0];
733     if (isupper(class) && bootverbose)
734         class = tolower(class);
735
736     /* get action code, text string */
737     action = fp[1];
738     tp = &fp[2];
739
740     /*
741      * Print some information about the event.
742      *
743      * This code uses a table derived from the corresponding portion of the Linux
744      * driver, and thus the parser is very similar.
745      */
746     switch(class) {
747     case 'p':           /* error on physical device */
748         mly_printf(sc, "physical device %d:%d %s\n", me->channel, me->target, tp);
749         if (action == 'r')
750             sc->mly_btl[me->channel][me->target].mb_flags |= MLY_BTL_RESCAN;
751         break;
752     case 'l':           /* error on logical unit */
753     case 'm':           /* message about logical unit */
754         bus = MLY_LOGDEV_BUS(sc, me->lun);
755         target = MLY_LOGDEV_TARGET(me->lun);
756         mly_name_device(sc, bus, target);
757         mly_printf(sc, "logical device %d (%s) %s\n", me->lun, sc->mly_btl[bus][target].mb_name, tp);
758         if (action == 'r')
759             sc->mly_btl[bus][target].mb_flags |= MLY_BTL_RESCAN;
760         break;
761       break;
762     case 's':           /* report of sense data */
763         if (((ssd->flags & SSD_KEY) == SSD_KEY_NO_SENSE) ||
764             (((ssd->flags & SSD_KEY) == SSD_KEY_NOT_READY) && 
765              (ssd->add_sense_code == 0x04) && 
766              ((ssd->add_sense_code_qual == 0x01) || (ssd->add_sense_code_qual == 0x02))))
767             break;      /* ignore NO_SENSE or NOT_READY in one case */
768
769         mly_printf(sc, "physical device %d:%d %s\n", me->channel, me->target, tp);
770         mly_printf(sc, "  sense key %d  asc %02x  ascq %02x\n", 
771                       ssd->flags & SSD_KEY, ssd->add_sense_code, ssd->add_sense_code_qual);
772         mly_printf(sc, "  info %4D  csi %4D\n", ssd->info, "", ssd->cmd_spec_info, "");
773         if (action == 'r')
774             sc->mly_btl[me->channel][me->target].mb_flags |= MLY_BTL_RESCAN;
775         break;
776     case 'e':
777         mly_printf(sc, tp, me->target, me->lun);
778         break;
779     case 'c':
780         mly_printf(sc, "controller %s\n", tp);
781         break;
782     case '?':
783         mly_printf(sc, "%s - %d\n", tp, me->code);
784         break;
785     default:    /* probably a 'noisy' event being ignored */
786         break;
787     }
788 }
789
790 /********************************************************************************
791  * Perform periodic activities.
792  */
793 static void
794 mly_periodic(void *data)
795 {
796     struct mly_softc    *sc = (struct mly_softc *)data;
797     int                 nchn, bus, target;
798
799     debug_called(2);
800
801     /*
802      * Scan devices.
803      */
804     nchn = sc->mly_controllerinfo->physical_channels_present +
805         sc->mly_controllerinfo->virtual_channels_present;
806     for (bus = 0; bus < nchn; bus++) {
807         for (target = 0; target < MLY_MAX_TARGETS; target++) {
808
809             /* ignore the controller in this scan */
810             if (target == sc->mly_controllerparam->initiator_id)
811                 continue;
812
813             /* perform device rescan? */
814             if (sc->mly_btl[bus][target].mb_flags & MLY_BTL_RESCAN)
815                 mly_rescan_btl(sc, bus, target);
816         }
817     }
818
819     sc->mly_periodic = timeout(mly_periodic, sc, hz);
820 }
821
822 /********************************************************************************
823  ********************************************************************************
824                                                                Command Processing
825  ********************************************************************************
826  ********************************************************************************/
827
828 /********************************************************************************
829  * Run a command and wait for it to complete.
830  *
831  */
832 static int
833 mly_immediate_command(struct mly_command *mc)
834 {
835     struct mly_softc    *sc = mc->mc_sc;
836     int                 error, s;
837
838     debug_called(2);
839
840     /* spinning at splcam is ugly, but we're only used during controller init */
841     s = splcam();
842     if ((error = mly_start(mc)))
843         return(error);
844
845     if (sc->mly_state & MLY_STATE_INTERRUPTS_ON) {
846         /* sleep on the command */
847         while(!(mc->mc_flags & MLY_CMD_COMPLETE)) {
848             tsleep(mc, PRIBIO, "mlywait", 0);
849         }
850     } else {
851         /* spin and collect status while we do */
852         while(!(mc->mc_flags & MLY_CMD_COMPLETE)) {
853             mly_done(mc->mc_sc);
854         }
855     }
856     splx(s);
857     return(0);
858 }
859
860 /********************************************************************************
861  * Start as much queued I/O as possible on the controller
862  */
863 void
864 mly_startio(struct mly_softc *sc)
865 {
866     struct mly_command  *mc;
867
868     debug_called(2);
869
870     for (;;) {
871
872         /* try for a ready command */
873         mc = mly_dequeue_ready(sc);
874
875         /* try to build a command from a queued ccb */
876         if (!mc)
877             mly_cam_command(sc, &mc);
878
879         /* no command == nothing to do */
880         if (!mc)
881             break;
882
883         /* try to post the command */
884         if (mly_start(mc)) {
885             /* controller busy, or no resources - defer for later */
886             mly_requeue_ready(mc);
887             break;
888         }
889     }
890 }
891
892 /********************************************************************************
893  * Deliver a command to the controller; allocate controller resources at the
894  * last moment.
895  */
896 static int
897 mly_start(struct mly_command *mc)
898 {
899     struct mly_softc            *sc = mc->mc_sc;
900     union mly_command_packet    *pkt;
901     int                         s;
902
903     debug_called(2);
904
905     /* 
906      * Set the command up for delivery to the controller. 
907      */
908     mly_map_command(mc);
909     mc->mc_packet->generic.command_id = mc->mc_slot;
910
911     s = splcam();
912
913     /*
914      * Do we have to use the hardware mailbox?
915      */
916     if (!(sc->mly_state & MLY_STATE_MMBOX_ACTIVE)) {
917         /*
918          * Check to see if the controller is ready for us.
919          */
920         if (MLY_IDBR_TRUE(sc, MLY_HM_CMDSENT)) {
921             splx(s);
922             return(EBUSY);
923         }
924         mc->mc_flags |= MLY_CMD_BUSY;
925         
926         /*
927          * It's ready, send the command.
928          */
929         MLY_SET_MBOX(sc, sc->mly_command_mailbox, &mc->mc_packetphys);
930         MLY_SET_REG(sc, sc->mly_idbr, MLY_HM_CMDSENT);
931
932     } else {    /* use memory-mailbox mode */
933
934         pkt = &sc->mly_mmbox->mmm_command[sc->mly_mmbox_command_index];
935
936         /* check to see if the next index is free yet */
937         if (pkt->mmbox.flag != 0) {
938             splx(s);
939             return(EBUSY);
940         }
941         mc->mc_flags |= MLY_CMD_BUSY;
942         
943         /* copy in new command */
944         bcopy(mc->mc_packet->mmbox.data, pkt->mmbox.data, sizeof(pkt->mmbox.data));
945         /* barrier to ensure completion of previous write before we write the flag */
946         bus_space_barrier(NULL, NULL, 0, 0, BUS_SPACE_BARRIER_WRITE);   /* tag/handle? */
947         /* copy flag last */
948         pkt->mmbox.flag = mc->mc_packet->mmbox.flag;
949         /* barrier to ensure completion of previous write before we notify the controller */
950         bus_space_barrier(NULL, NULL, 0, 0, BUS_SPACE_BARRIER_WRITE);   /* tag/handle */
951
952         /* signal controller, update index */
953         MLY_SET_REG(sc, sc->mly_idbr, MLY_AM_CMDSENT);
954         sc->mly_mmbox_command_index = (sc->mly_mmbox_command_index + 1) % MLY_MMBOX_COMMANDS;
955     }
956
957     mly_enqueue_busy(mc);
958     splx(s);
959     return(0);
960 }
961
962 /********************************************************************************
963  * Pick up command status from the controller, schedule a completion event
964  */
965 void
966 mly_done(struct mly_softc *sc) 
967 {
968     struct mly_command          *mc;
969     union mly_status_packet     *sp;
970     u_int16_t                   slot;
971     int                         s, worked;
972
973     s = splcam();
974     worked = 0;
975
976     /* pick up hardware-mailbox commands */
977     if (MLY_ODBR_TRUE(sc, MLY_HM_STSREADY)) {
978         slot = MLY_GET_REG2(sc, sc->mly_status_mailbox);
979         if (slot < MLY_SLOT_MAX) {
980             mc = &sc->mly_command[slot - MLY_SLOT_START];
981             mc->mc_status = MLY_GET_REG(sc, sc->mly_status_mailbox + 2);
982             mc->mc_sense = MLY_GET_REG(sc, sc->mly_status_mailbox + 3);
983             mc->mc_resid = MLY_GET_REG4(sc, sc->mly_status_mailbox + 4);
984             mly_remove_busy(mc);
985             mc->mc_flags &= ~MLY_CMD_BUSY;
986             mly_enqueue_complete(mc);
987             worked = 1;
988         } else {
989             /* slot 0xffff may mean "extremely bogus command" */
990             mly_printf(sc, "got HM completion for illegal slot %u\n", slot);
991         }
992         /* unconditionally acknowledge status */
993         MLY_SET_REG(sc, sc->mly_odbr, MLY_HM_STSREADY);
994         MLY_SET_REG(sc, sc->mly_idbr, MLY_HM_STSACK);
995     }
996
997     /* pick up memory-mailbox commands */
998     if (MLY_ODBR_TRUE(sc, MLY_AM_STSREADY)) {
999         for (;;) {
1000             sp = &sc->mly_mmbox->mmm_status[sc->mly_mmbox_status_index];
1001
1002             /* check for more status */
1003             if (sp->mmbox.flag == 0)
1004                 break;
1005
1006             /* get slot number */
1007             slot = sp->status.command_id;
1008             if (slot < MLY_SLOT_MAX) {
1009                 mc = &sc->mly_command[slot - MLY_SLOT_START];
1010                 mc->mc_status = sp->status.status;
1011                 mc->mc_sense = sp->status.sense_length;
1012                 mc->mc_resid = sp->status.residue;
1013                 mly_remove_busy(mc);
1014                 mc->mc_flags &= ~MLY_CMD_BUSY;
1015                 mly_enqueue_complete(mc);
1016                 worked = 1;
1017             } else {
1018                 /* slot 0xffff may mean "extremely bogus command" */
1019                 mly_printf(sc, "got AM completion for illegal slot %u at %d\n", 
1020                            slot, sc->mly_mmbox_status_index);
1021             }
1022
1023             /* clear and move to next index */
1024             sp->mmbox.flag = 0;
1025             sc->mly_mmbox_status_index = (sc->mly_mmbox_status_index + 1) % MLY_MMBOX_STATUS;
1026         }
1027         /* acknowledge that we have collected status value(s) */
1028         MLY_SET_REG(sc, sc->mly_odbr, MLY_AM_STSREADY);
1029     }
1030
1031     splx(s);
1032     if (worked) {
1033 #if __FreeBSD_version >= 500005
1034         if (sc->mly_state & MLY_STATE_INTERRUPTS_ON)
1035             taskqueue_enqueue(taskqueue_swi, &sc->mly_task_complete);
1036         else
1037 #endif
1038             mly_complete(sc, 0);
1039     }
1040 }
1041
1042 /********************************************************************************
1043  * Process completed commands
1044  */
1045 static void
1046 mly_complete(void *context, int pending)
1047 {
1048     struct mly_softc    *sc = (struct mly_softc *)context;
1049     struct mly_command  *mc;
1050     void                (* mc_complete)(struct mly_command *mc);
1051
1052
1053     debug_called(2);
1054
1055     /* 
1056      * Spin pulling commands off the completed queue and processing them.
1057      */
1058     while ((mc = mly_dequeue_complete(sc)) != NULL) {
1059
1060         /*
1061          * Free controller resources, mark command complete.
1062          *
1063          * Note that as soon as we mark the command complete, it may be freed
1064          * out from under us, so we need to save the mc_complete field in
1065          * order to later avoid dereferencing mc.  (We would not expect to
1066          * have a polling/sleeping consumer with mc_complete != NULL).
1067          */
1068         mly_unmap_command(mc);
1069         mc_complete = mc->mc_complete;
1070         mc->mc_flags |= MLY_CMD_COMPLETE;
1071
1072         /* 
1073          * Call completion handler or wake up sleeping consumer.
1074          */
1075         if (mc_complete != NULL) {
1076             mc_complete(mc);
1077         } else {
1078             wakeup(mc);
1079         }
1080     }
1081
1082     /*
1083      * We may have freed up controller resources which would allow us
1084      * to push more commands onto the controller, so we check here.
1085      */
1086     mly_startio(sc);
1087
1088     /*
1089      * The controller may have updated the health status information,
1090      * so check for it here.
1091      *
1092      * Note that we only check for health status after a completed command.  It
1093      * might be wise to ping the controller occasionally if it's been idle for
1094      * a while just to check up on it.  While a filesystem is mounted, or I/O is
1095      * active this isn't really an issue.
1096      */
1097     if (sc->mly_mmbox->mmm_health.status.change_counter != sc->mly_event_change) {
1098         sc->mly_event_change = sc->mly_mmbox->mmm_health.status.change_counter;
1099         debug(1, "event change %d, event status update, %d -> %d", sc->mly_event_change,
1100               sc->mly_event_waiting, sc->mly_mmbox->mmm_health.status.next_event);
1101         sc->mly_event_waiting = sc->mly_mmbox->mmm_health.status.next_event;
1102
1103         /* wake up anyone that might be interested in this */
1104         wakeup(&sc->mly_event_change);
1105     }
1106     if (sc->mly_event_counter != sc->mly_event_waiting)
1107         mly_fetch_event(sc);
1108 }
1109
1110 /********************************************************************************
1111  ********************************************************************************
1112                                                         Command Buffer Management
1113  ********************************************************************************
1114  ********************************************************************************/
1115
1116 /********************************************************************************
1117  * Allocate a command.
1118  */
1119 int
1120 mly_alloc_command(struct mly_softc *sc, struct mly_command **mcp)
1121 {
1122     struct mly_command  *mc;
1123
1124     debug_called(3);
1125
1126     if ((mc = mly_dequeue_free(sc)) == NULL)
1127         return(ENOMEM);
1128
1129     *mcp = mc;
1130     return(0);
1131 }
1132
1133 /********************************************************************************
1134  * Release a command back to the freelist.
1135  */
1136 void
1137 mly_release_command(struct mly_command *mc)
1138 {
1139     debug_called(3);
1140
1141     /*
1142      * Fill in parts of the command that may cause confusion if
1143      * a consumer doesn't when we are later allocated.
1144      */
1145     mc->mc_data = NULL;
1146     mc->mc_flags = 0;
1147     mc->mc_complete = NULL;
1148     mc->mc_private = NULL;
1149
1150     /*
1151      * By default, we set up to overwrite the command packet with
1152      * sense information.
1153      */
1154     mc->mc_packet->generic.sense_buffer_address = mc->mc_packetphys;
1155     mc->mc_packet->generic.maximum_sense_size = sizeof(union mly_command_packet);
1156
1157     mly_enqueue_free(mc);
1158 }
1159
1160 /********************************************************************************
1161  * Map helper for command allocation.
1162  */
1163 static void
1164 mly_alloc_commands_map(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1165 {
1166     struct mly_softc    *sc = (struct mly_softc *)arg
1167
1168     debug_called(2);
1169
1170     sc->mly_packetphys = segs[0].ds_addr;
1171 }
1172
1173 /********************************************************************************
1174  * Allocate and initialise command and packet structures.
1175  */
1176 static int
1177 mly_alloc_commands(struct mly_softc *sc)
1178 {
1179     struct mly_command          *mc;
1180     int                         i;
1181  
1182     /*
1183      * Allocate enough space for all the command packets in one chunk and
1184      * map them permanently into controller-visible space.
1185      */
1186     if (bus_dmamem_alloc(sc->mly_packet_dmat, (void **)&sc->mly_packet, 
1187                          BUS_DMA_NOWAIT, &sc->mly_packetmap)) {
1188         return(ENOMEM);
1189     }
1190     bus_dmamap_load(sc->mly_packet_dmat, sc->mly_packetmap, sc->mly_packet, 
1191                     MLY_MAXCOMMANDS * sizeof(union mly_command_packet), 
1192                     mly_alloc_commands_map, sc, 0);
1193
1194     for (i = 0; i < MLY_MAXCOMMANDS; i++) {
1195         mc = &sc->mly_command[i];
1196         bzero(mc, sizeof(*mc));
1197         mc->mc_sc = sc;
1198         mc->mc_slot = MLY_SLOT_START + i;
1199         mc->mc_packet = sc->mly_packet + i;
1200         mc->mc_packetphys = sc->mly_packetphys + (i * sizeof(union mly_command_packet));
1201         if (!bus_dmamap_create(sc->mly_buffer_dmat, 0, &mc->mc_datamap))
1202             mly_release_command(mc);
1203     }
1204     return(0);
1205 }
1206
1207 /********************************************************************************
1208  * Command-mapping helper function - populate this command's s/g table
1209  * with the s/g entries for its data.
1210  */
1211 static void
1212 mly_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1213 {
1214     struct mly_command          *mc = (struct mly_command *)arg;
1215     struct mly_softc            *sc = mc->mc_sc;
1216     struct mly_command_generic  *gen = &(mc->mc_packet->generic);
1217     struct mly_sg_entry         *sg;
1218     int                         i, tabofs;
1219
1220     debug_called(3);
1221
1222     /* can we use the transfer structure directly? */
1223     if (nseg <= 2) {
1224         sg = &gen->transfer.direct.sg[0];
1225         gen->command_control.extended_sg_table = 0;
1226     } else {
1227         tabofs = ((mc->mc_slot - MLY_SLOT_START) * MLY_MAXSGENTRIES);
1228         sg = sc->mly_sg_table + tabofs;
1229         gen->transfer.indirect.entries[0] = nseg;
1230         gen->transfer.indirect.table_physaddr[0] = sc->mly_sg_busaddr + (tabofs * sizeof(struct mly_sg_entry));
1231         gen->command_control.extended_sg_table = 1;
1232     }
1233
1234     /* copy the s/g table */
1235     for (i = 0; i < nseg; i++) {
1236         sg[i].physaddr = segs[i].ds_addr;
1237         sg[i].length = segs[i].ds_len;
1238     }
1239
1240 }
1241
1242 #if 0
1243 /********************************************************************************
1244  * Command-mapping helper function - save the cdb's physical address.
1245  *
1246  * We don't support 'large' SCSI commands at this time, so this is unused.
1247  */
1248 static void
1249 mly_map_command_cdb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1250 {
1251     struct mly_command                  *mc = (struct mly_command *)arg;
1252
1253     debug_called(3);
1254
1255     /* XXX can we safely assume that a CDB will never cross a page boundary? */
1256     if ((segs[0].ds_addr % PAGE_SIZE) > 
1257         ((segs[0].ds_addr + mc->mc_packet->scsi_large.cdb_length) % PAGE_SIZE))
1258         panic("cdb crosses page boundary");
1259
1260     /* fix up fields in the command packet */
1261     mc->mc_packet->scsi_large.cdb_physaddr = segs[0].ds_addr;
1262 }
1263 #endif
1264
1265 /********************************************************************************
1266  * Map a command into controller-visible space
1267  */
1268 static void
1269 mly_map_command(struct mly_command *mc)
1270 {
1271     struct mly_softc    *sc = mc->mc_sc;
1272
1273     debug_called(2);
1274
1275     /* don't map more than once */
1276     if (mc->mc_flags & MLY_CMD_MAPPED)
1277         return;
1278
1279     /* does the command have a data buffer? */
1280     if (mc->mc_data != NULL)
1281         bus_dmamap_load(sc->mly_buffer_dmat, mc->mc_datamap, mc->mc_data, mc->mc_length, 
1282                         mly_map_command_sg, mc, 0);
1283         
1284     if (mc->mc_flags & MLY_CMD_DATAIN)
1285         bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_PREREAD);
1286     if (mc->mc_flags & MLY_CMD_DATAOUT)
1287         bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_PREWRITE);
1288
1289     mc->mc_flags |= MLY_CMD_MAPPED;
1290 }
1291
1292 /********************************************************************************
1293  * Unmap a command from controller-visible space
1294  */
1295 static void
1296 mly_unmap_command(struct mly_command *mc)
1297 {
1298     struct mly_softc    *sc = mc->mc_sc;
1299
1300     debug_called(2);
1301
1302     if (!(mc->mc_flags & MLY_CMD_MAPPED))
1303         return;
1304
1305     if (mc->mc_flags & MLY_CMD_DATAIN)
1306         bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_POSTREAD);
1307     if (mc->mc_flags & MLY_CMD_DATAOUT)
1308         bus_dmamap_sync(sc->mly_buffer_dmat, mc->mc_datamap, BUS_DMASYNC_POSTWRITE);
1309
1310     /* does the command have a data buffer? */
1311     if (mc->mc_data != NULL)
1312         bus_dmamap_unload(sc->mly_buffer_dmat, mc->mc_datamap);
1313
1314     mc->mc_flags &= ~MLY_CMD_MAPPED;
1315 }
1316
1317 /********************************************************************************
1318  ********************************************************************************
1319                                                                  Hardware Control
1320  ********************************************************************************
1321  ********************************************************************************/
1322
1323 /********************************************************************************
1324  * Handshake with the firmware while the card is being initialised.
1325  */
1326 static int
1327 mly_fwhandshake(struct mly_softc *sc) 
1328 {
1329     u_int8_t    error, param0, param1;
1330     int         spinup = 0;
1331
1332     debug_called(1);
1333
1334     /* set HM_STSACK and let the firmware initialise */
1335     MLY_SET_REG(sc, sc->mly_idbr, MLY_HM_STSACK);
1336     DELAY(1000);        /* too short? */
1337
1338     /* if HM_STSACK is still true, the controller is initialising */
1339     if (!MLY_IDBR_TRUE(sc, MLY_HM_STSACK))
1340         return(0);
1341     mly_printf(sc, "controller initialisation started\n");
1342
1343     /* spin waiting for initialisation to finish, or for a message to be delivered */
1344     while (MLY_IDBR_TRUE(sc, MLY_HM_STSACK)) {
1345         /* check for a message */
1346         if (MLY_ERROR_VALID(sc)) {
1347             error = MLY_GET_REG(sc, sc->mly_error_status) & ~MLY_MSG_EMPTY;
1348             param0 = MLY_GET_REG(sc, sc->mly_command_mailbox);
1349             param1 = MLY_GET_REG(sc, sc->mly_command_mailbox + 1);
1350
1351             switch(error) {
1352             case MLY_MSG_SPINUP:
1353                 if (!spinup) {
1354                     mly_printf(sc, "drive spinup in progress\n");
1355                     spinup = 1;                 /* only print this once (should print drive being spun?) */
1356                 }
1357                 break;
1358             case MLY_MSG_RACE_RECOVERY_FAIL:
1359                 mly_printf(sc, "mirror race recovery failed, one or more drives offline\n");
1360                 break;
1361             case MLY_MSG_RACE_IN_PROGRESS:
1362                 mly_printf(sc, "mirror race recovery in progress\n");
1363                 break;
1364             case MLY_MSG_RACE_ON_CRITICAL:
1365                 mly_printf(sc, "mirror race recovery on a critical drive\n");
1366                 break;
1367             case MLY_MSG_PARITY_ERROR:
1368                 mly_printf(sc, "FATAL MEMORY PARITY ERROR\n");
1369                 return(ENXIO);
1370             default:
1371                 mly_printf(sc, "unknown initialisation code 0x%x\n", error);
1372             }
1373         }
1374     }
1375     return(0);
1376 }
1377
1378 /********************************************************************************
1379  ********************************************************************************
1380                                                         Debugging and Diagnostics
1381  ********************************************************************************
1382  ********************************************************************************/
1383
1384 /********************************************************************************
1385  * Print some information about the controller.
1386  */
1387 static void
1388 mly_describe_controller(struct mly_softc *sc)
1389 {
1390     struct mly_ioctl_getcontrollerinfo  *mi = sc->mly_controllerinfo;
1391
1392     mly_printf(sc, "%16s, %d channel%s, firmware %d.%02d-%d-%02d (%02d%02d%02d%02d), %dMB RAM\n", 
1393                mi->controller_name, mi->physical_channels_present, (mi->physical_channels_present) > 1 ? "s" : "",
1394                mi->fw_major, mi->fw_minor, mi->fw_turn, mi->fw_build,   /* XXX turn encoding? */
1395                mi->fw_century, mi->fw_year, mi->fw_month, mi->fw_day,
1396                mi->memory_size);
1397
1398     if (bootverbose) {
1399         mly_printf(sc, "%s %s (%x), %dMHz %d-bit %.16s\n", 
1400                    mly_describe_code(mly_table_oemname, mi->oem_information), 
1401                    mly_describe_code(mly_table_controllertype, mi->controller_type), mi->controller_type,
1402                    mi->interface_speed, mi->interface_width, mi->interface_name);
1403         mly_printf(sc, "%dMB %dMHz %d-bit %s%s%s, cache %dMB\n",
1404                    mi->memory_size, mi->memory_speed, mi->memory_width, 
1405                    mly_describe_code(mly_table_memorytype, mi->memory_type),
1406                    mi->memory_parity ? "+parity": "",mi->memory_ecc ? "+ECC": "",
1407                    mi->cache_size);
1408         mly_printf(sc, "CPU: %s @ %dMHZ\n", 
1409                    mly_describe_code(mly_table_cputype, mi->cpu[0].type), mi->cpu[0].speed);
1410         if (mi->l2cache_size != 0)
1411             mly_printf(sc, "%dKB L2 cache\n", mi->l2cache_size);
1412         if (mi->exmemory_size != 0)
1413             mly_printf(sc, "%dMB %dMHz %d-bit private %s%s%s\n",
1414                        mi->exmemory_size, mi->exmemory_speed, mi->exmemory_width,
1415                        mly_describe_code(mly_table_memorytype, mi->exmemory_type),
1416                        mi->exmemory_parity ? "+parity": "",mi->exmemory_ecc ? "+ECC": "");
1417         mly_printf(sc, "battery backup %s\n", mi->bbu_present ? "present" : "not installed");
1418         mly_printf(sc, "maximum data transfer %d blocks, maximum sg entries/command %d\n",
1419                    mi->maximum_block_count, mi->maximum_sg_entries);
1420         mly_printf(sc, "logical devices present/critical/offline %d/%d/%d\n",
1421                    mi->logical_devices_present, mi->logical_devices_critical, mi->logical_devices_offline);
1422         mly_printf(sc, "physical devices present %d\n",
1423                    mi->physical_devices_present);
1424         mly_printf(sc, "physical disks present/offline %d/%d\n",
1425                    mi->physical_disks_present, mi->physical_disks_offline);
1426         mly_printf(sc, "%d physical channel%s, %d virtual channel%s of %d possible\n",
1427                    mi->physical_channels_present, mi->physical_channels_present == 1 ? "" : "s",
1428                    mi->virtual_channels_present, mi->virtual_channels_present == 1 ? "" : "s",
1429                    mi->virtual_channels_possible);
1430         mly_printf(sc, "%d parallel commands supported\n", mi->maximum_parallel_commands);
1431         mly_printf(sc, "%dMB flash ROM, %d of %d maximum cycles\n",
1432                    mi->flash_size, mi->flash_age, mi->flash_maximum_age);
1433     }
1434 }
1435
1436 #ifdef MLY_DEBUG
1437 /********************************************************************************
1438  * Print some controller state
1439  */
1440 static void
1441 mly_printstate(struct mly_softc *sc)
1442 {
1443     mly_printf(sc, "IDBR %02x  ODBR %02x  ERROR %02x  (%x %x %x)\n",
1444                   MLY_GET_REG(sc, sc->mly_idbr),
1445                   MLY_GET_REG(sc, sc->mly_odbr),
1446                   MLY_GET_REG(sc, sc->mly_error_status),
1447                   sc->mly_idbr,
1448                   sc->mly_odbr,
1449                   sc->mly_error_status);
1450     mly_printf(sc, "IMASK %02x  ISTATUS %02x\n",
1451                   MLY_GET_REG(sc, sc->mly_interrupt_mask),
1452                   MLY_GET_REG(sc, sc->mly_interrupt_status));
1453     mly_printf(sc, "COMMAND %02x %02x %02x %02x %02x %02x %02x %02x\n",
1454                   MLY_GET_REG(sc, sc->mly_command_mailbox),
1455                   MLY_GET_REG(sc, sc->mly_command_mailbox + 1),
1456                   MLY_GET_REG(sc, sc->mly_command_mailbox + 2),
1457                   MLY_GET_REG(sc, sc->mly_command_mailbox + 3),
1458                   MLY_GET_REG(sc, sc->mly_command_mailbox + 4),
1459                   MLY_GET_REG(sc, sc->mly_command_mailbox + 5),
1460                   MLY_GET_REG(sc, sc->mly_command_mailbox + 6),
1461                   MLY_GET_REG(sc, sc->mly_command_mailbox + 7));
1462     mly_printf(sc, "STATUS  %02x %02x %02x %02x %02x %02x %02x %02x\n",
1463                   MLY_GET_REG(sc, sc->mly_status_mailbox),
1464                   MLY_GET_REG(sc, sc->mly_status_mailbox + 1),
1465                   MLY_GET_REG(sc, sc->mly_status_mailbox + 2),
1466                   MLY_GET_REG(sc, sc->mly_status_mailbox + 3),
1467                   MLY_GET_REG(sc, sc->mly_status_mailbox + 4),
1468                   MLY_GET_REG(sc, sc->mly_status_mailbox + 5),
1469                   MLY_GET_REG(sc, sc->mly_status_mailbox + 6),
1470                   MLY_GET_REG(sc, sc->mly_status_mailbox + 7));
1471     mly_printf(sc, "        %04x        %08x\n",
1472                   MLY_GET_REG2(sc, sc->mly_status_mailbox),
1473                   MLY_GET_REG4(sc, sc->mly_status_mailbox + 4));
1474 }
1475
1476 struct mly_softc        *mly_softc0 = NULL;
1477 void
1478 mly_printstate0(void)
1479 {
1480     if (mly_softc0 != NULL)
1481         mly_printstate(mly_softc0);
1482 }
1483
1484 /********************************************************************************
1485  * Print a command
1486  */
1487 static void
1488 mly_print_command(struct mly_command *mc)
1489 {
1490     struct mly_softc    *sc = mc->mc_sc;
1491     
1492     mly_printf(sc, "COMMAND @ %p\n", mc);
1493     mly_printf(sc, "  slot      %d\n", mc->mc_slot);
1494     mly_printf(sc, "  status    0x%x\n", mc->mc_status);
1495     mly_printf(sc, "  sense len %d\n", mc->mc_sense);
1496     mly_printf(sc, "  resid     %d\n", mc->mc_resid);
1497     mly_printf(sc, "  packet    %p/0x%llx\n", mc->mc_packet, mc->mc_packetphys);
1498     if (mc->mc_packet != NULL)
1499         mly_print_packet(mc);
1500     mly_printf(sc, "  data      %p/%d\n", mc->mc_data, mc->mc_length);
1501     mly_printf(sc, "  flags     %b\n", mc->mc_flags, "\20\1busy\2complete\3slotted\4mapped\5datain\6dataout\n");
1502     mly_printf(sc, "  complete  %p\n", mc->mc_complete);
1503     mly_printf(sc, "  private   %p\n", mc->mc_private);
1504 }
1505
1506 /********************************************************************************
1507  * Print a command packet
1508  */
1509 static void
1510 mly_print_packet(struct mly_command *mc)
1511 {
1512     struct mly_softc                    *sc = mc->mc_sc;
1513     struct mly_command_generic          *ge = (struct mly_command_generic *)mc->mc_packet;
1514     struct mly_command_scsi_small       *ss = (struct mly_command_scsi_small *)mc->mc_packet;
1515     struct mly_command_scsi_large       *sl = (struct mly_command_scsi_large *)mc->mc_packet;
1516     struct mly_command_ioctl            *io = (struct mly_command_ioctl *)mc->mc_packet;
1517     int                                 transfer;
1518
1519     mly_printf(sc, "   command_id           %d\n", ge->command_id);
1520     mly_printf(sc, "   opcode               %d\n", ge->opcode);
1521     mly_printf(sc, "   command_control      fua %d  dpo %d  est %d  dd %s  nas %d ddis %d\n",
1522                   ge->command_control.force_unit_access,
1523                   ge->command_control.disable_page_out,
1524                   ge->command_control.extended_sg_table,
1525                   (ge->command_control.data_direction == MLY_CCB_WRITE) ? "WRITE" : "READ",
1526                   ge->command_control.no_auto_sense,
1527                   ge->command_control.disable_disconnect);
1528     mly_printf(sc, "   data_size            %d\n", ge->data_size);
1529     mly_printf(sc, "   sense_buffer_address 0x%llx\n", ge->sense_buffer_address);
1530     mly_printf(sc, "   lun                  %d\n", ge->addr.phys.lun);
1531     mly_printf(sc, "   target               %d\n", ge->addr.phys.target);
1532     mly_printf(sc, "   channel              %d\n", ge->addr.phys.channel);
1533     mly_printf(sc, "   logical device       %d\n", ge->addr.log.logdev);
1534     mly_printf(sc, "   controller           %d\n", ge->addr.phys.controller);
1535     mly_printf(sc, "   timeout              %d %s\n", 
1536                   ge->timeout.value,
1537                   (ge->timeout.scale == MLY_TIMEOUT_SECONDS) ? "seconds" : 
1538                   ((ge->timeout.scale == MLY_TIMEOUT_MINUTES) ? "minutes" : "hours"));
1539     mly_printf(sc, "   maximum_sense_size   %d\n", ge->maximum_sense_size);
1540     switch(ge->opcode) {
1541     case MDACMD_SCSIPT:
1542     case MDACMD_SCSI:
1543         mly_printf(sc, "   cdb length           %d\n", ss->cdb_length);
1544         mly_printf(sc, "   cdb                  %*D\n", ss->cdb_length, ss->cdb, " ");
1545         transfer = 1;
1546         break;
1547     case MDACMD_SCSILC:
1548     case MDACMD_SCSILCPT:
1549         mly_printf(sc, "   cdb length           %d\n", sl->cdb_length);
1550         mly_printf(sc, "   cdb                  0x%llx\n", sl->cdb_physaddr);
1551         transfer = 1;
1552         break;
1553     case MDACMD_IOCTL:
1554         mly_printf(sc, "   sub_ioctl            0x%x\n", io->sub_ioctl);
1555         switch(io->sub_ioctl) {
1556         case MDACIOCTL_SETMEMORYMAILBOX:
1557             mly_printf(sc, "   health_buffer_size   %d\n", 
1558                           io->param.setmemorymailbox.health_buffer_size);
1559             mly_printf(sc, "   health_buffer_phys   0x%llx\n",
1560                           io->param.setmemorymailbox.health_buffer_physaddr);
1561             mly_printf(sc, "   command_mailbox      0x%llx\n",
1562                           io->param.setmemorymailbox.command_mailbox_physaddr);
1563             mly_printf(sc, "   status_mailbox       0x%llx\n",
1564                           io->param.setmemorymailbox.status_mailbox_physaddr);
1565             transfer = 0;
1566             break;
1567
1568         case MDACIOCTL_SETREALTIMECLOCK:
1569         case MDACIOCTL_GETHEALTHSTATUS:
1570         case MDACIOCTL_GETCONTROLLERINFO:
1571         case MDACIOCTL_GETLOGDEVINFOVALID:
1572         case MDACIOCTL_GETPHYSDEVINFOVALID:
1573         case MDACIOCTL_GETPHYSDEVSTATISTICS:
1574         case MDACIOCTL_GETLOGDEVSTATISTICS:
1575         case MDACIOCTL_GETCONTROLLERSTATISTICS:
1576         case MDACIOCTL_GETBDT_FOR_SYSDRIVE:         
1577         case MDACIOCTL_CREATENEWCONF:
1578         case MDACIOCTL_ADDNEWCONF:
1579         case MDACIOCTL_GETDEVCONFINFO:
1580         case MDACIOCTL_GETFREESPACELIST:
1581         case MDACIOCTL_MORE:
1582         case MDACIOCTL_SETPHYSDEVPARAMETER:
1583         case MDACIOCTL_GETPHYSDEVPARAMETER:
1584         case MDACIOCTL_GETLOGDEVPARAMETER:
1585         case MDACIOCTL_SETLOGDEVPARAMETER:
1586             mly_printf(sc, "   param                %10D\n", io->param.data.param, " ");
1587             transfer = 1;
1588             break;
1589
1590         case MDACIOCTL_GETEVENT:
1591             mly_printf(sc, "   event                %d\n", 
1592                        io->param.getevent.sequence_number_low + ((u_int32_t)io->addr.log.logdev << 16));
1593             transfer = 1;
1594             break;
1595
1596         case MDACIOCTL_SETRAIDDEVSTATE:
1597             mly_printf(sc, "   state                %d\n", io->param.setraiddevstate.state);
1598             transfer = 0;
1599             break;
1600
1601         case MDACIOCTL_XLATEPHYSDEVTORAIDDEV:
1602             mly_printf(sc, "   raid_device          %d\n", io->param.xlatephysdevtoraiddev.raid_device);
1603             mly_printf(sc, "   controller           %d\n", io->param.xlatephysdevtoraiddev.controller);
1604             mly_printf(sc, "   channel              %d\n", io->param.xlatephysdevtoraiddev.channel);
1605             mly_printf(sc, "   target               %d\n", io->param.xlatephysdevtoraiddev.target);
1606             mly_printf(sc, "   lun                  %d\n", io->param.xlatephysdevtoraiddev.lun);
1607             transfer = 0;
1608             break;
1609
1610         case MDACIOCTL_GETGROUPCONFINFO:
1611             mly_printf(sc, "   group                %d\n", io->param.getgroupconfinfo.group);
1612             transfer = 1;
1613             break;
1614
1615         case MDACIOCTL_GET_SUBSYSTEM_DATA:
1616         case MDACIOCTL_SET_SUBSYSTEM_DATA:
1617         case MDACIOCTL_STARTDISOCVERY:
1618         case MDACIOCTL_INITPHYSDEVSTART:
1619         case MDACIOCTL_INITPHYSDEVSTOP:
1620         case MDACIOCTL_INITRAIDDEVSTART:
1621         case MDACIOCTL_INITRAIDDEVSTOP:
1622         case MDACIOCTL_REBUILDRAIDDEVSTART:
1623         case MDACIOCTL_REBUILDRAIDDEVSTOP:
1624         case MDACIOCTL_MAKECONSISTENTDATASTART:
1625         case MDACIOCTL_MAKECONSISTENTDATASTOP:
1626         case MDACIOCTL_CONSISTENCYCHECKSTART:
1627         case MDACIOCTL_CONSISTENCYCHECKSTOP:
1628         case MDACIOCTL_RESETDEVICE:
1629         case MDACIOCTL_FLUSHDEVICEDATA:
1630         case MDACIOCTL_PAUSEDEVICE:
1631         case MDACIOCTL_UNPAUSEDEVICE:
1632         case MDACIOCTL_LOCATEDEVICE:
1633         case MDACIOCTL_SETMASTERSLAVEMODE:
1634         case MDACIOCTL_DELETERAIDDEV:
1635         case MDACIOCTL_REPLACEINTERNALDEV:
1636         case MDACIOCTL_CLEARCONF:
1637         case MDACIOCTL_GETCONTROLLERPARAMETER:
1638         case MDACIOCTL_SETCONTRLLERPARAMETER:
1639         case MDACIOCTL_CLEARCONFSUSPMODE:
1640         case MDACIOCTL_STOREIMAGE:
1641         case MDACIOCTL_READIMAGE:
1642         case MDACIOCTL_FLASHIMAGES:
1643         case MDACIOCTL_RENAMERAIDDEV:
1644         default:                        /* no idea what to print */
1645             transfer = 0;
1646             break;
1647         }
1648         break;
1649
1650     case MDACMD_IOCTLCHECK:
1651     case MDACMD_MEMCOPY:
1652     default:
1653         transfer = 0;
1654         break;  /* print nothing */
1655     }
1656     if (transfer) {
1657         if (ge->command_control.extended_sg_table) {
1658             mly_printf(sc, "   sg table             0x%llx/%d\n",
1659                           ge->transfer.indirect.table_physaddr[0], ge->transfer.indirect.entries[0]);
1660         } else {
1661             mly_printf(sc, "   0000                 0x%llx/%lld\n",
1662                           ge->transfer.direct.sg[0].physaddr, ge->transfer.direct.sg[0].length);
1663             mly_printf(sc, "   0001                 0x%llx/%lld\n",
1664                           ge->transfer.direct.sg[1].physaddr, ge->transfer.direct.sg[1].length);
1665         }
1666     }
1667 }
1668
1669 /********************************************************************************
1670  * Panic in a slightly informative fashion
1671  */
1672 static void
1673 mly_panic(struct mly_softc *sc, char *reason)
1674 {
1675     mly_printstate(sc);
1676     panic(reason);
1677 }
1678 #endif
1679
1680 /********************************************************************************
1681  * Print queue statistics, callable from DDB.
1682  */
1683 void
1684 mly_print_controller(int controller)
1685 {
1686     struct mly_softc    *sc;
1687     
1688     if ((sc = devclass_get_softc(devclass_find("mly"), controller)) == NULL) {
1689         printf("mly: controller %d invalid\n", controller);
1690     } else {
1691         device_printf(sc->mly_dev, "queue    curr max\n");
1692         device_printf(sc->mly_dev, "free     %04d/%04d\n", 
1693                       sc->mly_qstat[MLYQ_FREE].q_length, sc->mly_qstat[MLYQ_FREE].q_max);
1694         device_printf(sc->mly_dev, "ready    %04d/%04d\n", 
1695                       sc->mly_qstat[MLYQ_READY].q_length, sc->mly_qstat[MLYQ_READY].q_max);
1696         device_printf(sc->mly_dev, "busy     %04d/%04d\n", 
1697                       sc->mly_qstat[MLYQ_BUSY].q_length, sc->mly_qstat[MLYQ_BUSY].q_max);
1698         device_printf(sc->mly_dev, "complete %04d/%04d\n", 
1699                       sc->mly_qstat[MLYQ_COMPLETE].q_length, sc->mly_qstat[MLYQ_COMPLETE].q_max);
1700     }
1701 }
1702
1703
1704 /********************************************************************************
1705  ********************************************************************************
1706                                                          Control device interface
1707  ********************************************************************************
1708  ********************************************************************************/
1709
1710 /********************************************************************************
1711  * Accept an open operation on the control device.
1712  */
1713 static int
1714 mly_user_open(dev_t dev, int flags, int fmt, struct proc *p)
1715 {
1716     int                 unit = minor(dev);
1717     struct mly_softc    *sc = devclass_get_softc(devclass_find("mly"), unit);
1718
1719     sc->mly_state |= MLY_STATE_OPEN;
1720     return(0);
1721 }
1722
1723 /********************************************************************************
1724  * Accept the last close on the control device.
1725  */
1726 static int
1727 mly_user_close(dev_t dev, int flags, int fmt, struct proc *p)
1728 {
1729     int                 unit = minor(dev);
1730     struct mly_softc    *sc = devclass_get_softc(devclass_find("mly"), unit);
1731
1732     sc->mly_state &= ~MLY_STATE_OPEN;
1733     return (0);
1734 }
1735
1736 /********************************************************************************
1737  * Handle controller-specific control operations.
1738  */
1739 static int
1740 mly_user_ioctl(dev_t dev, u_long cmd, caddr_t addr, int32_t flag, struct proc *p)
1741 {
1742     struct mly_softc            *sc = (struct mly_softc *)dev->si_drv1;
1743     struct mly_user_command     *uc = (struct mly_user_command *)addr;
1744     struct mly_user_health      *uh = (struct mly_user_health *)addr;
1745     
1746     switch(cmd) {
1747     case MLYIO_COMMAND:
1748         return(mly_user_command(sc, uc));
1749     case MLYIO_HEALTH:
1750         return(mly_user_health(sc, uh));
1751     default:
1752         return(ENOIOCTL);
1753     }
1754 }
1755
1756 /********************************************************************************
1757  * Execute a command passed in from userspace.
1758  *
1759  * The control structure contains the actual command for the controller, as well
1760  * as the user-space data pointer and data size, and an optional sense buffer
1761  * size/pointer.  On completion, the data size is adjusted to the command
1762  * residual, and the sense buffer size to the size of the returned sense data.
1763  * 
1764  */
1765 static int
1766 mly_user_command(struct mly_softc *sc, struct mly_user_command *uc)
1767 {
1768     struct mly_command                  *mc;
1769     int                                 error, s;
1770
1771     /* allocate a command */
1772     if (mly_alloc_command(sc, &mc)) {
1773         error = ENOMEM;
1774         goto out;               /* XXX Linux version will wait for a command */
1775     }
1776
1777     /* handle data size/direction */
1778     mc->mc_length = (uc->DataTransferLength >= 0) ? uc->DataTransferLength : -uc->DataTransferLength;
1779     if (mc->mc_length > 0) {
1780         if ((mc->mc_data = malloc(mc->mc_length, M_DEVBUF, M_NOWAIT)) == NULL) {
1781             error = ENOMEM;
1782             goto out;
1783         }
1784     }
1785     if (uc->DataTransferLength > 0) {
1786         mc->mc_flags |= MLY_CMD_DATAIN;
1787         bzero(mc->mc_data, mc->mc_length);
1788     }
1789     if (uc->DataTransferLength < 0) {
1790         mc->mc_flags |= MLY_CMD_DATAOUT;
1791         if ((error = copyin(uc->DataTransferBuffer, mc->mc_data, mc->mc_length)) != 0)
1792             goto out;
1793     }
1794
1795     /* copy the controller command */
1796     bcopy(&uc->CommandMailbox, mc->mc_packet, sizeof(uc->CommandMailbox));
1797
1798     /* clear command completion handler so that we get woken up */
1799     mc->mc_complete = NULL;
1800
1801     /* execute the command */
1802     s = splcam();
1803     mly_requeue_ready(mc);
1804     mly_startio(sc);
1805     while (!(mc->mc_flags & MLY_CMD_COMPLETE))
1806         tsleep(mc, PRIBIO, "mlyioctl", 0);
1807     splx(s);
1808
1809     /* return the data to userspace */
1810     if (uc->DataTransferLength > 0)
1811         if ((error = copyout(mc->mc_data, uc->DataTransferBuffer, mc->mc_length)) != 0)
1812             goto out;
1813     
1814     /* return the sense buffer to userspace */
1815     if ((uc->RequestSenseLength > 0) && (mc->mc_sense > 0)) {
1816         if ((error = copyout(mc->mc_packet, uc->RequestSenseBuffer, 
1817                              min(uc->RequestSenseLength, mc->mc_sense))) != 0)
1818             goto out;
1819     }
1820     
1821     /* return command results to userspace (caller will copy out) */
1822     uc->DataTransferLength = mc->mc_resid;
1823     uc->RequestSenseLength = min(uc->RequestSenseLength, mc->mc_sense);
1824     uc->CommandStatus = mc->mc_status;
1825     error = 0;
1826
1827  out:
1828     if (mc->mc_data != NULL)
1829         free(mc->mc_data, M_DEVBUF);
1830     if (mc != NULL)
1831         mly_release_command(mc);
1832     return(error);
1833 }
1834
1835 /********************************************************************************
1836  * Return health status to userspace.  If the health change index in the user
1837  * structure does not match that currently exported by the controller, we
1838  * return the current status immediately.  Otherwise, we block until either
1839  * interrupted or new status is delivered.
1840  */
1841 static int
1842 mly_user_health(struct mly_softc *sc, struct mly_user_health *uh)
1843 {
1844     struct mly_health_status            mh;
1845     int                                 error, s;
1846     
1847     /* fetch the current health status from userspace */
1848     if ((error = copyin(uh->HealthStatusBuffer, &mh, sizeof(mh))) != 0)
1849         return(error);
1850
1851     /* spin waiting for a status update */
1852     s = splcam();
1853     error = EWOULDBLOCK;
1854     while ((error != 0) && (sc->mly_event_change == mh.change_counter))
1855         error = tsleep(&sc->mly_event_change, PRIBIO | PCATCH, "mlyhealth", 0);
1856     splx(s);
1857     
1858     /* copy the controller's health status buffer out (there is a race here if it changes again) */
1859     error = copyout(&sc->mly_mmbox->mmm_health.status, uh->HealthStatusBuffer, 
1860                     sizeof(uh->HealthStatusBuffer));
1861     return(error);
1862 }