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