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