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