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