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