xref: /freebsd/sys/dev/ciss/ciss.c (revision e0c27215058b5786c78fcfb3963eebe61a989511)
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 (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 (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 (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 (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 = 0;
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      * Check to see if the command succeeded.
1971      */
1972     ce = (struct ciss_error_info *)&(cc->sg[0]);
1973     if (ciss_report_request(cr, NULL, NULL) == 0)
1974 	bzero(ce, sizeof(*ce));
1975     else
1976 	error = EIO;
1977 
1978     /*
1979      * Copy the results back to the user.
1980      */
1981     bcopy(ce, &ioc->error_info, sizeof(*ce));
1982     if ((ioc->buf_size > 0) &&
1983 	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
1984 	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
1985 	goto out;
1986     }
1987 
1988     /* done OK */
1989     error = 0;
1990 
1991 out:
1992     if ((cr != NULL) && (cr->cr_data != NULL))
1993 	free(cr->cr_data, CISS_MALLOC_CLASS);
1994     if (cr != NULL)
1995 	ciss_release_request(cr);
1996     return(error);
1997 }
1998 
1999 /************************************************************************
2000  * Map a request into bus-visible space, initialise the scatter/gather
2001  * list.
2002  */
2003 static int
2004 ciss_map_request(struct ciss_request *cr)
2005 {
2006     struct ciss_softc	*sc;
2007 
2008     debug_called(2);
2009 
2010     sc = cr->cr_sc;
2011 
2012     /* check that mapping is necessary */
2013     if ((cr->cr_flags & CISS_REQ_MAPPED) || (cr->cr_data == NULL))
2014 	return(0);
2015 
2016     bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap, cr->cr_data, cr->cr_length,
2017 		    ciss_request_map_helper, CISS_FIND_COMMAND(cr), 0);
2018 
2019     if (cr->cr_flags & CISS_REQ_DATAIN)
2020 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2021     if (cr->cr_flags & CISS_REQ_DATAOUT)
2022 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2023 
2024     cr->cr_flags |= CISS_REQ_MAPPED;
2025     return(0);
2026 }
2027 
2028 static void
2029 ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2030 {
2031     struct ciss_command	*cc;
2032     int			i;
2033 
2034     debug_called(2);
2035 
2036     cc = (struct ciss_command *)arg;
2037     for (i = 0; i < nseg; i++) {
2038 	cc->sg[i].address = segs[i].ds_addr;
2039 	cc->sg[i].length = segs[i].ds_len;
2040 	cc->sg[i].extension = 0;
2041     }
2042     /* we leave the s/g table entirely within the command */
2043     cc->header.sg_in_list = nseg;
2044     cc->header.sg_total = nseg;
2045 }
2046 
2047 /************************************************************************
2048  * Unmap a request from bus-visible space.
2049  */
2050 static void
2051 ciss_unmap_request(struct ciss_request *cr)
2052 {
2053     struct ciss_softc	*sc;
2054 
2055     debug_called(2);
2056 
2057     sc = cr->cr_sc;
2058 
2059     /* check that unmapping is necessary */
2060     if (!(cr->cr_flags & CISS_REQ_MAPPED) || (cr->cr_data == NULL))
2061 	return;
2062 
2063     if (cr->cr_flags & CISS_REQ_DATAIN)
2064 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2065     if (cr->cr_flags & CISS_REQ_DATAOUT)
2066 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2067 
2068     bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2069     cr->cr_flags &= ~CISS_REQ_MAPPED;
2070 }
2071 
2072 /************************************************************************
2073  * Attach the driver to CAM.
2074  *
2075  * We put all the logical drives on a single SCSI bus.
2076  */
2077 static int
2078 ciss_cam_init(struct ciss_softc *sc)
2079 {
2080 
2081     debug_called(1);
2082 
2083     /*
2084      * Allocate a devq.  We can reuse this for the masked physical
2085      * devices if we decide to export these as well.
2086      */
2087     if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests)) == NULL) {
2088 	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2089 	return(ENOMEM);
2090     }
2091 
2092     /*
2093      * Create a SIM.
2094      */
2095     if ((sc->ciss_cam_sim = cam_sim_alloc(ciss_cam_action, ciss_cam_poll, "ciss", sc,
2096 					  device_get_unit(sc->ciss_dev),
2097 					  sc->ciss_max_requests - 2,
2098 					  1,
2099 					  sc->ciss_cam_devq)) == NULL) {
2100 	ciss_printf(sc, "can't allocate CAM SIM\n");
2101 	return(ENOMEM);
2102     }
2103 
2104     /*
2105      * Register bus 0 (the 'logical drives' bus) with this SIM.
2106      */
2107     if (xpt_bus_register(sc->ciss_cam_sim, 0) != 0) {
2108 	ciss_printf(sc, "can't register SCSI bus 0\n");
2109 	return(ENXIO);
2110     }
2111 
2112     /*
2113      * Initiate a rescan of the bus.
2114      */
2115     ciss_cam_rescan_all(sc);
2116 
2117     return(0);
2118 }
2119 
2120 /************************************************************************
2121  * Initiate a rescan of the 'logical devices' SIM
2122  */
2123 static void
2124 ciss_cam_rescan_target(struct ciss_softc *sc, int target)
2125 {
2126     union ccb	*ccb;
2127 
2128     debug_called(1);
2129 
2130     if ((ccb = malloc(sizeof(union ccb), M_TEMP, M_WAITOK | M_ZERO)) == NULL) {
2131 	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2132 	return;
2133     }
2134 
2135     if (xpt_create_path(&sc->ciss_cam_path, xpt_periph, cam_sim_path(sc->ciss_cam_sim), target, 0)
2136 	!= CAM_REQ_CMP) {
2137 	ciss_printf(sc, "rescan failed (can't create path)\n");
2138 	return;
2139     }
2140 
2141     xpt_setup_ccb(&ccb->ccb_h, sc->ciss_cam_path, 5/*priority (low)*/);
2142     ccb->ccb_h.func_code = XPT_SCAN_BUS;
2143     ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2144     ccb->crcn.flags = CAM_FLAG_NONE;
2145     xpt_action(ccb);
2146 
2147     /* scan is now in progress */
2148 }
2149 
2150 static void
2151 ciss_cam_rescan_all(struct ciss_softc *sc)
2152 {
2153     ciss_cam_rescan_target(sc, 0);
2154 }
2155 
2156 static void
2157 ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2158 {
2159     xpt_free_path(ccb->ccb_h.path);
2160     free(ccb, M_TEMP);
2161 }
2162 
2163 /************************************************************************
2164  * Handle requests coming from CAM
2165  */
2166 static void
2167 ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2168 {
2169     struct ciss_softc	*sc;
2170     struct ccb_scsiio	*csio;
2171     int			target;
2172 
2173     sc = cam_sim_softc(sim);
2174     csio = (struct ccb_scsiio *)&ccb->csio;
2175     target = csio->ccb_h.target_id;
2176 
2177     switch (ccb->ccb_h.func_code) {
2178 
2179 	/* perform SCSI I/O */
2180     case XPT_SCSI_IO:
2181 	if (!ciss_cam_action_io(sim, csio))
2182 	    return;
2183 	break;
2184 
2185 	/* perform geometry calculations */
2186     case XPT_CALC_GEOMETRY:
2187     {
2188 	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2189 	struct ciss_ldrive		*ld = &sc->ciss_logical[target];
2190 
2191 	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2192 
2193 	/*
2194 	 * Use the cached geometry settings unless the fault tolerance
2195 	 * is invalid.
2196 	 */
2197 	if (ld->cl_geometry.fault_tolerance == 0xFF) {
2198 	    u_int32_t			secs_per_cylinder;
2199 
2200 	    ccg->heads = 255;
2201 	    ccg->secs_per_track = 32;
2202 	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2203 	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2204 	} else {
2205 	    ccg->heads = ld->cl_geometry.heads;
2206 	    ccg->secs_per_track = ld->cl_geometry.sectors;
2207 	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2208 	}
2209 	ccb->ccb_h.status = CAM_REQ_CMP;
2210         break;
2211     }
2212 
2213 	/* handle path attribute inquiry */
2214     case XPT_PATH_INQ:
2215     {
2216 	struct ccb_pathinq	*cpi = &ccb->cpi;
2217 
2218 	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2219 
2220 	cpi->version_num = 1;
2221 	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2222 	cpi->target_sprt = 0;
2223 	cpi->hba_misc = 0;
2224 	cpi->max_target = CISS_MAX_LOGICAL;
2225 	cpi->max_lun = 0;		/* 'logical drive' channel only */
2226 	cpi->initiator_id = CISS_MAX_LOGICAL;
2227 	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2228         strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2229         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2230         cpi->unit_number = cam_sim_unit(sim);
2231         cpi->bus_id = cam_sim_bus(sim);
2232 	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2233 	ccb->ccb_h.status = CAM_REQ_CMP;
2234 	break;
2235     }
2236 
2237     case XPT_GET_TRAN_SETTINGS:
2238     {
2239 	struct ccb_trans_settings	*cts = &ccb->cts;
2240 	int				bus, target;
2241 
2242 	bus = cam_sim_bus(sim);
2243 	target = cts->ccb_h.target_id;
2244 
2245 	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2246 	cts->valid = 0;
2247 
2248 	/* disconnect always OK */
2249 	cts->flags |= CCB_TRANS_DISC_ENB;
2250 	cts->valid |= CCB_TRANS_DISC_VALID;
2251 
2252 	cts->ccb_h.status = CAM_REQ_CMP;
2253 	break;
2254     }
2255 
2256     default:		/* we can't do this */
2257 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
2258 	ccb->ccb_h.status = CAM_REQ_INVALID;
2259 	break;
2260     }
2261 
2262     xpt_done(ccb);
2263 }
2264 
2265 /************************************************************************
2266  * Handle a CAM SCSI I/O request.
2267  */
2268 static int
2269 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
2270 {
2271     struct ciss_softc	*sc;
2272     int			bus, target;
2273     struct ciss_request	*cr;
2274     struct ciss_command	*cc;
2275     int			error;
2276 
2277     sc = cam_sim_softc(sim);
2278     bus = cam_sim_bus(sim);
2279     target = csio->ccb_h.target_id;
2280 
2281     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
2282 
2283     /* check for I/O attempt to nonexistent device */
2284     if ((bus != 0) ||
2285 	(target >= CISS_MAX_LOGICAL) ||
2286 	(sc->ciss_logical[target].cl_status == CISS_LD_NONEXISTENT)) {
2287 	debug(3, "  device does not exist");
2288 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2289     }
2290 
2291     /* firmware does not support commands > 10 bytes */
2292     if (csio->cdb_len > 12/*CISS_CDB_BUFFER_SIZE*/) {
2293 	debug(3, "  command too large (%d > %d)", csio->cdb_len, CISS_CDB_BUFFER_SIZE);
2294 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2295     }
2296 
2297     /* check that the CDB pointer is not to a physical address */
2298     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
2299 	debug(3, "  CDB pointer is to physical address");
2300 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2301     }
2302 
2303     /* if there is data transfer, it must be to/from a virtual address */
2304     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2305 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
2306 	    debug(3, "  data pointer is to physical address");
2307 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2308 	}
2309 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
2310 	    debug(3, "  data has premature s/g setup");
2311 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2312 	}
2313     }
2314 
2315     /* abandon aborted ccbs or those that have failed validation */
2316     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2317 	debug(3, "abandoning CCB due to abort/validation failure");
2318 	return(EINVAL);
2319     }
2320 
2321     /* handle emulation of some SCSI commands ourself */
2322     if (ciss_cam_emulate(sc, csio))
2323 	return(0);
2324 
2325     /*
2326      * Get a request to manage this command.  If we can't, return the
2327      * ccb, freeze the queue and flag so that we unfreeze it when a
2328      * request completes.
2329      */
2330     if ((error = ciss_get_request(sc, &cr)) != 0) {
2331 	xpt_freeze_simq(sc->ciss_cam_sim, 1);
2332 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
2333 	return(error);
2334     }
2335 
2336     /*
2337      * Build the command.
2338      */
2339     cc = CISS_FIND_COMMAND(cr);
2340     cr->cr_data = csio->data_ptr;
2341     cr->cr_length = csio->dxfer_len;
2342     cr->cr_complete = ciss_cam_complete;
2343     cr->cr_private = csio;
2344 
2345     cc->header.address.logical.mode = CISS_HDR_ADDRESS_MODE_LOGICAL;
2346     cc->header.address.logical.lun = target;
2347     cc->cdb.cdb_length = csio->cdb_len;
2348     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2349     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
2350     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2351 	cr->cr_flags = CISS_REQ_DATAOUT;
2352 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
2353     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2354 	cr->cr_flags = CISS_REQ_DATAIN;
2355 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2356     } else {
2357 	cr->cr_flags = 0;
2358 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2359     }
2360     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
2361     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2362 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
2363     } else {
2364 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
2365     }
2366 
2367     /*
2368      * Submit the request to the adapter.
2369      *
2370      * Note that this may fail if we're unable to map the request (and
2371      * if we ever learn a transport layer other than simple, may fail
2372      * if the adapter rejects the command).
2373      */
2374     if ((error = ciss_start(cr)) != 0) {
2375 	xpt_freeze_simq(sc->ciss_cam_sim, 1);
2376 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
2377 	ciss_release_request(cr);
2378 	return(error);
2379     }
2380 
2381     return(0);
2382 }
2383 
2384 /************************************************************************
2385  * Emulate SCSI commands the adapter doesn't handle as we might like.
2386  */
2387 static int
2388 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
2389 {
2390     int		target;
2391     u_int8_t	opcode;
2392 
2393 
2394     target = csio->ccb_h.target_id;
2395     opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
2396 	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
2397 
2398     /*
2399      * Handle requests for volumes that don't exist.  A selection timeout
2400      * is slightly better than an illegal request.  Other errors might be
2401      * better.
2402      */
2403     if (sc->ciss_logical[target].cl_status == CISS_LD_NONEXISTENT) {
2404 	csio->ccb_h.status = CAM_SEL_TIMEOUT;
2405 	xpt_done((union ccb *)csio);
2406 	return(1);
2407     }
2408 
2409     /*
2410      * Handle requests for volumes that exist but are offline.
2411      *
2412      * I/O operations should fail, everything else should work.
2413      */
2414     if (sc->ciss_logical[target].cl_status == CISS_LD_OFFLINE) {
2415 	switch(opcode) {
2416 	case READ_6:
2417 	case READ_10:
2418 	case READ_12:
2419 	case WRITE_6:
2420 	case WRITE_10:
2421 	case WRITE_12:
2422 	    csio->ccb_h.status = CAM_SEL_TIMEOUT;
2423 	    xpt_done((union ccb *)csio);
2424 	    return(1);
2425 	}
2426     }
2427 
2428 
2429     /* if we have to fake Synchronise Cache */
2430     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
2431 
2432 	/*
2433 	 * If this is a Synchronise Cache command, typically issued when
2434 	 * a device is closed, flush the adapter and complete now.
2435 	 */
2436 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2437 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
2438 	    ciss_flush_adapter(sc);
2439 	    csio->ccb_h.status = CAM_REQ_CMP;
2440 	    xpt_done((union ccb *)csio);
2441 	    return(1);
2442 	}
2443     }
2444 
2445     return(0);
2446 }
2447 
2448 /************************************************************************
2449  * Check for possibly-completed commands.
2450  */
2451 static void
2452 ciss_cam_poll(struct cam_sim *sim)
2453 {
2454     struct ciss_softc	*sc = cam_sim_softc(sim);
2455 
2456     debug_called(2);
2457 
2458     ciss_done(sc);
2459 }
2460 
2461 /************************************************************************
2462  * Handle completion of a command - pass results back through the CCB
2463  */
2464 static void
2465 ciss_cam_complete(struct ciss_request *cr)
2466 {
2467     struct ciss_softc		*sc;
2468     struct ciss_command		*cc;
2469     struct ciss_error_info	*ce;
2470     struct ccb_scsiio		*csio;
2471     int				scsi_status;
2472     int				command_status;
2473 
2474     debug_called(2);
2475 
2476     sc = cr->cr_sc;
2477     cc = CISS_FIND_COMMAND(cr);
2478     ce = (struct ciss_error_info *)&(cc->sg[0]);
2479     csio = (struct ccb_scsiio *)cr->cr_private;
2480 
2481     /*
2482      * Extract status values from request.
2483      */
2484     ciss_report_request(cr, &command_status, &scsi_status);
2485     csio->scsi_status = scsi_status;
2486 
2487     /*
2488      * Handle specific SCSI status values.
2489      */
2490     switch(scsi_status) {
2491 	/* no status due to adapter error */
2492     case -1:
2493 	debug(0, "adapter error");
2494 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2495 	break;
2496 
2497 	/* no status due to command completed OK */
2498     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
2499 	debug(2, "SCSI_STATUS_OK");
2500 	csio->ccb_h.status = CAM_REQ_CMP;
2501 	break;
2502 
2503 	/* check condition, sense data included */
2504     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
2505 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d",
2506 	      ce->sense_length, ce->residual_count);
2507 	bzero(&csio->sense_data, SSD_FULL_SIZE);
2508 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
2509 	csio->sense_len = ce->sense_length;
2510 	csio->resid = ce->residual_count;
2511 	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
2512 #ifdef CISS_DEBUG
2513 	{
2514 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
2515 	    debug(0, "sense key %x", sns->flags & SSD_KEY);
2516 	}
2517 #endif
2518 	break;
2519 
2520     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
2521 	debug(0, "SCSI_STATUS_BUSY");
2522 	csio->ccb_h.status = CAM_SCSI_BUSY;
2523 	break;
2524 
2525     default:
2526 	debug(0, "unknown status 0x%x", csio->scsi_status);
2527 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2528 	break;
2529     }
2530 
2531     /* handle post-command fixup */
2532     ciss_cam_complete_fixup(sc, csio);
2533 
2534     /* tell CAM we're ready for more commands */
2535     csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2536 
2537     xpt_done((union ccb *)csio);
2538     ciss_release_request(cr);
2539 }
2540 
2541 /********************************************************************************
2542  * Fix up the result of some commands here.
2543  */
2544 static void
2545 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
2546 {
2547     struct scsi_inquiry_data	*inq;
2548     struct ciss_ldrive		*cl;
2549     int				target;
2550 
2551     if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2552 	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
2553 
2554 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
2555 	target = csio->ccb_h.target_id;
2556 	cl = &sc->ciss_logical[target];
2557 
2558 	padstr(inq->vendor, "COMPAQ", 8);
2559 	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
2560 	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
2561     }
2562 }
2563 
2564 
2565 /********************************************************************************
2566  * Find a peripheral attached at (target)
2567  */
2568 static struct cam_periph *
2569 ciss_find_periph(struct ciss_softc *sc, int target)
2570 {
2571     struct cam_periph	*periph;
2572     struct cam_path	*path;
2573     int			status;
2574 
2575     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim), target, 0);
2576     if (status == CAM_REQ_CMP) {
2577 	periph = cam_periph_find(path, NULL);
2578 	xpt_free_path(path);
2579     } else {
2580 	periph = NULL;
2581     }
2582     return(periph);
2583 }
2584 
2585 /********************************************************************************
2586  * Name the device at (target)
2587  *
2588  * XXX is this strictly correct?
2589  */
2590 static int
2591 ciss_name_device(struct ciss_softc *sc, int target)
2592 {
2593     struct cam_periph	*periph;
2594 
2595     if ((periph = ciss_find_periph(sc, target)) != NULL) {
2596 	sprintf(sc->ciss_logical[target].cl_name, "%s%d", periph->periph_name, periph->unit_number);
2597 	return(0);
2598     }
2599     sc->ciss_logical[target].cl_name[0] = 0;
2600     return(ENOENT);
2601 }
2602 
2603 /************************************************************************
2604  * Periodic status monitoring.
2605  */
2606 static void
2607 ciss_periodic(void *arg)
2608 {
2609     struct ciss_softc	*sc;
2610 
2611     debug_called(1);
2612 
2613     sc = (struct ciss_softc *)arg;
2614 
2615     /*
2616      * Check the adapter heartbeat.
2617      */
2618     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
2619 	sc->ciss_heart_attack++;
2620 	debug(0, "adapter heart attack in progress 0x%x/%d",
2621 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
2622 	if (sc->ciss_heart_attack == 3) {
2623 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
2624 	    /* XXX should reset adapter here */
2625 	}
2626     } else {
2627 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
2628 	sc->ciss_heart_attack = 0;
2629 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
2630     }
2631 
2632     /*
2633      * If the notify event request has died for some reason, or has
2634      * not started yet, restart it.
2635      */
2636     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
2637 	debug(0, "(re)starting Event Notify chain");
2638 	ciss_notify_event(sc);
2639     }
2640 
2641     /*
2642      * Reschedule.
2643      */
2644     if (!(sc->ciss_flags & CISS_FLAG_ABORTING))
2645 	sc->ciss_periodic = timeout(ciss_periodic, sc, CISS_HEARTBEAT_RATE * hz);
2646 }
2647 
2648 /************************************************************************
2649  * Request a notification response from the adapter.
2650  *
2651  * If (cr) is NULL, this is the first request of the adapter, so
2652  * reset the adapter's message pointer and start with the oldest
2653  * message available.
2654  */
2655 static void
2656 ciss_notify_event(struct ciss_softc *sc)
2657 {
2658     struct ciss_request		*cr;
2659     struct ciss_command		*cc;
2660     struct ciss_notify_cdb	*cnc;
2661     int				error;
2662 
2663     debug_called(1);
2664 
2665     cr = sc->ciss_periodic_notify;
2666 
2667     /* get a request if we don't already have one */
2668     if (cr == NULL) {
2669 	if ((error = ciss_get_request(sc, &cr)) != 0) {
2670 	    debug(0, "can't get notify event request");
2671 	    goto out;
2672 	}
2673 	sc->ciss_periodic_notify = cr;
2674 	cr->cr_complete = ciss_notify_complete;
2675 	debug(1, "acquired request %d", cr->cr_tag);
2676     }
2677 
2678     /*
2679      * Get a databuffer if we don't already have one, note that the
2680      * adapter command wants a larger buffer than the actual
2681      * structure.
2682      */
2683     if (cr->cr_data == NULL) {
2684 	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2685 	    debug(0, "can't get notify event request buffer");
2686 	    error = ENOMEM;
2687 	    goto out;
2688 	}
2689 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
2690     }
2691 
2692     /* re-setup the request's command (since we never release it) XXX overkill*/
2693     ciss_preen_command(cr);
2694 
2695     /* (re)build the notify event command */
2696     cc = CISS_FIND_COMMAND(cr);
2697     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2698     cc->header.address.physical.bus = 0;
2699     cc->header.address.physical.target = 0;
2700 
2701     cc->cdb.cdb_length = sizeof(*cnc);
2702     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2703     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2704     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2705     cc->cdb.timeout = 0;	/* no timeout, we hope */
2706 
2707     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
2708     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
2709     cnc->opcode = CISS_OPCODE_READ;
2710     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
2711     cnc->timeout = 0;		/* no timeout, we hope */
2712     cnc->synchronous = 0;
2713     cnc->ordered = 0;
2714     cnc->seek_to_oldest = 0;
2715     cnc->new_only = 0;
2716     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
2717 
2718     /* submit the request */
2719     error = ciss_start(cr);
2720 
2721  out:
2722     if (error) {
2723 	if (cr != NULL) {
2724 	    if (cr->cr_data != NULL)
2725 		free(cr->cr_data, CISS_MALLOC_CLASS);
2726 	    ciss_release_request(cr);
2727 	}
2728 	sc->ciss_periodic_notify = NULL;
2729 	debug(0, "can't submit notify event request");
2730 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2731     } else {
2732 	debug(1, "notify event submitted");
2733 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
2734     }
2735 }
2736 
2737 static void
2738 ciss_notify_complete(struct ciss_request *cr)
2739 {
2740     struct ciss_command	*cc;
2741     struct ciss_notify	*cn;
2742     struct ciss_softc	*sc;
2743     int			scsi_status;
2744     int			command_status;
2745 
2746     debug_called(1);
2747 
2748     cc = CISS_FIND_COMMAND(cr);
2749     cn = (struct ciss_notify *)cr->cr_data;
2750     sc = cr->cr_sc;
2751 
2752     /*
2753      * Report request results, decode status.
2754      */
2755     ciss_report_request(cr, &command_status, &scsi_status);
2756 
2757     /*
2758      * Abort the chain on a fatal error.
2759      *
2760      * XXX which of these are actually errors?
2761      */
2762     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
2763 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
2764 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
2765 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
2766 		    ciss_name_command_status(command_status));
2767 	ciss_release_request(cr);
2768 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2769 	return;
2770     }
2771 
2772     /*
2773      * If the adapter gave us a text message, print it.
2774      */
2775     if (cn->message[0] != 0)
2776 	ciss_printf(sc, "*** %.80s\n", cn->message);
2777 
2778     debug(0, "notify event class %d subclass %d detail %d",
2779 		cn->class, cn->subclass, cn->detail);
2780 
2781     /*
2782      * If there's room, save the event for a user-level tool.
2783      */
2784     if (((sc->ciss_notify_head + 1) % CISS_MAX_EVENTS) != sc->ciss_notify_tail) {
2785 	sc->ciss_notify[sc->ciss_notify_head] = *cn;
2786 	sc->ciss_notify_head = (sc->ciss_notify_head + 1) % CISS_MAX_EVENTS;
2787     }
2788 
2789     /*
2790      * Some events are directly of interest to us.
2791      */
2792     switch (cn->class) {
2793     case CISS_NOTIFY_LOGICAL:
2794 	ciss_notify_logical(sc, cn);
2795 	break;
2796     case CISS_NOTIFY_PHYSICAL:
2797 	ciss_notify_physical(sc, cn);
2798 	break;
2799     }
2800 
2801     /*
2802      * If the response indicates that the notifier has been aborted,
2803      * release the notifier command.
2804      */
2805     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
2806 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
2807 	(cn->detail == 1)) {
2808 	debug(0, "notifier exiting");
2809 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2810 	ciss_release_request(cr);
2811 	sc->ciss_periodic_notify = NULL;
2812 	wakeup(&sc->ciss_periodic_notify);
2813     }
2814 
2815     /*
2816      * Send a new notify event command, if we're not aborting.
2817      */
2818     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
2819 	ciss_notify_event(sc);
2820     }
2821 }
2822 
2823 /************************************************************************
2824  * Abort the Notify Event chain.
2825  *
2826  * Note that we can't just abort the command in progress; we have to
2827  * explicitly issue an Abort Notify Event command in order for the
2828  * adapter to clean up correctly.
2829  *
2830  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
2831  * the chain will not restart itself.
2832  */
2833 static int
2834 ciss_notify_abort(struct ciss_softc *sc)
2835 {
2836     struct ciss_request		*cr;
2837     struct ciss_command		*cc;
2838     struct ciss_notify_cdb	*cnc;
2839     int				error, s, command_status, scsi_status;
2840 
2841     debug_called(1);
2842 
2843     cr = NULL;
2844     error = 0;
2845 
2846     /* verify that there's an outstanding command */
2847     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
2848 	goto out;
2849 
2850     /* get a command to issue the abort with */
2851     if ((error = ciss_get_request(sc, &cr)))
2852 	goto out;
2853 
2854     /* get a buffer for the result */
2855     if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2856 	debug(0, "can't get notify event request buffer");
2857 	error = ENOMEM;
2858 	goto out;
2859     }
2860     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
2861 
2862     /* build the CDB */
2863     cc = CISS_FIND_COMMAND(cr);
2864     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2865     cc->header.address.physical.bus = 0;
2866     cc->header.address.physical.target = 0;
2867     cc->cdb.cdb_length = sizeof(*cnc);
2868     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2869     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2870     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2871     cc->cdb.timeout = 0;	/* no timeout, we hope */
2872 
2873     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
2874     bzero(cnc, sizeof(*cnc));
2875     cnc->opcode = CISS_OPCODE_WRITE;
2876     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
2877     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
2878 
2879     ciss_print_request(cr);
2880 
2881     /*
2882      * Submit the request and wait for it to complete.
2883      */
2884     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
2885 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
2886 	goto out;
2887     }
2888 
2889     /*
2890      * Check response.
2891      */
2892     ciss_report_request(cr, &command_status, &scsi_status);
2893     switch(command_status) {
2894     case CISS_CMD_STATUS_SUCCESS:
2895 	break;
2896     case CISS_CMD_STATUS_INVALID_COMMAND:
2897 	/*
2898 	 * Some older adapters don't support the CISS version of this
2899 	 * command.  Fall back to using the BMIC version.
2900 	 */
2901 	error = ciss_notify_abort_bmic(sc);
2902 	if (error != 0)
2903 	    goto out;
2904 	break;
2905 
2906     case CISS_CMD_STATUS_TARGET_STATUS:
2907 	/*
2908 	 * This can happen if the adapter thinks there wasn't an outstanding
2909 	 * Notify Event command but we did.  We clean up here.
2910 	 */
2911 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
2912 	    if (sc->ciss_periodic_notify != NULL)
2913 		ciss_release_request(sc->ciss_periodic_notify);
2914 	    error = 0;
2915 	    goto out;
2916 	}
2917 	/* FALLTHROUGH */
2918 
2919     default:
2920 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
2921 		    ciss_name_command_status(command_status));
2922 	error = EIO;
2923 	goto out;
2924     }
2925 
2926     /*
2927      * Sleep waiting for the notifier command to complete.  Note
2928      * that if it doesn't, we may end up in a bad situation, since
2929      * the adapter may deliver it later.  Also note that the adapter
2930      * requires the Notify Event command to be cancelled in order to
2931      * maintain internal bookkeeping.
2932      */
2933     s = splcam();
2934     while (sc->ciss_periodic_notify != NULL) {
2935 	error = tsleep(&sc->ciss_periodic_notify, 0, "cissNEA", hz * 5);
2936 	if (error == EWOULDBLOCK) {
2937 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
2938 	    break;
2939 	}
2940     }
2941     splx(s);
2942 
2943  out:
2944     /* release the cancel request */
2945     if (cr != NULL) {
2946 	if (cr->cr_data != NULL)
2947 	    free(cr->cr_data, CISS_MALLOC_CLASS);
2948 	ciss_release_request(cr);
2949     }
2950     if (error == 0)
2951 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2952     return(error);
2953 }
2954 
2955 /************************************************************************
2956  * Abort the Notify Event chain using a BMIC command.
2957  */
2958 static int
2959 ciss_notify_abort_bmic(struct ciss_softc *sc)
2960 {
2961     struct ciss_request			*cr;
2962     int					error, command_status;
2963 
2964     debug_called(1);
2965 
2966     cr = NULL;
2967     error = 0;
2968 
2969     /* verify that there's an outstanding command */
2970     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
2971 	goto out;
2972 
2973     /*
2974      * Build a BMIC command to cancel the Notify on Event command.
2975      *
2976      * Note that we are sending a CISS opcode here.  Odd.
2977      */
2978     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
2979 				       NULL, 0)) != 0)
2980 	goto out;
2981 
2982     /*
2983      * Submit the request and wait for it to complete.
2984      */
2985     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
2986 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
2987 	goto out;
2988     }
2989 
2990     /*
2991      * Check response.
2992      */
2993     ciss_report_request(cr, &command_status, NULL);
2994     switch(command_status) {
2995     case CISS_CMD_STATUS_SUCCESS:
2996 	break;
2997     default:
2998 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
2999 		    ciss_name_command_status(command_status));
3000 	error = EIO;
3001 	goto out;
3002     }
3003 
3004 out:
3005     if (cr != NULL)
3006 	ciss_release_request(cr);
3007     return(error);
3008 }
3009 
3010 /************************************************************************
3011  * Handle a notify event relating to the status of a logical drive.
3012  *
3013  * XXX need to be able to defer some of these to properly handle
3014  *     calling the "ID Physical drive" command, unless the 'extended'
3015  *     drive IDs are always in BIG_MAP format.
3016  */
3017 static void
3018 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3019 {
3020     struct ciss_ldrive	*ld;
3021     int			ostatus;
3022 
3023     debug_called(2);
3024 
3025     ld = &sc->ciss_logical[cn->data.logical_status.logical_drive];
3026 
3027     switch (cn->subclass) {
3028     case CISS_NOTIFY_LOGICAL_STATUS:
3029 	switch (cn->detail) {
3030 	case 0:
3031 	    ciss_name_device(sc, cn->data.logical_status.logical_drive);
3032 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3033 			cn->data.logical_status.logical_drive, ld->cl_name,
3034 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3035 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3036 			cn->data.logical_status.spare_state,
3037 			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3038 
3039 	    /*
3040 	     * Update our idea of the drive's status.
3041 	     */
3042 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3043 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3044 	    if (ld->cl_lstatus != NULL)
3045 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3046 
3047 #if 0
3048 	    /*
3049 	     * Have CAM rescan the drive if its status has changed.
3050 	     */
3051 	    if (ostatus != ld->cl_status)
3052 		ciss_cam_rescan_target(sc, cn->data.logical_status.logical_drive);
3053 #endif
3054 
3055 	    break;
3056 
3057 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3058 	    ciss_name_device(sc, cn->data.logical_status.logical_drive);
3059 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3060 			cn->data.logical_status.logical_drive, ld->cl_name);
3061 	    ciss_accept_media(sc, cn->data.logical_status.logical_drive, 1);
3062 	    break;
3063 
3064 	case 2:
3065 	case 3:
3066 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3067 			cn->data.rebuild_aborted.logical_drive,
3068 			sc->ciss_logical[cn->data.rebuild_aborted.logical_drive].cl_name,
3069 			(cn->detail == 2) ? "read" : "write");
3070 	    break;
3071 	}
3072 	break;
3073 
3074     case CISS_NOTIFY_LOGICAL_ERROR:
3075 	if (cn->detail == 0) {
3076 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3077 			cn->data.io_error.logical_drive,
3078 			sc->ciss_logical[cn->data.io_error.logical_drive].cl_name,
3079 			cn->data.io_error.failure_bus,
3080 			cn->data.io_error.failure_drive);
3081 	    /* XXX should we take the drive down at this point, or will we be told? */
3082 	}
3083 	break;
3084 
3085     case CISS_NOTIFY_LOGICAL_SURFACE:
3086 	if (cn->detail == 0)
3087 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
3088 			cn->data.consistency_completed.logical_drive,
3089 			sc->ciss_logical[cn->data.consistency_completed.logical_drive].cl_name);
3090 	break;
3091     }
3092 }
3093 
3094 /************************************************************************
3095  * Handle a notify event relating to the status of a physical drive.
3096  */
3097 static void
3098 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
3099 {
3100 
3101 }
3102 
3103 /************************************************************************
3104  * Print a request.
3105  */
3106 static void
3107 ciss_print_request(struct ciss_request *cr)
3108 {
3109     struct ciss_softc	*sc;
3110     struct ciss_command	*cc;
3111     int			i;
3112 
3113     sc = cr->cr_sc;
3114     cc = CISS_FIND_COMMAND(cr);
3115 
3116     ciss_printf(sc, "REQUEST @ %p\n", cr);
3117     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
3118 	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
3119 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
3120     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
3121 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
3122     switch(cc->header.address.mode.mode) {
3123     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
3124     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
3125 	ciss_printf(sc, "  physical bus %d target %d\n",
3126 		    cc->header.address.physical.bus, cc->header.address.physical.target);
3127 	break;
3128     case CISS_HDR_ADDRESS_MODE_LOGICAL:
3129 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
3130 	break;
3131     }
3132     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
3133 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
3134 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
3135 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
3136 		cc->cdb.cdb_length,
3137 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
3138 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
3139 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
3140 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
3141 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
3142 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
3143 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
3144     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
3145 
3146     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
3147 	/* XXX print error info */
3148     } else {
3149 	/* since we don't use chained s/g, don't support it here */
3150 	for (i = 0; i < cc->header.sg_in_list; i++) {
3151 	    if ((i % 4) == 0)
3152 		ciss_printf(sc, "   ");
3153 	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
3154 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
3155 		printf("\n");
3156 	}
3157     }
3158 }
3159 
3160 /************************************************************************
3161  * Print information about the status of a logical drive.
3162  */
3163 static void
3164 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
3165 {
3166     int		bus, target, i;
3167 
3168     if (ld->cl_lstatus == NULL) {
3169 	printf("does not exist\n");
3170 	return;
3171     }
3172 
3173     /* print drive status */
3174     switch(ld->cl_lstatus->status) {
3175     case CISS_LSTATUS_OK:
3176 	printf("online\n");
3177 	break;
3178     case CISS_LSTATUS_INTERIM_RECOVERY:
3179 	printf("in interim recovery mode\n");
3180 	break;
3181     case CISS_LSTATUS_READY_RECOVERY:
3182 	printf("ready to begin recovery\n");
3183 	break;
3184     case CISS_LSTATUS_RECOVERING:
3185 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3186 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3187 	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
3188 	       bus, target, ld->cl_lstatus->blocks_to_recover);
3189 	break;
3190     case CISS_LSTATUS_EXPANDING:
3191 	printf("being expanded, %u blocks remaining\n",
3192 	       ld->cl_lstatus->blocks_to_recover);
3193 	break;
3194     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3195 	printf("queued for expansion\n");
3196 	break;
3197     case CISS_LSTATUS_FAILED:
3198 	printf("queued for expansion\n");
3199 	break;
3200     case CISS_LSTATUS_WRONG_PDRIVE:
3201 	printf("wrong physical drive inserted\n");
3202 	break;
3203     case CISS_LSTATUS_MISSING_PDRIVE:
3204 	printf("missing a needed physical drive\n");
3205 	break;
3206     case CISS_LSTATUS_BECOMING_READY:
3207 	printf("becoming ready\n");
3208 	break;
3209     }
3210 
3211     /* print failed physical drives */
3212     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
3213 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
3214 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
3215 	if (bus == -1)
3216 	    continue;
3217 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
3218 		    ld->cl_lstatus->drive_failure_map[i]);
3219     }
3220 }
3221 
3222 #ifdef CISS_DEBUG
3223 /************************************************************************
3224  * Print information about the controller/driver.
3225  */
3226 static void
3227 ciss_print_adapter(struct ciss_softc *sc)
3228 {
3229     int		i;
3230 
3231     ciss_printf(sc, "ADAPTER:\n");
3232     for (i = 0; i < CISSQ_COUNT; i++) {
3233 	ciss_printf(sc, "%s     %d/%d\n",
3234 	    i == 0 ? "free" :
3235 	    i == 1 ? "busy" : "complete",
3236 	    sc->ciss_qstat[i].q_length,
3237 	    sc->ciss_qstat[i].q_max);
3238     }
3239     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
3240     ciss_printf(sc, "notify_head/tail %d/%d\n",
3241 	sc->ciss_notify_head, sc->ciss_notify_tail);
3242     ciss_printf(sc, "flags %b\n", sc->ciss_flags,
3243 	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
3244 
3245     for (i = 0; i < CISS_MAX_LOGICAL; i++) {
3246 	ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
3247 	ciss_print_ldrive(sc, sc->ciss_logical + i);
3248     }
3249 
3250     for (i = 1; i < sc->ciss_max_requests; i++)
3251 	ciss_print_request(sc->ciss_request + i);
3252 
3253 }
3254 
3255 /* DDB hook */
3256 static void
3257 ciss_print0(void)
3258 {
3259     struct ciss_softc	*sc;
3260 
3261     sc = devclass_get_softc(devclass_find("ciss"), 0);
3262     if (sc == NULL) {
3263 	printf("no ciss controllers\n");
3264     } else {
3265 	ciss_print_adapter(sc);
3266     }
3267 }
3268 #endif
3269 
3270 /************************************************************************
3271  * Return a name for a logical drive status value.
3272  */
3273 static const char *
3274 ciss_name_ldrive_status(int status)
3275 {
3276     switch (status) {
3277     case CISS_LSTATUS_OK:
3278 	return("OK");
3279     case CISS_LSTATUS_FAILED:
3280 	return("failed");
3281     case CISS_LSTATUS_NOT_CONFIGURED:
3282 	return("not configured");
3283     case CISS_LSTATUS_INTERIM_RECOVERY:
3284 	return("interim recovery");
3285     case CISS_LSTATUS_READY_RECOVERY:
3286 	return("ready for recovery");
3287     case CISS_LSTATUS_RECOVERING:
3288 	return("recovering");
3289     case CISS_LSTATUS_WRONG_PDRIVE:
3290 	return("wrong physical drive inserted");
3291     case CISS_LSTATUS_MISSING_PDRIVE:
3292 	return("missing physical drive");
3293     case CISS_LSTATUS_EXPANDING:
3294 	return("expanding");
3295     case CISS_LSTATUS_BECOMING_READY:
3296 	return("becoming ready");
3297     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3298 	return("queued for expansion");
3299     }
3300     return("unknown status");
3301 }
3302 
3303 /************************************************************************
3304  * Return an online/offline/nonexistent value for a logical drive
3305  * status value.
3306  */
3307 static int
3308 ciss_decode_ldrive_status(int status)
3309 {
3310     switch(status) {
3311     case CISS_LSTATUS_NOT_CONFIGURED:
3312 	return(CISS_LD_NONEXISTENT);
3313 
3314     case CISS_LSTATUS_OK:
3315     case CISS_LSTATUS_INTERIM_RECOVERY:
3316     case CISS_LSTATUS_READY_RECOVERY:
3317     case CISS_LSTATUS_RECOVERING:
3318     case CISS_LSTATUS_EXPANDING:
3319     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3320 	return(CISS_LD_ONLINE);
3321 
3322     case CISS_LSTATUS_FAILED:
3323     case CISS_LSTATUS_WRONG_PDRIVE:
3324     case CISS_LSTATUS_MISSING_PDRIVE:
3325     case CISS_LSTATUS_BECOMING_READY:
3326     default:
3327 	return(CISS_LD_OFFLINE);
3328     }
3329 }
3330 
3331 
3332 /************************************************************************
3333  * Return a name for a logical drive's organisation.
3334  */
3335 static const char *
3336 ciss_name_ldrive_org(int org)
3337 {
3338     switch(org) {
3339     case CISS_LDRIVE_RAID0:
3340 	return("RAID 0");
3341     case CISS_LDRIVE_RAID1:
3342 	return("RAID 1");
3343     case CISS_LDRIVE_RAID4:
3344 	return("RAID 4");
3345     case CISS_LDRIVE_RAID5:
3346 	return("RAID 5");
3347     }
3348     return("unkown");
3349 }
3350 
3351 /************************************************************************
3352  * Return a name for a command status value.
3353  */
3354 static const char *
3355 ciss_name_command_status(int status)
3356 {
3357     switch(status) {
3358     case CISS_CMD_STATUS_SUCCESS:
3359 	return("success");
3360     case CISS_CMD_STATUS_TARGET_STATUS:
3361 	return("target status");
3362     case CISS_CMD_STATUS_DATA_UNDERRUN:
3363 	return("data underrun");
3364     case CISS_CMD_STATUS_DATA_OVERRUN:
3365 	return("data overrun");
3366     case CISS_CMD_STATUS_INVALID_COMMAND:
3367 	return("invalid command");
3368     case CISS_CMD_STATUS_PROTOCOL_ERROR:
3369 	return("protocol error");
3370     case CISS_CMD_STATUS_HARDWARE_ERROR:
3371 	return("hardware error");
3372     case CISS_CMD_STATUS_CONNECTION_LOST:
3373 	return("connection lost");
3374     case CISS_CMD_STATUS_ABORTED:
3375 	return("aborted");
3376     case CISS_CMD_STATUS_ABORT_FAILED:
3377 	return("abort failed");
3378     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
3379 	return("unsolicited abort");
3380     case CISS_CMD_STATUS_TIMEOUT:
3381 	return("timeout");
3382     case CISS_CMD_STATUS_UNABORTABLE:
3383 	return("unabortable");
3384     }
3385     return("unknown status");
3386 }
3387 
3388 /************************************************************************
3389  * Handle an open on the control device.
3390  */
3391 static int
3392 ciss_open(dev_t dev, int flags, int fmt, d_thread_t *p)
3393 {
3394     struct ciss_softc	*sc;
3395 
3396     debug_called(1);
3397 
3398     sc = (struct ciss_softc *)dev->si_drv1;
3399 
3400     /* we might want to veto if someone already has us open */
3401 
3402     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
3403     return(0);
3404 }
3405 
3406 /************************************************************************
3407  * Handle the last close on the control device.
3408  */
3409 static int
3410 ciss_close(dev_t dev, int flags, int fmt, d_thread_t *p)
3411 {
3412     struct ciss_softc	*sc;
3413 
3414     debug_called(1);
3415 
3416     sc = (struct ciss_softc *)dev->si_drv1;
3417 
3418     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
3419     return (0);
3420 }
3421 
3422 /********************************************************************************
3423  * Handle adapter-specific control operations.
3424  *
3425  * Note that the API here is compatible with the Linux driver, in order to
3426  * simplify the porting of Compaq's userland tools.
3427  */
3428 static int
3429 ciss_ioctl(dev_t dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *p)
3430 {
3431     struct ciss_softc		*sc;
3432     int				error;
3433 
3434     debug_called(1);
3435 
3436     sc = (struct ciss_softc *)dev->si_drv1;
3437     error = 0;
3438 
3439     switch(cmd) {
3440     case CCISS_GETPCIINFO:
3441     {
3442 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
3443 
3444 	pis->bus = pci_get_bus(sc->ciss_dev);
3445 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
3446 	pis->board_id = pci_get_devid(sc->ciss_dev);
3447 
3448 	break;
3449     }
3450 
3451     case CCISS_GETINTINFO:
3452     {
3453 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
3454 
3455 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
3456 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
3457 
3458 	break;
3459     }
3460 
3461     case CCISS_SETINTINFO:
3462     {
3463 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
3464 
3465 	if ((cis->delay == 0) && (cis->count == 0)) {
3466 	    error = EINVAL;
3467 	    break;
3468 	}
3469 
3470 	/*
3471 	 * XXX apparently this is only safe if the controller is idle,
3472 	 *     we should suspend it before doing this.
3473 	 */
3474 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
3475 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
3476 
3477 	if (ciss_update_config(sc))
3478 	    error = EIO;
3479 
3480 	/* XXX resume the controller here */
3481 	break;
3482     }
3483 
3484     case CCISS_GETNODENAME:
3485 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
3486 	      sizeof(NodeName_type));
3487 	break;
3488 
3489     case CCISS_SETNODENAME:
3490 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
3491 	      sizeof(NodeName_type));
3492 	if (ciss_update_config(sc))
3493 	    error = EIO;
3494 	break;
3495 
3496     case CCISS_GETHEARTBEAT:
3497 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
3498 	break;
3499 
3500     case CCISS_GETBUSTYPES:
3501 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
3502 	break;
3503 
3504     case CCISS_GETFIRMVER:
3505 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
3506 	      sizeof(FirmwareVer_type));
3507 	break;
3508 
3509     case CCISS_GETDRIVERVER:
3510 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
3511 	break;
3512 
3513     case CCISS_REVALIDVOLS:
3514 	/*
3515 	 * This is a bit ugly; to do it "right" we really need
3516 	 * to find any disks that have changed, kick CAM off them,
3517 	 * then rescan only these disks.  It'd be nice if they
3518 	 * a) told us which disk(s) they were going to play with,
3519 	 * and b) which ones had arrived. 8(
3520 	 */
3521 	break;
3522 
3523     case CCISS_PASSTHRU:
3524 	error = ciss_user_command(sc, (IOCTL_Command_struct *)addr);
3525 	break;
3526 
3527     default:
3528 	debug(0, "unknown ioctl 0x%lx", cmd);
3529 
3530 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
3531 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
3532 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
3533 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
3534 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
3535 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
3536 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
3537 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
3538 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
3539 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
3540 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
3541 
3542 	error = ENOIOCTL;
3543 	break;
3544     }
3545 
3546     return(error);
3547 }
3548