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