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