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