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