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