xref: /freebsd/sys/dev/ciss/ciss.c (revision 2546665afcaf0d53dc2c7058fee96354b3680f5a)
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     { 0x0e11, 0x409E, CISS_BOARD_SA5,	"HP Smart Array 6422" },
272     { 0x103C, 0x3210, CISS_BOARD_SA5,	"HP Smart Array V100" },
273     { 0x103C, 0x3220, CISS_BOARD_SA5,	"HP Smart Array" },
274     { 0x103C, 0x3222, CISS_BOARD_SA5,	"HP Smart Array" },
275     { 0x103C, 0x3230, CISS_BOARD_SA5,	"HP Smart Array" },
276     { 0x103C, 0x3231, CISS_BOARD_SA5,	"HP Smart Array" },
277     { 0x103C, 0x3232, CISS_BOARD_SA5,	"HP Smart Array" },
278     { 0x103C, 0x3233, CISS_BOARD_SA5,	"HP Smart Array" },
279     { 0x103C, 0x3234, CISS_BOARD_SA5,	"HP Smart Array" },
280     { 0x103C, 0x3235, CISS_BOARD_SA5,	"HP Smart Array" },
281     { 0x103C, 0x3236, CISS_BOARD_SA5,	"HP Smart Array" },
282     { 0x103C, 0x3237, CISS_BOARD_SA5,	"HP Smart Array" },
283     { 0x103C, 0x3238, CISS_BOARD_SA5,	"HP Smart Array" },
284     { 0x103C, 0x3239, CISS_BOARD_SA5,	"HP Smart Array" },
285     { 0x103C, 0x323A, CISS_BOARD_SA5,	"HP Smart Array" },
286     { 0x103C, 0x323B, CISS_BOARD_SA5,	"HP Smart Array" },
287     { 0x103C, 0x323C, CISS_BOARD_SA5,	"HP Smart Array" },
288     { 0, 0, 0, NULL }
289 };
290 
291 /************************************************************************
292  * Find a match for the device in our list of known adapters.
293  */
294 static int
295 ciss_lookup(device_t dev)
296 {
297     int 	i;
298 
299     for (i = 0; ciss_vendor_data[i].desc != NULL; i++)
300 	if ((pci_get_subvendor(dev) == ciss_vendor_data[i].subvendor) &&
301 	    (pci_get_subdevice(dev) == ciss_vendor_data[i].subdevice)) {
302 	    return(i);
303 	}
304     return(-1);
305 }
306 
307 /************************************************************************
308  * Match a known CISS adapter.
309  */
310 static int
311 ciss_probe(device_t dev)
312 {
313     int		i;
314 
315     i = ciss_lookup(dev);
316     if (i != -1) {
317 	device_set_desc(dev, ciss_vendor_data[i].desc);
318 	return(-10);
319     }
320     return(ENOENT);
321 }
322 
323 /************************************************************************
324  * Attach the driver to this adapter.
325  */
326 static int
327 ciss_attach(device_t dev)
328 {
329     struct ciss_softc	*sc;
330     int			i, error;
331 
332     debug_called(1);
333 
334 #ifdef CISS_DEBUG
335     /* print structure/union sizes */
336     debug_struct(ciss_command);
337     debug_struct(ciss_header);
338     debug_union(ciss_device_address);
339     debug_struct(ciss_cdb);
340     debug_struct(ciss_report_cdb);
341     debug_struct(ciss_notify_cdb);
342     debug_struct(ciss_notify);
343     debug_struct(ciss_message_cdb);
344     debug_struct(ciss_error_info_pointer);
345     debug_struct(ciss_error_info);
346     debug_struct(ciss_sg_entry);
347     debug_struct(ciss_config_table);
348     debug_struct(ciss_bmic_cdb);
349     debug_struct(ciss_bmic_id_ldrive);
350     debug_struct(ciss_bmic_id_lstatus);
351     debug_struct(ciss_bmic_id_table);
352     debug_struct(ciss_bmic_id_pdrive);
353     debug_struct(ciss_bmic_blink_pdrive);
354     debug_struct(ciss_bmic_flush_cache);
355     debug_const(CISS_MAX_REQUESTS);
356     debug_const(CISS_MAX_LOGICAL);
357     debug_const(CISS_INTERRUPT_COALESCE_DELAY);
358     debug_const(CISS_INTERRUPT_COALESCE_COUNT);
359     debug_const(CISS_COMMAND_ALLOC_SIZE);
360     debug_const(CISS_COMMAND_SG_LENGTH);
361 
362     debug_type(cciss_pci_info_struct);
363     debug_type(cciss_coalint_struct);
364     debug_type(cciss_coalint_struct);
365     debug_type(NodeName_type);
366     debug_type(NodeName_type);
367     debug_type(Heartbeat_type);
368     debug_type(BusTypes_type);
369     debug_type(FirmwareVer_type);
370     debug_type(DriverVer_type);
371     debug_type(IOCTL_Command_struct);
372 #endif
373 
374     sc = device_get_softc(dev);
375     sc->ciss_dev = dev;
376 
377     /*
378      * Work out adapter type.
379      */
380     i = ciss_lookup(dev);
381     if (ciss_vendor_data[i].flags & CISS_BOARD_SA5) {
382 	sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5;
383     } else if (ciss_vendor_data[i].flags & CISS_BOARD_SA5B) {
384 	sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5B;
385     } else {
386 	/* really an error on our part */
387 	ciss_printf(sc, "unable to determine hardware type\n");
388 	error = ENXIO;
389 	goto out;
390     }
391 
392     /*
393      * Do PCI-specific init.
394      */
395     if ((error = ciss_init_pci(sc)) != 0)
396 	goto out;
397 
398     /*
399      * Initialise driver queues.
400      */
401     ciss_initq_free(sc);
402     ciss_initq_busy(sc);
403     ciss_initq_complete(sc);
404     ciss_initq_notify(sc);
405 
406     /*
407      * Initialise command/request pool.
408      */
409     if ((error = ciss_init_requests(sc)) != 0)
410 	goto out;
411 
412     /*
413      * Get adapter information.
414      */
415     if ((error = ciss_identify_adapter(sc)) != 0)
416 	goto out;
417 
418     /*
419      * Find all the physical devices.
420      */
421     if ((error = ciss_init_physical(sc)) != 0)
422 	goto out;
423 
424     /*
425      * Build our private table of logical devices.
426      */
427     if ((error = ciss_init_logical(sc)) != 0)
428 	goto out;
429 
430     /*
431      * Enable interrupts so that the CAM scan can complete.
432      */
433     CISS_TL_SIMPLE_ENABLE_INTERRUPTS(sc);
434 
435     /*
436      * Initialise the CAM interface.
437      */
438     if ((error = ciss_cam_init(sc)) != 0)
439 	goto out;
440 
441     /*
442      * Start the heartbeat routine and event chain.
443      */
444     ciss_periodic(sc);
445 
446    /*
447      * Create the control device.
448      */
449     sc->ciss_dev_t = make_dev(&ciss_cdevsw, device_get_unit(sc->ciss_dev),
450 			      UID_ROOT, GID_OPERATOR, S_IRUSR | S_IWUSR,
451 			      "ciss%d", device_get_unit(sc->ciss_dev));
452     sc->ciss_dev_t->si_drv1 = sc;
453 
454     /*
455      * The adapter is running; synchronous commands can now sleep
456      * waiting for an interrupt to signal completion.
457      */
458     sc->ciss_flags |= CISS_FLAG_RUNNING;
459 
460     ciss_spawn_notify_thread(sc);
461 
462     error = 0;
463  out:
464     if (error != 0)
465 	ciss_free(sc);
466     return(error);
467 }
468 
469 /************************************************************************
470  * Detach the driver from this adapter.
471  */
472 static int
473 ciss_detach(device_t dev)
474 {
475     struct ciss_softc	*sc = device_get_softc(dev);
476 
477     debug_called(1);
478 
479     if (sc->ciss_flags & CISS_FLAG_CONTROL_OPEN)
480 	return (EBUSY);
481 
482     /* flush adapter cache */
483     ciss_flush_adapter(sc);
484 
485     /* release all resources */
486     ciss_free(sc);
487 
488     return(0);
489 }
490 
491 /************************************************************************
492  * Prepare adapter for system shutdown.
493  */
494 static int
495 ciss_shutdown(device_t dev)
496 {
497     struct ciss_softc	*sc = device_get_softc(dev);
498 
499     debug_called(1);
500 
501     /* flush adapter cache */
502     ciss_flush_adapter(sc);
503 
504     return(0);
505 }
506 
507 /************************************************************************
508  * Perform PCI-specific attachment actions.
509  */
510 static int
511 ciss_init_pci(struct ciss_softc *sc)
512 {
513     uintptr_t		cbase, csize, cofs;
514     int			error;
515 
516     debug_called(1);
517 
518     /*
519      * Allocate register window first (we need this to find the config
520      * struct).
521      */
522     error = ENXIO;
523     sc->ciss_regs_rid = CISS_TL_SIMPLE_BAR_REGS;
524     if ((sc->ciss_regs_resource =
525 	 bus_alloc_resource_any(sc->ciss_dev, SYS_RES_MEMORY,
526 				&sc->ciss_regs_rid, RF_ACTIVE)) == NULL) {
527 	ciss_printf(sc, "can't allocate register window\n");
528 	return(ENXIO);
529     }
530     sc->ciss_regs_bhandle = rman_get_bushandle(sc->ciss_regs_resource);
531     sc->ciss_regs_btag = rman_get_bustag(sc->ciss_regs_resource);
532 
533     /*
534      * Find the BAR holding the config structure.  If it's not the one
535      * we already mapped for registers, map it too.
536      */
537     sc->ciss_cfg_rid = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_BAR) & 0xffff;
538     if (sc->ciss_cfg_rid != sc->ciss_regs_rid) {
539 	if ((sc->ciss_cfg_resource =
540 	     bus_alloc_resource_any(sc->ciss_dev, SYS_RES_MEMORY,
541 				    &sc->ciss_cfg_rid, RF_ACTIVE)) == NULL) {
542 	    ciss_printf(sc, "can't allocate config window\n");
543 	    return(ENXIO);
544 	}
545 	cbase = (uintptr_t)rman_get_virtual(sc->ciss_cfg_resource);
546 	csize = rman_get_end(sc->ciss_cfg_resource) -
547 	    rman_get_start(sc->ciss_cfg_resource) + 1;
548     } else {
549 	cbase = (uintptr_t)rman_get_virtual(sc->ciss_regs_resource);
550 	csize = rman_get_end(sc->ciss_regs_resource) -
551 	    rman_get_start(sc->ciss_regs_resource) + 1;
552     }
553     cofs = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_OFF);
554 
555     /*
556      * Use the base/size/offset values we just calculated to
557      * sanity-check the config structure.  If it's OK, point to it.
558      */
559     if ((cofs + sizeof(struct ciss_config_table)) > csize) {
560 	ciss_printf(sc, "config table outside window\n");
561 	return(ENXIO);
562     }
563     sc->ciss_cfg = (struct ciss_config_table *)(cbase + cofs);
564     debug(1, "config struct at %p", sc->ciss_cfg);
565 
566     /*
567      * Validate the config structure.  If we supported other transport
568      * methods, we could select amongst them at this point in time.
569      */
570     if (strncmp(sc->ciss_cfg->signature, "CISS", 4)) {
571 	ciss_printf(sc, "config signature mismatch (got '%c%c%c%c')\n",
572 		    sc->ciss_cfg->signature[0], sc->ciss_cfg->signature[1],
573 		    sc->ciss_cfg->signature[2], sc->ciss_cfg->signature[3]);
574 	return(ENXIO);
575     }
576     if ((sc->ciss_cfg->valence < CISS_MIN_VALENCE) ||
577 	(sc->ciss_cfg->valence > CISS_MAX_VALENCE)) {
578 	ciss_printf(sc, "adapter interface specification (%d) unsupported\n",
579 		    sc->ciss_cfg->valence);
580 	return(ENXIO);
581     }
582 
583     /*
584      * Put the board into simple mode, and tell it we're using the low
585      * 4GB of RAM.  Set the default interrupt coalescing options.
586      */
587     if (!(sc->ciss_cfg->supported_methods & CISS_TRANSPORT_METHOD_SIMPLE)) {
588 	ciss_printf(sc, "adapter does not support 'simple' transport layer\n");
589 	return(ENXIO);
590     }
591     sc->ciss_cfg->requested_method = CISS_TRANSPORT_METHOD_SIMPLE;
592     sc->ciss_cfg->command_physlimit = 0;
593     sc->ciss_cfg->interrupt_coalesce_delay = CISS_INTERRUPT_COALESCE_DELAY;
594     sc->ciss_cfg->interrupt_coalesce_count = CISS_INTERRUPT_COALESCE_COUNT;
595 
596 #ifdef __i386__
597     sc->ciss_cfg->host_driver |= CISS_DRIVER_SCSI_PREFETCH;
598 #endif
599 
600     if (ciss_update_config(sc)) {
601 	ciss_printf(sc, "adapter refuses to accept config update (IDBR 0x%x)\n",
602 		    CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR));
603 	return(ENXIO);
604     }
605     if (!(sc->ciss_cfg->active_method != CISS_TRANSPORT_METHOD_SIMPLE)) {
606 	ciss_printf(sc,
607 		    "adapter refuses to go into 'simple' transport mode (0x%x, 0x%x)\n",
608 		    sc->ciss_cfg->supported_methods, sc->ciss_cfg->active_method);
609 	return(ENXIO);
610     }
611 
612     /*
613      * Wait for the adapter to come ready.
614      */
615     if ((error = ciss_wait_adapter(sc)) != 0)
616 	return(error);
617 
618     /*
619      * Turn off interrupts before we go routing anything.
620      */
621     CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
622 
623     /*
624      * Allocate and set up our interrupt.
625      */
626     sc->ciss_irq_rid = 0;
627     if ((sc->ciss_irq_resource =
628 	 bus_alloc_resource_any(sc->ciss_dev, SYS_RES_IRQ, &sc->ciss_irq_rid,
629 				RF_ACTIVE | RF_SHAREABLE)) == NULL) {
630 	ciss_printf(sc, "can't allocate interrupt\n");
631 	return(ENXIO);
632     }
633     if (bus_setup_intr(sc->ciss_dev, sc->ciss_irq_resource, INTR_TYPE_CAM, 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 	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
2171 	    free(buf, CISS_MALLOC_CLASS);
2172     } else {
2173 	*crp = cr;
2174 	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
2175 	    *bufp = buf;
2176     }
2177     return(error);
2178 }
2179 
2180 /************************************************************************
2181  * Handle a command passed in from userspace.
2182  */
2183 static int
2184 ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
2185 {
2186     struct ciss_request		*cr;
2187     struct ciss_command		*cc;
2188     struct ciss_error_info	*ce;
2189     int				error = 0;
2190 
2191     debug_called(1);
2192 
2193     cr = NULL;
2194 
2195     /*
2196      * Get a request.
2197      */
2198     if ((error = ciss_get_request(sc, &cr)) != 0)
2199 	goto out;
2200     cc = CISS_FIND_COMMAND(cr);
2201 
2202     /*
2203      * Allocate an in-kernel databuffer if required, copy in user data.
2204      */
2205     cr->cr_length = ioc->buf_size;
2206     if (ioc->buf_size > 0) {
2207 	if ((cr->cr_data = malloc(ioc->buf_size, CISS_MALLOC_CLASS, M_WAITOK)) == NULL) {
2208 	    error = ENOMEM;
2209 	    goto out;
2210 	}
2211 	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
2212 	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2213 	    goto out;
2214 	}
2215     }
2216 
2217     /*
2218      * Build the request based on the user command.
2219      */
2220     bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
2221     bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
2222 
2223     /* XXX anything else to populate here? */
2224 
2225     /*
2226      * Run the command.
2227      */
2228     if ((error = ciss_synch_request(cr, 60 * 1000))) {
2229 	debug(0, "request failed - %d", error);
2230 	goto out;
2231     }
2232 
2233     /*
2234      * Check to see if the command succeeded.
2235      */
2236     ce = (struct ciss_error_info *)&(cc->sg[0]);
2237     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) == 0)
2238 	bzero(ce, sizeof(*ce));
2239 
2240     /*
2241      * Copy the results back to the user.
2242      */
2243     bcopy(ce, &ioc->error_info, sizeof(*ce));
2244     if ((ioc->buf_size > 0) &&
2245 	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
2246 	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2247 	goto out;
2248     }
2249 
2250     /* done OK */
2251     error = 0;
2252 
2253 out:
2254     if ((cr != NULL) && (cr->cr_data != NULL))
2255 	free(cr->cr_data, CISS_MALLOC_CLASS);
2256     if (cr != NULL)
2257 	ciss_release_request(cr);
2258     return(error);
2259 }
2260 
2261 /************************************************************************
2262  * Map a request into bus-visible space, initialise the scatter/gather
2263  * list.
2264  */
2265 static int
2266 ciss_map_request(struct ciss_request *cr)
2267 {
2268     struct ciss_softc	*sc;
2269     int			error = 0;
2270 
2271     debug_called(2);
2272 
2273     sc = cr->cr_sc;
2274 
2275     /* check that mapping is necessary */
2276     if (cr->cr_flags & CISS_REQ_MAPPED)
2277 	return(0);
2278 
2279     cr->cr_flags |= CISS_REQ_MAPPED;
2280 
2281     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2282 		    BUS_DMASYNC_PREWRITE);
2283 
2284     if (cr->cr_data != NULL) {
2285 	error = bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap,
2286 				cr->cr_data, cr->cr_length,
2287 				ciss_request_map_helper, cr, 0);
2288 	if (error != 0)
2289 	    return (error);
2290     } else {
2291 	/*
2292 	 * Post the command to the adapter.
2293 	 */
2294 	ciss_enqueue_busy(cr);
2295 	CISS_TL_SIMPLE_POST_CMD(cr->cr_sc, CISS_FIND_COMMANDPHYS(cr));
2296     }
2297 
2298     return(0);
2299 }
2300 
2301 static void
2302 ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2303 {
2304     struct ciss_command	*cc;
2305     struct ciss_request *cr;
2306     struct ciss_softc	*sc;
2307     int			i;
2308 
2309     debug_called(2);
2310 
2311     cr = (struct ciss_request *)arg;
2312     sc = cr->cr_sc;
2313     cc = CISS_FIND_COMMAND(cr);
2314 
2315     for (i = 0; i < nseg; i++) {
2316 	cc->sg[i].address = segs[i].ds_addr;
2317 	cc->sg[i].length = segs[i].ds_len;
2318 	cc->sg[i].extension = 0;
2319     }
2320     /* we leave the s/g table entirely within the command */
2321     cc->header.sg_in_list = nseg;
2322     cc->header.sg_total = nseg;
2323 
2324     if (cr->cr_flags & CISS_REQ_DATAIN)
2325 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2326     if (cr->cr_flags & CISS_REQ_DATAOUT)
2327 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2328 
2329     /*
2330      * Post the command to the adapter.
2331      */
2332     ciss_enqueue_busy(cr);
2333     CISS_TL_SIMPLE_POST_CMD(cr->cr_sc, CISS_FIND_COMMANDPHYS(cr));
2334 }
2335 
2336 /************************************************************************
2337  * Unmap a request from bus-visible space.
2338  */
2339 static void
2340 ciss_unmap_request(struct ciss_request *cr)
2341 {
2342     struct ciss_softc	*sc;
2343 
2344     debug_called(2);
2345 
2346     sc = cr->cr_sc;
2347 
2348     /* check that unmapping is necessary */
2349     if ((cr->cr_flags & CISS_REQ_MAPPED) == 0)
2350 	return;
2351 
2352     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2353 		    BUS_DMASYNC_POSTWRITE);
2354 
2355     if (cr->cr_data == NULL)
2356 	goto out;
2357 
2358     if (cr->cr_flags & CISS_REQ_DATAIN)
2359 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2360     if (cr->cr_flags & CISS_REQ_DATAOUT)
2361 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2362 
2363     bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2364 out:
2365     cr->cr_flags &= ~CISS_REQ_MAPPED;
2366 }
2367 
2368 /************************************************************************
2369  * Attach the driver to CAM.
2370  *
2371  * We put all the logical drives on a single SCSI bus.
2372  */
2373 static int
2374 ciss_cam_init(struct ciss_softc *sc)
2375 {
2376     int			i, maxbus;
2377 
2378     debug_called(1);
2379 
2380     /*
2381      * Allocate a devq.  We can reuse this for the masked physical
2382      * devices if we decide to export these as well.
2383      */
2384     if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests)) == NULL) {
2385 	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2386 	return(ENOMEM);
2387     }
2388 
2389     /*
2390      * Create a SIM.
2391      *
2392      * This naturally wastes a bit of memory.  The alternative is to allocate
2393      * and register each bus as it is found, and then track them on a linked
2394      * list.  Unfortunately, the driver has a few places where it needs to
2395      * look up the SIM based solely on bus number, and it's unclear whether
2396      * a list traversal would work for these situations.
2397      */
2398     maxbus = max(sc->ciss_max_logical_bus, sc->ciss_max_physical_bus +
2399 		 CISS_PHYSICAL_BASE);
2400     sc->ciss_cam_sim = malloc(maxbus * sizeof(struct cam_sim*),
2401 			      CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
2402     if (sc->ciss_cam_sim == NULL) {
2403 	ciss_printf(sc, "can't allocate memory for controller SIM\n");
2404 	return(ENOMEM);
2405     }
2406 
2407     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
2408 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2409 						 "ciss", sc,
2410 						 device_get_unit(sc->ciss_dev),
2411 						 sc->ciss_max_requests - 2,
2412 						 1,
2413 						 sc->ciss_cam_devq)) == NULL) {
2414 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2415 	    return(ENOMEM);
2416 	}
2417 
2418 	/*
2419 	 * Register bus with this SIM.
2420 	 */
2421 	if (i == 0 || sc->ciss_controllers[i].physical.bus != 0) {
2422 	    if (xpt_bus_register(sc->ciss_cam_sim[i], i) != 0) {
2423 		ciss_printf(sc, "can't register SCSI bus %d\n", i);
2424 		return (ENXIO);
2425 	    }
2426 	}
2427     }
2428 
2429     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2430 	 CISS_PHYSICAL_BASE; i++) {
2431 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2432 						 "ciss", sc,
2433 						 device_get_unit(sc->ciss_dev),
2434 						 sc->ciss_max_requests - 2,
2435 						 1,
2436 						 sc->ciss_cam_devq)) == NULL) {
2437 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2438 	    return (ENOMEM);
2439 	}
2440 
2441 	if (xpt_bus_register(sc->ciss_cam_sim[i], i) != 0) {
2442 	    ciss_printf(sc, "can't register SCSI bus %d\n", i);
2443 	    return (ENXIO);
2444 	}
2445     }
2446 
2447     /*
2448      * Initiate a rescan of the bus.
2449      */
2450     ciss_cam_rescan_all(sc);
2451 
2452     return(0);
2453 }
2454 
2455 /************************************************************************
2456  * Initiate a rescan of the 'logical devices' SIM
2457  */
2458 static void
2459 ciss_cam_rescan_target(struct ciss_softc *sc, int bus, int target)
2460 {
2461     struct cam_path	*path;
2462     union ccb		*ccb;
2463 
2464     debug_called(1);
2465 
2466     if ((ccb = malloc(sizeof(union ccb), M_TEMP, M_WAITOK | M_ZERO)) == NULL) {
2467 	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2468 	return;
2469     }
2470 
2471     if (xpt_create_path(&path, xpt_periph, cam_sim_path(sc->ciss_cam_sim[bus]),
2472 			target, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2473 	ciss_printf(sc, "rescan failed (can't create path)\n");
2474 	free(ccb, M_TEMP);
2475 	return;
2476     }
2477 
2478     xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
2479     ccb->ccb_h.func_code = XPT_SCAN_BUS;
2480     ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2481     ccb->crcn.flags = CAM_FLAG_NONE;
2482     xpt_action(ccb);
2483 
2484     /* scan is now in progress */
2485 }
2486 
2487 static void
2488 ciss_cam_rescan_all(struct ciss_softc *sc)
2489 {
2490     int i;
2491 
2492     /* Rescan the logical buses */
2493     for (i = 0; i < sc->ciss_max_logical_bus; i++)
2494 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2495     /* Rescan the physical buses */
2496     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2497 	 CISS_PHYSICAL_BASE; i++)
2498 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2499 }
2500 
2501 static void
2502 ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2503 {
2504     xpt_free_path(ccb->ccb_h.path);
2505     free(ccb, M_TEMP);
2506 }
2507 
2508 /************************************************************************
2509  * Handle requests coming from CAM
2510  */
2511 static void
2512 ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2513 {
2514     struct ciss_softc	*sc;
2515     struct ccb_scsiio	*csio;
2516     int			bus, target;
2517     int			physical;
2518 
2519     sc = cam_sim_softc(sim);
2520     bus = cam_sim_bus(sim);
2521     csio = (struct ccb_scsiio *)&ccb->csio;
2522     target = csio->ccb_h.target_id;
2523     physical = CISS_IS_PHYSICAL(bus);
2524 
2525     switch (ccb->ccb_h.func_code) {
2526 
2527 	/* perform SCSI I/O */
2528     case XPT_SCSI_IO:
2529 	if (!ciss_cam_action_io(sim, csio))
2530 	    return;
2531 	break;
2532 
2533 	/* perform geometry calculations */
2534     case XPT_CALC_GEOMETRY:
2535     {
2536 	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2537 	struct ciss_ldrive		*ld;
2538 
2539 	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2540 
2541 	ld = NULL;
2542 	if (!physical)
2543 	    ld = &sc->ciss_logical[bus][target];
2544 
2545 	/*
2546 	 * Use the cached geometry settings unless the fault tolerance
2547 	 * is invalid.
2548 	 */
2549 	if (physical || ld->cl_geometry.fault_tolerance == 0xFF) {
2550 	    u_int32_t			secs_per_cylinder;
2551 
2552 	    ccg->heads = 255;
2553 	    ccg->secs_per_track = 32;
2554 	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2555 	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2556 	} else {
2557 	    ccg->heads = ld->cl_geometry.heads;
2558 	    ccg->secs_per_track = ld->cl_geometry.sectors;
2559 	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2560 	}
2561 	ccb->ccb_h.status = CAM_REQ_CMP;
2562         break;
2563     }
2564 
2565 	/* handle path attribute inquiry */
2566     case XPT_PATH_INQ:
2567     {
2568 	struct ccb_pathinq	*cpi = &ccb->cpi;
2569 
2570 	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2571 
2572 	cpi->version_num = 1;
2573 	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2574 	cpi->target_sprt = 0;
2575 	cpi->hba_misc = 0;
2576 	cpi->max_target = CISS_MAX_LOGICAL;
2577 	cpi->max_lun = 0;		/* 'logical drive' channel only */
2578 	cpi->initiator_id = CISS_MAX_LOGICAL;
2579 	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2580         strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2581         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2582         cpi->unit_number = cam_sim_unit(sim);
2583         cpi->bus_id = cam_sim_bus(sim);
2584 	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2585 	ccb->ccb_h.status = CAM_REQ_CMP;
2586 	break;
2587     }
2588 
2589     case XPT_GET_TRAN_SETTINGS:
2590     {
2591 	struct ccb_trans_settings	*cts = &ccb->cts;
2592 	int				bus, target;
2593 
2594 	bus = cam_sim_bus(sim);
2595 	target = cts->ccb_h.target_id;
2596 
2597 	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2598 	cts->valid = 0;
2599 
2600 	/* disconnect always OK */
2601 	cts->flags |= CCB_TRANS_DISC_ENB;
2602 	cts->valid |= CCB_TRANS_DISC_VALID;
2603 
2604 	cts->ccb_h.status = CAM_REQ_CMP;
2605 	break;
2606     }
2607 
2608     default:		/* we can't do this */
2609 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
2610 	ccb->ccb_h.status = CAM_REQ_INVALID;
2611 	break;
2612     }
2613 
2614     xpt_done(ccb);
2615 }
2616 
2617 /************************************************************************
2618  * Handle a CAM SCSI I/O request.
2619  */
2620 static int
2621 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
2622 {
2623     struct ciss_softc	*sc;
2624     int			bus, target;
2625     struct ciss_request	*cr;
2626     struct ciss_command	*cc;
2627     int			error;
2628 
2629     sc = cam_sim_softc(sim);
2630     bus = cam_sim_bus(sim);
2631     target = csio->ccb_h.target_id;
2632 
2633     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
2634 
2635     /* firmware does not support commands > 10 bytes */
2636     if (csio->cdb_len > 12/*CISS_CDB_BUFFER_SIZE*/) {
2637 	debug(3, "  command too large (%d > %d)", csio->cdb_len, CISS_CDB_BUFFER_SIZE);
2638 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2639     }
2640 
2641     /* check that the CDB pointer is not to a physical address */
2642     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
2643 	debug(3, "  CDB pointer is to physical address");
2644 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2645     }
2646 
2647     /* if there is data transfer, it must be to/from a virtual address */
2648     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2649 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
2650 	    debug(3, "  data pointer is to physical address");
2651 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2652 	}
2653 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
2654 	    debug(3, "  data has premature s/g setup");
2655 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2656 	}
2657     }
2658 
2659     /* abandon aborted ccbs or those that have failed validation */
2660     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2661 	debug(3, "abandoning CCB due to abort/validation failure");
2662 	return(EINVAL);
2663     }
2664 
2665     /* handle emulation of some SCSI commands ourself */
2666     if (ciss_cam_emulate(sc, csio))
2667 	return(0);
2668 
2669     /*
2670      * Get a request to manage this command.  If we can't, return the
2671      * ccb, freeze the queue and flag so that we unfreeze it when a
2672      * request completes.
2673      */
2674     if ((error = ciss_get_request(sc, &cr)) != 0) {
2675 	xpt_freeze_simq(sim, 1);
2676 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
2677 	return(error);
2678     }
2679 
2680     /*
2681      * Build the command.
2682      */
2683     cc = CISS_FIND_COMMAND(cr);
2684     cr->cr_data = csio->data_ptr;
2685     cr->cr_length = csio->dxfer_len;
2686     cr->cr_complete = ciss_cam_complete;
2687     cr->cr_private = csio;
2688 
2689     /*
2690      * Target the right logical volume.
2691      */
2692     if (CISS_IS_PHYSICAL(bus))
2693 	cc->header.address =
2694 	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
2695     else
2696 	cc->header.address =
2697 	    sc->ciss_logical[bus][target].cl_address;
2698     cc->cdb.cdb_length = csio->cdb_len;
2699     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2700     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
2701     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2702 	cr->cr_flags = CISS_REQ_DATAOUT;
2703 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
2704     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2705 	cr->cr_flags = CISS_REQ_DATAIN;
2706 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2707     } else {
2708 	cr->cr_flags = 0;
2709 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2710     }
2711     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
2712     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2713 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
2714     } else {
2715 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
2716     }
2717 
2718     /*
2719      * Submit the request to the adapter.
2720      *
2721      * Note that this may fail if we're unable to map the request (and
2722      * if we ever learn a transport layer other than simple, may fail
2723      * if the adapter rejects the command).
2724      */
2725     if ((error = ciss_start(cr)) != 0) {
2726 	xpt_freeze_simq(sim, 1);
2727 	if (error == EINPROGRESS) {
2728 	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2729 	    error = 0;
2730 	} else {
2731 	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
2732 	    ciss_release_request(cr);
2733 	}
2734 	return(error);
2735     }
2736 
2737     return(0);
2738 }
2739 
2740 /************************************************************************
2741  * Emulate SCSI commands the adapter doesn't handle as we might like.
2742  */
2743 static int
2744 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
2745 {
2746     int		bus, target;
2747     u_int8_t	opcode;
2748 
2749     target = csio->ccb_h.target_id;
2750     bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
2751     opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
2752 	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
2753 
2754     if (CISS_IS_PHYSICAL(bus)) {
2755 	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
2756 	    csio->ccb_h.status = CAM_SEL_TIMEOUT;
2757 	    xpt_done((union ccb *)csio);
2758 	    return(1);
2759 	} else
2760 	    return(0);
2761     }
2762 
2763     /*
2764      * Handle requests for volumes that don't exist or are not online.
2765      * A selection timeout is slightly better than an illegal request.
2766      * Other errors might be better.
2767      */
2768     if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
2769 	csio->ccb_h.status = CAM_SEL_TIMEOUT;
2770 	xpt_done((union ccb *)csio);
2771 	return(1);
2772     }
2773 
2774     /* if we have to fake Synchronise Cache */
2775     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
2776 	/*
2777 	 * If this is a Synchronise Cache command, typically issued when
2778 	 * a device is closed, flush the adapter and complete now.
2779 	 */
2780 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2781 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
2782 	    ciss_flush_adapter(sc);
2783 	    csio->ccb_h.status = CAM_REQ_CMP;
2784 	    xpt_done((union ccb *)csio);
2785 	    return(1);
2786 	}
2787     }
2788 
2789     return(0);
2790 }
2791 
2792 /************************************************************************
2793  * Check for possibly-completed commands.
2794  */
2795 static void
2796 ciss_cam_poll(struct cam_sim *sim)
2797 {
2798     struct ciss_softc	*sc = cam_sim_softc(sim);
2799 
2800     debug_called(2);
2801 
2802     ciss_done(sc);
2803 }
2804 
2805 /************************************************************************
2806  * Handle completion of a command - pass results back through the CCB
2807  */
2808 static void
2809 ciss_cam_complete(struct ciss_request *cr)
2810 {
2811     struct ciss_softc		*sc;
2812     struct ciss_command		*cc;
2813     struct ciss_error_info	*ce;
2814     struct ccb_scsiio		*csio;
2815     int				scsi_status;
2816     int				command_status;
2817 
2818     debug_called(2);
2819 
2820     sc = cr->cr_sc;
2821     cc = CISS_FIND_COMMAND(cr);
2822     ce = (struct ciss_error_info *)&(cc->sg[0]);
2823     csio = (struct ccb_scsiio *)cr->cr_private;
2824 
2825     /*
2826      * Extract status values from request.
2827      */
2828     ciss_report_request(cr, &command_status, &scsi_status);
2829     csio->scsi_status = scsi_status;
2830 
2831     /*
2832      * Handle specific SCSI status values.
2833      */
2834     switch(scsi_status) {
2835 	/* no status due to adapter error */
2836     case -1:
2837 	debug(0, "adapter error");
2838 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2839 	break;
2840 
2841 	/* no status due to command completed OK */
2842     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
2843 	debug(2, "SCSI_STATUS_OK");
2844 	csio->ccb_h.status = CAM_REQ_CMP;
2845 	break;
2846 
2847 	/* check condition, sense data included */
2848     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
2849 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
2850 	      ce->sense_length, ce->residual_count);
2851 	bzero(&csio->sense_data, SSD_FULL_SIZE);
2852 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
2853 	csio->sense_len = ce->sense_length;
2854 	csio->resid = ce->residual_count;
2855 	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
2856 #ifdef CISS_DEBUG
2857 	{
2858 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
2859 	    debug(0, "sense key %x", sns->flags & SSD_KEY);
2860 	}
2861 #endif
2862 	break;
2863 
2864     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
2865 	debug(0, "SCSI_STATUS_BUSY");
2866 	csio->ccb_h.status = CAM_SCSI_BUSY;
2867 	break;
2868 
2869     default:
2870 	debug(0, "unknown status 0x%x", csio->scsi_status);
2871 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2872 	break;
2873     }
2874 
2875     /* handle post-command fixup */
2876     ciss_cam_complete_fixup(sc, csio);
2877 
2878     /* tell CAM we're ready for more commands */
2879     csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2880 
2881     xpt_done((union ccb *)csio);
2882     ciss_release_request(cr);
2883 }
2884 
2885 /********************************************************************************
2886  * Fix up the result of some commands here.
2887  */
2888 static void
2889 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
2890 {
2891     struct scsi_inquiry_data	*inq;
2892     struct ciss_ldrive		*cl;
2893     int				bus, target;
2894 
2895     if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2896 	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
2897 
2898 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
2899 	target = csio->ccb_h.target_id;
2900 	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
2901 
2902 	/*
2903 	 * Don't let hard drives be seen by the DA driver.  They will still be
2904 	 * attached by the PASS driver.
2905 	 */
2906 	if (CISS_IS_PHYSICAL(bus)) {
2907 	    if (SID_TYPE(inq) == T_DIRECT)
2908 		inq->device = (inq->device & 0xe0) | T_NODEVICE;
2909 	    return;
2910 	}
2911 
2912 	cl = &sc->ciss_logical[bus][target];
2913 
2914 	padstr(inq->vendor, "COMPAQ", 8);
2915 	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
2916 	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
2917     }
2918 }
2919 
2920 
2921 /********************************************************************************
2922  * Find a peripheral attached at (target)
2923  */
2924 static struct cam_periph *
2925 ciss_find_periph(struct ciss_softc *sc, int bus, int target)
2926 {
2927     struct cam_periph	*periph;
2928     struct cam_path	*path;
2929     int			status;
2930 
2931     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
2932 			     target, 0);
2933     if (status == CAM_REQ_CMP) {
2934 	periph = cam_periph_find(path, NULL);
2935 	xpt_free_path(path);
2936     } else {
2937 	periph = NULL;
2938     }
2939     return(periph);
2940 }
2941 
2942 /********************************************************************************
2943  * Name the device at (target)
2944  *
2945  * XXX is this strictly correct?
2946  */
2947 static int
2948 ciss_name_device(struct ciss_softc *sc, int bus, int target)
2949 {
2950     struct cam_periph	*periph;
2951 
2952     if (CISS_IS_PHYSICAL(bus))
2953 	return (0);
2954     if ((periph = ciss_find_periph(sc, bus, target)) != NULL) {
2955 	sprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
2956 		periph->periph_name, periph->unit_number);
2957 	return(0);
2958     }
2959     sc->ciss_logical[bus][target].cl_name[0] = 0;
2960     return(ENOENT);
2961 }
2962 
2963 /************************************************************************
2964  * Periodic status monitoring.
2965  */
2966 static void
2967 ciss_periodic(void *arg)
2968 {
2969     struct ciss_softc	*sc;
2970 
2971     debug_called(1);
2972 
2973     sc = (struct ciss_softc *)arg;
2974 
2975     /*
2976      * Check the adapter heartbeat.
2977      */
2978     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
2979 	sc->ciss_heart_attack++;
2980 	debug(0, "adapter heart attack in progress 0x%x/%d",
2981 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
2982 	if (sc->ciss_heart_attack == 3) {
2983 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
2984 	    /* XXX should reset adapter here */
2985 	}
2986     } else {
2987 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
2988 	sc->ciss_heart_attack = 0;
2989 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
2990     }
2991 
2992     /*
2993      * If the notify event request has died for some reason, or has
2994      * not started yet, restart it.
2995      */
2996     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
2997 	debug(0, "(re)starting Event Notify chain");
2998 	ciss_notify_event(sc);
2999     }
3000 
3001     /*
3002      * Reschedule.
3003      */
3004     if (!(sc->ciss_flags & CISS_FLAG_ABORTING))
3005 	sc->ciss_periodic = timeout(ciss_periodic, sc, CISS_HEARTBEAT_RATE * hz);
3006 }
3007 
3008 /************************************************************************
3009  * Request a notification response from the adapter.
3010  *
3011  * If (cr) is NULL, this is the first request of the adapter, so
3012  * reset the adapter's message pointer and start with the oldest
3013  * message available.
3014  */
3015 static void
3016 ciss_notify_event(struct ciss_softc *sc)
3017 {
3018     struct ciss_request		*cr;
3019     struct ciss_command		*cc;
3020     struct ciss_notify_cdb	*cnc;
3021     int				error;
3022 
3023     debug_called(1);
3024 
3025     cr = sc->ciss_periodic_notify;
3026 
3027     /* get a request if we don't already have one */
3028     if (cr == NULL) {
3029 	if ((error = ciss_get_request(sc, &cr)) != 0) {
3030 	    debug(0, "can't get notify event request");
3031 	    goto out;
3032 	}
3033 	sc->ciss_periodic_notify = cr;
3034 	cr->cr_complete = ciss_notify_complete;
3035 	debug(1, "acquired request %d", cr->cr_tag);
3036     }
3037 
3038     /*
3039      * Get a databuffer if we don't already have one, note that the
3040      * adapter command wants a larger buffer than the actual
3041      * structure.
3042      */
3043     if (cr->cr_data == NULL) {
3044 	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3045 	    debug(0, "can't get notify event request buffer");
3046 	    error = ENOMEM;
3047 	    goto out;
3048 	}
3049 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3050     }
3051 
3052     /* re-setup the request's command (since we never release it) XXX overkill*/
3053     ciss_preen_command(cr);
3054 
3055     /* (re)build the notify event command */
3056     cc = CISS_FIND_COMMAND(cr);
3057     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3058     cc->header.address.physical.bus = 0;
3059     cc->header.address.physical.target = 0;
3060 
3061     cc->cdb.cdb_length = sizeof(*cnc);
3062     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3063     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3064     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3065     cc->cdb.timeout = 0;	/* no timeout, we hope */
3066 
3067     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3068     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3069     cnc->opcode = CISS_OPCODE_READ;
3070     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3071     cnc->timeout = 0;		/* no timeout, we hope */
3072     cnc->synchronous = 0;
3073     cnc->ordered = 0;
3074     cnc->seek_to_oldest = 0;
3075     if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3076 	cnc->new_only = 1;
3077     else
3078 	cnc->new_only = 0;
3079     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3080 
3081     /* submit the request */
3082     error = ciss_start(cr);
3083 
3084  out:
3085     if (error) {
3086 	if (cr != NULL) {
3087 	    if (cr->cr_data != NULL)
3088 		free(cr->cr_data, CISS_MALLOC_CLASS);
3089 	    ciss_release_request(cr);
3090 	}
3091 	sc->ciss_periodic_notify = NULL;
3092 	debug(0, "can't submit notify event request");
3093 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3094     } else {
3095 	debug(1, "notify event submitted");
3096 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3097     }
3098 }
3099 
3100 static void
3101 ciss_notify_complete(struct ciss_request *cr)
3102 {
3103     struct ciss_command	*cc;
3104     struct ciss_notify	*cn;
3105     struct ciss_softc	*sc;
3106     int			scsi_status;
3107     int			command_status;
3108     debug_called(1);
3109 
3110     cc = CISS_FIND_COMMAND(cr);
3111     cn = (struct ciss_notify *)cr->cr_data;
3112     sc = cr->cr_sc;
3113 
3114     /*
3115      * Report request results, decode status.
3116      */
3117     ciss_report_request(cr, &command_status, &scsi_status);
3118 
3119     /*
3120      * Abort the chain on a fatal error.
3121      *
3122      * XXX which of these are actually errors?
3123      */
3124     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3125 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3126 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3127 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3128 		    ciss_name_command_status(command_status));
3129 	ciss_release_request(cr);
3130 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3131 	return;
3132     }
3133 
3134     /*
3135      * If the adapter gave us a text message, print it.
3136      */
3137     if (cn->message[0] != 0)
3138 	ciss_printf(sc, "*** %.80s\n", cn->message);
3139 
3140     debug(0, "notify event class %d subclass %d detail %d",
3141 		cn->class, cn->subclass, cn->detail);
3142 
3143     /*
3144      * If the response indicates that the notifier has been aborted,
3145      * release the notifier command.
3146      */
3147     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3148 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3149 	(cn->detail == 1)) {
3150 	debug(0, "notifier exiting");
3151 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3152 	ciss_release_request(cr);
3153 	sc->ciss_periodic_notify = NULL;
3154 	wakeup(&sc->ciss_periodic_notify);
3155     } else {
3156 	/* Handle notify events in a kernel thread */
3157 	ciss_enqueue_notify(cr);
3158 	sc->ciss_periodic_notify = NULL;
3159 	wakeup(&sc->ciss_periodic_notify);
3160 	wakeup(&sc->ciss_notify);
3161     }
3162     /*
3163      * Send a new notify event command, if we're not aborting.
3164      */
3165     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3166 	ciss_notify_event(sc);
3167     }
3168 }
3169 
3170 /************************************************************************
3171  * Abort the Notify Event chain.
3172  *
3173  * Note that we can't just abort the command in progress; we have to
3174  * explicitly issue an Abort Notify Event command in order for the
3175  * adapter to clean up correctly.
3176  *
3177  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3178  * the chain will not restart itself.
3179  */
3180 static int
3181 ciss_notify_abort(struct ciss_softc *sc)
3182 {
3183     struct ciss_request		*cr;
3184     struct ciss_command		*cc;
3185     struct ciss_notify_cdb	*cnc;
3186     int				error, s, command_status, scsi_status;
3187 
3188     debug_called(1);
3189 
3190     cr = NULL;
3191     error = 0;
3192 
3193     /* verify that there's an outstanding command */
3194     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3195 	goto out;
3196 
3197     /* get a command to issue the abort with */
3198     if ((error = ciss_get_request(sc, &cr)))
3199 	goto out;
3200 
3201     /* get a buffer for the result */
3202     if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3203 	debug(0, "can't get notify event request buffer");
3204 	error = ENOMEM;
3205 	goto out;
3206     }
3207     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3208 
3209     /* build the CDB */
3210     cc = CISS_FIND_COMMAND(cr);
3211     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3212     cc->header.address.physical.bus = 0;
3213     cc->header.address.physical.target = 0;
3214     cc->cdb.cdb_length = sizeof(*cnc);
3215     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3216     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3217     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3218     cc->cdb.timeout = 0;	/* no timeout, we hope */
3219 
3220     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3221     bzero(cnc, sizeof(*cnc));
3222     cnc->opcode = CISS_OPCODE_WRITE;
3223     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3224     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3225 
3226     ciss_print_request(cr);
3227 
3228     /*
3229      * Submit the request and wait for it to complete.
3230      */
3231     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3232 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3233 	goto out;
3234     }
3235 
3236     /*
3237      * Check response.
3238      */
3239     ciss_report_request(cr, &command_status, &scsi_status);
3240     switch(command_status) {
3241     case CISS_CMD_STATUS_SUCCESS:
3242 	break;
3243     case CISS_CMD_STATUS_INVALID_COMMAND:
3244 	/*
3245 	 * Some older adapters don't support the CISS version of this
3246 	 * command.  Fall back to using the BMIC version.
3247 	 */
3248 	error = ciss_notify_abort_bmic(sc);
3249 	if (error != 0)
3250 	    goto out;
3251 	break;
3252 
3253     case CISS_CMD_STATUS_TARGET_STATUS:
3254 	/*
3255 	 * This can happen if the adapter thinks there wasn't an outstanding
3256 	 * Notify Event command but we did.  We clean up here.
3257 	 */
3258 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3259 	    if (sc->ciss_periodic_notify != NULL)
3260 		ciss_release_request(sc->ciss_periodic_notify);
3261 	    error = 0;
3262 	    goto out;
3263 	}
3264 	/* FALLTHROUGH */
3265 
3266     default:
3267 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3268 		    ciss_name_command_status(command_status));
3269 	error = EIO;
3270 	goto out;
3271     }
3272 
3273     /*
3274      * Sleep waiting for the notifier command to complete.  Note
3275      * that if it doesn't, we may end up in a bad situation, since
3276      * the adapter may deliver it later.  Also note that the adapter
3277      * requires the Notify Event command to be cancelled in order to
3278      * maintain internal bookkeeping.
3279      */
3280     s = splcam();
3281     while (sc->ciss_periodic_notify != NULL) {
3282 	error = tsleep(&sc->ciss_periodic_notify, 0, "cissNEA", hz * 5);
3283 	if (error == EWOULDBLOCK) {
3284 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3285 	    break;
3286 	}
3287     }
3288     splx(s);
3289 
3290  out:
3291     /* release the cancel request */
3292     if (cr != NULL) {
3293 	if (cr->cr_data != NULL)
3294 	    free(cr->cr_data, CISS_MALLOC_CLASS);
3295 	ciss_release_request(cr);
3296     }
3297     if (error == 0)
3298 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3299     return(error);
3300 }
3301 
3302 /************************************************************************
3303  * Abort the Notify Event chain using a BMIC command.
3304  */
3305 static int
3306 ciss_notify_abort_bmic(struct ciss_softc *sc)
3307 {
3308     struct ciss_request			*cr;
3309     int					error, command_status;
3310 
3311     debug_called(1);
3312 
3313     cr = NULL;
3314     error = 0;
3315 
3316     /* verify that there's an outstanding command */
3317     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3318 	goto out;
3319 
3320     /*
3321      * Build a BMIC command to cancel the Notify on Event command.
3322      *
3323      * Note that we are sending a CISS opcode here.  Odd.
3324      */
3325     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3326 				       NULL, 0)) != 0)
3327 	goto out;
3328 
3329     /*
3330      * Submit the request and wait for it to complete.
3331      */
3332     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3333 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3334 	goto out;
3335     }
3336 
3337     /*
3338      * Check response.
3339      */
3340     ciss_report_request(cr, &command_status, NULL);
3341     switch(command_status) {
3342     case CISS_CMD_STATUS_SUCCESS:
3343 	break;
3344     default:
3345 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3346 		    ciss_name_command_status(command_status));
3347 	error = EIO;
3348 	goto out;
3349     }
3350 
3351 out:
3352     if (cr != NULL)
3353 	ciss_release_request(cr);
3354     return(error);
3355 }
3356 
3357 /************************************************************************
3358  * Handle rescanning all the logical volumes when a notify event
3359  * causes the drives to come online or offline.
3360  */
3361 static void
3362 ciss_notify_rescan_logical(struct ciss_softc *sc)
3363 {
3364     struct ciss_lun_report      *cll;
3365     struct ciss_ldrive		*ld;
3366     int                         i, j, ndrives;
3367 
3368     /*
3369      * We must rescan all logical volumes to get the right logical
3370      * drive address.
3371      */
3372     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3373                            CISS_MAX_LOGICAL);
3374     if (cll == NULL)
3375         return;
3376 
3377     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3378 
3379     /*
3380      * Delete any of the drives which were destroyed by the
3381      * firmware.
3382      */
3383     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3384 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3385 	    ld = &sc->ciss_logical[i][j];
3386 
3387 	    if (ld->cl_update == 0)
3388 		continue;
3389 
3390 	    if (ld->cl_status != CISS_LD_ONLINE) {
3391 		ciss_cam_rescan_target(sc, i, j);
3392 		ld->cl_update = 0;
3393 		if (ld->cl_ldrive)
3394 		    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
3395 		if (ld->cl_lstatus)
3396 		    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
3397 
3398 		ld->cl_ldrive = NULL;
3399 		ld->cl_lstatus = NULL;
3400 	    }
3401 	}
3402     }
3403 
3404     /*
3405      * Scan for new drives.
3406      */
3407     for (i = 0; i < ndrives; i++) {
3408 	int	bus, target;
3409 
3410 	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3411 	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3412 	ld	= &sc->ciss_logical[bus][target];
3413 
3414 	if (ld->cl_update == 0)
3415 		continue;
3416 
3417 	ld->cl_update		= 0;
3418 	ld->cl_address		= cll->lun[i];
3419 	ld->cl_controller	= &sc->ciss_controllers[bus];
3420 	if (ciss_identify_logical(sc, ld) == 0) {
3421 	    ciss_cam_rescan_target(sc, bus, target);
3422 	}
3423     }
3424     free(cll, CISS_MALLOC_CLASS);
3425 }
3426 
3427 /************************************************************************
3428  * Handle a notify event relating to the status of a logical drive.
3429  *
3430  * XXX need to be able to defer some of these to properly handle
3431  *     calling the "ID Physical drive" command, unless the 'extended'
3432  *     drive IDs are always in BIG_MAP format.
3433  */
3434 static void
3435 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3436 {
3437     struct ciss_ldrive	*ld;
3438     int			ostatus, bus, target;
3439 
3440     debug_called(2);
3441 
3442     bus		= cn->device.physical.bus;
3443     target	= cn->data.logical_status.logical_drive;
3444     ld		= &sc->ciss_logical[bus][target];
3445 
3446     switch (cn->subclass) {
3447     case CISS_NOTIFY_LOGICAL_STATUS:
3448 	switch (cn->detail) {
3449 	case 0:
3450 	    ciss_name_device(sc, bus, target);
3451 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3452 			cn->data.logical_status.logical_drive, ld->cl_name,
3453 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3454 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3455 			cn->data.logical_status.spare_state,
3456 			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3457 
3458 	    /*
3459 	     * Update our idea of the drive's status.
3460 	     */
3461 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3462 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3463 	    if (ld->cl_lstatus != NULL)
3464 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3465 
3466 	    /*
3467 	     * Have CAM rescan the drive if its status has changed.
3468 	     */
3469 	    if (ostatus != ld->cl_status) {
3470 		ld->cl_update = 1;
3471 		ciss_notify_rescan_logical(sc);
3472 	    }
3473 
3474 	    break;
3475 
3476 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3477 	    ciss_name_device(sc, bus, target);
3478 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3479 			cn->data.logical_status.logical_drive, ld->cl_name);
3480 	    ciss_accept_media(sc, ld);
3481 
3482 	    ld->cl_update = 1;
3483 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3484 	    ciss_notify_rescan_logical(sc);
3485 	    break;
3486 
3487 	case 2:
3488 	case 3:
3489 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3490 			cn->data.rebuild_aborted.logical_drive,
3491 			ld->cl_name,
3492 			(cn->detail == 2) ? "read" : "write");
3493 	    break;
3494 	}
3495 	break;
3496 
3497     case CISS_NOTIFY_LOGICAL_ERROR:
3498 	if (cn->detail == 0) {
3499 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3500 			cn->data.io_error.logical_drive,
3501 			ld->cl_name,
3502 			cn->data.io_error.failure_bus,
3503 			cn->data.io_error.failure_drive);
3504 	    /* XXX should we take the drive down at this point, or will we be told? */
3505 	}
3506 	break;
3507 
3508     case CISS_NOTIFY_LOGICAL_SURFACE:
3509 	if (cn->detail == 0)
3510 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
3511 			cn->data.consistency_completed.logical_drive,
3512 			ld->cl_name);
3513 	break;
3514     }
3515 }
3516 
3517 /************************************************************************
3518  * Handle a notify event relating to the status of a physical drive.
3519  */
3520 static void
3521 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
3522 {
3523 }
3524 
3525 /************************************************************************
3526  * Handle a notify event relating to the status of a physical drive.
3527  */
3528 static void
3529 ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
3530 {
3531     struct ciss_lun_report *cll;
3532     int bus, target;
3533     int s;
3534 
3535     switch (cn->subclass) {
3536     case CISS_NOTIFY_HOTPLUG_PHYSICAL:
3537     case CISS_NOTIFY_HOTPLUG_NONDISK:
3538 	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
3539 	target =
3540 	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
3541 
3542 	s = splcam();
3543 	if (cn->detail == 0) {
3544 	    /*
3545 	     * Mark the device offline so that it'll start producing selection
3546 	     * timeouts to the upper layer.
3547 	     */
3548 	    sc->ciss_physical[bus][target].cp_online = 0;
3549 	} else {
3550 	    /*
3551 	     * Rescan the physical lun list for new items
3552 	     */
3553 	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
3554 				   CISS_MAX_PHYSICAL);
3555 	    if (cll == NULL) {
3556 		ciss_printf(sc, "Warning, cannot get physical lun list\n");
3557 		break;
3558 	    }
3559 	    ciss_filter_physical(sc, cll);
3560 	}
3561 	splx(s);
3562 	break;
3563 
3564     default:
3565 	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
3566 	return;
3567     }
3568 }
3569 
3570 /************************************************************************
3571  * Handle deferred processing of notify events.  Notify events may need
3572  * sleep which is unsafe during an interrupt.
3573  */
3574 static void
3575 ciss_notify_thread(void *arg)
3576 {
3577     struct ciss_softc		*sc;
3578     struct ciss_request		*cr;
3579     struct ciss_notify		*cn;
3580     int				s;
3581 
3582 #if __FreeBSD_version >= 500000
3583     mtx_lock(&Giant);
3584 #endif
3585     sc = (struct ciss_softc *)arg;
3586 
3587     s = splcam();
3588     for (;;) {
3589 	if (TAILQ_EMPTY(&sc->ciss_notify) != 0 &&
3590 	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
3591 	    tsleep(&sc->ciss_notify, PUSER, "idle", 0);
3592 	}
3593 
3594 	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
3595 	    break;
3596 
3597 	cr = ciss_dequeue_notify(sc);
3598 	splx(s);
3599 
3600 	if (cr == NULL)
3601 		panic("cr null");
3602 	cn = (struct ciss_notify *)cr->cr_data;
3603 
3604 	switch (cn->class) {
3605 	case CISS_NOTIFY_HOTPLUG:
3606 	    ciss_notify_hotplug(sc, cn);
3607 	    break;
3608 	case CISS_NOTIFY_LOGICAL:
3609 	    ciss_notify_logical(sc, cn);
3610 	    break;
3611 	case CISS_NOTIFY_PHYSICAL:
3612 	    ciss_notify_physical(sc, cn);
3613 	    break;
3614 	}
3615 
3616 	ciss_release_request(cr);
3617 
3618 	s = splcam();
3619     }
3620     sc->ciss_notify_thread = NULL;
3621     wakeup(&sc->ciss_notify_thread);
3622     splx(s);
3623 
3624 #if __FreeBSD_version >= 500000
3625     mtx_unlock(&Giant);
3626 #endif
3627     kthread_exit(0);
3628 }
3629 
3630 /************************************************************************
3631  * Start the notification kernel thread.
3632  */
3633 static void
3634 ciss_spawn_notify_thread(struct ciss_softc *sc)
3635 {
3636 
3637 #if __FreeBSD_version > 500005
3638     if (kthread_create((void(*)(void *))ciss_notify_thread, sc,
3639 		       &sc->ciss_notify_thread, 0, 0, "ciss_notify%d",
3640 		       device_get_unit(sc->ciss_dev)))
3641 #else
3642     if (kthread_create((void(*)(void *))ciss_notify_thread, sc,
3643 		       &sc->ciss_notify_thread, "ciss_notify%d",
3644 		       device_get_unit(sc->ciss_dev)))
3645 #endif
3646 	panic("Could not create notify thread\n");
3647 }
3648 
3649 /************************************************************************
3650  * Kill the notification kernel thread.
3651  */
3652 static void
3653 ciss_kill_notify_thread(struct ciss_softc *sc)
3654 {
3655 
3656     if (sc->ciss_notify_thread == NULL)
3657 	return;
3658 
3659     sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
3660     wakeup(&sc->ciss_notify);
3661     tsleep(&sc->ciss_notify_thread, PUSER, "thtrm", 0);
3662 }
3663 
3664 /************************************************************************
3665  * Print a request.
3666  */
3667 static void
3668 ciss_print_request(struct ciss_request *cr)
3669 {
3670     struct ciss_softc	*sc;
3671     struct ciss_command	*cc;
3672     int			i;
3673 
3674     sc = cr->cr_sc;
3675     cc = CISS_FIND_COMMAND(cr);
3676 
3677     ciss_printf(sc, "REQUEST @ %p\n", cr);
3678     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
3679 	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
3680 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
3681     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
3682 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
3683     switch(cc->header.address.mode.mode) {
3684     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
3685     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
3686 	ciss_printf(sc, "  physical bus %d target %d\n",
3687 		    cc->header.address.physical.bus, cc->header.address.physical.target);
3688 	break;
3689     case CISS_HDR_ADDRESS_MODE_LOGICAL:
3690 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
3691 	break;
3692     }
3693     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
3694 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
3695 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
3696 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
3697 		cc->cdb.cdb_length,
3698 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
3699 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
3700 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
3701 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
3702 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
3703 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
3704 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
3705     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
3706 
3707     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
3708 	/* XXX print error info */
3709     } else {
3710 	/* since we don't use chained s/g, don't support it here */
3711 	for (i = 0; i < cc->header.sg_in_list; i++) {
3712 	    if ((i % 4) == 0)
3713 		ciss_printf(sc, "   ");
3714 	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
3715 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
3716 		printf("\n");
3717 	}
3718     }
3719 }
3720 
3721 /************************************************************************
3722  * Print information about the status of a logical drive.
3723  */
3724 static void
3725 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
3726 {
3727     int		bus, target, i;
3728 
3729     if (ld->cl_lstatus == NULL) {
3730 	printf("does not exist\n");
3731 	return;
3732     }
3733 
3734     /* print drive status */
3735     switch(ld->cl_lstatus->status) {
3736     case CISS_LSTATUS_OK:
3737 	printf("online\n");
3738 	break;
3739     case CISS_LSTATUS_INTERIM_RECOVERY:
3740 	printf("in interim recovery mode\n");
3741 	break;
3742     case CISS_LSTATUS_READY_RECOVERY:
3743 	printf("ready to begin recovery\n");
3744 	break;
3745     case CISS_LSTATUS_RECOVERING:
3746 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3747 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3748 	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
3749 	       bus, target, ld->cl_lstatus->blocks_to_recover);
3750 	break;
3751     case CISS_LSTATUS_EXPANDING:
3752 	printf("being expanded, %u blocks remaining\n",
3753 	       ld->cl_lstatus->blocks_to_recover);
3754 	break;
3755     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3756 	printf("queued for expansion\n");
3757 	break;
3758     case CISS_LSTATUS_FAILED:
3759 	printf("queued for expansion\n");
3760 	break;
3761     case CISS_LSTATUS_WRONG_PDRIVE:
3762 	printf("wrong physical drive inserted\n");
3763 	break;
3764     case CISS_LSTATUS_MISSING_PDRIVE:
3765 	printf("missing a needed physical drive\n");
3766 	break;
3767     case CISS_LSTATUS_BECOMING_READY:
3768 	printf("becoming ready\n");
3769 	break;
3770     }
3771 
3772     /* print failed physical drives */
3773     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
3774 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
3775 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
3776 	if (bus == -1)
3777 	    continue;
3778 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
3779 		    ld->cl_lstatus->drive_failure_map[i]);
3780     }
3781 }
3782 
3783 #ifdef CISS_DEBUG
3784 /************************************************************************
3785  * Print information about the controller/driver.
3786  */
3787 static void
3788 ciss_print_adapter(struct ciss_softc *sc)
3789 {
3790     int		i, j;
3791 
3792     ciss_printf(sc, "ADAPTER:\n");
3793     for (i = 0; i < CISSQ_COUNT; i++) {
3794 	ciss_printf(sc, "%s     %d/%d\n",
3795 	    i == 0 ? "free" :
3796 	    i == 1 ? "busy" : "complete",
3797 	    sc->ciss_qstat[i].q_length,
3798 	    sc->ciss_qstat[i].q_max);
3799     }
3800     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
3801     ciss_printf(sc, "flags %b\n", sc->ciss_flags,
3802 	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
3803 
3804     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3805 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3806 	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
3807 	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
3808 	}
3809     }
3810 
3811     /* XXX Should physical drives be printed out here? */
3812 
3813     for (i = 1; i < sc->ciss_max_requests; i++)
3814 	ciss_print_request(sc->ciss_request + i);
3815 }
3816 
3817 /* DDB hook */
3818 static void
3819 ciss_print0(void)
3820 {
3821     struct ciss_softc	*sc;
3822 
3823     sc = devclass_get_softc(devclass_find("ciss"), 0);
3824     if (sc == NULL) {
3825 	printf("no ciss controllers\n");
3826     } else {
3827 	ciss_print_adapter(sc);
3828     }
3829 }
3830 #endif
3831 
3832 /************************************************************************
3833  * Return a name for a logical drive status value.
3834  */
3835 static const char *
3836 ciss_name_ldrive_status(int status)
3837 {
3838     switch (status) {
3839     case CISS_LSTATUS_OK:
3840 	return("OK");
3841     case CISS_LSTATUS_FAILED:
3842 	return("failed");
3843     case CISS_LSTATUS_NOT_CONFIGURED:
3844 	return("not configured");
3845     case CISS_LSTATUS_INTERIM_RECOVERY:
3846 	return("interim recovery");
3847     case CISS_LSTATUS_READY_RECOVERY:
3848 	return("ready for recovery");
3849     case CISS_LSTATUS_RECOVERING:
3850 	return("recovering");
3851     case CISS_LSTATUS_WRONG_PDRIVE:
3852 	return("wrong physical drive inserted");
3853     case CISS_LSTATUS_MISSING_PDRIVE:
3854 	return("missing physical drive");
3855     case CISS_LSTATUS_EXPANDING:
3856 	return("expanding");
3857     case CISS_LSTATUS_BECOMING_READY:
3858 	return("becoming ready");
3859     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3860 	return("queued for expansion");
3861     }
3862     return("unknown status");
3863 }
3864 
3865 /************************************************************************
3866  * Return an online/offline/nonexistent value for a logical drive
3867  * status value.
3868  */
3869 static int
3870 ciss_decode_ldrive_status(int status)
3871 {
3872     switch(status) {
3873     case CISS_LSTATUS_NOT_CONFIGURED:
3874 	return(CISS_LD_NONEXISTENT);
3875 
3876     case CISS_LSTATUS_OK:
3877     case CISS_LSTATUS_INTERIM_RECOVERY:
3878     case CISS_LSTATUS_READY_RECOVERY:
3879     case CISS_LSTATUS_RECOVERING:
3880     case CISS_LSTATUS_EXPANDING:
3881     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3882 	return(CISS_LD_ONLINE);
3883 
3884     case CISS_LSTATUS_FAILED:
3885     case CISS_LSTATUS_WRONG_PDRIVE:
3886     case CISS_LSTATUS_MISSING_PDRIVE:
3887     case CISS_LSTATUS_BECOMING_READY:
3888     default:
3889 	return(CISS_LD_OFFLINE);
3890     }
3891 }
3892 
3893 
3894 /************************************************************************
3895  * Return a name for a logical drive's organisation.
3896  */
3897 static const char *
3898 ciss_name_ldrive_org(int org)
3899 {
3900     switch(org) {
3901     case CISS_LDRIVE_RAID0:
3902 	return("RAID 0");
3903     case CISS_LDRIVE_RAID1:
3904 	return("RAID 1");
3905     case CISS_LDRIVE_RAID4:
3906 	return("RAID 4");
3907     case CISS_LDRIVE_RAID5:
3908 	return("RAID 5");
3909     case CISS_LDRIVE_RAID51:
3910 	return("RAID 5+1");
3911     case CISS_LDRIVE_RAIDADG:
3912 	return("RAID ADG");
3913     }
3914     return("unkown");
3915 }
3916 
3917 /************************************************************************
3918  * Return a name for a command status value.
3919  */
3920 static const char *
3921 ciss_name_command_status(int status)
3922 {
3923     switch(status) {
3924     case CISS_CMD_STATUS_SUCCESS:
3925 	return("success");
3926     case CISS_CMD_STATUS_TARGET_STATUS:
3927 	return("target status");
3928     case CISS_CMD_STATUS_DATA_UNDERRUN:
3929 	return("data underrun");
3930     case CISS_CMD_STATUS_DATA_OVERRUN:
3931 	return("data overrun");
3932     case CISS_CMD_STATUS_INVALID_COMMAND:
3933 	return("invalid command");
3934     case CISS_CMD_STATUS_PROTOCOL_ERROR:
3935 	return("protocol error");
3936     case CISS_CMD_STATUS_HARDWARE_ERROR:
3937 	return("hardware error");
3938     case CISS_CMD_STATUS_CONNECTION_LOST:
3939 	return("connection lost");
3940     case CISS_CMD_STATUS_ABORTED:
3941 	return("aborted");
3942     case CISS_CMD_STATUS_ABORT_FAILED:
3943 	return("abort failed");
3944     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
3945 	return("unsolicited abort");
3946     case CISS_CMD_STATUS_TIMEOUT:
3947 	return("timeout");
3948     case CISS_CMD_STATUS_UNABORTABLE:
3949 	return("unabortable");
3950     }
3951     return("unknown status");
3952 }
3953 
3954 /************************************************************************
3955  * Handle an open on the control device.
3956  */
3957 static int
3958 ciss_open(struct cdev *dev, int flags, int fmt, d_thread_t *p)
3959 {
3960     struct ciss_softc	*sc;
3961 
3962     debug_called(1);
3963 
3964     sc = (struct ciss_softc *)dev->si_drv1;
3965 
3966     /* we might want to veto if someone already has us open */
3967 
3968     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
3969     return(0);
3970 }
3971 
3972 /************************************************************************
3973  * Handle the last close on the control device.
3974  */
3975 static int
3976 ciss_close(struct cdev *dev, int flags, int fmt, d_thread_t *p)
3977 {
3978     struct ciss_softc	*sc;
3979 
3980     debug_called(1);
3981 
3982     sc = (struct ciss_softc *)dev->si_drv1;
3983 
3984     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
3985     return (0);
3986 }
3987 
3988 /********************************************************************************
3989  * Handle adapter-specific control operations.
3990  *
3991  * Note that the API here is compatible with the Linux driver, in order to
3992  * simplify the porting of Compaq's userland tools.
3993  */
3994 static int
3995 ciss_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *p)
3996 {
3997     struct ciss_softc		*sc;
3998     int				error;
3999 
4000     debug_called(1);
4001 
4002     sc = (struct ciss_softc *)dev->si_drv1;
4003     error = 0;
4004 
4005     switch(cmd) {
4006     case CCISS_GETPCIINFO:
4007     {
4008 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4009 
4010 	pis->bus = pci_get_bus(sc->ciss_dev);
4011 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4012 	pis->board_id = pci_get_devid(sc->ciss_dev);
4013 
4014 	break;
4015     }
4016 
4017     case CCISS_GETINTINFO:
4018     {
4019 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4020 
4021 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4022 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4023 
4024 	break;
4025     }
4026 
4027     case CCISS_SETINTINFO:
4028     {
4029 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4030 
4031 	if ((cis->delay == 0) && (cis->count == 0)) {
4032 	    error = EINVAL;
4033 	    break;
4034 	}
4035 
4036 	/*
4037 	 * XXX apparently this is only safe if the controller is idle,
4038 	 *     we should suspend it before doing this.
4039 	 */
4040 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4041 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4042 
4043 	if (ciss_update_config(sc))
4044 	    error = EIO;
4045 
4046 	/* XXX resume the controller here */
4047 	break;
4048     }
4049 
4050     case CCISS_GETNODENAME:
4051 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4052 	      sizeof(NodeName_type));
4053 	break;
4054 
4055     case CCISS_SETNODENAME:
4056 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4057 	      sizeof(NodeName_type));
4058 	if (ciss_update_config(sc))
4059 	    error = EIO;
4060 	break;
4061 
4062     case CCISS_GETHEARTBEAT:
4063 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4064 	break;
4065 
4066     case CCISS_GETBUSTYPES:
4067 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4068 	break;
4069 
4070     case CCISS_GETFIRMVER:
4071 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4072 	      sizeof(FirmwareVer_type));
4073 	break;
4074 
4075     case CCISS_GETDRIVERVER:
4076 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4077 	break;
4078 
4079     case CCISS_REVALIDVOLS:
4080 	/*
4081 	 * This is a bit ugly; to do it "right" we really need
4082 	 * to find any disks that have changed, kick CAM off them,
4083 	 * then rescan only these disks.  It'd be nice if they
4084 	 * a) told us which disk(s) they were going to play with,
4085 	 * and b) which ones had arrived. 8(
4086 	 */
4087 	break;
4088 
4089     case CCISS_PASSTHRU:
4090 	error = ciss_user_command(sc, (IOCTL_Command_struct *)addr);
4091 	break;
4092 
4093     default:
4094 	debug(0, "unknown ioctl 0x%lx", cmd);
4095 
4096 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4097 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4098 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4099 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4100 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4101 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4102 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4103 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4104 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4105 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4106 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4107 
4108 	error = ENOIOCTL;
4109 	break;
4110     }
4111 
4112     return(error);
4113 }
4114