xref: /freebsd/sys/dev/ciss/ciss.c (revision 8fa113e5fc65fe6abc757f0089f477a87ee4d185)
1 /*-
2  * Copyright (c) 2001 Michael Smith
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *	$FreeBSD$
27  */
28 
29 /*
30  * Common Interface for SCSI-3 Support driver.
31  *
32  * CISS claims to provide a common interface between a generic SCSI
33  * transport and an intelligent host adapter.
34  *
35  * This driver supports CISS as defined in the document "CISS Command
36  * Interface for SCSI-3 Support Open Specification", Version 1.04,
37  * Valence Number 1, dated 20001127, produced by Compaq Computer
38  * Corporation.  This document appears to be a hastily and somewhat
39  * arbitrarlily cut-down version of a larger (and probably even more
40  * chaotic and inconsistent) Compaq internal document.  Various
41  * details were also gleaned from Compaq's "cciss" driver for Linux.
42  *
43  * We provide a shim layer between the CISS interface and CAM,
44  * offloading most of the queueing and being-a-disk chores onto CAM.
45  * Entry to the driver is via the PCI bus attachment (ciss_probe,
46  * ciss_attach, etc) and via the CAM interface (ciss_cam_action,
47  * ciss_cam_poll).  The Compaq CISS adapters are, however, poor SCSI
48  * citizens and we have to fake up some responses to get reasonable
49  * behaviour out of them.  In addition, the CISS command set is by no
50  * means adequate to support the functionality of a RAID controller,
51  * and thus the supported Compaq adapters utilise portions of the
52  * control protocol from earlier Compaq adapter families.
53  *
54  * Note that we only support the "simple" transport layer over PCI.
55  * This interface (ab)uses the I2O register set (specifically the post
56  * queues) to exchange commands with the adapter.  Other interfaces
57  * are available, but we aren't supposed to know about them, and it is
58  * dubious whether they would provide major performance improvements
59  * except under extreme load.
60  *
61  * Currently the only supported CISS adapters are the Compaq Smart
62  * Array 5* series (5300, 5i, 532).  Even with only three adapters,
63  * Compaq still manage to have interface variations.
64  *
65  *
66  * Thanks must go to Fred Harris and Darryl DeVinney at Compaq, as
67  * well as Paul Saab at Yahoo! for their assistance in making this
68  * driver happen.
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/malloc.h>
74 #include <sys/kernel.h>
75 #include <sys/bus.h>
76 #include <sys/conf.h>
77 #include <sys/devicestat.h>
78 #include <sys/stat.h>
79 
80 #include <cam/cam.h>
81 #include <cam/cam_ccb.h>
82 #include <cam/cam_periph.h>
83 #include <cam/cam_sim.h>
84 #include <cam/cam_xpt_sim.h>
85 #include <cam/scsi/scsi_all.h>
86 #include <cam/scsi/scsi_message.h>
87 
88 #include <machine/clock.h>
89 #include <machine/bus_memio.h>
90 #include <machine/bus.h>
91 #include <machine/endian.h>
92 #include <machine/resource.h>
93 #include <sys/rman.h>
94 
95 #include <pci/pcireg.h>
96 #include <pci/pcivar.h>
97 
98 #include <dev/ciss/cissreg.h>
99 #include <dev/ciss/cissvar.h>
100 #include <dev/ciss/cissio.h>
101 
102 MALLOC_DEFINE(CISS_MALLOC_CLASS, "ciss_data", "ciss internal data buffers");
103 
104 /* pci interface */
105 static int	ciss_lookup(device_t dev);
106 static int	ciss_probe(device_t dev);
107 static int	ciss_attach(device_t dev);
108 static int	ciss_detach(device_t dev);
109 static int	ciss_shutdown(device_t dev);
110 
111 /* (de)initialisation functions, control wrappers */
112 static int	ciss_init_pci(struct ciss_softc *sc);
113 static int	ciss_wait_adapter(struct ciss_softc *sc);
114 static int	ciss_flush_adapter(struct ciss_softc *sc);
115 static int	ciss_init_requests(struct ciss_softc *sc);
116 static void	ciss_command_map_helper(void *arg, bus_dma_segment_t *segs,
117 					int nseg, int error);
118 static int	ciss_identify_adapter(struct ciss_softc *sc);
119 static int	ciss_init_logical(struct ciss_softc *sc);
120 static int	ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld);
121 static int	ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld);
122 static int	ciss_update_config(struct ciss_softc *sc);
123 static int	ciss_accept_media(struct ciss_softc *sc, int ldrive, int async);
124 static void	ciss_accept_media_complete(struct ciss_request *cr);
125 static void	ciss_free(struct ciss_softc *sc);
126 
127 /* request submission/completion */
128 static int	ciss_start(struct ciss_request *cr);
129 static void	ciss_done(struct ciss_softc *sc);
130 static void	ciss_intr(void *arg);
131 static void	ciss_complete(struct ciss_softc *sc);
132 static int	ciss_report_request(struct ciss_request *cr, int *command_status,
133 				    int *scsi_status);
134 static int	ciss_synch_request(struct ciss_request *cr, int timeout);
135 static int	ciss_poll_request(struct ciss_request *cr, int timeout);
136 static int	ciss_wait_request(struct ciss_request *cr, int timeout);
137 static int	ciss_abort_request(struct ciss_request *cr);
138 
139 /* request queueing */
140 static int	ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp);
141 static void	ciss_preen_command(struct ciss_request *cr);
142 static void 	ciss_release_request(struct ciss_request *cr);
143 
144 /* request helpers */
145 static int	ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
146 				      int opcode, void **bufp, size_t bufsize);
147 static int	ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc);
148 
149 /* DMA map/unmap */
150 static int	ciss_map_request(struct ciss_request *cr);
151 static void	ciss_request_map_helper(void *arg, bus_dma_segment_t *segs,
152 					int nseg, int error);
153 static void	ciss_unmap_request(struct ciss_request *cr);
154 
155 /* CAM interface */
156 static int	ciss_cam_init(struct ciss_softc *sc);
157 static void	ciss_cam_rescan_target(struct ciss_softc *sc, int target);
158 static void	ciss_cam_rescan_all(struct ciss_softc *sc);
159 static void	ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb);
160 static void	ciss_cam_action(struct cam_sim *sim, union ccb *ccb);
161 static int	ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio);
162 static int	ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio);
163 static void	ciss_cam_poll(struct cam_sim *sim);
164 static void	ciss_cam_complete(struct ciss_request *cr);
165 static void	ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio);
166 static struct cam_periph *ciss_find_periph(struct ciss_softc *sc, int target);
167 static int	ciss_name_device(struct ciss_softc *sc, int target);
168 
169 /* periodic status monitoring */
170 static void	ciss_periodic(void *arg);
171 static void	ciss_notify_event(struct ciss_softc *sc);
172 static void	ciss_notify_complete(struct ciss_request *cr);
173 static int	ciss_notify_abort(struct ciss_softc *sc);
174 static int	ciss_notify_abort_bmic(struct ciss_softc *sc);
175 static void	ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn);
176 static void	ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn);
177 
178 /* debugging output */
179 static void	ciss_print_request(struct ciss_request *cr);
180 static void	ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld);
181 static const char *ciss_name_ldrive_status(int status);
182 static int	ciss_decode_ldrive_status(int status);
183 static const char *ciss_name_ldrive_org(int org);
184 static const char *ciss_name_command_status(int status);
185 
186 /*
187  * PCI bus interface.
188  */
189 static device_method_t ciss_methods[] = {
190     /* Device interface */
191     DEVMETHOD(device_probe,	ciss_probe),
192     DEVMETHOD(device_attach,	ciss_attach),
193     DEVMETHOD(device_detach,	ciss_detach),
194     DEVMETHOD(device_shutdown,	ciss_shutdown),
195     { 0, 0 }
196 };
197 
198 static driver_t ciss_pci_driver = {
199     "ciss",
200     ciss_methods,
201     sizeof(struct ciss_softc)
202 };
203 
204 static devclass_t	ciss_devclass;
205 DRIVER_MODULE(ciss, pci, ciss_pci_driver, ciss_devclass, 0, 0);
206 
207 /*
208  * Control device interface.
209  */
210 static d_open_t		ciss_open;
211 static d_close_t	ciss_close;
212 static d_ioctl_t	ciss_ioctl;
213 
214 #define CISS_CDEV_MAJOR  166
215 
216 static struct cdevsw ciss_cdevsw = {
217     ciss_open, ciss_close, noread, nowrite, ciss_ioctl,
218     nopoll, nommap, nostrategy, "ciss", CISS_CDEV_MAJOR,
219     nodump, nopsize, 0, -1
220 };
221 
222 /************************************************************************
223  * CISS adapters amazingly don't have a defined programming interface
224  * value.  (One could say some very despairing things about PCI and
225  * people just not getting the general idea.)  So we are forced to
226  * stick with matching against subvendor/subdevice, and thus have to
227  * be updated for every new CISS adapter that appears.
228  */
229 #define CISS_BOARD_SA5	(1<<0)
230 #define CISS_BOARD_SA5B	(1<<1)
231 
232 static struct
233 {
234     u_int16_t	subvendor;
235     u_int16_t	subdevice;
236     int		flags;
237     char	*desc;
238 } ciss_vendor_data[] = {
239     { 0x0e11, 0x4070, CISS_BOARD_SA5,	"Compaq Smart Array 5300" },
240     { 0x0e11, 0x4080, CISS_BOARD_SA5B,	"Compaq Smart Array 5i" },
241     { 0x0e11, 0x4082, CISS_BOARD_SA5B,	"Compaq Smart Array 532" },
242     { 0, 0, NULL }
243 };
244 
245 /************************************************************************
246  * Find a match for the device in our list of known adapters.
247  */
248 static int
249 ciss_lookup(device_t dev)
250 {
251     int 	i;
252 
253     for (i = 0; ciss_vendor_data[i].desc != NULL; i++)
254 	if ((pci_get_subvendor(dev) == ciss_vendor_data[i].subvendor) &&
255 	    (pci_get_subdevice(dev) == ciss_vendor_data[i].subdevice)) {
256 	    return(i);
257 	}
258     return(-1);
259 }
260 
261 /************************************************************************
262  * Match a known CISS adapter.
263  */
264 static int
265 ciss_probe(device_t dev)
266 {
267     int		i;
268 
269     i = ciss_lookup(dev);
270     if (i != -1) {
271 	device_set_desc(dev, ciss_vendor_data[i].desc);
272 	return(-10);
273     }
274     return(ENOENT);
275 }
276 
277 /************************************************************************
278  * Attach the driver to this adapter.
279  */
280 static int
281 ciss_attach(device_t dev)
282 {
283     struct ciss_softc	*sc;
284     int			i, error;
285 
286     debug_called(1);
287 
288 #ifdef CISS_DEBUG
289     /* print structure/union sizes */
290     debug_struct(ciss_command);
291     debug_struct(ciss_header);
292     debug_union(ciss_device_address);
293     debug_struct(ciss_cdb);
294     debug_struct(ciss_report_cdb);
295     debug_struct(ciss_notify_cdb);
296     debug_struct(ciss_notify);
297     debug_struct(ciss_message_cdb);
298     debug_struct(ciss_error_info_pointer);
299     debug_struct(ciss_error_info);
300     debug_struct(ciss_sg_entry);
301     debug_struct(ciss_config_table);
302     debug_struct(ciss_bmic_cdb);
303     debug_struct(ciss_bmic_id_ldrive);
304     debug_struct(ciss_bmic_id_lstatus);
305     debug_struct(ciss_bmic_id_table);
306     debug_struct(ciss_bmic_id_pdrive);
307     debug_struct(ciss_bmic_blink_pdrive);
308     debug_struct(ciss_bmic_flush_cache);
309     debug_const(CISS_MAX_REQUESTS);
310     debug_const(CISS_MAX_LOGICAL);
311     debug_const(CISS_INTERRUPT_COALESCE_DELAY);
312     debug_const(CISS_INTERRUPT_COALESCE_COUNT);
313     debug_const(CISS_COMMAND_ALLOC_SIZE);
314     debug_const(CISS_COMMAND_SG_LENGTH);
315 
316     debug_type(cciss_pci_info_struct);
317     debug_type(cciss_coalint_struct);
318     debug_type(cciss_coalint_struct);
319     debug_type(NodeName_type);
320     debug_type(NodeName_type);
321     debug_type(Heartbeat_type);
322     debug_type(BusTypes_type);
323     debug_type(FirmwareVer_type);
324     debug_type(DriverVer_type);
325     debug_type(IOCTL_Command_struct);
326 #endif
327 
328     sc = device_get_softc(dev);
329     sc->ciss_dev = dev;
330 
331     /*
332      * Work out adapter type.
333      */
334     i = ciss_lookup(dev);
335     if (ciss_vendor_data[i].flags & CISS_BOARD_SA5) {
336 	sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5;
337     } else if (ciss_vendor_data[i].flags & CISS_BOARD_SA5B) {
338 	sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5B;
339     } else {
340 	/* really an error on our part */
341 	ciss_printf(sc, "unable to determine hardware type\n");
342 	error = ENXIO;
343 	goto out;
344     }
345 
346     /*
347      * Do PCI-specific init.
348      */
349     if ((error = ciss_init_pci(sc)) != 0)
350 	goto out;
351 
352     /*
353      * Initialise driver queues.
354      */
355     ciss_initq_free(sc);
356     ciss_initq_busy(sc);
357     ciss_initq_complete(sc);
358 
359     /*
360      * Initialise command/request pool.
361      */
362     if ((error = ciss_init_requests(sc)) != 0)
363 	goto out;
364 
365     /*
366      * Get adapter information.
367      */
368     if ((error = ciss_identify_adapter(sc)) != 0)
369 	goto out;
370 
371     /*
372      * Build our private table of logical devices.
373      */
374     if ((error = ciss_init_logical(sc)) != 0)
375 	goto out;
376 
377     /*
378      * Enable interrupts so that the CAM scan can complete.
379      */
380     CISS_TL_SIMPLE_ENABLE_INTERRUPTS(sc);
381 
382     /*
383      * Initialise the CAM interface.
384      */
385     if ((error = ciss_cam_init(sc)) != 0)
386 	goto out;
387 
388     /*
389      * Start the heartbeat routine and event chain.
390      */
391     ciss_periodic(sc);
392 
393    /*
394      * Create the control device.
395      */
396     sc->ciss_dev_t = make_dev(&ciss_cdevsw, device_get_unit(sc->ciss_dev),
397 			      UID_ROOT, GID_OPERATOR, S_IRUSR | S_IWUSR,
398 			      "ciss%d", device_get_unit(sc->ciss_dev));
399     sc->ciss_dev_t->si_drv1 = sc;
400 
401     /*
402      * The adapter is running; synchronous commands can now sleep
403      * waiting for an interrupt to signal completion.
404      */
405     sc->ciss_flags |= CISS_FLAG_RUNNING;
406 
407     error = 0;
408  out:
409     if (error != 0)
410 	ciss_free(sc);
411     return(error);
412 }
413 
414 /************************************************************************
415  * Detach the driver from this adapter.
416  */
417 static int
418 ciss_detach(device_t dev)
419 {
420     struct ciss_softc	*sc = device_get_softc(dev);
421 
422     debug_called(1);
423 
424     /* flush adapter cache */
425     ciss_flush_adapter(sc);
426 
427     /* release all resources */
428     ciss_free(sc);
429 
430     return(0);
431 
432 }
433 
434 /************************************************************************
435  * Prepare adapter for system shutdown.
436  */
437 static int
438 ciss_shutdown(device_t dev)
439 {
440     struct ciss_softc	*sc = device_get_softc(dev);
441 
442     debug_called(1);
443 
444     /* flush adapter cache */
445     ciss_flush_adapter(sc);
446 
447     return(0);
448 }
449 
450 /************************************************************************
451  * Perform PCI-specific attachment actions.
452  */
453 static int
454 ciss_init_pci(struct ciss_softc *sc)
455 {
456     uintptr_t		cbase, csize, cofs;
457     int			error;
458 
459     debug_called(1);
460 
461     /*
462      * Allocate register window first (we need this to find the config
463      * struct).
464      */
465     error = ENXIO;
466     sc->ciss_regs_rid = CISS_TL_SIMPLE_BAR_REGS;
467     if ((sc->ciss_regs_resource =
468 	 bus_alloc_resource(sc->ciss_dev, SYS_RES_MEMORY, &sc->ciss_regs_rid,
469 			    0, ~0, 1, RF_ACTIVE)) == NULL) {
470 	ciss_printf(sc, "can't allocate register window\n");
471 	return(ENXIO);
472     }
473     sc->ciss_regs_bhandle = rman_get_bushandle(sc->ciss_regs_resource);
474     sc->ciss_regs_btag = rman_get_bustag(sc->ciss_regs_resource);
475 
476     /*
477      * Find the BAR holding the config structure.  If it's not the one
478      * we already mapped for registers, map it too.
479      */
480     sc->ciss_cfg_rid = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_BAR) & 0xffff;
481     if (sc->ciss_cfg_rid != sc->ciss_regs_rid) {
482 	if ((sc->ciss_cfg_resource =
483 	     bus_alloc_resource(sc->ciss_dev, SYS_RES_MEMORY, &sc->ciss_cfg_rid,
484 				0, ~0, 1, RF_ACTIVE)) == NULL) {
485 	    ciss_printf(sc, "can't allocate config window\n");
486 	    return(ENXIO);
487 	}
488 	cbase = (uintptr_t)rman_get_virtual(sc->ciss_cfg_resource);
489 	csize = rman_get_end(sc->ciss_cfg_resource) -
490 	    rman_get_start(sc->ciss_cfg_resource) + 1;
491     } else {
492 	cbase = (uintptr_t)rman_get_virtual(sc->ciss_regs_resource);
493 	csize = rman_get_end(sc->ciss_regs_resource) -
494 	    rman_get_start(sc->ciss_regs_resource) + 1;
495     }
496     cofs = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_OFF);
497 
498     /*
499      * Use the base/size/offset values we just calculated to
500      * sanity-check the config structure.  If it's OK, point to it.
501      */
502     if ((cofs + sizeof(struct ciss_config_table)) > csize) {
503 	ciss_printf(sc, "config table outside window\n");
504 	return(ENXIO);
505     }
506     sc->ciss_cfg = (struct ciss_config_table *)(cbase + cofs);
507     debug(1, "config struct at %p", sc->ciss_cfg);
508 
509     /*
510      * Validate the config structure.  If we supported other transport
511      * methods, we could select amongst them at this point in time.
512      */
513     if (strncmp(sc->ciss_cfg->signature, "CISS", 4)) {
514 	ciss_printf(sc, "config signature mismatch (got '%c%c%c%c')\n",
515 		    sc->ciss_cfg->signature[0], sc->ciss_cfg->signature[1],
516 		    sc->ciss_cfg->signature[2], sc->ciss_cfg->signature[3]);
517 	return(ENXIO);
518     }
519     if ((sc->ciss_cfg->valence < CISS_MIN_VALENCE) ||
520 	(sc->ciss_cfg->valence > CISS_MAX_VALENCE)) {
521 	ciss_printf(sc, "adapter interface specification (%d) unsupported\n",
522 		    sc->ciss_cfg->valence);
523 	return(ENXIO);
524     }
525 
526     /*
527      * Put the board into simple mode, and tell it we're using the low
528      * 4GB of RAM.  Set the default interrupt coalescing options.
529      */
530     if (!(sc->ciss_cfg->supported_methods & CISS_TRANSPORT_METHOD_SIMPLE)) {
531 	ciss_printf(sc, "adapter does not support 'simple' transport layer\n");
532 	return(ENXIO);
533     }
534     sc->ciss_cfg->requested_method = CISS_TRANSPORT_METHOD_SIMPLE;
535     sc->ciss_cfg->command_physlimit = 0;
536     sc->ciss_cfg->interrupt_coalesce_delay = CISS_INTERRUPT_COALESCE_DELAY;
537     sc->ciss_cfg->interrupt_coalesce_count = CISS_INTERRUPT_COALESCE_COUNT;
538 
539     if (ciss_update_config(sc)) {
540 	ciss_printf(sc, "adapter refuses to accept config update (IDBR 0x%x)\n",
541 		    CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR));
542 	return(ENXIO);
543     }
544     if (!(sc->ciss_cfg->active_method != CISS_TRANSPORT_METHOD_SIMPLE)) {
545 	ciss_printf(sc,
546 		    "adapter refuses to go into 'simple' transport mode (0x%x, 0x%x)\n",
547 		    sc->ciss_cfg->supported_methods, sc->ciss_cfg->active_method);
548 	return(ENXIO);
549     }
550 
551     /*
552      * Wait for the adapter to come ready.
553      */
554     if ((error = ciss_wait_adapter(sc)) != 0)
555 	return(error);
556 
557     /*
558      * Turn off interrupts before we go routing anything.
559      */
560     CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
561 
562     /*
563      * Allocate and set up our interrupt.
564      */
565     sc->ciss_irq_rid = 0;
566     if ((sc->ciss_irq_resource =
567 	 bus_alloc_resource(sc->ciss_dev, SYS_RES_IRQ, &sc->ciss_irq_rid, 0, ~0, 1,
568 			    RF_ACTIVE | RF_SHAREABLE)) == NULL) {
569 	ciss_printf(sc, "can't allocate interrupt\n");
570 	return(ENXIO);
571     }
572     if (bus_setup_intr(sc->ciss_dev, sc->ciss_irq_resource, INTR_TYPE_CAM, ciss_intr, sc,
573 		       &sc->ciss_intr)) {
574 	ciss_printf(sc, "can't set up interrupt\n");
575 	return(ENXIO);
576     }
577 
578     /*
579      * Allocate the parent bus DMA tag appropriate for our PCI
580      * interface.
581      *
582      * Note that "simple" adapters can only address within a 32-bit
583      * span.
584      */
585     if (bus_dma_tag_create(NULL, 			/* parent */
586 			   1, 0, 			/* alignment, boundary */
587 			   BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
588 			   BUS_SPACE_MAXADDR, 		/* highaddr */
589 			   NULL, NULL, 			/* filter, filterarg */
590 			   MAXBSIZE, CISS_COMMAND_SG_LENGTH,	/* maxsize, nsegments */
591 			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
592 			   BUS_DMA_ALLOCNOW,		/* flags */
593 			   &sc->ciss_parent_dmat)) {
594 	ciss_printf(sc, "can't allocate parent DMA tag\n");
595 	return(ENOMEM);
596     }
597 
598     /*
599      * Create DMA tag for mapping buffers into adapter-addressable
600      * space.
601      */
602     if (bus_dma_tag_create(sc->ciss_parent_dmat, 	/* parent */
603 			   1, 0, 			/* alignment, boundary */
604 			   BUS_SPACE_MAXADDR,		/* lowaddr */
605 			   BUS_SPACE_MAXADDR, 		/* highaddr */
606 			   NULL, NULL, 			/* filter, filterarg */
607 			   MAXBSIZE, CISS_COMMAND_SG_LENGTH,	/* maxsize, nsegments */
608 			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
609 			   0,				/* flags */
610 			   &sc->ciss_buffer_dmat)) {
611 	ciss_printf(sc, "can't allocate buffer DMA tag\n");
612 	return(ENOMEM);
613     }
614     return(0);
615 }
616 
617 /************************************************************************
618  * Wait for the adapter to come ready.
619  */
620 static int
621 ciss_wait_adapter(struct ciss_softc *sc)
622 {
623     int		i;
624 
625     debug_called(1);
626 
627     /*
628      * Wait for the adapter to come ready.
629      */
630     if (!(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY)) {
631 	ciss_printf(sc, "waiting for adapter to come ready...\n");
632 	for (i = 0; !(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY); i++) {
633 	    DELAY(1000000);	/* one second */
634 	    if (i > 30) {
635 		ciss_printf(sc, "timed out waiting for adapter to come ready\n");
636 		return(EIO);
637 	    }
638 	}
639     }
640     return(0);
641 }
642 
643 /************************************************************************
644  * Flush the adapter cache.
645  */
646 static int
647 ciss_flush_adapter(struct ciss_softc *sc)
648 {
649     struct ciss_request			*cr;
650     struct ciss_bmic_flush_cache	*cbfc;
651     int					error, command_status;
652 
653     debug_called(1);
654 
655     cr = NULL;
656     cbfc = NULL;
657 
658     /*
659      * Build a BMIC request to flush the cache.  We don't disable
660      * it, as we may be going to do more I/O (eg. we are emulating
661      * the Synchronise Cache command).
662      */
663     if ((cbfc = malloc(sizeof(*cbfc), CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
664 	error = ENOMEM;
665 	goto out;
666     }
667     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_FLUSH_CACHE,
668 				       (void **)&cbfc, sizeof(*cbfc))) != 0)
669 	goto out;
670 
671     /*
672      * Submit the request and wait for it to complete.
673      */
674     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
675 	ciss_printf(sc, "error sending BMIC FLUSH_CACHE command (%d)\n", error);
676 	goto out;
677     }
678 
679     /*
680      * Check response.
681      */
682     ciss_report_request(cr, &command_status, NULL);
683     switch(command_status) {
684     case CISS_CMD_STATUS_SUCCESS:
685 	break;
686     default:
687 	ciss_printf(sc, "error flushing cache (%s)\n",
688 		    ciss_name_command_status(command_status));
689 	error = EIO;
690 	goto out;
691     }
692 
693 out:
694     if (cbfc != NULL)
695 	free(cbfc, CISS_MALLOC_CLASS);
696     if (cr != NULL)
697 	ciss_release_request(cr);
698     return(error);
699 }
700 
701 /************************************************************************
702  * Allocate memory for the adapter command structures, initialise
703  * the request structures.
704  *
705  * Note that the entire set of commands are allocated in a single
706  * contiguous slab.
707  */
708 static int
709 ciss_init_requests(struct ciss_softc *sc)
710 {
711     struct ciss_request	*cr;
712     int			i;
713 
714     debug_called(1);
715 
716     /*
717      * Calculate the number of request structures/commands we are
718      * going to provide for this adapter.
719      */
720     sc->ciss_max_requests = min(CISS_MAX_REQUESTS, sc->ciss_cfg->max_outstanding_commands);
721 
722     if (1/*bootverbose*/)
723 	ciss_printf(sc, "using %d of %d available commands\n",
724 		    sc->ciss_max_requests, sc->ciss_cfg->max_outstanding_commands);
725 
726     /*
727      * Create the DMA tag for commands.
728      */
729     if (bus_dma_tag_create(sc->ciss_parent_dmat,	/* parent */
730 			   1, 0, 			/* alignment, boundary */
731 			   BUS_SPACE_MAXADDR,		/* lowaddr */
732 			   BUS_SPACE_MAXADDR, 		/* highaddr */
733 			   NULL, NULL, 			/* filter, filterarg */
734 			   CISS_COMMAND_ALLOC_SIZE *
735 			   sc->ciss_max_requests, 1,	/* maxsize, nsegments */
736 			   BUS_SPACE_MAXSIZE_32BIT,	/* maxsegsize */
737 			   0,				/* flags */
738 			   &sc->ciss_command_dmat)) {
739 	ciss_printf(sc, "can't allocate command DMA tag\n");
740 	return(ENOMEM);
741     }
742     /*
743      * Allocate memory and make it available for DMA.
744      */
745     if (bus_dmamem_alloc(sc->ciss_command_dmat, (void **)&sc->ciss_command,
746 			 BUS_DMA_NOWAIT, &sc->ciss_command_map)) {
747 	ciss_printf(sc, "can't allocate command memory\n");
748 	return(ENOMEM);
749     }
750     bus_dmamap_load(sc->ciss_command_dmat, sc->ciss_command_map, sc->ciss_command,
751 		    sizeof(struct ciss_command) * sc->ciss_max_requests,
752 		    ciss_command_map_helper, sc, 0);
753     bzero(sc->ciss_command, CISS_COMMAND_ALLOC_SIZE * sc->ciss_max_requests);
754 
755     /*
756      * Set up the request and command structures, push requests onto
757      * the free queue.
758      */
759     for (i = 1; i < sc->ciss_max_requests; i++) {
760 	cr = &sc->ciss_request[i];
761 	cr->cr_sc = sc;
762 	cr->cr_tag = i;
763 	ciss_enqueue_free(cr);
764     }
765     return(0);
766 }
767 
768 static void
769 ciss_command_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
770 {
771     struct ciss_softc	*sc = (struct ciss_softc *)arg;
772 
773     sc->ciss_command_phys = segs->ds_addr;
774 }
775 
776 /************************************************************************
777  * Identify the adapter, print some information about it.
778  */
779 static int
780 ciss_identify_adapter(struct ciss_softc *sc)
781 {
782     struct ciss_request	*cr;
783     int			error, command_status;
784 
785     debug_called(1);
786 
787     cr = NULL;
788 
789     /*
790      * Get a request, allocate storage for the adapter data.
791      */
792     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_CTLR,
793 				       (void **)&sc->ciss_id,
794 				       sizeof(*sc->ciss_id))) != 0)
795 	goto out;
796 
797     /*
798      * Submit the request and wait for it to complete.
799      */
800     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
801 	ciss_printf(sc, "error sending BMIC ID_CTLR command (%d)\n", error);
802 	goto out;
803     }
804 
805     /*
806      * Check response.
807      */
808     ciss_report_request(cr, &command_status, NULL);
809     switch(command_status) {
810     case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
811 	break;
812     case CISS_CMD_STATUS_DATA_UNDERRUN:
813     case CISS_CMD_STATUS_DATA_OVERRUN:
814 	ciss_printf(sc, "data over/underrun reading adapter information\n");
815     default:
816 	ciss_printf(sc, "error reading adapter information (%s)\n",
817 		    ciss_name_command_status(command_status));
818 	error = EIO;
819 	goto out;
820     }
821 
822     /* sanity-check reply */
823     if (!sc->ciss_id->big_map_supported) {
824 	ciss_printf(sc, "adapter does not support BIG_MAP\n");
825 	error = ENXIO;
826 	goto out;
827     }
828 
829     /* XXX later revisions may not need this */
830     sc->ciss_flags |= CISS_FLAG_FAKE_SYNCH;
831 
832     /* XXX only really required for old 5300 adapters? */
833     sc->ciss_flags |= CISS_FLAG_BMIC_ABORT;
834 
835     /* print information */
836     if (1/*bootverbose*/) {
837 	ciss_printf(sc, "  %d logical drive%s configured\n",
838 		    sc->ciss_id->configured_logical_drives,
839 		    (sc->ciss_id->configured_logical_drives == 1) ? "" : "s");
840 	ciss_printf(sc, "  firmware %4.4s\n", sc->ciss_id->running_firmware_revision);
841 	ciss_printf(sc, "  %d SCSI channels\n", sc->ciss_id->scsi_bus_count);
842 
843 	ciss_printf(sc, "  signature '%.4s'\n", sc->ciss_cfg->signature);
844 	ciss_printf(sc, "  valence %d\n", sc->ciss_cfg->valence);
845 	ciss_printf(sc, "  supported I/O methods 0x%b\n",
846 		    sc->ciss_cfg->supported_methods,
847 		    "\20\1READY\2simple\3performant\4MEMQ\n");
848 	ciss_printf(sc, "  active I/O method 0x%b\n",
849 		    sc->ciss_cfg->active_method, "\20\2simple\3performant\4MEMQ\n");
850 	ciss_printf(sc, "  4G page base 0x%08x\n",
851 		    sc->ciss_cfg->command_physlimit);
852 	ciss_printf(sc, "  interrupt coalesce delay %dus\n",
853 		    sc->ciss_cfg->interrupt_coalesce_delay);
854 	ciss_printf(sc, "  interrupt coalesce count %d\n",
855 		    sc->ciss_cfg->interrupt_coalesce_count);
856 	ciss_printf(sc, "  max outstanding commands %d\n",
857 		    sc->ciss_cfg->max_outstanding_commands);
858 	ciss_printf(sc, "  bus types 0x%b\n", sc->ciss_cfg->bus_types,
859 		    "\20\1ultra2\2ultra3\10fibre1\11fibre2\n");
860 	ciss_printf(sc, "  server name '%.16s'\n", sc->ciss_cfg->server_name);
861 	ciss_printf(sc, "  heartbeat 0x%x\n", sc->ciss_cfg->heartbeat);
862     }
863 
864 out:
865     if (error) {
866 	if (sc->ciss_id != NULL) {
867 	    free(sc->ciss_id, CISS_MALLOC_CLASS);
868 	    sc->ciss_id = NULL;
869 	}
870     }
871     if (cr != NULL)
872 	ciss_release_request(cr);
873     return(error);
874 }
875 
876 /************************************************************************
877  * Find logical drives on the adapter.
878  */
879 static int
880 ciss_init_logical(struct ciss_softc *sc)
881 {
882     struct ciss_request		*cr;
883     struct ciss_command		*cc;
884     struct ciss_report_cdb	*crc;
885     struct ciss_lun_report	*cll;
886     int				error, i;
887     size_t			report_size;
888     int				ndrives;
889     int				command_status;
890 
891     debug_called(1);
892 
893     cr = NULL;
894     cll = NULL;
895 
896     /*
897      * Get a request, allocate storage for the address list.
898      */
899     if ((error = ciss_get_request(sc, &cr)) != 0)
900 	goto out;
901     report_size = sizeof(*cll) + CISS_MAX_LOGICAL * sizeof(union ciss_device_address);
902     if ((cll = malloc(report_size, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
903 	ciss_printf(sc, "can't allocate memory for logical drive list\n");
904 	error = ENOMEM;
905 	goto out;
906     }
907 
908     /*
909      * Build the Report Logical LUNs command.
910      */
911     cc = CISS_FIND_COMMAND(cr);
912     cr->cr_data = cll;
913     cr->cr_length = report_size;
914     cr->cr_flags = CISS_REQ_DATAIN;
915 
916     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
917     cc->header.address.physical.bus = 0;
918     cc->header.address.physical.target = 0;
919     cc->cdb.cdb_length = sizeof(*crc);
920     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
921     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
922     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
923     cc->cdb.timeout = 30;	/* XXX better suggestions? */
924 
925     crc = (struct ciss_report_cdb *)&(cc->cdb.cdb[0]);
926     bzero(crc, sizeof(*crc));
927     crc->opcode = CISS_OPCODE_REPORT_LOGICAL_LUNS;
928     crc->length = htonl(report_size);			/* big-endian field */
929     cll->list_size = htonl(report_size - sizeof(*cll));	/* big-endian field */
930 
931     /*
932      * Submit the request and wait for it to complete.  (timeout
933      * here should be much greater than above)
934      */
935     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
936 	ciss_printf(sc, "error sending Report Logical LUNs command (%d)\n", error);
937 	goto out;
938     }
939 
940     /*
941      * Check response.  Note that data over/underrun is OK.
942      */
943     ciss_report_request(cr, &command_status, NULL);
944     switch(command_status) {
945     case CISS_CMD_STATUS_SUCCESS:	/* buffer right size */
946     case CISS_CMD_STATUS_DATA_UNDERRUN:	/* buffer too large, not bad */
947 	break;
948     case CISS_CMD_STATUS_DATA_OVERRUN:
949 	ciss_printf(sc, "WARNING: more logical drives than driver limit (%d), adjust CISS_MAX_LOGICAL\n",
950 		    CISS_MAX_LOGICAL);
951 	break;
952     default:
953 	ciss_printf(sc, "error detecting logical drive configuration (%s)\n",
954 		    ciss_name_command_status(command_status));
955 	error = EIO;
956 	goto out;
957     }
958     ciss_release_request(cr);
959     cr = NULL;
960 
961     /* sanity-check reply */
962     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
963     if ((ndrives < 0) || (ndrives > CISS_MAX_LOGICAL)) {
964 	ciss_printf(sc, "adapter claims to report absurd number of logical drives (%d > %d)\n",
965 		    ndrives, CISS_MAX_LOGICAL);
966 	return(ENXIO);
967     }
968 
969     /*
970      * Save logical drive information.
971      */
972     if (1/*bootverbose*/)
973 	ciss_printf(sc, "%d logical drive%s\n", ndrives, (ndrives > 1) ? "s" : "");
974     if (ndrives != sc->ciss_id->configured_logical_drives)
975 	ciss_printf(sc, "logical drive map claims %d drives, but adapter claims %d\n",
976 		    ndrives, sc->ciss_id->configured_logical_drives);
977     for (i = 0; i < CISS_MAX_LOGICAL; i++) {
978 	if (i < ndrives) {
979 	    sc->ciss_logical[i].cl_address = cll->lun[i];	/* XXX endianness? */
980 	    if (ciss_identify_logical(sc, &sc->ciss_logical[i]) != 0)
981 		continue;
982 	    /*
983 	     * If the drive has had media exchanged, we should bring it online.
984 	     */
985 	    if (sc->ciss_logical[i].cl_lstatus->media_exchanged)
986 		ciss_accept_media(sc, i, 0);
987 
988 	} else {
989 	    sc->ciss_logical[i].cl_status = CISS_LD_NONEXISTENT;
990 	}
991     }
992     error = 0;
993 
994  out:
995     /*
996      * Note that if the error is a timeout, we are taking a slight
997      * risk here and assuming that the adapter will not respond at a
998      * later time, scribbling over host memory.
999      */
1000     if (cr != NULL)
1001 	ciss_release_request(cr);
1002     if (cll != NULL)
1003 	free(cll, CISS_MALLOC_CLASS);
1004     return(error);
1005 }
1006 
1007 /************************************************************************
1008  * Identify a logical drive, initialise state related to it.
1009  */
1010 static int
1011 ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld)
1012 {
1013     struct ciss_request		*cr;
1014     struct ciss_command		*cc;
1015     struct ciss_bmic_cdb	*cbc;
1016     int				error, command_status;
1017 
1018     debug_called(1);
1019 
1020     cr = NULL;
1021 
1022     /*
1023      * Build a BMIC request to fetch the drive ID.
1024      */
1025     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LDRIVE,
1026 				       (void **)&ld->cl_ldrive,
1027 				       sizeof(*ld->cl_ldrive))) != 0)
1028 	goto out;
1029     cc = CISS_FIND_COMMAND(cr);
1030     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1031     cbc->log_drive = ld->cl_address.logical.lun;
1032 
1033     /*
1034      * Submit the request and wait for it to complete.
1035      */
1036     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1037 	ciss_printf(sc, "error sending BMIC LDRIVE command (%d)\n", error);
1038 	goto out;
1039     }
1040 
1041     /*
1042      * Check response.
1043      */
1044     ciss_report_request(cr, &command_status, NULL);
1045     switch(command_status) {
1046     case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1047 	break;
1048     case CISS_CMD_STATUS_DATA_UNDERRUN:
1049     case CISS_CMD_STATUS_DATA_OVERRUN:
1050 	ciss_printf(sc, "data over/underrun reading logical drive ID\n");
1051     default:
1052 	ciss_printf(sc, "error reading logical drive ID (%s)\n",
1053 		    ciss_name_command_status(command_status));
1054 	error = EIO;
1055 	goto out;
1056     }
1057     ciss_release_request(cr);
1058     cr = NULL;
1059 
1060     /*
1061      * Build a CISS BMIC command to get the logical drive status.
1062      */
1063     if ((error = ciss_get_ldrive_status(sc, ld)) != 0)
1064 	goto out;
1065 
1066     /*
1067      * Print the drive's basic characteristics.
1068      */
1069     if (1/*bootverbose*/) {
1070 	ciss_printf(sc, "logical drive %d: %s, %dMB ",
1071 		    cbc->log_drive, ciss_name_ldrive_org(ld->cl_ldrive->fault_tolerance),
1072 		    ((ld->cl_ldrive->blocks_available / (1024 * 1024)) *
1073 		     ld->cl_ldrive->block_size));
1074 
1075 	ciss_print_ldrive(sc, ld);
1076     }
1077 out:
1078     if (error != 0) {
1079 	/* make the drive not-exist */
1080 	ld->cl_status = CISS_LD_NONEXISTENT;
1081 	if (ld->cl_ldrive != NULL) {
1082 	    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
1083 	    ld->cl_ldrive = NULL;
1084 	}
1085 	if (ld->cl_lstatus != NULL) {
1086 	    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
1087 	    ld->cl_lstatus = NULL;
1088 	}
1089     }
1090     if (cr != NULL)
1091 	ciss_release_request(cr);
1092 
1093     return(error);
1094 }
1095 
1096 /************************************************************************
1097  * Get status for a logical drive.
1098  *
1099  * XXX should we also do this in response to Test Unit Ready?
1100  */
1101 static int
1102 ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld)
1103 {
1104     struct ciss_request		*cr;
1105     struct ciss_command		*cc;
1106     struct ciss_bmic_cdb	*cbc;
1107     int				error, command_status;
1108 
1109     /*
1110      * Build a CISS BMIC command to get the logical drive status.
1111      */
1112     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LSTATUS,
1113 				       (void **)&ld->cl_lstatus,
1114 				       sizeof(*ld->cl_lstatus))) != 0)
1115 	goto out;
1116     cc = CISS_FIND_COMMAND(cr);
1117     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1118     cbc->log_drive = ld->cl_address.logical.lun;
1119 
1120     /*
1121      * Submit the request and wait for it to complete.
1122      */
1123     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1124 	ciss_printf(sc, "error sending BMIC LSTATUS command (%d)\n", error);
1125 	goto out;
1126     }
1127 
1128     /*
1129      * Check response.
1130      */
1131     ciss_report_request(cr, &command_status, NULL);
1132     switch(command_status) {
1133     case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1134 	break;
1135     case CISS_CMD_STATUS_DATA_UNDERRUN:
1136     case CISS_CMD_STATUS_DATA_OVERRUN:
1137 	ciss_printf(sc, "data over/underrun reading logical drive status\n");
1138     default:
1139 	ciss_printf(sc, "error reading logical drive status (%s)\n",
1140 		    ciss_name_command_status(command_status));
1141 	error = EIO;
1142 	goto out;
1143     }
1144 
1145     /*
1146      * Set the drive's summary status based on the returned status.
1147      *
1148      * XXX testing shows that a failed JBOD drive comes back at next
1149      * boot in "queued for expansion" mode.  WTF?
1150      */
1151     ld->cl_status = ciss_decode_ldrive_status(ld->cl_lstatus->status);
1152 
1153 out:
1154     if (cr != NULL)
1155 	ciss_release_request(cr);
1156     return(error);
1157 }
1158 
1159 /************************************************************************
1160  * Notify the adapter of a config update.
1161  */
1162 static int
1163 ciss_update_config(struct ciss_softc *sc)
1164 {
1165     int		i;
1166 
1167     debug_called(1);
1168 
1169     CISS_TL_SIMPLE_WRITE(sc, CISS_TL_SIMPLE_IDBR, CISS_TL_SIMPLE_IDBR_CFG_TABLE);
1170     for (i = 0; i < 1000; i++) {
1171 	if (!(CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR) &
1172 	      CISS_TL_SIMPLE_IDBR_CFG_TABLE)) {
1173 	    return(0);
1174 	}
1175 	DELAY(1000);
1176     }
1177     return(1);
1178 }
1179 
1180 /************************************************************************
1181  * Accept new media into a logical drive.
1182  *
1183  * XXX The drive has previously been offline; it would be good if we
1184  *     could make sure it's not open right now.
1185  */
1186 static int
1187 ciss_accept_media(struct ciss_softc *sc, int ldrive, int async)
1188 {
1189     struct ciss_request		*cr;
1190     struct ciss_command		*cc;
1191     struct ciss_bmic_cdb	*cbc;
1192     int				error;
1193 
1194     debug(0, "bringing logical drive %d back online %ssynchronously",
1195 	  ldrive, async ? "a" : "");
1196 
1197     /*
1198      * Build a CISS BMIC command to bring the drive back online.
1199      */
1200     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ACCEPT_MEDIA,
1201 				       NULL, 0)) != 0)
1202 	goto out;
1203     cc = CISS_FIND_COMMAND(cr);
1204     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1205     cbc->log_drive = ldrive;
1206 
1207     /*
1208      * Dispatch the request asynchronously if we can't sleep waiting
1209      * for it to complete.
1210      */
1211     if (async) {
1212 	cr->cr_complete = ciss_accept_media_complete;
1213 	if ((error = ciss_start(cr)) != 0)
1214 	    goto out;
1215 	return(0);
1216     } else {
1217 	/*
1218 	 * Submit the request and wait for it to complete.
1219 	 */
1220 	if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1221 	    ciss_printf(sc, "error sending BMIC LSTATUS command (%d)\n", error);
1222 	    goto out;
1223 	}
1224     }
1225 
1226     /*
1227      * Call the completion callback manually.
1228      */
1229     ciss_accept_media_complete(cr);
1230     return(0);
1231 
1232 out:
1233     if (cr != NULL)
1234 	ciss_release_request(cr);
1235     return(error);
1236 }
1237 
1238 static void
1239 ciss_accept_media_complete(struct ciss_request *cr)
1240 {
1241     int				command_status;
1242 
1243     /*
1244      * Check response.
1245      */
1246     ciss_report_request(cr, &command_status, NULL);
1247     switch(command_status) {
1248     case CISS_CMD_STATUS_SUCCESS:		/* all OK */
1249 	/* we should get a logical drive status changed event here */
1250 	break;
1251     default:
1252 	ciss_printf(cr->cr_sc, "error accepting media into failed logical drive (%s)\n",
1253 		    ciss_name_command_status(command_status));
1254 	break;
1255     }
1256     ciss_release_request(cr);
1257 }
1258 
1259 /************************************************************************
1260  * Release adapter resources.
1261  */
1262 static void
1263 ciss_free(struct ciss_softc *sc)
1264 {
1265     debug_called(1);
1266 
1267     /* we're going away */
1268     sc->ciss_flags |= CISS_FLAG_ABORTING;
1269 
1270     /* terminate the periodic heartbeat routine */
1271     untimeout(ciss_periodic, sc, sc->ciss_periodic);
1272 
1273     /* cancel the Event Notify chain */
1274     ciss_notify_abort(sc);
1275 
1276     /* free the controller data */
1277     if (sc->ciss_id != NULL)
1278 	free(sc->ciss_id, CISS_MALLOC_CLASS);
1279 
1280     /* release I/O resources */
1281     if (sc->ciss_regs_resource != NULL)
1282 	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1283 			     sc->ciss_regs_rid, sc->ciss_regs_resource);
1284     if (sc->ciss_cfg_resource != NULL)
1285 	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1286 			     sc->ciss_cfg_rid, sc->ciss_cfg_resource);
1287     if (sc->ciss_intr != NULL)
1288 	bus_teardown_intr(sc->ciss_dev, sc->ciss_irq_resource, sc->ciss_intr);
1289     if (sc->ciss_irq_resource != NULL)
1290 	bus_release_resource(sc->ciss_dev, SYS_RES_IRQ,
1291 			     sc->ciss_irq_rid, sc->ciss_irq_resource);
1292 
1293     /* destroy DMA tags */
1294     if (sc->ciss_parent_dmat)
1295 	bus_dma_tag_destroy(sc->ciss_parent_dmat);
1296     if (sc->ciss_buffer_dmat)
1297 	bus_dma_tag_destroy(sc->ciss_buffer_dmat);
1298 
1299     /* destroy command memory and DMA tag */
1300     if (sc->ciss_command != NULL) {
1301 	bus_dmamap_unload(sc->ciss_command_dmat, sc->ciss_command_map);
1302 	bus_dmamem_free(sc->ciss_command_dmat, sc->ciss_command, sc->ciss_command_map);
1303     }
1304     if (sc->ciss_buffer_dmat)
1305 	bus_dma_tag_destroy(sc->ciss_command_dmat);
1306 
1307     /* disconnect from CAM */
1308     if (sc->ciss_cam_sim) {
1309 	xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim));
1310 	cam_sim_free(sc->ciss_cam_sim, 0);
1311     }
1312     if (sc->ciss_cam_devq)
1313 	cam_simq_free(sc->ciss_cam_devq);
1314     /* XXX what about ciss_cam_path? */
1315 }
1316 
1317 /************************************************************************
1318  * Give a command to the adapter.
1319  *
1320  * Note that this uses the simple transport layer directly.  If we
1321  * want to add support for other layers, we'll need a switch of some
1322  * sort.
1323  *
1324  * Note that the simple transport layer has no way of refusing a
1325  * command; we only have as many request structures as the adapter
1326  * supports commands, so we don't have to check (this presumes that
1327  * the adapter can handle commands as fast as we throw them at it).
1328  */
1329 static int
1330 ciss_start(struct ciss_request *cr)
1331 {
1332     struct ciss_command	*cc;	/* XXX debugging only */
1333     int			error;
1334 
1335     cc = CISS_FIND_COMMAND(cr);
1336     debug(2, "post command %d tag %d ", cr->cr_tag, cc->header.host_tag);
1337 
1338     /*
1339      * Map the request's data.
1340      */
1341     if ((error = ciss_map_request(cr)))
1342 	return(error);
1343 
1344 #if 0
1345     ciss_print_request(cr);
1346 #endif
1347 
1348     /*
1349      * Post the command to the adapter.
1350      */
1351     ciss_enqueue_busy(cr);
1352     CISS_TL_SIMPLE_POST_CMD(cr->cr_sc, CISS_FIND_COMMANDPHYS(cr));
1353 
1354     return(0);
1355 }
1356 
1357 /************************************************************************
1358  * Fetch completed request(s) from the adapter, queue them for
1359  * completion handling.
1360  *
1361  * Note that this uses the simple transport layer directly.  If we
1362  * want to add support for other layers, we'll need a switch of some
1363  * sort.
1364  *
1365  * Note that the simple transport mechanism does not require any
1366  * reentrancy protection; the OPQ read is atomic.  If there is a
1367  * chance of a race with something else that might move the request
1368  * off the busy list, then we will have to lock against that
1369  * (eg. timeouts, etc.)
1370  */
1371 static void
1372 ciss_done(struct ciss_softc *sc)
1373 {
1374     struct ciss_request	*cr;
1375     struct ciss_command	*cc;
1376     u_int32_t		tag, index;
1377     int			complete;
1378 
1379     debug_called(3);
1380 
1381     /*
1382      * Loop quickly taking requests from the adapter and moving them
1383      * from the busy queue to the completed queue.
1384      */
1385     complete = 0;
1386     for (;;) {
1387 
1388 	/* see if the OPQ contains anything */
1389 	if (!CISS_TL_SIMPLE_OPQ_INTERRUPT(sc))
1390 	    break;
1391 
1392 	tag = CISS_TL_SIMPLE_FETCH_CMD(sc);
1393 	if (tag == CISS_TL_SIMPLE_OPQ_EMPTY)
1394 	    break;
1395 	index = tag >> 2;
1396 	debug(2, "completed command %d%s", index,
1397 	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
1398 	if (index >= sc->ciss_max_requests) {
1399 	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
1400 	    continue;
1401 	}
1402 	cr = &(sc->ciss_request[index]);
1403 	cc = CISS_FIND_COMMAND(cr);
1404 	cc->header.host_tag = tag;	/* not updated by adapter */
1405 	if (ciss_remove_busy(cr)) {
1406 	    /* assume this is garbage out of the adapter */
1407 	    ciss_printf(sc, "completed nonbusy request %d\n", index);
1408 	} else {
1409 	    ciss_enqueue_complete(cr);
1410 	}
1411 	complete = 1;
1412     }
1413 
1414     /*
1415      * Invoke completion processing.  If we can defer this out of
1416      * interrupt context, that'd be good.
1417      */
1418     if (complete)
1419 	ciss_complete(sc);
1420 }
1421 
1422 /************************************************************************
1423  * Take an interrupt from the adapter.
1424  */
1425 static void
1426 ciss_intr(void *arg)
1427 {
1428     struct ciss_softc	*sc = (struct ciss_softc *)arg;
1429 
1430     /*
1431      * The only interrupt we recognise indicates that there are
1432      * entries in the outbound post queue.
1433      */
1434     ciss_done(sc);
1435 }
1436 
1437 /************************************************************************
1438  * Process completed requests.
1439  *
1440  * Requests can be completed in three fashions:
1441  *
1442  * - by invoking a callback function (cr_complete is non-null)
1443  * - by waking up a sleeper (cr_flags has CISS_REQ_SLEEP set)
1444  * - by clearing the CISS_REQ_POLL flag in interrupt/timeout context
1445  */
1446 static void
1447 ciss_complete(struct ciss_softc *sc)
1448 {
1449     struct ciss_request	*cr;
1450 
1451     debug_called(2);
1452 
1453     /*
1454      * Loop taking requests off the completed queue and performing
1455      * completion processing on them.
1456      */
1457     for (;;) {
1458 	if ((cr = ciss_dequeue_complete(sc)) == NULL)
1459 	    break;
1460 	ciss_unmap_request(cr);
1461 
1462 	/*
1463 	 * If the request has a callback, invoke it.
1464 	 */
1465 	if (cr->cr_complete != NULL) {
1466 	    cr->cr_complete(cr);
1467 	    continue;
1468 	}
1469 
1470 	/*
1471 	 * If someone is sleeping on this request, wake them up.
1472 	 */
1473 	if (cr->cr_flags & CISS_REQ_SLEEP) {
1474 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
1475 	    wakeup(cr);
1476 	    continue;
1477 	}
1478 
1479 	/*
1480 	 * If someone is polling this request for completion, signal.
1481 	 */
1482 	if (cr->cr_flags & CISS_REQ_POLL) {
1483 	    cr->cr_flags &= ~CISS_REQ_POLL;
1484 	    continue;
1485 	}
1486 
1487 	/*
1488 	 * Give up and throw the request back on the free queue.  This
1489 	 * should never happen; resources will probably be lost.
1490 	 */
1491 	ciss_printf(sc, "WARNING: completed command with no submitter\n");
1492 	ciss_enqueue_free(cr);
1493     }
1494 }
1495 
1496 /************************************************************************
1497  * Report on the completion status of a request, and pass back SCSI
1498  * and command status values.
1499  */
1500 static int
1501 ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status)
1502 {
1503     struct ciss_command		*cc;
1504     struct ciss_error_info	*ce;
1505 
1506     debug_called(2);
1507 
1508     cc = CISS_FIND_COMMAND(cr);
1509     ce = (struct ciss_error_info *)&(cc->sg[0]);
1510 
1511     /*
1512      * We don't consider data under/overrun an error for the Report
1513      * Logical/Physical LUNs commands.
1514      */
1515     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) &&
1516 	((cc->cdb.cdb[0] == CISS_OPCODE_REPORT_LOGICAL_LUNS) ||
1517 	 (cc->cdb.cdb[0] == CISS_OPCODE_REPORT_PHYSICAL_LUNS))) {
1518 	cc->header.host_tag &= ~CISS_HDR_HOST_TAG_ERROR;
1519 	debug(2, "ignoring irrelevant under/overrun error");
1520     }
1521 
1522     /*
1523      * Check the command's error bit, if clear, there's no status and
1524      * everything is OK.
1525      */
1526     if (!(cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR)) {
1527 	if (scsi_status != NULL)
1528 	    *scsi_status = SCSI_STATUS_OK;
1529 	if (command_status != NULL)
1530 	    *command_status = CISS_CMD_STATUS_SUCCESS;
1531 	return(0);
1532     } else {
1533 	if (command_status != NULL)
1534 	    *command_status = ce->command_status;
1535 	if (scsi_status != NULL) {
1536 	    if (ce->command_status == CISS_CMD_STATUS_TARGET_STATUS) {
1537 		*scsi_status = ce->scsi_status;
1538 	    } else {
1539 		*scsi_status = -1;
1540 	    }
1541 	}
1542 	if (bootverbose)
1543 	    ciss_printf(cr->cr_sc, "command status 0x%x (%s) scsi status 0x%x\n",
1544 			ce->command_status, ciss_name_command_status(ce->command_status),
1545 			ce->scsi_status);
1546 	if (ce->command_status == CISS_CMD_STATUS_INVALID_COMMAND) {
1547 	    ciss_printf(cr->cr_sc, "invalid command, offense size %d at %d, value 0x%x\n",
1548 			ce->additional_error_info.invalid_command.offense_size,
1549 			ce->additional_error_info.invalid_command.offense_offset,
1550 			ce->additional_error_info.invalid_command.offense_value);
1551 	}
1552     }
1553     return(1);
1554 }
1555 
1556 /************************************************************************
1557  * Issue a request and don't return until it's completed.
1558  *
1559  * Depending on adapter status, we may poll or sleep waiting for
1560  * completion.
1561  */
1562 static int
1563 ciss_synch_request(struct ciss_request *cr, int timeout)
1564 {
1565     if (cr->cr_sc->ciss_flags & CISS_FLAG_RUNNING) {
1566 	return(ciss_wait_request(cr, timeout));
1567     } else {
1568 	return(ciss_poll_request(cr, timeout));
1569     }
1570 }
1571 
1572 /************************************************************************
1573  * Issue a request and poll for completion.
1574  *
1575  * Timeout in milliseconds.
1576  */
1577 static int
1578 ciss_poll_request(struct ciss_request *cr, int timeout)
1579 {
1580     int		error;
1581 
1582     debug_called(2);
1583 
1584     cr->cr_flags |= CISS_REQ_POLL;
1585     if ((error = ciss_start(cr)) != 0)
1586 	return(error);
1587 
1588     do {
1589 	ciss_done(cr->cr_sc);
1590 	if (!(cr->cr_flags & CISS_REQ_POLL))
1591 	    return(0);
1592 	DELAY(1000);
1593     } while (timeout-- >= 0);
1594     return(EWOULDBLOCK);
1595 }
1596 
1597 /************************************************************************
1598  * Issue a request and sleep waiting for completion.
1599  *
1600  * Timeout in milliseconds.  Note that a spurious wakeup will reset
1601  * the timeout.
1602  */
1603 static int
1604 ciss_wait_request(struct ciss_request *cr, int timeout)
1605 {
1606     int		s, error;
1607 
1608     debug_called(2);
1609 
1610     cr->cr_flags |= CISS_REQ_SLEEP;
1611     if ((error = ciss_start(cr)) != 0)
1612 	return(error);
1613 
1614     s = splcam();
1615     while (cr->cr_flags & CISS_REQ_SLEEP) {
1616 	error = tsleep(cr, PCATCH, "cissREQ", (timeout * hz) / 1000);
1617 	/*
1618 	 * On wakeup or interruption due to restartable activity, go
1619 	 * back and check to see if we're done.
1620 	 */
1621 	if ((error == 0) || (error == ERESTART)) {
1622 	    error = 0;
1623 	    continue;
1624 	}
1625 	/*
1626 	 * Timeout, interrupted system call, etc.
1627 	 */
1628 	break;
1629     }
1630     splx(s);
1631     return(error);
1632 }
1633 
1634 /************************************************************************
1635  * Abort a request.  Note that a potential exists here to race the
1636  * request being completed; the caller must deal with this.
1637  */
1638 static int
1639 ciss_abort_request(struct ciss_request *ar)
1640 {
1641     struct ciss_request		*cr;
1642     struct ciss_command		*cc;
1643     struct ciss_message_cdb	*cmc;
1644     int				error;
1645 
1646     debug_called(1);
1647 
1648     /* get a request */
1649     if ((error = ciss_get_request(ar->cr_sc, &cr)) != 0)
1650 	return(error);
1651 
1652     /* build the abort command */
1653     cc = CISS_FIND_COMMAND(cr);
1654     cc->header.address.mode.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;	/* addressing? */
1655     cc->header.address.physical.target = 0;
1656     cc->header.address.physical.bus = 0;
1657     cc->cdb.cdb_length = sizeof(*cmc);
1658     cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
1659     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1660     cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
1661     cc->cdb.timeout = 30;
1662 
1663     cmc = (struct ciss_message_cdb *)&(cc->cdb.cdb[0]);
1664     cmc->opcode = CISS_OPCODE_MESSAGE_ABORT;
1665     cmc->type = CISS_MESSAGE_ABORT_TASK;
1666     cmc->abort_tag = ar->cr_tag;	/* endianness?? */
1667 
1668     /*
1669      * Send the request and wait for a response.  If we believe we
1670      * aborted the request OK, clear the flag that indicates it's
1671      * running.
1672      */
1673     error = ciss_synch_request(cr, 35 * 1000);
1674     if (!error)
1675 	error = ciss_report_request(cr, NULL, NULL);
1676     ciss_release_request(cr);
1677 
1678     return(error);
1679 }
1680 
1681 
1682 /************************************************************************
1683  * Fetch and initialise a request
1684  */
1685 static int
1686 ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp)
1687 {
1688     struct ciss_request *cr;
1689 
1690     debug_called(2);
1691 
1692     /*
1693      * Get a request and clean it up.
1694      */
1695     if ((cr = ciss_dequeue_free(sc)) == NULL)
1696 	return(ENOMEM);
1697 
1698     cr->cr_data = NULL;
1699     cr->cr_flags = 0;
1700     cr->cr_complete = NULL;
1701 
1702     ciss_preen_command(cr);
1703     *crp = cr;
1704     return(0);
1705 }
1706 
1707 static void
1708 ciss_preen_command(struct ciss_request *cr)
1709 {
1710     struct ciss_command	*cc;
1711     u_int32_t		cmdphys;
1712 
1713     /*
1714      * Clean up the command structure.
1715      *
1716      * Note that we set up the error_info structure here, since the
1717      * length can be overwritten by any command.
1718      */
1719     cc = CISS_FIND_COMMAND(cr);
1720     cc->header.sg_in_list = 0;		/* kinda inefficient this way */
1721     cc->header.sg_total = 0;
1722     cc->header.host_tag = cr->cr_tag << 2;
1723     cc->header.host_tag_zeroes = 0;
1724     cmdphys = CISS_FIND_COMMANDPHYS(cr);
1725     cc->error_info.error_info_address = cmdphys + sizeof(struct ciss_command);
1726     cc->error_info.error_info_length = CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command);
1727 
1728 }
1729 
1730 /************************************************************************
1731  * Release a request to the free list.
1732  */
1733 static void
1734 ciss_release_request(struct ciss_request *cr)
1735 {
1736     struct ciss_softc	*sc;
1737 
1738     debug_called(2);
1739 
1740     sc = cr->cr_sc;
1741 
1742     /* release the request to the free queue */
1743     ciss_requeue_free(cr);
1744 }
1745 
1746 /************************************************************************
1747  * Allocate a request that will be used to send a BMIC command.  Do some
1748  * of the common setup here to avoid duplicating it everywhere else.
1749  */
1750 static int
1751 ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
1752 		      int opcode, void **bufp, size_t bufsize)
1753 {
1754     struct ciss_request		*cr;
1755     struct ciss_command		*cc;
1756     struct ciss_bmic_cdb	*cbc;
1757     void			*buf;
1758     int				error;
1759     int				dataout;
1760 
1761     debug_called(2);
1762 
1763     cr = NULL;
1764     buf = NULL;
1765 
1766     /*
1767      * Get a request.
1768      */
1769     if ((error = ciss_get_request(sc, &cr)) != 0)
1770 	goto out;
1771 
1772     /*
1773      * Allocate data storage if requested, determine the data direction.
1774      */
1775     dataout = 0;
1776     if ((bufsize > 0) && (bufp != NULL)) {
1777 	if (*bufp == NULL) {
1778 	    if ((buf = malloc(bufsize, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
1779 		error = ENOMEM;
1780 		goto out;
1781 	    }
1782 	} else {
1783 	    buf = *bufp;
1784 	    dataout = 1;	/* we are given a buffer, so we are writing */
1785 	}
1786     }
1787 
1788     /*
1789      * Build a CISS BMIC command to get the logical drive ID.
1790      */
1791     cr->cr_data = buf;
1792     cr->cr_length = bufsize;
1793     if (!dataout)
1794 	cr->cr_flags = CISS_REQ_DATAIN;
1795 
1796     cc = CISS_FIND_COMMAND(cr);
1797     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
1798     cc->header.address.physical.bus = 0;
1799     cc->header.address.physical.target = 0;
1800     cc->cdb.cdb_length = sizeof(*cbc);
1801     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1802     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1803     cc->cdb.direction = dataout ? CISS_CDB_DIRECTION_WRITE : CISS_CDB_DIRECTION_READ;
1804     cc->cdb.timeout = 0;
1805 
1806     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1807     bzero(cbc, sizeof(*cbc));
1808     cbc->opcode = dataout ? CISS_ARRAY_CONTROLLER_WRITE : CISS_ARRAY_CONTROLLER_READ;
1809     cbc->bmic_opcode = opcode;
1810     cbc->size = htons((u_int16_t)bufsize);
1811 
1812 out:
1813     if (error) {
1814 	if (cr != NULL)
1815 	    ciss_release_request(cr);
1816 	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
1817 	    free(buf, CISS_MALLOC_CLASS);
1818     } else {
1819 	*crp = cr;
1820 	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
1821 	    *bufp = buf;
1822     }
1823     return(error);
1824 }
1825 
1826 /************************************************************************
1827  * Handle a command passed in from userspace.
1828  */
1829 static int
1830 ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
1831 {
1832     struct ciss_request		*cr;
1833     struct ciss_command		*cc;
1834     struct ciss_error_info	*ce;
1835     int				error;
1836 
1837     debug_called(1);
1838 
1839     cr = NULL;
1840 
1841     /*
1842      * Get a request.
1843      */
1844     if ((error = ciss_get_request(sc, &cr)) != 0)
1845 	goto out;
1846     cc = CISS_FIND_COMMAND(cr);
1847 
1848     /*
1849      * Allocate an in-kernel databuffer if required, copy in user data.
1850      */
1851     cr->cr_length = ioc->buf_size;
1852     if (ioc->buf_size > 0) {
1853 	if ((cr->cr_data = malloc(ioc->buf_size, CISS_MALLOC_CLASS, M_WAITOK)) == NULL) {
1854 	    error = ENOMEM;
1855 	    goto out;
1856 	}
1857 	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
1858 	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
1859 	    goto out;
1860 	}
1861     }
1862 
1863     /*
1864      * Build the request based on the user command.
1865      */
1866     bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
1867     bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
1868 
1869     /* XXX anything else to populate here? */
1870 
1871     /*
1872      * Run the command.
1873      */
1874     if ((error = ciss_synch_request(cr, 60 * 1000))) {
1875 	debug(0, "request failed - %d", error);
1876 	goto out;
1877     }
1878 
1879     /*
1880      * Copy the results back to the user.
1881      */
1882     ce = (struct ciss_error_info *)&(cc->sg[0]);
1883     bcopy(ce, &ioc->error_info, sizeof(*ce));
1884     if ((ioc->buf_size > 0) &&
1885 	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
1886 	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
1887 	goto out;
1888     }
1889 
1890     /* done OK */
1891     error = 0;
1892 
1893 out:
1894     if ((cr != NULL) && (cr->cr_data != NULL))
1895 	free(cr->cr_data, CISS_MALLOC_CLASS);
1896     if (cr != NULL)
1897 	ciss_release_request(cr);
1898     return(error);
1899 }
1900 
1901 /************************************************************************
1902  * Map a request into bus-visible space, initialise the scatter/gather
1903  * list.
1904  */
1905 static int
1906 ciss_map_request(struct ciss_request *cr)
1907 {
1908     struct ciss_softc	*sc;
1909 
1910     debug_called(2);
1911 
1912     sc = cr->cr_sc;
1913 
1914     /* check that mapping is necessary */
1915     if ((cr->cr_flags & CISS_REQ_MAPPED) || (cr->cr_data == NULL))
1916 	return(0);
1917 
1918     bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap, cr->cr_data, cr->cr_length,
1919 		    ciss_request_map_helper, CISS_FIND_COMMAND(cr), 0);
1920 
1921     if (cr->cr_flags & CISS_REQ_DATAIN)
1922 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
1923     if (cr->cr_flags & CISS_REQ_DATAOUT)
1924 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
1925 
1926     cr->cr_flags |= CISS_REQ_MAPPED;
1927     return(0);
1928 }
1929 
1930 static void
1931 ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1932 {
1933     struct ciss_command	*cc;
1934     int			i;
1935 
1936     debug_called(2);
1937 
1938     cc = (struct ciss_command *)arg;
1939     for (i = 0; i < nseg; i++) {
1940 	cc->sg[i].address = segs[i].ds_addr;
1941 	cc->sg[i].length = segs[i].ds_len;
1942 	cc->sg[i].extension = 0;
1943     }
1944     /* we leave the s/g table entirely within the command */
1945     cc->header.sg_in_list = nseg;
1946     cc->header.sg_total = nseg;
1947 }
1948 
1949 /************************************************************************
1950  * Unmap a request from bus-visible space.
1951  */
1952 static void
1953 ciss_unmap_request(struct ciss_request *cr)
1954 {
1955     struct ciss_softc	*sc;
1956 
1957     debug_called(2);
1958 
1959     sc = cr->cr_sc;
1960 
1961     /* check that unmapping is necessary */
1962     if (!(cr->cr_flags & CISS_REQ_MAPPED) || (cr->cr_data == NULL))
1963 	return;
1964 
1965     if (cr->cr_flags & CISS_REQ_DATAIN)
1966 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
1967     if (cr->cr_flags & CISS_REQ_DATAOUT)
1968 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
1969 
1970     bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
1971     cr->cr_flags &= ~CISS_REQ_MAPPED;
1972 }
1973 
1974 /************************************************************************
1975  * Attach the driver to CAM.
1976  *
1977  * We put all the logical drives on a single SCSI bus.
1978  */
1979 static int
1980 ciss_cam_init(struct ciss_softc *sc)
1981 {
1982 
1983     debug_called(1);
1984 
1985     /*
1986      * Allocate a devq.  We can reuse this for the masked physical
1987      * devices if we decide to export these as well.
1988      */
1989     if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests)) == NULL) {
1990 	ciss_printf(sc, "can't allocate CAM SIM queue\n");
1991 	return(ENOMEM);
1992     }
1993 
1994     /*
1995      * Create a SIM.
1996      */
1997     if ((sc->ciss_cam_sim = cam_sim_alloc(ciss_cam_action, ciss_cam_poll, "ciss", sc,
1998 					  device_get_unit(sc->ciss_dev), 1,
1999 					  sc->ciss_cfg->max_outstanding_commands,
2000 					  sc->ciss_cam_devq)) == NULL) {
2001 	ciss_printf(sc, "can't allocate CAM SIM\n");
2002 	return(ENOMEM);
2003     }
2004 
2005     /*
2006      * Register bus 0 (the 'logical drives' bus) with this SIM.
2007      */
2008     if (xpt_bus_register(sc->ciss_cam_sim, 0) != 0) {
2009 	ciss_printf(sc, "can't register SCSI bus 0\n");
2010 	return(ENXIO);
2011     }
2012 
2013     /*
2014      * Initiate a rescan of the bus.
2015      */
2016     ciss_cam_rescan_all(sc);
2017 
2018     return(0);
2019 }
2020 
2021 /************************************************************************
2022  * Initiate a rescan of the 'logical devices' SIM
2023  */
2024 static void
2025 ciss_cam_rescan_target(struct ciss_softc *sc, int target)
2026 {
2027     union ccb	*ccb;
2028 
2029     debug_called(1);
2030 
2031     if ((ccb = malloc(sizeof(union ccb), M_TEMP, M_WAITOK | M_ZERO)) == NULL) {
2032 	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2033 	return;
2034     }
2035 
2036     if (xpt_create_path(&sc->ciss_cam_path, xpt_periph, cam_sim_path(sc->ciss_cam_sim), target, 0)
2037 	!= CAM_REQ_CMP) {
2038 	ciss_printf(sc, "rescan failed (can't create path)\n");
2039 	return;
2040     }
2041 
2042     xpt_setup_ccb(&ccb->ccb_h, sc->ciss_cam_path, 5/*priority (low)*/);
2043     ccb->ccb_h.func_code = XPT_SCAN_BUS;
2044     ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2045     ccb->crcn.flags = CAM_FLAG_NONE;
2046     xpt_action(ccb);
2047 
2048     /* scan is now in progress */
2049 }
2050 
2051 static void
2052 ciss_cam_rescan_all(struct ciss_softc *sc)
2053 {
2054     return(ciss_cam_rescan_target(sc, 0));
2055 }
2056 
2057 static void
2058 ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2059 {
2060     free(ccb, M_TEMP);
2061 }
2062 
2063 /************************************************************************
2064  * Handle requests coming from CAM
2065  */
2066 static void
2067 ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2068 {
2069     switch (ccb->ccb_h.func_code) {
2070 
2071 	/* perform SCSI I/O */
2072     case XPT_SCSI_IO:
2073 	if (!ciss_cam_action_io(sim, (struct ccb_scsiio *)&ccb->csio))
2074 	    return;
2075 	break;
2076 
2077 	/* perform geometry calculations */
2078     case XPT_CALC_GEOMETRY:
2079     {
2080 	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2081         u_int32_t			secs_per_cylinder;
2082 
2083 	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2084 
2085 	/*
2086 	 * This is the default geometry; hopefully we will have
2087 	 * successfully talked to the 'disk' and obtained its private
2088 	 * settings.
2089 	 */
2090 	ccg->heads = 255;
2091 	ccg->secs_per_track = 32;
2092 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2093         ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2094         ccb->ccb_h.status = CAM_REQ_CMP;
2095         break;
2096     }
2097 
2098 	/* handle path attribute inquiry */
2099     case XPT_PATH_INQ:
2100     {
2101 	struct ccb_pathinq	*cpi = &ccb->cpi;
2102 
2103 	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2104 
2105 	cpi->version_num = 1;
2106 	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2107 	cpi->target_sprt = 0;
2108 	cpi->hba_misc = 0;
2109 	cpi->max_target = CISS_MAX_LOGICAL;
2110 	cpi->max_lun = 0;		/* 'logical drive' channel only */
2111 	cpi->initiator_id = CISS_MAX_LOGICAL;
2112 	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2113         strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2114         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2115         cpi->unit_number = cam_sim_unit(sim);
2116         cpi->bus_id = cam_sim_bus(sim);
2117 	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2118 	ccb->ccb_h.status = CAM_REQ_CMP;
2119 	break;
2120     }
2121 
2122     case XPT_GET_TRAN_SETTINGS:
2123     {
2124 	struct ccb_trans_settings	*cts = &ccb->cts;
2125 	int				bus, target;
2126 
2127 	bus = cam_sim_bus(sim);
2128 	target = cts->ccb_h.target_id;
2129 
2130 	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2131 	cts->valid = 0;
2132 
2133 	/* disconnect always OK */
2134 	cts->flags |= CCB_TRANS_DISC_ENB;
2135 	cts->valid |= CCB_TRANS_DISC_VALID;
2136 
2137 	cts->ccb_h.status = CAM_REQ_CMP;
2138 	break;
2139     }
2140 
2141     default:		/* we can't do this */
2142 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
2143 	ccb->ccb_h.status = CAM_REQ_INVALID;
2144 	break;
2145     }
2146 
2147     xpt_done(ccb);
2148 }
2149 
2150 /************************************************************************
2151  * Handle a CAM SCSI I/O request.
2152  */
2153 static int
2154 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
2155 {
2156     struct ciss_softc	*sc;
2157     int			bus, target;
2158     struct ciss_request	*cr;
2159     struct ciss_command	*cc;
2160     int			error;
2161 
2162     sc = cam_sim_softc(sim);
2163     bus = cam_sim_bus(sim);
2164     target = csio->ccb_h.target_id;
2165 
2166     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
2167 
2168     /* check for I/O attempt to nonexistent device */
2169     if ((bus != 0) ||
2170 	(target > CISS_MAX_LOGICAL) ||
2171 	(sc->ciss_logical[target].cl_status == CISS_LD_NONEXISTENT)) {
2172 	debug(3, "  device does not exist");
2173 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2174     }
2175 
2176     /* firmware does not support commands > 10 bytes */
2177     if (csio->cdb_len > 12/*CISS_CDB_BUFFER_SIZE*/) {
2178 	debug(3, "  command too large (%d > %d)", csio->cdb_len, CISS_CDB_BUFFER_SIZE);
2179 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2180     }
2181 
2182     /* check that the CDB pointer is not to a physical address */
2183     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
2184 	debug(3, "  CDB pointer is to physical address");
2185 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2186     }
2187 
2188     /* if there is data transfer, it must be to/from a virtual address */
2189     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2190 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
2191 	    debug(3, "  data pointer is to physical address");
2192 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2193 	}
2194 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
2195 	    debug(3, "  data has premature s/g setup");
2196 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2197 	}
2198     }
2199 
2200     /* abandon aborted ccbs or those that have failed validation */
2201     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2202 	debug(3, "abandoning CCB due to abort/validation failure");
2203 	return(EINVAL);
2204     }
2205 
2206     /* handle emulation of some SCSI commands ourself */
2207     if (ciss_cam_emulate(sc, csio))
2208 	return(0);
2209 
2210     /*
2211      * Get a request to manage this command.  If we can't, return the
2212      * ccb, freeze the queue and flag so that we unfreeze it when a
2213      * request completes.
2214      */
2215     if ((error = ciss_get_request(sc, &cr)) != 0) {
2216 	xpt_freeze_simq(sc->ciss_cam_sim, 1);
2217 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
2218 	return(error);
2219     }
2220 
2221     /*
2222      * Build the command.
2223      */
2224     cc = CISS_FIND_COMMAND(cr);
2225     cr->cr_data = csio->data_ptr;
2226     cr->cr_length = csio->dxfer_len;
2227     cr->cr_complete = ciss_cam_complete;
2228     cr->cr_private = csio;
2229 
2230     cc->header.address.logical.mode = CISS_HDR_ADDRESS_MODE_LOGICAL;
2231     cc->header.address.logical.lun = target;
2232     cc->cdb.cdb_length = csio->cdb_len;
2233     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2234     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
2235     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2236 	cr->cr_flags = CISS_REQ_DATAOUT;
2237 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
2238     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2239 	cr->cr_flags = CISS_REQ_DATAIN;
2240 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2241     } else {
2242 	cr->cr_flags = 0;
2243 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2244     }
2245     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
2246     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2247 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
2248     } else {
2249 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
2250     }
2251 
2252     /*
2253      * Submit the request to the adapter.
2254      *
2255      * Note that this may fail if we're unable to map the request (and
2256      * if we ever learn a transport layer other than simple, may fail
2257      * if the adapter rejects the command).
2258      */
2259     if ((error = ciss_start(cr)) != 0) {
2260 	xpt_freeze_simq(sc->ciss_cam_sim, 1);
2261 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
2262 	ciss_release_request(cr);
2263 	return(error);
2264     }
2265 
2266     return(0);
2267 }
2268 
2269 /************************************************************************
2270  * Emulate SCSI commands the adapter doesn't handle as we might like.
2271  */
2272 static int
2273 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
2274 {
2275     int		target;
2276     u_int8_t	opcode;
2277 
2278 
2279     target = csio->ccb_h.target_id;
2280     opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
2281 	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
2282 
2283     /*
2284      * Handle requests for volumes that don't exist.  A selection timeout
2285      * is slightly better than an illegal request.  Other errors might be
2286      * better.
2287      */
2288     if (sc->ciss_logical[target].cl_status == CISS_LD_NONEXISTENT) {
2289 	csio->ccb_h.status = CAM_SEL_TIMEOUT;
2290 	xpt_done((union ccb *)csio);
2291 	return(1);
2292     }
2293 
2294     /*
2295      * Handle requests for volumes that exist but are offline.
2296      *
2297      * I/O operations should fail, everything else should work.
2298      */
2299     if (sc->ciss_logical[target].cl_status == CISS_LD_OFFLINE) {
2300 	switch(opcode) {
2301 	case READ_6:
2302 	case READ_10:
2303 	case READ_12:
2304 	case WRITE_6:
2305 	case WRITE_10:
2306 	case WRITE_12:
2307 	    csio->ccb_h.status = CAM_SEL_TIMEOUT;
2308 	    xpt_done((union ccb *)csio);
2309 	    return(1);
2310 	}
2311     }
2312 
2313 
2314     /* if we have to fake Synchronise Cache */
2315     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
2316 
2317 	/*
2318 	 * If this is a Synchronise Cache command, typically issued when
2319 	 * a device is closed, flush the adapter and complete now.
2320 	 */
2321 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2322 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
2323 	    ciss_flush_adapter(sc);
2324 	    csio->ccb_h.status = CAM_REQ_CMP;
2325 	    xpt_done((union ccb *)csio);
2326 	    return(1);
2327 	}
2328     }
2329 
2330     return(0);
2331 }
2332 
2333 /************************************************************************
2334  * Check for possibly-completed commands.
2335  */
2336 static void
2337 ciss_cam_poll(struct cam_sim *sim)
2338 {
2339     struct ciss_softc	*sc = cam_sim_softc(sim);
2340 
2341     debug_called(2);
2342 
2343     ciss_done(sc);
2344 }
2345 
2346 /************************************************************************
2347  * Handle completion of a command - pass results back through the CCB
2348  */
2349 static void
2350 ciss_cam_complete(struct ciss_request *cr)
2351 {
2352     struct ciss_softc		*sc;
2353     struct ciss_command		*cc;
2354     struct ciss_error_info	*ce;
2355     struct ccb_scsiio		*csio;
2356     int				scsi_status;
2357     int				command_status;
2358 
2359     debug_called(2);
2360 
2361     sc = cr->cr_sc;
2362     cc = CISS_FIND_COMMAND(cr);
2363     ce = (struct ciss_error_info *)&(cc->sg[0]);
2364     csio = (struct ccb_scsiio *)cr->cr_private;
2365 
2366     /*
2367      * Extract status values from request.
2368      */
2369     ciss_report_request(cr, &command_status, &scsi_status);
2370     csio->scsi_status = scsi_status;
2371 
2372     /*
2373      * Handle specific SCSI status values.
2374      */
2375     switch(scsi_status) {
2376 	/* no status due to adapter error */
2377     case -1:
2378 	debug(0, "adapter error");
2379 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2380 	break;
2381 
2382 	/* no status due to command completed OK */
2383     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
2384 	debug(2, "SCSI_STATUS_OK");
2385 	csio->ccb_h.status = CAM_REQ_CMP;
2386 	break;
2387 
2388 	/* check condition, sense data included */
2389     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
2390 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d",
2391 	      ce->sense_length, ce->residual_count);
2392 	bzero(&csio->sense_data, SSD_FULL_SIZE);
2393 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
2394 	csio->sense_len = ce->sense_length;
2395 	csio->resid = ce->residual_count;
2396 	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
2397 #ifdef CISS_DEBUG
2398 	{
2399 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
2400 	    debug(0, "sense key %x", sns->flags & SSD_KEY);
2401 	}
2402 #endif
2403 	break;
2404 
2405     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
2406 	debug(0, "SCSI_STATUS_BUSY");
2407 	csio->ccb_h.status = CAM_SCSI_BUSY;
2408 	break;
2409 
2410     default:
2411 	debug(0, "unknown status 0x%x", csio->scsi_status);
2412 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2413 	break;
2414     }
2415 
2416     /* handle post-command fixup */
2417     ciss_cam_complete_fixup(sc, csio);
2418 
2419     xpt_done((union ccb *)csio);
2420     ciss_release_request(cr);
2421 }
2422 
2423 /********************************************************************************
2424  * Fix up the result of some commands here.
2425  */
2426 static void
2427 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
2428 {
2429     struct scsi_inquiry_data	*inq;
2430     struct ciss_ldrive		*cl;
2431     int				target;
2432 
2433     if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2434 	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
2435 
2436 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
2437 	target = csio->ccb_h.target_id;
2438 	cl = &sc->ciss_logical[target];
2439 
2440 	padstr(inq->vendor, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
2441 	padstr(inq->product, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
2442 	padstr(inq->revision, "", 4);
2443     }
2444 }
2445 
2446 
2447 /********************************************************************************
2448  * Find a peripheral attahed at (target)
2449  */
2450 static struct cam_periph *
2451 ciss_find_periph(struct ciss_softc *sc, int target)
2452 {
2453     struct cam_periph	*periph;
2454     struct cam_path	*path;
2455     int			status;
2456 
2457     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim), target, 0);
2458     if (status == CAM_REQ_CMP) {
2459 	periph = cam_periph_find(path, NULL);
2460 	xpt_free_path(path);
2461     } else {
2462 	periph = NULL;
2463     }
2464     return(periph);
2465 }
2466 
2467 /********************************************************************************
2468  * Name the device at (target)
2469  *
2470  * XXX is this strictly correct?
2471  */
2472 int
2473 ciss_name_device(struct ciss_softc *sc, int target)
2474 {
2475     struct cam_periph	*periph;
2476 
2477     if ((periph = ciss_find_periph(sc, target)) != NULL) {
2478 	sprintf(sc->ciss_logical[target].cl_name, "%s%d", periph->periph_name, periph->unit_number);
2479 	return(0);
2480     }
2481     sc->ciss_logical[target].cl_name[0] = 0;
2482     return(ENOENT);
2483 }
2484 
2485 /************************************************************************
2486  * Periodic status monitoring.
2487  */
2488 static void
2489 ciss_periodic(void *arg)
2490 {
2491     struct ciss_softc	*sc;
2492 
2493     debug_called(1);
2494 
2495     sc = (struct ciss_softc *)arg;
2496 
2497     /*
2498      * Check the adapter heartbeat.
2499      */
2500     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
2501 	sc->ciss_heart_attack++;
2502 	debug(0, "adapter heart attack in progress 0x%x/%d",
2503 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
2504 	if (sc->ciss_heart_attack == 3) {
2505 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
2506 	    /* XXX should reset adapter here */
2507 	}
2508     } else {
2509 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
2510 	sc->ciss_heart_attack = 0;
2511 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
2512     }
2513 
2514     /*
2515      * If the notify event request has died for some reason, or has
2516      * not started yet, restart it.
2517      */
2518     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
2519 	debug(0, "(re)starting Event Notify chain");
2520 	ciss_notify_event(sc);
2521     }
2522 
2523     /*
2524      * Reschedule.
2525      */
2526     if (!(sc->ciss_flags & CISS_FLAG_ABORTING))
2527 	sc->ciss_periodic = timeout(ciss_periodic, sc, CISS_HEARTBEAT_RATE * hz);
2528 }
2529 
2530 /************************************************************************
2531  * Request a notification response from the adapter.
2532  *
2533  * If (cr) is NULL, this is the first request of the adapter, so
2534  * reset the adapter's message pointer and start with the oldest
2535  * message available.
2536  */
2537 static void
2538 ciss_notify_event(struct ciss_softc *sc)
2539 {
2540     struct ciss_request		*cr;
2541     struct ciss_command		*cc;
2542     struct ciss_notify_cdb	*cnc;
2543     int				error;
2544 
2545     debug_called(1);
2546 
2547     cr = sc->ciss_periodic_notify;
2548 
2549     /* get a request if we don't already have one */
2550     if (cr == NULL) {
2551 	if ((error = ciss_get_request(sc, &cr)) != 0) {
2552 	    debug(0, "can't get notify event request");
2553 	    goto out;
2554 	}
2555 	sc->ciss_periodic_notify = cr;
2556 	cr->cr_complete = ciss_notify_complete;
2557 	debug(1, "acquired request %d", cr->cr_tag);
2558     }
2559 
2560     /*
2561      * Get a databuffer if we don't already have one, note that the
2562      * adapter command wants a larger buffer than the actual
2563      * structure.
2564      */
2565     if (cr->cr_data == NULL) {
2566 	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2567 	    debug(0, "can't get notify event request buffer");
2568 	    error = ENOMEM;
2569 	    goto out;
2570 	}
2571 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
2572     }
2573 
2574     /* re-setup the request's command (since we never release it) XXX overkill*/
2575     ciss_preen_command(cr);
2576 
2577     /* (re)build the notify event command */
2578     cc = CISS_FIND_COMMAND(cr);
2579     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2580     cc->header.address.physical.bus = 0;
2581     cc->header.address.physical.target = 0;
2582 
2583     cc->cdb.cdb_length = sizeof(*cnc);
2584     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2585     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2586     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2587     cc->cdb.timeout = 0;	/* no timeout, we hope */
2588 
2589     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
2590     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
2591     cnc->opcode = CISS_OPCODE_READ;
2592     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
2593     cnc->timeout = 0;		/* no timeout, we hope */
2594     cnc->synchronous = 0;
2595     cnc->ordered = 0;
2596     cnc->seek_to_oldest = 0;
2597     cnc->new_only = 0;
2598     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
2599 
2600     /* submit the request */
2601     error = ciss_start(cr);
2602 
2603  out:
2604     if (error) {
2605 	if (cr != NULL) {
2606 	    if (cr->cr_data != NULL)
2607 		free(cr->cr_data, CISS_MALLOC_CLASS);
2608 	    ciss_release_request(cr);
2609 	}
2610 	sc->ciss_periodic_notify = NULL;
2611 	debug(0, "can't submit notify event request");
2612 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2613     } else {
2614 	debug(1, "notify event submitted");
2615 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
2616     }
2617 }
2618 
2619 static void
2620 ciss_notify_complete(struct ciss_request *cr)
2621 {
2622     struct ciss_command	*cc;
2623     struct ciss_notify	*cn;
2624     struct ciss_softc	*sc;
2625     int			scsi_status;
2626     int			command_status;
2627 
2628     debug_called(1);
2629 
2630     cc = CISS_FIND_COMMAND(cr);
2631     cn = (struct ciss_notify *)cr->cr_data;
2632     sc = cr->cr_sc;
2633 
2634     /*
2635      * Report request results, decode status.
2636      */
2637     ciss_report_request(cr, &command_status, &scsi_status);
2638 
2639     /*
2640      * Abort the chain on a fatal error.
2641      *
2642      * XXX which of these are actually errors?
2643      */
2644     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
2645 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
2646 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
2647 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
2648 		    ciss_name_command_status(command_status));
2649 	ciss_release_request(cr);
2650 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2651 	return;
2652     }
2653 
2654     /*
2655      * If the adapter gave us a text message, print it.
2656      */
2657     if (cn->message[0] != 0)
2658 	ciss_printf(sc, "*** %.80s\n", cn->message);
2659 
2660     debug(0, "notify event class %d subclass %d detail %d",
2661 		cn->class, cn->subclass, cn->detail);
2662 
2663     /*
2664      * If there's room, save the event for a user-level tool.
2665      */
2666     if (((sc->ciss_notify_head + 1) % CISS_MAX_EVENTS) != sc->ciss_notify_tail) {
2667 	sc->ciss_notify[sc->ciss_notify_head] = *cn;
2668 	sc->ciss_notify_head = (sc->ciss_notify_head + 1) % CISS_MAX_EVENTS;
2669     }
2670 
2671     /*
2672      * Some events are directly of interest to us.
2673      */
2674     switch (cn->class) {
2675     case CISS_NOTIFY_LOGICAL:
2676 	ciss_notify_logical(sc, cn);
2677 	break;
2678     case CISS_NOTIFY_PHYSICAL:
2679 	ciss_notify_physical(sc, cn);
2680 	break;
2681     }
2682 
2683     /*
2684      * If the response indicates that the notifier has been aborted,
2685      * release the notifier command.
2686      */
2687     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
2688 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
2689 	(cn->detail == 1)) {
2690 	debug(0, "notifier exiting");
2691 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2692 	ciss_release_request(cr);
2693 	sc->ciss_periodic_notify = NULL;
2694 	wakeup(&sc->ciss_periodic_notify);
2695     }
2696 
2697     /*
2698      * Send a new notify event command, if we're not aborting.
2699      */
2700     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
2701 	ciss_notify_event(sc);
2702     }
2703 }
2704 
2705 /************************************************************************
2706  * Abort the Notify Event chain.
2707  *
2708  * Note that we can't just abort the command in progress; we have to
2709  * explicitly issue an Abort Notify Event command in order for the
2710  * adapter to clean up correctly.
2711  *
2712  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
2713  * the chain will not restart itself.
2714  */
2715 static int
2716 ciss_notify_abort(struct ciss_softc *sc)
2717 {
2718     struct ciss_request		*cr;
2719     struct ciss_command		*cc;
2720     struct ciss_notify_cdb	*cnc;
2721     int				error, s, command_status, scsi_status;
2722 
2723     debug_called(1);
2724 
2725     cr = NULL;
2726     error = 0;
2727 
2728     /* verify that there's an outstanding command */
2729     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
2730 	goto out;
2731 
2732     /* get a command to issue the abort with */
2733     if ((error = ciss_get_request(sc, &cr)))
2734 	goto out;
2735 
2736     /* get a buffer for the result */
2737     if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2738 	debug(0, "can't get notify event request buffer");
2739 	error = ENOMEM;
2740 	goto out;
2741     }
2742     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
2743 
2744     /* build the CDB */
2745     cc = CISS_FIND_COMMAND(cr);
2746     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2747     cc->header.address.physical.bus = 0;
2748     cc->header.address.physical.target = 0;
2749     cc->cdb.cdb_length = sizeof(*cnc);
2750     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2751     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2752     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2753     cc->cdb.timeout = 0;	/* no timeout, we hope */
2754 
2755     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
2756     bzero(cnc, sizeof(*cnc));
2757     cnc->opcode = CISS_OPCODE_WRITE;
2758     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
2759     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
2760 
2761     ciss_print_request(cr);
2762 
2763     /*
2764      * Submit the request and wait for it to complete.
2765      */
2766     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
2767 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
2768 	goto out;
2769     }
2770 
2771     /*
2772      * Check response.
2773      */
2774     ciss_report_request(cr, &command_status, &scsi_status);
2775     switch(command_status) {
2776     case CISS_CMD_STATUS_SUCCESS:
2777 	break;
2778     case CISS_CMD_STATUS_INVALID_COMMAND:
2779 	/*
2780 	 * Some older adapters don't support the CISS version of this
2781 	 * command.  Fall back to using the BMIC version.
2782 	 */
2783 	error = ciss_notify_abort_bmic(sc);
2784 	if (error != 0)
2785 	    goto out;
2786 	break;
2787 
2788     case CISS_CMD_STATUS_TARGET_STATUS:
2789 	/*
2790 	 * This can happen if the adapter thinks there wasn't an outstanding
2791 	 * Notify Event command but we did.  We clean up here.
2792 	 */
2793 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
2794 	    if (sc->ciss_periodic_notify != NULL)
2795 		ciss_release_request(sc->ciss_periodic_notify);
2796 	    error = 0;
2797 	    goto out;
2798 	}
2799 	/* FALLTHROUGH */
2800 
2801     default:
2802 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
2803 		    ciss_name_command_status(command_status));
2804 	error = EIO;
2805 	goto out;
2806     }
2807 
2808     /*
2809      * Sleep waiting for the notifier command to complete.  Note
2810      * that if it doesn't, we may end up in a bad situation, since
2811      * the adapter may deliver it later.  Also note that the adapter
2812      * requires the Notify Event command to be cancelled in order to
2813      * maintain internal bookkeeping.
2814      */
2815     s = splcam();
2816     while (sc->ciss_periodic_notify != NULL) {
2817 	error = tsleep(&sc->ciss_periodic_notify, 0, "cissNEA", hz * 5);
2818 	if (error == EWOULDBLOCK) {
2819 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
2820 	    break;
2821 	}
2822     }
2823     splx(s);
2824 
2825  out:
2826     /* release the cancel request */
2827     if (cr != NULL) {
2828 	if (cr->cr_data != NULL)
2829 	    free(cr->cr_data, CISS_MALLOC_CLASS);
2830 	ciss_release_request(cr);
2831     }
2832     if (error == 0)
2833 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2834     return(error);
2835 }
2836 
2837 /************************************************************************
2838  * Abort the Notify Event chain using a BMIC command.
2839  */
2840 static int
2841 ciss_notify_abort_bmic(struct ciss_softc *sc)
2842 {
2843     struct ciss_request			*cr;
2844     int					error, command_status;
2845 
2846     debug_called(1);
2847 
2848     cr = NULL;
2849     error = 0;
2850 
2851     /* verify that there's an outstanding command */
2852     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
2853 	goto out;
2854 
2855     /*
2856      * Build a BMIC command to cancel the Notify on Event command.
2857      *
2858      * Note that we are sending a CISS opcode here.  Odd.
2859      */
2860     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
2861 				       NULL, 0)) != 0)
2862 	goto out;
2863 
2864     /*
2865      * Submit the request and wait for it to complete.
2866      */
2867     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
2868 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
2869 	goto out;
2870     }
2871 
2872     /*
2873      * Check response.
2874      */
2875     ciss_report_request(cr, &command_status, NULL);
2876     switch(command_status) {
2877     case CISS_CMD_STATUS_SUCCESS:
2878 	break;
2879     default:
2880 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
2881 		    ciss_name_command_status(command_status));
2882 	error = EIO;
2883 	goto out;
2884     }
2885 
2886 out:
2887     if (cr != NULL)
2888 	ciss_release_request(cr);
2889     return(error);
2890 }
2891 
2892 /************************************************************************
2893  * Handle a notify event relating to the status of a logical drive.
2894  *
2895  * XXX need to be able to defer some of these to properly handle
2896  *     calling the "ID Physical drive" command, unless the 'extended'
2897  *     drive IDs are always in BIG_MAP format.
2898  */
2899 static void
2900 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
2901 {
2902     struct ciss_ldrive	*ld;
2903     int			ostatus;
2904 
2905     debug_called(2);
2906 
2907     ld = &sc->ciss_logical[cn->data.logical_status.logical_drive];
2908 
2909     switch (cn->subclass) {
2910     case CISS_NOTIFY_LOGICAL_STATUS:
2911 	switch (cn->detail) {
2912 	case 0:
2913 	    ciss_name_device(sc, cn->data.logical_status.logical_drive);
2914 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
2915 			cn->data.logical_status.logical_drive, ld->cl_name,
2916 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
2917 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
2918 			cn->data.logical_status.spare_state,
2919 			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
2920 
2921 	    /*
2922 	     * Update our idea of the drive's status.
2923 	     */
2924 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
2925 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
2926 	    if (ld->cl_status != NULL)
2927 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
2928 
2929 	    break;
2930 
2931 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
2932 	    ciss_name_device(sc, cn->data.logical_status.logical_drive);
2933 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
2934 			cn->data.logical_status.logical_drive, ld->cl_name);
2935 	    ciss_accept_media(sc, cn->data.logical_status.logical_drive, 1);
2936 	    break;
2937 
2938 	case 2:
2939 	case 3:
2940 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
2941 			cn->data.rebuild_aborted.logical_drive,
2942 			sc->ciss_logical[cn->data.rebuild_aborted.logical_drive].cl_name,
2943 			(cn->detail == 2) ? "read" : "write");
2944 	    break;
2945 	}
2946 	break;
2947 
2948     case CISS_NOTIFY_LOGICAL_ERROR:
2949 	if (cn->detail == 0) {
2950 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
2951 			cn->data.io_error.logical_drive,
2952 			sc->ciss_logical[cn->data.io_error.logical_drive].cl_name,
2953 			cn->data.io_error.failure_bus,
2954 			cn->data.io_error.failure_drive);
2955 	    /* XXX should we take the drive down at this point, or will we be told? */
2956 	}
2957 	break;
2958 
2959     case CISS_NOTIFY_LOGICAL_SURFACE:
2960 	if (cn->detail == 0)
2961 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
2962 			cn->data.consistency_completed.logical_drive,
2963 			sc->ciss_logical[cn->data.consistency_completed.logical_drive].cl_name);
2964 	break;
2965     }
2966 }
2967 
2968 /************************************************************************
2969  * Handle a notify event relating to the status of a physical drive.
2970  */
2971 static void
2972 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
2973 {
2974 
2975 }
2976 
2977 /************************************************************************
2978  * Print a request.
2979  */
2980 static void
2981 ciss_print_request(struct ciss_request *cr)
2982 {
2983     struct ciss_softc	*sc;
2984     struct ciss_command	*cc;
2985     int			i;
2986 
2987     sc = cr->cr_sc;
2988     cc = CISS_FIND_COMMAND(cr);
2989 
2990     ciss_printf(sc, "REQUEST @ %p\n", cr);
2991     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
2992 	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
2993 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
2994     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
2995 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
2996     switch(cc->header.address.mode.mode) {
2997     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
2998     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
2999 	ciss_printf(sc, "  physical bus %d target %d\n",
3000 		    cc->header.address.physical.bus, cc->header.address.physical.target);
3001 	break;
3002     case CISS_HDR_ADDRESS_MODE_LOGICAL:
3003 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
3004 	break;
3005     }
3006     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
3007 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
3008 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
3009 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
3010 		cc->cdb.cdb_length,
3011 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
3012 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
3013 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
3014 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
3015 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
3016 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
3017 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
3018     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
3019 
3020     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
3021 	/* XXX print error info */
3022     } else {
3023 	/* since we don't use chained s/g, don't support it here */
3024 	for (i = 0; i < cc->header.sg_in_list; i++) {
3025 	    if ((i % 4) == 0)
3026 		ciss_printf(sc, "   ");
3027 	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
3028 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
3029 		printf("\n");
3030 	}
3031     }
3032 }
3033 
3034 /************************************************************************
3035  * Print information about the status of a logical drive.
3036  */
3037 static void
3038 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
3039 {
3040     int		bus, target, i;
3041 
3042     /* print drive status */
3043     switch(ld->cl_lstatus->status) {
3044     case CISS_LSTATUS_OK:
3045 	printf("online\n");
3046 	break;
3047     case CISS_LSTATUS_INTERIM_RECOVERY:
3048 	printf("in interim recovery mode\n");
3049 	break;
3050     case CISS_LSTATUS_READY_RECOVERY:
3051 	printf("ready to begin recovery\n");
3052 	break;
3053     case CISS_LSTATUS_RECOVERING:
3054 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3055 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3056 	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
3057 	       bus, target, ld->cl_lstatus->blocks_to_recover);
3058 	break;
3059     case CISS_LSTATUS_EXPANDING:
3060 	printf("being expanded, %u blocks remaining\n",
3061 	       ld->cl_lstatus->blocks_to_recover);
3062 	break;
3063     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3064 	printf("queued for expansion\n");
3065 	break;
3066     case CISS_LSTATUS_FAILED:
3067 	printf("queued for expansion\n");
3068 	break;
3069     case CISS_LSTATUS_WRONG_PDRIVE:
3070 	printf("wrong physical drive inserted\n");
3071 	break;
3072     case CISS_LSTATUS_MISSING_PDRIVE:
3073 	printf("missing a needed physical drive\n");
3074 	break;
3075     case CISS_LSTATUS_BECOMING_READY:
3076 	printf("becoming ready\n");
3077 	break;
3078     }
3079 
3080     /* print failed drives */
3081     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
3082 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
3083 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
3084 	if (bus == -1)
3085 	    continue;
3086 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
3087 		    ld->cl_lstatus->drive_failure_map[i]);
3088     }
3089 }
3090 
3091 /************************************************************************
3092  * Return a name for a logical drive status value.
3093  */
3094 static const char *
3095 ciss_name_ldrive_status(int status)
3096 {
3097     switch (status) {
3098     case CISS_LSTATUS_OK:
3099 	return("OK");
3100     case CISS_LSTATUS_FAILED:
3101 	return("failed");
3102     case CISS_LSTATUS_NOT_CONFIGURED:
3103 	return("not configured");
3104     case CISS_LSTATUS_INTERIM_RECOVERY:
3105 	return("interim recovery");
3106     case CISS_LSTATUS_READY_RECOVERY:
3107 	return("ready for recovery");
3108     case CISS_LSTATUS_RECOVERING:
3109 	return("recovering");
3110     case CISS_LSTATUS_WRONG_PDRIVE:
3111 	return("wrong physical drive inserted");
3112     case CISS_LSTATUS_MISSING_PDRIVE:
3113 	return("missing physical drive");
3114     case CISS_LSTATUS_EXPANDING:
3115 	return("expanding");
3116     case CISS_LSTATUS_BECOMING_READY:
3117 	return("becoming ready");
3118     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3119 	return("queued for expansion");
3120     }
3121     return("unknown status");
3122 }
3123 
3124 /************************************************************************
3125  * Return an online/offline/nonexistent value for a logical drive
3126  * status value.
3127  */
3128 static int
3129 ciss_decode_ldrive_status(int status)
3130 {
3131     switch(status) {
3132     case CISS_LSTATUS_NOT_CONFIGURED:
3133 	return(CISS_LD_NONEXISTENT);
3134 
3135     case CISS_LSTATUS_OK:
3136     case CISS_LSTATUS_INTERIM_RECOVERY:
3137     case CISS_LSTATUS_READY_RECOVERY:
3138     case CISS_LSTATUS_RECOVERING:
3139     case CISS_LSTATUS_EXPANDING:
3140     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3141 	return(CISS_LD_ONLINE);
3142 
3143     case CISS_LSTATUS_FAILED:
3144     case CISS_LSTATUS_WRONG_PDRIVE:
3145     case CISS_LSTATUS_MISSING_PDRIVE:
3146     case CISS_LSTATUS_BECOMING_READY:
3147     default:
3148 	return(CISS_LD_OFFLINE);
3149     }
3150 }
3151 
3152 
3153 /************************************************************************
3154  * Return a name for a logical drive's organisation.
3155  */
3156 static const char *
3157 ciss_name_ldrive_org(int org)
3158 {
3159     switch(org) {
3160     case CISS_LDRIVE_RAID0:
3161 	return("RAID 0");
3162     case CISS_LDRIVE_RAID1:
3163 	return("RAID 1");
3164     case CISS_LDRIVE_RAID4:
3165 	return("RAID 4");
3166     case CISS_LDRIVE_RAID5:
3167 	return("RAID 5");
3168     }
3169     return("unkown");
3170 }
3171 
3172 /************************************************************************
3173  * Return a name for a command status value.
3174  */
3175 static const char *
3176 ciss_name_command_status(int status)
3177 {
3178     switch(status) {
3179     case CISS_CMD_STATUS_SUCCESS:
3180 	return("success");
3181     case CISS_CMD_STATUS_TARGET_STATUS:
3182 	return("target status");
3183     case CISS_CMD_STATUS_DATA_UNDERRUN:
3184 	return("data underrun");
3185     case CISS_CMD_STATUS_DATA_OVERRUN:
3186 	return("data overrun");
3187     case CISS_CMD_STATUS_INVALID_COMMAND:
3188 	return("invalid command");
3189     case CISS_CMD_STATUS_PROTOCOL_ERROR:
3190 	return("protocol error");
3191     case CISS_CMD_STATUS_HARDWARE_ERROR:
3192 	return("hardware error");
3193     case CISS_CMD_STATUS_CONNECTION_LOST:
3194 	return("connection lost");
3195     case CISS_CMD_STATUS_ABORTED:
3196 	return("aborted");
3197     case CISS_CMD_STATUS_ABORT_FAILED:
3198 	return("abort failed");
3199     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
3200 	return("unsolicited abort");
3201     case CISS_CMD_STATUS_TIMEOUT:
3202 	return("timeout");
3203     case CISS_CMD_STATUS_UNABORTABLE:
3204 	return("unabortable");
3205     }
3206     return("unknown status");
3207 }
3208 
3209 /************************************************************************
3210  * Handle an open on the control device.
3211  */
3212 static int
3213 ciss_open(dev_t dev, int flags, int fmt, struct proc *p)
3214 {
3215     struct ciss_softc	*sc;
3216 
3217     debug_called(1);
3218 
3219     sc = (struct ciss_softc *)dev->si_drv1;
3220 
3221     /* we might want to veto if someone already has us open */
3222 
3223     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
3224     return(0);
3225 }
3226 
3227 /************************************************************************
3228  * Handle the last close on the control device.
3229  */
3230 static int
3231 ciss_close(dev_t dev, int flags, int fmt, struct proc *p)
3232 {
3233     struct ciss_softc	*sc;
3234 
3235     debug_called(1);
3236 
3237     sc = (struct ciss_softc *)dev->si_drv1;
3238 
3239     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
3240     return (0);
3241 }
3242 
3243 /********************************************************************************
3244  * Handle adapter-specific control operations.
3245  *
3246  * Note that the API here is compatible with the Linux driver, in order to
3247  * simplify the porting of Compaq's userland tools.
3248  */
3249 static int
3250 ciss_ioctl(dev_t dev, u_long cmd, caddr_t addr, int32_t flag, struct proc *p)
3251 {
3252     struct ciss_softc		*sc;
3253     int				error;
3254 
3255     debug_called(1);
3256 
3257     sc = (struct ciss_softc *)dev->si_drv1;
3258     error = 0;
3259 
3260     switch(cmd) {
3261     case CCISS_GETPCIINFO:
3262     {
3263 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
3264 
3265 	pis->bus = pci_get_bus(sc->ciss_dev);
3266 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
3267 	pis->board_id = pci_get_devid(sc->ciss_dev);
3268 
3269 	break;
3270     }
3271 
3272     case CCISS_GETINTINFO:
3273     {
3274 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
3275 
3276 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
3277 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
3278 
3279 	break;
3280     }
3281 
3282     case CCISS_SETINTINFO:
3283     {
3284 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
3285 
3286 	if ((cis->delay == 0) && (cis->count == 0)) {
3287 	    error = EINVAL;
3288 	    break;
3289 	}
3290 
3291 	/*
3292 	 * XXX apparently this is only safe if the controller is idle,
3293 	 *     we should suspend it before doing this.
3294 	 */
3295 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
3296 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
3297 
3298 	if (ciss_update_config(sc))
3299 	    error = EIO;
3300 
3301 	/* XXX resume the controller here */
3302 	break;
3303     }
3304 
3305     case CCISS_GETNODENAME:
3306 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
3307 	      sizeof(NodeName_type));
3308 	break;
3309 
3310     case CCISS_SETNODENAME:
3311 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
3312 	      sizeof(NodeName_type));
3313 	if (ciss_update_config(sc))
3314 	    error = EIO;
3315 	break;
3316 
3317     case CCISS_GETHEARTBEAT:
3318 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
3319 	break;
3320 
3321     case CCISS_GETBUSTYPES:
3322 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
3323 	break;
3324 
3325     case CCISS_GETFIRMVER:
3326 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
3327 	      sizeof(FirmwareVer_type));
3328 	break;
3329 
3330     case CCISS_GETDRIVERVER:
3331 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
3332 	break;
3333 
3334     case CCISS_REVALIDVOLS:
3335 	/*
3336 	 * This is a bit ugly; to do it "right" we really need
3337 	 * to find any disks that have changed, kick CAM off them,
3338 	 * then rescan only these disks.  It'd be nice if they
3339 	 * a) told us which disk(s) they were going to play with,
3340 	 * and b) which ones had arrived. 8(
3341 	 */
3342 	break;
3343 
3344     case CCISS_PASSTHRU:
3345 	error = ciss_user_command(sc, (IOCTL_Command_struct *)addr);
3346 	break;
3347 
3348     default:
3349 	debug(0, "unknown ioctl 0x%lx", cmd);
3350 
3351 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
3352 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
3353 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
3354 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
3355 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
3356 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
3357 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
3358 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
3359 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
3360 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
3361 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
3362 
3363 	error = ENOIOCTL;
3364 	break;
3365     }
3366 
3367     return(error);
3368 }
3369