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