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