xref: /freebsd/sys/dev/ciss/ciss.c (revision 2f6a179eb910129fb812c1ad1bdc300da1203dc0)
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 	/* see if the OPQ contains anything */
2032 	if (!CISS_TL_SIMPLE_OPQ_INTERRUPT(sc))
2033 	    break;
2034 
2035 	tag = CISS_TL_SIMPLE_FETCH_CMD(sc);
2036 	if (tag == CISS_TL_SIMPLE_OPQ_EMPTY)
2037 	    break;
2038 	index = tag >> 2;
2039 	debug(2, "completed command %d%s", index,
2040 	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2041 	if (index >= sc->ciss_max_requests) {
2042 	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2043 	    continue;
2044 	}
2045 	cr = &(sc->ciss_request[index]);
2046 	cc = CISS_FIND_COMMAND(cr);
2047 	cc->header.host_tag = tag;	/* not updated by adapter */
2048 	ciss_enqueue_complete(cr, qh);
2049     }
2050 
2051 }
2052 
2053 static void
2054 ciss_perf_done(struct ciss_softc *sc, cr_qhead_t *qh)
2055 {
2056     struct ciss_request	*cr;
2057     struct ciss_command	*cc;
2058     u_int32_t		tag, index;
2059 
2060     debug_called(3);
2061 
2062     /*
2063      * Loop quickly taking requests from the adapter and moving them
2064      * to the completed queue.
2065      */
2066     for (;;) {
2067 	tag = sc->ciss_reply[sc->ciss_rqidx];
2068 	if ((tag & CISS_CYCLE_MASK) != sc->ciss_cycle)
2069 	    break;
2070 	index = tag >> 2;
2071 	debug(2, "completed command %d%s\n", index,
2072 	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2073 	if (index < sc->ciss_max_requests) {
2074 	    cr = &(sc->ciss_request[index]);
2075 	    cc = CISS_FIND_COMMAND(cr);
2076 	    cc->header.host_tag = tag;	/* not updated by adapter */
2077 	    ciss_enqueue_complete(cr, qh);
2078 	} else {
2079 	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2080 	}
2081 	if (++sc->ciss_rqidx == sc->ciss_max_requests) {
2082 	    sc->ciss_rqidx = 0;
2083 	    sc->ciss_cycle ^= 1;
2084 	}
2085     }
2086 
2087 }
2088 
2089 /************************************************************************
2090  * Take an interrupt from the adapter.
2091  */
2092 static void
2093 ciss_intr(void *arg)
2094 {
2095     cr_qhead_t qh;
2096     struct ciss_softc	*sc = (struct ciss_softc *)arg;
2097 
2098     /*
2099      * The only interrupt we recognise indicates that there are
2100      * entries in the outbound post queue.
2101      */
2102     STAILQ_INIT(&qh);
2103     ciss_done(sc, &qh);
2104     mtx_lock(&sc->ciss_mtx);
2105     ciss_complete(sc, &qh);
2106     mtx_unlock(&sc->ciss_mtx);
2107 }
2108 
2109 static void
2110 ciss_perf_intr(void *arg)
2111 {
2112     struct ciss_softc	*sc = (struct ciss_softc *)arg;
2113 
2114     /* Clear the interrupt and flush the bridges.  Docs say that the flush
2115      * needs to be done twice, which doesn't seem right.
2116      */
2117     CISS_TL_PERF_CLEAR_INT(sc);
2118     CISS_TL_PERF_FLUSH_INT(sc);
2119 
2120     ciss_perf_msi_intr(sc);
2121 }
2122 
2123 static void
2124 ciss_perf_msi_intr(void *arg)
2125 {
2126     cr_qhead_t qh;
2127     struct ciss_softc	*sc = (struct ciss_softc *)arg;
2128 
2129     STAILQ_INIT(&qh);
2130     ciss_perf_done(sc, &qh);
2131     mtx_lock(&sc->ciss_mtx);
2132     ciss_complete(sc, &qh);
2133     mtx_unlock(&sc->ciss_mtx);
2134 }
2135 
2136 
2137 /************************************************************************
2138  * Process completed requests.
2139  *
2140  * Requests can be completed in three fashions:
2141  *
2142  * - by invoking a callback function (cr_complete is non-null)
2143  * - by waking up a sleeper (cr_flags has CISS_REQ_SLEEP set)
2144  * - by clearing the CISS_REQ_POLL flag in interrupt/timeout context
2145  */
2146 static void
2147 ciss_complete(struct ciss_softc *sc, cr_qhead_t *qh)
2148 {
2149     struct ciss_request	*cr;
2150 
2151     debug_called(2);
2152 
2153     /*
2154      * Loop taking requests off the completed queue and performing
2155      * completion processing on them.
2156      */
2157     for (;;) {
2158 	if ((cr = ciss_dequeue_complete(sc, qh)) == NULL)
2159 	    break;
2160 	ciss_unmap_request(cr);
2161 
2162 	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
2163 	    ciss_printf(sc, "WARNING: completing non-busy request\n");
2164 	cr->cr_flags &= ~CISS_REQ_BUSY;
2165 
2166 	/*
2167 	 * If the request has a callback, invoke it.
2168 	 */
2169 	if (cr->cr_complete != NULL) {
2170 	    cr->cr_complete(cr);
2171 	    continue;
2172 	}
2173 
2174 	/*
2175 	 * If someone is sleeping on this request, wake them up.
2176 	 */
2177 	if (cr->cr_flags & CISS_REQ_SLEEP) {
2178 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
2179 	    wakeup(cr);
2180 	    continue;
2181 	}
2182 
2183 	/*
2184 	 * If someone is polling this request for completion, signal.
2185 	 */
2186 	if (cr->cr_flags & CISS_REQ_POLL) {
2187 	    cr->cr_flags &= ~CISS_REQ_POLL;
2188 	    continue;
2189 	}
2190 
2191 	/*
2192 	 * Give up and throw the request back on the free queue.  This
2193 	 * should never happen; resources will probably be lost.
2194 	 */
2195 	ciss_printf(sc, "WARNING: completed command with no submitter\n");
2196 	ciss_enqueue_free(cr);
2197     }
2198 }
2199 
2200 /************************************************************************
2201  * Report on the completion status of a request, and pass back SCSI
2202  * and command status values.
2203  */
2204 static int
2205 _ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status, const char *func)
2206 {
2207     struct ciss_command		*cc;
2208     struct ciss_error_info	*ce;
2209 
2210     debug_called(2);
2211 
2212     cc = CISS_FIND_COMMAND(cr);
2213     ce = (struct ciss_error_info *)&(cc->sg[0]);
2214 
2215     /*
2216      * We don't consider data under/overrun an error for the Report
2217      * Logical/Physical LUNs commands.
2218      */
2219     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) &&
2220 	((ce->command_status == CISS_CMD_STATUS_DATA_OVERRUN) ||
2221 	 (ce->command_status == CISS_CMD_STATUS_DATA_UNDERRUN)) &&
2222 	((cc->cdb.cdb[0] == CISS_OPCODE_REPORT_LOGICAL_LUNS) ||
2223 	 (cc->cdb.cdb[0] == CISS_OPCODE_REPORT_PHYSICAL_LUNS) ||
2224 	 (cc->cdb.cdb[0] == INQUIRY))) {
2225 	cc->header.host_tag &= ~CISS_HDR_HOST_TAG_ERROR;
2226 	debug(2, "ignoring irrelevant under/overrun error");
2227     }
2228 
2229     /*
2230      * Check the command's error bit, if clear, there's no status and
2231      * everything is OK.
2232      */
2233     if (!(cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR)) {
2234 	if (scsi_status != NULL)
2235 	    *scsi_status = SCSI_STATUS_OK;
2236 	if (command_status != NULL)
2237 	    *command_status = CISS_CMD_STATUS_SUCCESS;
2238 	return(0);
2239     } else {
2240 	if (command_status != NULL)
2241 	    *command_status = ce->command_status;
2242 	if (scsi_status != NULL) {
2243 	    if (ce->command_status == CISS_CMD_STATUS_TARGET_STATUS) {
2244 		*scsi_status = ce->scsi_status;
2245 	    } else {
2246 		*scsi_status = -1;
2247 	    }
2248 	}
2249 	if (bootverbose)
2250 	    ciss_printf(cr->cr_sc, "command status 0x%x (%s) scsi status 0x%x\n",
2251 			ce->command_status, ciss_name_command_status(ce->command_status),
2252 			ce->scsi_status);
2253 	if (ce->command_status == CISS_CMD_STATUS_INVALID_COMMAND) {
2254 	    ciss_printf(cr->cr_sc, "invalid command, offense size %d at %d, value 0x%x, function %s\n",
2255 			ce->additional_error_info.invalid_command.offense_size,
2256 			ce->additional_error_info.invalid_command.offense_offset,
2257 			ce->additional_error_info.invalid_command.offense_value,
2258 			func);
2259 	}
2260     }
2261 #if 0
2262     ciss_print_request(cr);
2263 #endif
2264     return(1);
2265 }
2266 
2267 /************************************************************************
2268  * Issue a request and don't return until it's completed.
2269  *
2270  * Depending on adapter status, we may poll or sleep waiting for
2271  * completion.
2272  */
2273 static int
2274 ciss_synch_request(struct ciss_request *cr, int timeout)
2275 {
2276     if (cr->cr_sc->ciss_flags & CISS_FLAG_RUNNING) {
2277 	return(ciss_wait_request(cr, timeout));
2278     } else {
2279 	return(ciss_poll_request(cr, timeout));
2280     }
2281 }
2282 
2283 /************************************************************************
2284  * Issue a request and poll for completion.
2285  *
2286  * Timeout in milliseconds.
2287  */
2288 static int
2289 ciss_poll_request(struct ciss_request *cr, int timeout)
2290 {
2291     cr_qhead_t qh;
2292     struct ciss_softc *sc;
2293     int		error;
2294 
2295     debug_called(2);
2296 
2297     STAILQ_INIT(&qh);
2298     sc = cr->cr_sc;
2299     cr->cr_flags |= CISS_REQ_POLL;
2300     if ((error = ciss_start(cr)) != 0)
2301 	return(error);
2302 
2303     do {
2304 	if (sc->ciss_perf)
2305 	    ciss_perf_done(sc, &qh);
2306 	else
2307 	    ciss_done(sc, &qh);
2308 	ciss_complete(sc, &qh);
2309 	if (!(cr->cr_flags & CISS_REQ_POLL))
2310 	    return(0);
2311 	DELAY(1000);
2312     } while (timeout-- >= 0);
2313     return(EWOULDBLOCK);
2314 }
2315 
2316 /************************************************************************
2317  * Issue a request and sleep waiting for completion.
2318  *
2319  * Timeout in milliseconds.  Note that a spurious wakeup will reset
2320  * the timeout.
2321  */
2322 static int
2323 ciss_wait_request(struct ciss_request *cr, int timeout)
2324 {
2325     int		error;
2326 
2327     debug_called(2);
2328 
2329     cr->cr_flags |= CISS_REQ_SLEEP;
2330     if ((error = ciss_start(cr)) != 0)
2331 	return(error);
2332 
2333     while ((cr->cr_flags & CISS_REQ_SLEEP) && (error != EWOULDBLOCK)) {
2334 	error = msleep(cr, &cr->cr_sc->ciss_mtx, PRIBIO, "cissREQ", (timeout * hz) / 1000);
2335     }
2336     return(error);
2337 }
2338 
2339 #if 0
2340 /************************************************************************
2341  * Abort a request.  Note that a potential exists here to race the
2342  * request being completed; the caller must deal with this.
2343  */
2344 static int
2345 ciss_abort_request(struct ciss_request *ar)
2346 {
2347     struct ciss_request		*cr;
2348     struct ciss_command		*cc;
2349     struct ciss_message_cdb	*cmc;
2350     int				error;
2351 
2352     debug_called(1);
2353 
2354     /* get a request */
2355     if ((error = ciss_get_request(ar->cr_sc, &cr)) != 0)
2356 	return(error);
2357 
2358     /* build the abort command */
2359     cc = CISS_FIND_COMMAND(cr);
2360     cc->header.address.mode.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;	/* addressing? */
2361     cc->header.address.physical.target = 0;
2362     cc->header.address.physical.bus = 0;
2363     cc->cdb.cdb_length = sizeof(*cmc);
2364     cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
2365     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2366     cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2367     cc->cdb.timeout = 30;
2368 
2369     cmc = (struct ciss_message_cdb *)&(cc->cdb.cdb[0]);
2370     cmc->opcode = CISS_OPCODE_MESSAGE_ABORT;
2371     cmc->type = CISS_MESSAGE_ABORT_TASK;
2372     cmc->abort_tag = ar->cr_tag;	/* endianness?? */
2373 
2374     /*
2375      * Send the request and wait for a response.  If we believe we
2376      * aborted the request OK, clear the flag that indicates it's
2377      * running.
2378      */
2379     error = ciss_synch_request(cr, 35 * 1000);
2380     if (!error)
2381 	error = ciss_report_request(cr, NULL, NULL);
2382     ciss_release_request(cr);
2383 
2384     return(error);
2385 }
2386 #endif
2387 
2388 
2389 /************************************************************************
2390  * Fetch and initialise a request
2391  */
2392 static int
2393 ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp)
2394 {
2395     struct ciss_request *cr;
2396 
2397     debug_called(2);
2398 
2399     /*
2400      * Get a request and clean it up.
2401      */
2402     if ((cr = ciss_dequeue_free(sc)) == NULL)
2403 	return(ENOMEM);
2404 
2405     cr->cr_data = NULL;
2406     cr->cr_flags = 0;
2407     cr->cr_complete = NULL;
2408     cr->cr_private = NULL;
2409     cr->cr_sg_tag = CISS_SG_MAX;	/* Backstop to prevent accidents */
2410 
2411     ciss_preen_command(cr);
2412     *crp = cr;
2413     return(0);
2414 }
2415 
2416 static void
2417 ciss_preen_command(struct ciss_request *cr)
2418 {
2419     struct ciss_command	*cc;
2420     u_int32_t		cmdphys;
2421 
2422     /*
2423      * Clean up the command structure.
2424      *
2425      * Note that we set up the error_info structure here, since the
2426      * length can be overwritten by any command.
2427      */
2428     cc = CISS_FIND_COMMAND(cr);
2429     cc->header.sg_in_list = 0;		/* kinda inefficient this way */
2430     cc->header.sg_total = 0;
2431     cc->header.host_tag = cr->cr_tag << 2;
2432     cc->header.host_tag_zeroes = 0;
2433     cmdphys = CISS_FIND_COMMANDPHYS(cr);
2434     cc->error_info.error_info_address = cmdphys + sizeof(struct ciss_command);
2435     cc->error_info.error_info_length = CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command);
2436 }
2437 
2438 /************************************************************************
2439  * Release a request to the free list.
2440  */
2441 static void
2442 ciss_release_request(struct ciss_request *cr)
2443 {
2444     struct ciss_softc	*sc;
2445 
2446     debug_called(2);
2447 
2448     sc = cr->cr_sc;
2449 
2450     /* release the request to the free queue */
2451     ciss_requeue_free(cr);
2452 }
2453 
2454 /************************************************************************
2455  * Allocate a request that will be used to send a BMIC command.  Do some
2456  * of the common setup here to avoid duplicating it everywhere else.
2457  */
2458 static int
2459 ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
2460 		      int opcode, void **bufp, size_t bufsize)
2461 {
2462     struct ciss_request		*cr;
2463     struct ciss_command		*cc;
2464     struct ciss_bmic_cdb	*cbc;
2465     void			*buf;
2466     int				error;
2467     int				dataout;
2468 
2469     debug_called(2);
2470 
2471     cr = NULL;
2472     buf = NULL;
2473 
2474     /*
2475      * Get a request.
2476      */
2477     if ((error = ciss_get_request(sc, &cr)) != 0)
2478 	goto out;
2479 
2480     /*
2481      * Allocate data storage if requested, determine the data direction.
2482      */
2483     dataout = 0;
2484     if ((bufsize > 0) && (bufp != NULL)) {
2485 	if (*bufp == NULL) {
2486 	    if ((buf = malloc(bufsize, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
2487 		error = ENOMEM;
2488 		goto out;
2489 	    }
2490 	} else {
2491 	    buf = *bufp;
2492 	    dataout = 1;	/* we are given a buffer, so we are writing */
2493 	}
2494     }
2495 
2496     /*
2497      * Build a CISS BMIC command to get the logical drive ID.
2498      */
2499     cr->cr_data = buf;
2500     cr->cr_length = bufsize;
2501     if (!dataout)
2502 	cr->cr_flags = CISS_REQ_DATAIN;
2503 
2504     cc = CISS_FIND_COMMAND(cr);
2505     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2506     cc->header.address.physical.bus = 0;
2507     cc->header.address.physical.target = 0;
2508     cc->cdb.cdb_length = sizeof(*cbc);
2509     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2510     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2511     cc->cdb.direction = dataout ? CISS_CDB_DIRECTION_WRITE : CISS_CDB_DIRECTION_READ;
2512     cc->cdb.timeout = 0;
2513 
2514     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
2515     bzero(cbc, sizeof(*cbc));
2516     cbc->opcode = dataout ? CISS_ARRAY_CONTROLLER_WRITE : CISS_ARRAY_CONTROLLER_READ;
2517     cbc->bmic_opcode = opcode;
2518     cbc->size = htons((u_int16_t)bufsize);
2519 
2520 out:
2521     if (error) {
2522 	if (cr != NULL)
2523 	    ciss_release_request(cr);
2524     } else {
2525 	*crp = cr;
2526 	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
2527 	    *bufp = buf;
2528     }
2529     return(error);
2530 }
2531 
2532 /************************************************************************
2533  * Handle a command passed in from userspace.
2534  */
2535 static int
2536 ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
2537 {
2538     struct ciss_request		*cr;
2539     struct ciss_command		*cc;
2540     struct ciss_error_info	*ce;
2541     int				error = 0;
2542 
2543     debug_called(1);
2544 
2545     cr = NULL;
2546 
2547     /*
2548      * Get a request.
2549      */
2550     while (ciss_get_request(sc, &cr) != 0)
2551 	msleep(sc, &sc->ciss_mtx, PPAUSE, "cissREQ", hz);
2552     cc = CISS_FIND_COMMAND(cr);
2553 
2554     /*
2555      * Allocate an in-kernel databuffer if required, copy in user data.
2556      */
2557     cr->cr_length = ioc->buf_size;
2558     if (ioc->buf_size > 0) {
2559 	if ((cr->cr_data = malloc(ioc->buf_size, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2560 	    error = ENOMEM;
2561 	    goto out;
2562 	}
2563 	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
2564 	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2565 	    goto out;
2566 	}
2567     }
2568 
2569     /*
2570      * Build the request based on the user command.
2571      */
2572     bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
2573     bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
2574 
2575     /* XXX anything else to populate here? */
2576 
2577     /*
2578      * Run the command.
2579      */
2580     if ((error = ciss_synch_request(cr, 60 * 1000))) {
2581 	debug(0, "request failed - %d", error);
2582 	goto out;
2583     }
2584 
2585     /*
2586      * Check to see if the command succeeded.
2587      */
2588     ce = (struct ciss_error_info *)&(cc->sg[0]);
2589     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) == 0)
2590 	bzero(ce, sizeof(*ce));
2591 
2592     /*
2593      * Copy the results back to the user.
2594      */
2595     bcopy(ce, &ioc->error_info, sizeof(*ce));
2596     if ((ioc->buf_size > 0) &&
2597 	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
2598 	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2599 	goto out;
2600     }
2601 
2602     /* done OK */
2603     error = 0;
2604 
2605 out:
2606     if ((cr != NULL) && (cr->cr_data != NULL))
2607 	free(cr->cr_data, CISS_MALLOC_CLASS);
2608     if (cr != NULL)
2609 	ciss_release_request(cr);
2610     return(error);
2611 }
2612 
2613 /************************************************************************
2614  * Map a request into bus-visible space, initialise the scatter/gather
2615  * list.
2616  */
2617 static int
2618 ciss_map_request(struct ciss_request *cr)
2619 {
2620     struct ciss_softc	*sc;
2621     int			error = 0;
2622 
2623     debug_called(2);
2624 
2625     sc = cr->cr_sc;
2626 
2627     /* check that mapping is necessary */
2628     if (cr->cr_flags & CISS_REQ_MAPPED)
2629 	return(0);
2630 
2631     cr->cr_flags |= CISS_REQ_MAPPED;
2632 
2633     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2634 		    BUS_DMASYNC_PREWRITE);
2635 
2636     if (cr->cr_data != NULL) {
2637 	error = bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap,
2638 				cr->cr_data, cr->cr_length,
2639 				ciss_request_map_helper, cr, 0);
2640 	if (error != 0)
2641 	    return (error);
2642     } else {
2643 	/*
2644 	 * Post the command to the adapter.
2645 	 */
2646 	cr->cr_sg_tag = CISS_SG_NONE;
2647 	cr->cr_flags |= CISS_REQ_BUSY;
2648 	if (sc->ciss_perf)
2649 	    CISS_TL_PERF_POST_CMD(sc, cr);
2650 	else
2651 	    CISS_TL_SIMPLE_POST_CMD(sc, CISS_FIND_COMMANDPHYS(cr));
2652     }
2653 
2654     return(0);
2655 }
2656 
2657 static void
2658 ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2659 {
2660     struct ciss_command	*cc;
2661     struct ciss_request *cr;
2662     struct ciss_softc	*sc;
2663     int			i;
2664 
2665     debug_called(2);
2666 
2667     cr = (struct ciss_request *)arg;
2668     sc = cr->cr_sc;
2669     cc = CISS_FIND_COMMAND(cr);
2670 
2671     for (i = 0; i < nseg; i++) {
2672 	cc->sg[i].address = segs[i].ds_addr;
2673 	cc->sg[i].length = segs[i].ds_len;
2674 	cc->sg[i].extension = 0;
2675     }
2676     /* we leave the s/g table entirely within the command */
2677     cc->header.sg_in_list = nseg;
2678     cc->header.sg_total = nseg;
2679 
2680     if (cr->cr_flags & CISS_REQ_DATAIN)
2681 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2682     if (cr->cr_flags & CISS_REQ_DATAOUT)
2683 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2684 
2685     if (nseg == 1)
2686 	cr->cr_sg_tag = CISS_SG_NONE;
2687     else if (nseg == 1)
2688 	cr->cr_sg_tag = CISS_SG_1;
2689     else if (nseg == 2)
2690 	cr->cr_sg_tag = CISS_SG_2;
2691     else if (nseg <= 4)
2692 	cr->cr_sg_tag = CISS_SG_4;
2693     else if (nseg <= 8)
2694 	cr->cr_sg_tag = CISS_SG_8;
2695     else if (nseg <= 16)
2696 	cr->cr_sg_tag = CISS_SG_16;
2697     else if (nseg <= 32)
2698 	cr->cr_sg_tag = CISS_SG_32;
2699     else
2700 	cr->cr_sg_tag = CISS_SG_MAX;
2701 
2702     /*
2703      * Post the command to the adapter.
2704      */
2705     cr->cr_flags |= CISS_REQ_BUSY;
2706     if (sc->ciss_perf)
2707 	CISS_TL_PERF_POST_CMD(sc, cr);
2708     else
2709 	CISS_TL_SIMPLE_POST_CMD(sc, CISS_FIND_COMMANDPHYS(cr));
2710 }
2711 
2712 /************************************************************************
2713  * Unmap a request from bus-visible space.
2714  */
2715 static void
2716 ciss_unmap_request(struct ciss_request *cr)
2717 {
2718     struct ciss_softc	*sc;
2719 
2720     debug_called(2);
2721 
2722     sc = cr->cr_sc;
2723 
2724     /* check that unmapping is necessary */
2725     if ((cr->cr_flags & CISS_REQ_MAPPED) == 0)
2726 	return;
2727 
2728     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2729 		    BUS_DMASYNC_POSTWRITE);
2730 
2731     if (cr->cr_data == NULL)
2732 	goto out;
2733 
2734     if (cr->cr_flags & CISS_REQ_DATAIN)
2735 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2736     if (cr->cr_flags & CISS_REQ_DATAOUT)
2737 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2738 
2739     bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2740 out:
2741     cr->cr_flags &= ~CISS_REQ_MAPPED;
2742 }
2743 
2744 /************************************************************************
2745  * Attach the driver to CAM.
2746  *
2747  * We put all the logical drives on a single SCSI bus.
2748  */
2749 static int
2750 ciss_cam_init(struct ciss_softc *sc)
2751 {
2752     int			i, maxbus;
2753 
2754     debug_called(1);
2755 
2756     /*
2757      * Allocate a devq.  We can reuse this for the masked physical
2758      * devices if we decide to export these as well.
2759      */
2760     if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests)) == NULL) {
2761 	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2762 	return(ENOMEM);
2763     }
2764 
2765     /*
2766      * Create a SIM.
2767      *
2768      * This naturally wastes a bit of memory.  The alternative is to allocate
2769      * and register each bus as it is found, and then track them on a linked
2770      * list.  Unfortunately, the driver has a few places where it needs to
2771      * look up the SIM based solely on bus number, and it's unclear whether
2772      * a list traversal would work for these situations.
2773      */
2774     maxbus = max(sc->ciss_max_logical_bus, sc->ciss_max_physical_bus +
2775 		 CISS_PHYSICAL_BASE);
2776     sc->ciss_cam_sim = malloc(maxbus * sizeof(struct cam_sim*),
2777 			      CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
2778     if (sc->ciss_cam_sim == NULL) {
2779 	ciss_printf(sc, "can't allocate memory for controller SIM\n");
2780 	return(ENOMEM);
2781     }
2782 
2783     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
2784 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2785 						 "ciss", sc,
2786 						 device_get_unit(sc->ciss_dev),
2787 						 &sc->ciss_mtx,
2788 						 2,
2789 						 sc->ciss_max_requests - 2,
2790 						 sc->ciss_cam_devq)) == NULL) {
2791 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2792 	    return(ENOMEM);
2793 	}
2794 
2795 	/*
2796 	 * Register bus with this SIM.
2797 	 */
2798 	mtx_lock(&sc->ciss_mtx);
2799 	if (i == 0 || sc->ciss_controllers[i].physical.bus != 0) {
2800 	    if (xpt_bus_register(sc->ciss_cam_sim[i], sc->ciss_dev, i) != 0) {
2801 		ciss_printf(sc, "can't register SCSI bus %d\n", i);
2802 		mtx_unlock(&sc->ciss_mtx);
2803 		return (ENXIO);
2804 	    }
2805 	}
2806 	mtx_unlock(&sc->ciss_mtx);
2807     }
2808 
2809     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2810 	 CISS_PHYSICAL_BASE; i++) {
2811 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2812 						 "ciss", sc,
2813 						 device_get_unit(sc->ciss_dev),
2814 						 &sc->ciss_mtx, 1,
2815 						 sc->ciss_max_requests - 2,
2816 						 sc->ciss_cam_devq)) == NULL) {
2817 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2818 	    return (ENOMEM);
2819 	}
2820 
2821 	mtx_lock(&sc->ciss_mtx);
2822 	if (xpt_bus_register(sc->ciss_cam_sim[i], sc->ciss_dev, i) != 0) {
2823 	    ciss_printf(sc, "can't register SCSI bus %d\n", i);
2824 	    mtx_unlock(&sc->ciss_mtx);
2825 	    return (ENXIO);
2826 	}
2827 	mtx_unlock(&sc->ciss_mtx);
2828     }
2829 
2830     /*
2831      * Initiate a rescan of the bus.
2832      */
2833     mtx_lock(&sc->ciss_mtx);
2834     ciss_cam_rescan_all(sc);
2835     mtx_unlock(&sc->ciss_mtx);
2836 
2837     return(0);
2838 }
2839 
2840 /************************************************************************
2841  * Initiate a rescan of the 'logical devices' SIM
2842  */
2843 static void
2844 ciss_cam_rescan_target(struct ciss_softc *sc, int bus, int target)
2845 {
2846     struct cam_path	*path;
2847     union ccb		*ccb;
2848 
2849     debug_called(1);
2850 
2851     if ((ccb = malloc(sizeof(union ccb), CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
2852 	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2853 	return;
2854     }
2855 
2856     if (xpt_create_path(&path, xpt_periph, cam_sim_path(sc->ciss_cam_sim[bus]),
2857 			target, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2858 	ciss_printf(sc, "rescan failed (can't create path)\n");
2859 	free(ccb, CISS_MALLOC_CLASS);
2860 	return;
2861     }
2862 
2863     xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
2864     ccb->ccb_h.func_code = XPT_SCAN_BUS;
2865     ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2866     ccb->crcn.flags = CAM_FLAG_NONE;
2867     xpt_action(ccb);
2868 
2869     /* scan is now in progress */
2870 }
2871 
2872 static void
2873 ciss_cam_rescan_all(struct ciss_softc *sc)
2874 {
2875     int i;
2876 
2877     /* Rescan the logical buses */
2878     for (i = 0; i < sc->ciss_max_logical_bus; i++)
2879 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2880     /* Rescan the physical buses */
2881     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2882 	 CISS_PHYSICAL_BASE; i++)
2883 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2884 }
2885 
2886 static void
2887 ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2888 {
2889     xpt_free_path(ccb->ccb_h.path);
2890     free(ccb, CISS_MALLOC_CLASS);
2891 }
2892 
2893 /************************************************************************
2894  * Handle requests coming from CAM
2895  */
2896 static void
2897 ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2898 {
2899     struct ciss_softc	*sc;
2900     struct ccb_scsiio	*csio;
2901     int			bus, target;
2902     int			physical;
2903 
2904     sc = cam_sim_softc(sim);
2905     bus = cam_sim_bus(sim);
2906     csio = (struct ccb_scsiio *)&ccb->csio;
2907     target = csio->ccb_h.target_id;
2908     physical = CISS_IS_PHYSICAL(bus);
2909 
2910     switch (ccb->ccb_h.func_code) {
2911 
2912 	/* perform SCSI I/O */
2913     case XPT_SCSI_IO:
2914 	if (!ciss_cam_action_io(sim, csio))
2915 	    return;
2916 	break;
2917 
2918 	/* perform geometry calculations */
2919     case XPT_CALC_GEOMETRY:
2920     {
2921 	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2922 	struct ciss_ldrive		*ld;
2923 
2924 	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2925 
2926 	ld = NULL;
2927 	if (!physical)
2928 	    ld = &sc->ciss_logical[bus][target];
2929 
2930 	/*
2931 	 * Use the cached geometry settings unless the fault tolerance
2932 	 * is invalid.
2933 	 */
2934 	if (physical || ld->cl_geometry.fault_tolerance == 0xFF) {
2935 	    u_int32_t			secs_per_cylinder;
2936 
2937 	    ccg->heads = 255;
2938 	    ccg->secs_per_track = 32;
2939 	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2940 	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2941 	} else {
2942 	    ccg->heads = ld->cl_geometry.heads;
2943 	    ccg->secs_per_track = ld->cl_geometry.sectors;
2944 	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2945 	}
2946 	ccb->ccb_h.status = CAM_REQ_CMP;
2947         break;
2948     }
2949 
2950 	/* handle path attribute inquiry */
2951     case XPT_PATH_INQ:
2952     {
2953 	struct ccb_pathinq	*cpi = &ccb->cpi;
2954 
2955 	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2956 
2957 	cpi->version_num = 1;
2958 	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2959 	cpi->target_sprt = 0;
2960 	cpi->hba_misc = 0;
2961 	cpi->max_target = CISS_MAX_LOGICAL;
2962 	cpi->max_lun = 0;		/* 'logical drive' channel only */
2963 	cpi->initiator_id = CISS_MAX_LOGICAL;
2964 	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2965         strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2966         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2967         cpi->unit_number = cam_sim_unit(sim);
2968         cpi->bus_id = cam_sim_bus(sim);
2969 	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2970 	cpi->transport = XPORT_SPI;
2971 	cpi->transport_version = 2;
2972 	cpi->protocol = PROTO_SCSI;
2973 	cpi->protocol_version = SCSI_REV_2;
2974 	ccb->ccb_h.status = CAM_REQ_CMP;
2975 	break;
2976     }
2977 
2978     case XPT_GET_TRAN_SETTINGS:
2979     {
2980 	struct ccb_trans_settings	*cts = &ccb->cts;
2981 	int				bus, target;
2982 	struct ccb_trans_settings_spi *spi =
2983 	    &cts->xport_specific.spi;
2984 
2985 	bus = cam_sim_bus(sim);
2986 	target = cts->ccb_h.target_id;
2987 
2988 	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2989 	/* disconnect always OK */
2990 	cts->protocol = PROTO_SCSI;
2991 	cts->protocol_version = SCSI_REV_2;
2992 	cts->transport = XPORT_SPI;
2993 	cts->transport_version = 2;
2994 
2995 	spi->valid = CTS_SPI_VALID_DISC;
2996 	spi->flags = CTS_SPI_FLAGS_DISC_ENB;
2997 
2998 	cts->ccb_h.status = CAM_REQ_CMP;
2999 	break;
3000     }
3001 
3002     default:		/* we can't do this */
3003 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
3004 	ccb->ccb_h.status = CAM_REQ_INVALID;
3005 	break;
3006     }
3007 
3008     xpt_done(ccb);
3009 }
3010 
3011 /************************************************************************
3012  * Handle a CAM SCSI I/O request.
3013  */
3014 static int
3015 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
3016 {
3017     struct ciss_softc	*sc;
3018     int			bus, target;
3019     struct ciss_request	*cr;
3020     struct ciss_command	*cc;
3021     int			error;
3022 
3023     sc = cam_sim_softc(sim);
3024     bus = cam_sim_bus(sim);
3025     target = csio->ccb_h.target_id;
3026 
3027     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
3028 
3029     /* check that the CDB pointer is not to a physical address */
3030     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
3031 	debug(3, "  CDB pointer is to physical address");
3032 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3033     }
3034 
3035     /* if there is data transfer, it must be to/from a virtual address */
3036     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
3037 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
3038 	    debug(3, "  data pointer is to physical address");
3039 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3040 	}
3041 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
3042 	    debug(3, "  data has premature s/g setup");
3043 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3044 	}
3045     }
3046 
3047     /* abandon aborted ccbs or those that have failed validation */
3048     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3049 	debug(3, "abandoning CCB due to abort/validation failure");
3050 	return(EINVAL);
3051     }
3052 
3053     /* handle emulation of some SCSI commands ourself */
3054     if (ciss_cam_emulate(sc, csio))
3055 	return(0);
3056 
3057     /*
3058      * Get a request to manage this command.  If we can't, return the
3059      * ccb, freeze the queue and flag so that we unfreeze it when a
3060      * request completes.
3061      */
3062     if ((error = ciss_get_request(sc, &cr)) != 0) {
3063 	xpt_freeze_simq(sim, 1);
3064 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
3065 	return(error);
3066     }
3067 
3068     /*
3069      * Build the command.
3070      */
3071     cc = CISS_FIND_COMMAND(cr);
3072     cr->cr_data = csio->data_ptr;
3073     cr->cr_length = csio->dxfer_len;
3074     cr->cr_complete = ciss_cam_complete;
3075     cr->cr_private = csio;
3076 
3077     /*
3078      * Target the right logical volume.
3079      */
3080     if (CISS_IS_PHYSICAL(bus))
3081 	cc->header.address =
3082 	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
3083     else
3084 	cc->header.address =
3085 	    sc->ciss_logical[bus][target].cl_address;
3086     cc->cdb.cdb_length = csio->cdb_len;
3087     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3088     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
3089     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
3090 	cr->cr_flags = CISS_REQ_DATAOUT;
3091 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3092     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
3093 	cr->cr_flags = CISS_REQ_DATAIN;
3094 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3095     } else {
3096 	cr->cr_flags = 0;
3097 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
3098     }
3099     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
3100     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
3101 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
3102     } else {
3103 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
3104     }
3105 
3106     /*
3107      * Submit the request to the adapter.
3108      *
3109      * Note that this may fail if we're unable to map the request (and
3110      * if we ever learn a transport layer other than simple, may fail
3111      * if the adapter rejects the command).
3112      */
3113     if ((error = ciss_start(cr)) != 0) {
3114 	xpt_freeze_simq(sim, 1);
3115 	if (error == EINPROGRESS) {
3116 	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3117 	    error = 0;
3118 	} else {
3119 	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
3120 	    ciss_release_request(cr);
3121 	}
3122 	return(error);
3123     }
3124 
3125     return(0);
3126 }
3127 
3128 /************************************************************************
3129  * Emulate SCSI commands the adapter doesn't handle as we might like.
3130  */
3131 static int
3132 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
3133 {
3134     int		bus, target;
3135     u_int8_t	opcode;
3136 
3137     target = csio->ccb_h.target_id;
3138     bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3139     opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3140 	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
3141 
3142     if (CISS_IS_PHYSICAL(bus)) {
3143 	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
3144 	    csio->ccb_h.status = CAM_SEL_TIMEOUT;
3145 	    xpt_done((union ccb *)csio);
3146 	    return(1);
3147 	} else
3148 	    return(0);
3149     }
3150 
3151     /*
3152      * Handle requests for volumes that don't exist or are not online.
3153      * A selection timeout is slightly better than an illegal request.
3154      * Other errors might be better.
3155      */
3156     if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
3157 	csio->ccb_h.status = CAM_SEL_TIMEOUT;
3158 	xpt_done((union ccb *)csio);
3159 	return(1);
3160     }
3161 
3162     /* if we have to fake Synchronise Cache */
3163     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
3164 	/*
3165 	 * If this is a Synchronise Cache command, typically issued when
3166 	 * a device is closed, flush the adapter and complete now.
3167 	 */
3168 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3169 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
3170 	    ciss_flush_adapter(sc);
3171 	    csio->ccb_h.status = CAM_REQ_CMP;
3172 	    xpt_done((union ccb *)csio);
3173 	    return(1);
3174 	}
3175     }
3176 
3177     return(0);
3178 }
3179 
3180 /************************************************************************
3181  * Check for possibly-completed commands.
3182  */
3183 static void
3184 ciss_cam_poll(struct cam_sim *sim)
3185 {
3186     cr_qhead_t qh;
3187     struct ciss_softc	*sc = cam_sim_softc(sim);
3188 
3189     debug_called(2);
3190 
3191     STAILQ_INIT(&qh);
3192     if (sc->ciss_perf)
3193 	ciss_perf_done(sc, &qh);
3194     else
3195 	ciss_done(sc, &qh);
3196     ciss_complete(sc, &qh);
3197 }
3198 
3199 /************************************************************************
3200  * Handle completion of a command - pass results back through the CCB
3201  */
3202 static void
3203 ciss_cam_complete(struct ciss_request *cr)
3204 {
3205     struct ciss_softc		*sc;
3206     struct ciss_command		*cc;
3207     struct ciss_error_info	*ce;
3208     struct ccb_scsiio		*csio;
3209     int				scsi_status;
3210     int				command_status;
3211 
3212     debug_called(2);
3213 
3214     sc = cr->cr_sc;
3215     cc = CISS_FIND_COMMAND(cr);
3216     ce = (struct ciss_error_info *)&(cc->sg[0]);
3217     csio = (struct ccb_scsiio *)cr->cr_private;
3218 
3219     /*
3220      * Extract status values from request.
3221      */
3222     ciss_report_request(cr, &command_status, &scsi_status);
3223     csio->scsi_status = scsi_status;
3224 
3225     /*
3226      * Handle specific SCSI status values.
3227      */
3228     switch(scsi_status) {
3229 	/* no status due to adapter error */
3230     case -1:
3231 	debug(0, "adapter error");
3232 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3233 	break;
3234 
3235 	/* no status due to command completed OK */
3236     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
3237 	debug(2, "SCSI_STATUS_OK");
3238 	csio->ccb_h.status = CAM_REQ_CMP;
3239 	break;
3240 
3241 	/* check condition, sense data included */
3242     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
3243 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
3244 	      ce->sense_length, ce->residual_count);
3245 	bzero(&csio->sense_data, SSD_FULL_SIZE);
3246 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
3247 	csio->sense_len = ce->sense_length;
3248 	csio->resid = ce->residual_count;
3249 	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
3250 #ifdef CISS_DEBUG
3251 	{
3252 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
3253 	    debug(0, "sense key %x", sns->flags & SSD_KEY);
3254 	}
3255 #endif
3256 	break;
3257 
3258     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
3259 	debug(0, "SCSI_STATUS_BUSY");
3260 	csio->ccb_h.status = CAM_SCSI_BUSY;
3261 	break;
3262 
3263     default:
3264 	debug(0, "unknown status 0x%x", csio->scsi_status);
3265 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3266 	break;
3267     }
3268 
3269     /* handle post-command fixup */
3270     ciss_cam_complete_fixup(sc, csio);
3271 
3272     /* tell CAM we're ready for more commands */
3273     csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3274 
3275     ciss_release_request(cr);
3276     xpt_done((union ccb *)csio);
3277 }
3278 
3279 /********************************************************************************
3280  * Fix up the result of some commands here.
3281  */
3282 static void
3283 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
3284 {
3285     struct scsi_inquiry_data	*inq;
3286     struct ciss_ldrive		*cl;
3287     int				bus, target;
3288 
3289     if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3290 	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
3291 
3292 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
3293 	target = csio->ccb_h.target_id;
3294 	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3295 
3296 	/*
3297 	 * Don't let hard drives be seen by the DA driver.  They will still be
3298 	 * attached by the PASS driver.
3299 	 */
3300 	if (CISS_IS_PHYSICAL(bus)) {
3301 	    if (SID_TYPE(inq) == T_DIRECT)
3302 		inq->device = (inq->device & 0xe0) | T_NODEVICE;
3303 	    return;
3304 	}
3305 
3306 	cl = &sc->ciss_logical[bus][target];
3307 
3308 	padstr(inq->vendor, "COMPAQ", 8);
3309 	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
3310 	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
3311     }
3312 }
3313 
3314 
3315 /********************************************************************************
3316  * Find a peripheral attached at (target)
3317  */
3318 static struct cam_periph *
3319 ciss_find_periph(struct ciss_softc *sc, int bus, int target)
3320 {
3321     struct cam_periph	*periph;
3322     struct cam_path	*path;
3323     int			status;
3324 
3325     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
3326 			     target, 0);
3327     if (status == CAM_REQ_CMP) {
3328 	periph = cam_periph_find(path, NULL);
3329 	xpt_free_path(path);
3330     } else {
3331 	periph = NULL;
3332     }
3333     return(periph);
3334 }
3335 
3336 /********************************************************************************
3337  * Name the device at (target)
3338  *
3339  * XXX is this strictly correct?
3340  */
3341 static int
3342 ciss_name_device(struct ciss_softc *sc, int bus, int target)
3343 {
3344     struct cam_periph	*periph;
3345 
3346     if (CISS_IS_PHYSICAL(bus))
3347 	return (0);
3348     if ((periph = ciss_find_periph(sc, bus, target)) != NULL) {
3349 	sprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
3350 		periph->periph_name, periph->unit_number);
3351 	return(0);
3352     }
3353     sc->ciss_logical[bus][target].cl_name[0] = 0;
3354     return(ENOENT);
3355 }
3356 
3357 /************************************************************************
3358  * Periodic status monitoring.
3359  */
3360 static void
3361 ciss_periodic(void *arg)
3362 {
3363     struct ciss_softc	*sc;
3364     struct ciss_request	*cr = NULL;
3365     struct ciss_command	*cc = NULL;
3366     int			error = 0;
3367 
3368     debug_called(1);
3369 
3370     sc = (struct ciss_softc *)arg;
3371 
3372     /*
3373      * Check the adapter heartbeat.
3374      */
3375     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
3376 	sc->ciss_heart_attack++;
3377 	debug(0, "adapter heart attack in progress 0x%x/%d",
3378 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
3379 	if (sc->ciss_heart_attack == 3) {
3380 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
3381 	    ciss_disable_adapter(sc);
3382 	    return;
3383 	}
3384     } else {
3385 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
3386 	sc->ciss_heart_attack = 0;
3387 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
3388     }
3389 
3390     /*
3391      * Send the NOP message and wait for a response.
3392      */
3393     if (ciss_nop_message_heartbeat != 0 && (error = ciss_get_request(sc, &cr)) == 0) {
3394 	cc = CISS_FIND_COMMAND(cr);
3395 	cr->cr_complete = ciss_nop_complete;
3396 	cc->cdb.cdb_length = 1;
3397 	cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
3398 	cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3399 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3400 	cc->cdb.timeout = 0;
3401 	cc->cdb.cdb[0] = CISS_OPCODE_MESSAGE_NOP;
3402 
3403 	if ((error = ciss_start(cr)) != 0) {
3404 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED\n");
3405 	}
3406     }
3407 
3408     /*
3409      * If the notify event request has died for some reason, or has
3410      * not started yet, restart it.
3411      */
3412     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
3413 	debug(0, "(re)starting Event Notify chain");
3414 	ciss_notify_event(sc);
3415     }
3416 
3417     /*
3418      * Reschedule.
3419      */
3420     callout_reset(&sc->ciss_periodic, CISS_HEARTBEAT_RATE * hz, ciss_periodic, sc);
3421 }
3422 
3423 static void
3424 ciss_nop_complete(struct ciss_request *cr)
3425 {
3426     struct ciss_softc		*sc;
3427     static int			first_time = 1;
3428 
3429     sc = cr->cr_sc;
3430     if (ciss_report_request(cr, NULL, NULL) != 0) {
3431 	if (first_time == 1) {
3432 	    first_time = 0;
3433 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED (not logging anymore)\n");
3434 	}
3435     }
3436 
3437     ciss_release_request(cr);
3438 }
3439 
3440 /************************************************************************
3441  * Disable the adapter.
3442  *
3443  * The all requests in completed queue is failed with hardware error.
3444  * This will cause failover in a multipath configuration.
3445  */
3446 static void
3447 ciss_disable_adapter(struct ciss_softc *sc)
3448 {
3449     cr_qhead_t			qh;
3450     struct ciss_request		*cr;
3451     struct ciss_command		*cc;
3452     struct ciss_error_info	*ce;
3453     int				i;
3454 
3455     CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
3456     pci_disable_busmaster(sc->ciss_dev);
3457     sc->ciss_flags &= ~CISS_FLAG_RUNNING;
3458 
3459     for (i = 1; i < sc->ciss_max_requests; i++) {
3460 	cr = &sc->ciss_request[i];
3461 	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
3462 	    continue;
3463 
3464 	cc = CISS_FIND_COMMAND(cr);
3465 	ce = (struct ciss_error_info *)&(cc->sg[0]);
3466 	ce->command_status = CISS_CMD_STATUS_HARDWARE_ERROR;
3467 	ciss_enqueue_complete(cr, &qh);
3468     }
3469 
3470     for (;;) {
3471 	if ((cr = ciss_dequeue_complete(sc, &qh)) == NULL)
3472 	    break;
3473 
3474 	/*
3475 	 * If the request has a callback, invoke it.
3476 	 */
3477 	if (cr->cr_complete != NULL) {
3478 	    cr->cr_complete(cr);
3479 	    continue;
3480 	}
3481 
3482 	/*
3483 	 * If someone is sleeping on this request, wake them up.
3484 	 */
3485 	if (cr->cr_flags & CISS_REQ_SLEEP) {
3486 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
3487 	    wakeup(cr);
3488 	    continue;
3489 	}
3490     }
3491 }
3492 
3493 /************************************************************************
3494  * Request a notification response from the adapter.
3495  *
3496  * If (cr) is NULL, this is the first request of the adapter, so
3497  * reset the adapter's message pointer and start with the oldest
3498  * message available.
3499  */
3500 static void
3501 ciss_notify_event(struct ciss_softc *sc)
3502 {
3503     struct ciss_request		*cr;
3504     struct ciss_command		*cc;
3505     struct ciss_notify_cdb	*cnc;
3506     int				error;
3507 
3508     debug_called(1);
3509 
3510     cr = sc->ciss_periodic_notify;
3511 
3512     /* get a request if we don't already have one */
3513     if (cr == NULL) {
3514 	if ((error = ciss_get_request(sc, &cr)) != 0) {
3515 	    debug(0, "can't get notify event request");
3516 	    goto out;
3517 	}
3518 	sc->ciss_periodic_notify = cr;
3519 	cr->cr_complete = ciss_notify_complete;
3520 	debug(1, "acquired request %d", cr->cr_tag);
3521     }
3522 
3523     /*
3524      * Get a databuffer if we don't already have one, note that the
3525      * adapter command wants a larger buffer than the actual
3526      * structure.
3527      */
3528     if (cr->cr_data == NULL) {
3529 	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3530 	    debug(0, "can't get notify event request buffer");
3531 	    error = ENOMEM;
3532 	    goto out;
3533 	}
3534 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3535     }
3536 
3537     /* re-setup the request's command (since we never release it) XXX overkill*/
3538     ciss_preen_command(cr);
3539 
3540     /* (re)build the notify event command */
3541     cc = CISS_FIND_COMMAND(cr);
3542     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3543     cc->header.address.physical.bus = 0;
3544     cc->header.address.physical.target = 0;
3545 
3546     cc->cdb.cdb_length = sizeof(*cnc);
3547     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3548     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3549     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3550     cc->cdb.timeout = 0;	/* no timeout, we hope */
3551 
3552     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3553     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3554     cnc->opcode = CISS_OPCODE_READ;
3555     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3556     cnc->timeout = 0;		/* no timeout, we hope */
3557     cnc->synchronous = 0;
3558     cnc->ordered = 0;
3559     cnc->seek_to_oldest = 0;
3560     if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3561 	cnc->new_only = 1;
3562     else
3563 	cnc->new_only = 0;
3564     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3565 
3566     /* submit the request */
3567     error = ciss_start(cr);
3568 
3569  out:
3570     if (error) {
3571 	if (cr != NULL) {
3572 	    if (cr->cr_data != NULL)
3573 		free(cr->cr_data, CISS_MALLOC_CLASS);
3574 	    ciss_release_request(cr);
3575 	}
3576 	sc->ciss_periodic_notify = NULL;
3577 	debug(0, "can't submit notify event request");
3578 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3579     } else {
3580 	debug(1, "notify event submitted");
3581 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3582     }
3583 }
3584 
3585 static void
3586 ciss_notify_complete(struct ciss_request *cr)
3587 {
3588     struct ciss_command	*cc;
3589     struct ciss_notify	*cn;
3590     struct ciss_softc	*sc;
3591     int			scsi_status;
3592     int			command_status;
3593     debug_called(1);
3594 
3595     cc = CISS_FIND_COMMAND(cr);
3596     cn = (struct ciss_notify *)cr->cr_data;
3597     sc = cr->cr_sc;
3598 
3599     /*
3600      * Report request results, decode status.
3601      */
3602     ciss_report_request(cr, &command_status, &scsi_status);
3603 
3604     /*
3605      * Abort the chain on a fatal error.
3606      *
3607      * XXX which of these are actually errors?
3608      */
3609     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3610 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3611 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3612 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3613 		    ciss_name_command_status(command_status));
3614 	ciss_release_request(cr);
3615 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3616 	return;
3617     }
3618 
3619     /*
3620      * If the adapter gave us a text message, print it.
3621      */
3622     if (cn->message[0] != 0)
3623 	ciss_printf(sc, "*** %.80s\n", cn->message);
3624 
3625     debug(0, "notify event class %d subclass %d detail %d",
3626 		cn->class, cn->subclass, cn->detail);
3627 
3628     /*
3629      * If the response indicates that the notifier has been aborted,
3630      * release the notifier command.
3631      */
3632     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3633 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3634 	(cn->detail == 1)) {
3635 	debug(0, "notifier exiting");
3636 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3637 	ciss_release_request(cr);
3638 	sc->ciss_periodic_notify = NULL;
3639 	wakeup(&sc->ciss_periodic_notify);
3640     } else {
3641 	/* Handle notify events in a kernel thread */
3642 	ciss_enqueue_notify(cr);
3643 	sc->ciss_periodic_notify = NULL;
3644 	wakeup(&sc->ciss_periodic_notify);
3645 	wakeup(&sc->ciss_notify);
3646     }
3647     /*
3648      * Send a new notify event command, if we're not aborting.
3649      */
3650     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3651 	ciss_notify_event(sc);
3652     }
3653 }
3654 
3655 /************************************************************************
3656  * Abort the Notify Event chain.
3657  *
3658  * Note that we can't just abort the command in progress; we have to
3659  * explicitly issue an Abort Notify Event command in order for the
3660  * adapter to clean up correctly.
3661  *
3662  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3663  * the chain will not restart itself.
3664  */
3665 static int
3666 ciss_notify_abort(struct ciss_softc *sc)
3667 {
3668     struct ciss_request		*cr;
3669     struct ciss_command		*cc;
3670     struct ciss_notify_cdb	*cnc;
3671     int				error, command_status, scsi_status;
3672 
3673     debug_called(1);
3674 
3675     cr = NULL;
3676     error = 0;
3677 
3678     /* verify that there's an outstanding command */
3679     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3680 	goto out;
3681 
3682     /* get a command to issue the abort with */
3683     if ((error = ciss_get_request(sc, &cr)))
3684 	goto out;
3685 
3686     /* get a buffer for the result */
3687     if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3688 	debug(0, "can't get notify event request buffer");
3689 	error = ENOMEM;
3690 	goto out;
3691     }
3692     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3693 
3694     /* build the CDB */
3695     cc = CISS_FIND_COMMAND(cr);
3696     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3697     cc->header.address.physical.bus = 0;
3698     cc->header.address.physical.target = 0;
3699     cc->cdb.cdb_length = sizeof(*cnc);
3700     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3701     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3702     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3703     cc->cdb.timeout = 0;	/* no timeout, we hope */
3704 
3705     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3706     bzero(cnc, sizeof(*cnc));
3707     cnc->opcode = CISS_OPCODE_WRITE;
3708     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3709     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3710 
3711     ciss_print_request(cr);
3712 
3713     /*
3714      * Submit the request and wait for it to complete.
3715      */
3716     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3717 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3718 	goto out;
3719     }
3720 
3721     /*
3722      * Check response.
3723      */
3724     ciss_report_request(cr, &command_status, &scsi_status);
3725     switch(command_status) {
3726     case CISS_CMD_STATUS_SUCCESS:
3727 	break;
3728     case CISS_CMD_STATUS_INVALID_COMMAND:
3729 	/*
3730 	 * Some older adapters don't support the CISS version of this
3731 	 * command.  Fall back to using the BMIC version.
3732 	 */
3733 	error = ciss_notify_abort_bmic(sc);
3734 	if (error != 0)
3735 	    goto out;
3736 	break;
3737 
3738     case CISS_CMD_STATUS_TARGET_STATUS:
3739 	/*
3740 	 * This can happen if the adapter thinks there wasn't an outstanding
3741 	 * Notify Event command but we did.  We clean up here.
3742 	 */
3743 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3744 	    if (sc->ciss_periodic_notify != NULL)
3745 		ciss_release_request(sc->ciss_periodic_notify);
3746 	    error = 0;
3747 	    goto out;
3748 	}
3749 	/* FALLTHROUGH */
3750 
3751     default:
3752 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3753 		    ciss_name_command_status(command_status));
3754 	error = EIO;
3755 	goto out;
3756     }
3757 
3758     /*
3759      * Sleep waiting for the notifier command to complete.  Note
3760      * that if it doesn't, we may end up in a bad situation, since
3761      * the adapter may deliver it later.  Also note that the adapter
3762      * requires the Notify Event command to be cancelled in order to
3763      * maintain internal bookkeeping.
3764      */
3765     while (sc->ciss_periodic_notify != NULL) {
3766 	error = msleep(&sc->ciss_periodic_notify, &sc->ciss_mtx, PRIBIO, "cissNEA", hz * 5);
3767 	if (error == EWOULDBLOCK) {
3768 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3769 	    break;
3770 	}
3771     }
3772 
3773  out:
3774     /* release the cancel request */
3775     if (cr != NULL) {
3776 	if (cr->cr_data != NULL)
3777 	    free(cr->cr_data, CISS_MALLOC_CLASS);
3778 	ciss_release_request(cr);
3779     }
3780     if (error == 0)
3781 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3782     return(error);
3783 }
3784 
3785 /************************************************************************
3786  * Abort the Notify Event chain using a BMIC command.
3787  */
3788 static int
3789 ciss_notify_abort_bmic(struct ciss_softc *sc)
3790 {
3791     struct ciss_request			*cr;
3792     int					error, command_status;
3793 
3794     debug_called(1);
3795 
3796     cr = NULL;
3797     error = 0;
3798 
3799     /* verify that there's an outstanding command */
3800     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3801 	goto out;
3802 
3803     /*
3804      * Build a BMIC command to cancel the Notify on Event command.
3805      *
3806      * Note that we are sending a CISS opcode here.  Odd.
3807      */
3808     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3809 				       NULL, 0)) != 0)
3810 	goto out;
3811 
3812     /*
3813      * Submit the request and wait for it to complete.
3814      */
3815     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3816 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3817 	goto out;
3818     }
3819 
3820     /*
3821      * Check response.
3822      */
3823     ciss_report_request(cr, &command_status, NULL);
3824     switch(command_status) {
3825     case CISS_CMD_STATUS_SUCCESS:
3826 	break;
3827     default:
3828 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3829 		    ciss_name_command_status(command_status));
3830 	error = EIO;
3831 	goto out;
3832     }
3833 
3834 out:
3835     if (cr != NULL)
3836 	ciss_release_request(cr);
3837     return(error);
3838 }
3839 
3840 /************************************************************************
3841  * Handle rescanning all the logical volumes when a notify event
3842  * causes the drives to come online or offline.
3843  */
3844 static void
3845 ciss_notify_rescan_logical(struct ciss_softc *sc)
3846 {
3847     struct ciss_lun_report      *cll;
3848     struct ciss_ldrive		*ld;
3849     int                         i, j, ndrives;
3850 
3851     /*
3852      * We must rescan all logical volumes to get the right logical
3853      * drive address.
3854      */
3855     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3856                            CISS_MAX_LOGICAL);
3857     if (cll == NULL)
3858         return;
3859 
3860     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3861 
3862     /*
3863      * Delete any of the drives which were destroyed by the
3864      * firmware.
3865      */
3866     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3867 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3868 	    ld = &sc->ciss_logical[i][j];
3869 
3870 	    if (ld->cl_update == 0)
3871 		continue;
3872 
3873 	    if (ld->cl_status != CISS_LD_ONLINE) {
3874 		ciss_cam_rescan_target(sc, i, j);
3875 		ld->cl_update = 0;
3876 		if (ld->cl_ldrive)
3877 		    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
3878 		if (ld->cl_lstatus)
3879 		    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
3880 
3881 		ld->cl_ldrive = NULL;
3882 		ld->cl_lstatus = NULL;
3883 	    }
3884 	}
3885     }
3886 
3887     /*
3888      * Scan for new drives.
3889      */
3890     for (i = 0; i < ndrives; i++) {
3891 	int	bus, target;
3892 
3893 	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3894 	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3895 	ld	= &sc->ciss_logical[bus][target];
3896 
3897 	if (ld->cl_update == 0)
3898 		continue;
3899 
3900 	ld->cl_update		= 0;
3901 	ld->cl_address		= cll->lun[i];
3902 	ld->cl_controller	= &sc->ciss_controllers[bus];
3903 	if (ciss_identify_logical(sc, ld) == 0) {
3904 	    ciss_cam_rescan_target(sc, bus, target);
3905 	}
3906     }
3907     free(cll, CISS_MALLOC_CLASS);
3908 }
3909 
3910 /************************************************************************
3911  * Handle a notify event relating to the status of a logical drive.
3912  *
3913  * XXX need to be able to defer some of these to properly handle
3914  *     calling the "ID Physical drive" command, unless the 'extended'
3915  *     drive IDs are always in BIG_MAP format.
3916  */
3917 static void
3918 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3919 {
3920     struct ciss_ldrive	*ld;
3921     int			ostatus, bus, target;
3922 
3923     debug_called(2);
3924 
3925     bus		= cn->device.physical.bus;
3926     target	= cn->data.logical_status.logical_drive;
3927     ld		= &sc->ciss_logical[bus][target];
3928 
3929     switch (cn->subclass) {
3930     case CISS_NOTIFY_LOGICAL_STATUS:
3931 	switch (cn->detail) {
3932 	case 0:
3933 	    ciss_name_device(sc, bus, target);
3934 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3935 			cn->data.logical_status.logical_drive, ld->cl_name,
3936 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3937 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3938 			cn->data.logical_status.spare_state,
3939 			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3940 
3941 	    /*
3942 	     * Update our idea of the drive's status.
3943 	     */
3944 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3945 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3946 	    if (ld->cl_lstatus != NULL)
3947 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3948 
3949 	    /*
3950 	     * Have CAM rescan the drive if its status has changed.
3951 	     */
3952 	    if (ostatus != ld->cl_status) {
3953 		ld->cl_update = 1;
3954 		ciss_notify_rescan_logical(sc);
3955 	    }
3956 
3957 	    break;
3958 
3959 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3960 	    ciss_name_device(sc, bus, target);
3961 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3962 			cn->data.logical_status.logical_drive, ld->cl_name);
3963 	    ciss_accept_media(sc, ld);
3964 
3965 	    ld->cl_update = 1;
3966 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3967 	    ciss_notify_rescan_logical(sc);
3968 	    break;
3969 
3970 	case 2:
3971 	case 3:
3972 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3973 			cn->data.rebuild_aborted.logical_drive,
3974 			ld->cl_name,
3975 			(cn->detail == 2) ? "read" : "write");
3976 	    break;
3977 	}
3978 	break;
3979 
3980     case CISS_NOTIFY_LOGICAL_ERROR:
3981 	if (cn->detail == 0) {
3982 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3983 			cn->data.io_error.logical_drive,
3984 			ld->cl_name,
3985 			cn->data.io_error.failure_bus,
3986 			cn->data.io_error.failure_drive);
3987 	    /* XXX should we take the drive down at this point, or will we be told? */
3988 	}
3989 	break;
3990 
3991     case CISS_NOTIFY_LOGICAL_SURFACE:
3992 	if (cn->detail == 0)
3993 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
3994 			cn->data.consistency_completed.logical_drive,
3995 			ld->cl_name);
3996 	break;
3997     }
3998 }
3999 
4000 /************************************************************************
4001  * Handle a notify event relating to the status of a physical drive.
4002  */
4003 static void
4004 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
4005 {
4006 }
4007 
4008 /************************************************************************
4009  * Handle a notify event relating to the status of a physical drive.
4010  */
4011 static void
4012 ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
4013 {
4014     struct ciss_lun_report *cll = NULL;
4015     int bus, target;
4016 
4017     switch (cn->subclass) {
4018     case CISS_NOTIFY_HOTPLUG_PHYSICAL:
4019     case CISS_NOTIFY_HOTPLUG_NONDISK:
4020 	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
4021 	target =
4022 	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
4023 
4024 	if (cn->detail == 0) {
4025 	    /*
4026 	     * Mark the device offline so that it'll start producing selection
4027 	     * timeouts to the upper layer.
4028 	     */
4029 	    if ((bus >= 0) && (target >= 0))
4030 		sc->ciss_physical[bus][target].cp_online = 0;
4031 	} else {
4032 	    /*
4033 	     * Rescan the physical lun list for new items
4034 	     */
4035 	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
4036 				   CISS_MAX_PHYSICAL);
4037 	    if (cll == NULL) {
4038 		ciss_printf(sc, "Warning, cannot get physical lun list\n");
4039 		break;
4040 	    }
4041 	    ciss_filter_physical(sc, cll);
4042 	}
4043 	break;
4044 
4045     default:
4046 	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
4047 	return;
4048     }
4049 
4050     if (cll != NULL)
4051 	free(cll, CISS_MALLOC_CLASS);
4052 }
4053 
4054 /************************************************************************
4055  * Handle deferred processing of notify events.  Notify events may need
4056  * sleep which is unsafe during an interrupt.
4057  */
4058 static void
4059 ciss_notify_thread(void *arg)
4060 {
4061     struct ciss_softc		*sc;
4062     struct ciss_request		*cr;
4063     struct ciss_notify		*cn;
4064 
4065     sc = (struct ciss_softc *)arg;
4066 #if __FreeBSD_version >= 500000
4067     mtx_lock(&sc->ciss_mtx);
4068 #endif
4069 
4070     for (;;) {
4071 	if (STAILQ_EMPTY(&sc->ciss_notify) != 0 &&
4072 	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
4073 	    msleep(&sc->ciss_notify, &sc->ciss_mtx, PUSER, "idle", 0);
4074 	}
4075 
4076 	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
4077 	    break;
4078 
4079 	cr = ciss_dequeue_notify(sc);
4080 
4081 	if (cr == NULL)
4082 		panic("cr null");
4083 	cn = (struct ciss_notify *)cr->cr_data;
4084 
4085 	switch (cn->class) {
4086 	case CISS_NOTIFY_HOTPLUG:
4087 	    ciss_notify_hotplug(sc, cn);
4088 	    break;
4089 	case CISS_NOTIFY_LOGICAL:
4090 	    ciss_notify_logical(sc, cn);
4091 	    break;
4092 	case CISS_NOTIFY_PHYSICAL:
4093 	    ciss_notify_physical(sc, cn);
4094 	    break;
4095 	}
4096 
4097 	ciss_release_request(cr);
4098 
4099     }
4100     sc->ciss_notify_thread = NULL;
4101     wakeup(&sc->ciss_notify_thread);
4102 
4103 #if __FreeBSD_version >= 500000
4104     mtx_unlock(&sc->ciss_mtx);
4105 #endif
4106     kproc_exit(0);
4107 }
4108 
4109 /************************************************************************
4110  * Start the notification kernel thread.
4111  */
4112 static void
4113 ciss_spawn_notify_thread(struct ciss_softc *sc)
4114 {
4115 
4116 #if __FreeBSD_version > 500005
4117     if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4118 		       &sc->ciss_notify_thread, 0, 0, "ciss_notify%d",
4119 		       device_get_unit(sc->ciss_dev)))
4120 #else
4121     if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4122 		       &sc->ciss_notify_thread, "ciss_notify%d",
4123 		       device_get_unit(sc->ciss_dev)))
4124 #endif
4125 	panic("Could not create notify thread\n");
4126 }
4127 
4128 /************************************************************************
4129  * Kill the notification kernel thread.
4130  */
4131 static void
4132 ciss_kill_notify_thread(struct ciss_softc *sc)
4133 {
4134 
4135     if (sc->ciss_notify_thread == NULL)
4136 	return;
4137 
4138     sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
4139     wakeup(&sc->ciss_notify);
4140     msleep(&sc->ciss_notify_thread, &sc->ciss_mtx, PUSER, "thtrm", 0);
4141 }
4142 
4143 /************************************************************************
4144  * Print a request.
4145  */
4146 static void
4147 ciss_print_request(struct ciss_request *cr)
4148 {
4149     struct ciss_softc	*sc;
4150     struct ciss_command	*cc;
4151     int			i;
4152 
4153     sc = cr->cr_sc;
4154     cc = CISS_FIND_COMMAND(cr);
4155 
4156     ciss_printf(sc, "REQUEST @ %p\n", cr);
4157     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
4158 	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
4159 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
4160     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
4161 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
4162     switch(cc->header.address.mode.mode) {
4163     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
4164     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
4165 	ciss_printf(sc, "  physical bus %d target %d\n",
4166 		    cc->header.address.physical.bus, cc->header.address.physical.target);
4167 	break;
4168     case CISS_HDR_ADDRESS_MODE_LOGICAL:
4169 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
4170 	break;
4171     }
4172     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
4173 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
4174 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
4175 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
4176 		cc->cdb.cdb_length,
4177 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
4178 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
4179 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
4180 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
4181 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
4182 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
4183 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
4184     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
4185 
4186     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
4187 	/* XXX print error info */
4188     } else {
4189 	/* since we don't use chained s/g, don't support it here */
4190 	for (i = 0; i < cc->header.sg_in_list; i++) {
4191 	    if ((i % 4) == 0)
4192 		ciss_printf(sc, "   ");
4193 	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
4194 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
4195 		printf("\n");
4196 	}
4197     }
4198 }
4199 
4200 /************************************************************************
4201  * Print information about the status of a logical drive.
4202  */
4203 static void
4204 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
4205 {
4206     int		bus, target, i;
4207 
4208     if (ld->cl_lstatus == NULL) {
4209 	printf("does not exist\n");
4210 	return;
4211     }
4212 
4213     /* print drive status */
4214     switch(ld->cl_lstatus->status) {
4215     case CISS_LSTATUS_OK:
4216 	printf("online\n");
4217 	break;
4218     case CISS_LSTATUS_INTERIM_RECOVERY:
4219 	printf("in interim recovery mode\n");
4220 	break;
4221     case CISS_LSTATUS_READY_RECOVERY:
4222 	printf("ready to begin recovery\n");
4223 	break;
4224     case CISS_LSTATUS_RECOVERING:
4225 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4226 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4227 	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
4228 	       bus, target, ld->cl_lstatus->blocks_to_recover);
4229 	break;
4230     case CISS_LSTATUS_EXPANDING:
4231 	printf("being expanded, %u blocks remaining\n",
4232 	       ld->cl_lstatus->blocks_to_recover);
4233 	break;
4234     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4235 	printf("queued for expansion\n");
4236 	break;
4237     case CISS_LSTATUS_FAILED:
4238 	printf("queued for expansion\n");
4239 	break;
4240     case CISS_LSTATUS_WRONG_PDRIVE:
4241 	printf("wrong physical drive inserted\n");
4242 	break;
4243     case CISS_LSTATUS_MISSING_PDRIVE:
4244 	printf("missing a needed physical drive\n");
4245 	break;
4246     case CISS_LSTATUS_BECOMING_READY:
4247 	printf("becoming ready\n");
4248 	break;
4249     }
4250 
4251     /* print failed physical drives */
4252     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
4253 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
4254 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
4255 	if (bus == -1)
4256 	    continue;
4257 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
4258 		    ld->cl_lstatus->drive_failure_map[i]);
4259     }
4260 }
4261 
4262 #ifdef CISS_DEBUG
4263 /************************************************************************
4264  * Print information about the controller/driver.
4265  */
4266 static void
4267 ciss_print_adapter(struct ciss_softc *sc)
4268 {
4269     int		i, j;
4270 
4271     ciss_printf(sc, "ADAPTER:\n");
4272     for (i = 0; i < CISSQ_COUNT; i++) {
4273 	ciss_printf(sc, "%s     %d/%d\n",
4274 	    i == 0 ? "free" :
4275 	    i == 1 ? "busy" : "complete",
4276 	    sc->ciss_qstat[i].q_length,
4277 	    sc->ciss_qstat[i].q_max);
4278     }
4279     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
4280     ciss_printf(sc, "flags %b\n", sc->ciss_flags,
4281 	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
4282 
4283     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
4284 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
4285 	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
4286 	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
4287 	}
4288     }
4289 
4290     /* XXX Should physical drives be printed out here? */
4291 
4292     for (i = 1; i < sc->ciss_max_requests; i++)
4293 	ciss_print_request(sc->ciss_request + i);
4294 }
4295 
4296 /* DDB hook */
4297 static void
4298 ciss_print0(void)
4299 {
4300     struct ciss_softc	*sc;
4301 
4302     sc = devclass_get_softc(devclass_find("ciss"), 0);
4303     if (sc == NULL) {
4304 	printf("no ciss controllers\n");
4305     } else {
4306 	ciss_print_adapter(sc);
4307     }
4308 }
4309 #endif
4310 
4311 /************************************************************************
4312  * Return a name for a logical drive status value.
4313  */
4314 static const char *
4315 ciss_name_ldrive_status(int status)
4316 {
4317     switch (status) {
4318     case CISS_LSTATUS_OK:
4319 	return("OK");
4320     case CISS_LSTATUS_FAILED:
4321 	return("failed");
4322     case CISS_LSTATUS_NOT_CONFIGURED:
4323 	return("not configured");
4324     case CISS_LSTATUS_INTERIM_RECOVERY:
4325 	return("interim recovery");
4326     case CISS_LSTATUS_READY_RECOVERY:
4327 	return("ready for recovery");
4328     case CISS_LSTATUS_RECOVERING:
4329 	return("recovering");
4330     case CISS_LSTATUS_WRONG_PDRIVE:
4331 	return("wrong physical drive inserted");
4332     case CISS_LSTATUS_MISSING_PDRIVE:
4333 	return("missing physical drive");
4334     case CISS_LSTATUS_EXPANDING:
4335 	return("expanding");
4336     case CISS_LSTATUS_BECOMING_READY:
4337 	return("becoming ready");
4338     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4339 	return("queued for expansion");
4340     }
4341     return("unknown status");
4342 }
4343 
4344 /************************************************************************
4345  * Return an online/offline/nonexistent value for a logical drive
4346  * status value.
4347  */
4348 static int
4349 ciss_decode_ldrive_status(int status)
4350 {
4351     switch(status) {
4352     case CISS_LSTATUS_NOT_CONFIGURED:
4353 	return(CISS_LD_NONEXISTENT);
4354 
4355     case CISS_LSTATUS_OK:
4356     case CISS_LSTATUS_INTERIM_RECOVERY:
4357     case CISS_LSTATUS_READY_RECOVERY:
4358     case CISS_LSTATUS_RECOVERING:
4359     case CISS_LSTATUS_EXPANDING:
4360     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4361 	return(CISS_LD_ONLINE);
4362 
4363     case CISS_LSTATUS_FAILED:
4364     case CISS_LSTATUS_WRONG_PDRIVE:
4365     case CISS_LSTATUS_MISSING_PDRIVE:
4366     case CISS_LSTATUS_BECOMING_READY:
4367     default:
4368 	return(CISS_LD_OFFLINE);
4369     }
4370 }
4371 
4372 
4373 /************************************************************************
4374  * Return a name for a logical drive's organisation.
4375  */
4376 static const char *
4377 ciss_name_ldrive_org(int org)
4378 {
4379     switch(org) {
4380     case CISS_LDRIVE_RAID0:
4381 	return("RAID 0");
4382     case CISS_LDRIVE_RAID1:
4383 	return("RAID 1");
4384     case CISS_LDRIVE_RAID4:
4385 	return("RAID 4");
4386     case CISS_LDRIVE_RAID5:
4387 	return("RAID 5");
4388     case CISS_LDRIVE_RAID51:
4389 	return("RAID 5+1");
4390     case CISS_LDRIVE_RAIDADG:
4391 	return("RAID ADG");
4392     }
4393     return("unkown");
4394 }
4395 
4396 /************************************************************************
4397  * Return a name for a command status value.
4398  */
4399 static const char *
4400 ciss_name_command_status(int status)
4401 {
4402     switch(status) {
4403     case CISS_CMD_STATUS_SUCCESS:
4404 	return("success");
4405     case CISS_CMD_STATUS_TARGET_STATUS:
4406 	return("target status");
4407     case CISS_CMD_STATUS_DATA_UNDERRUN:
4408 	return("data underrun");
4409     case CISS_CMD_STATUS_DATA_OVERRUN:
4410 	return("data overrun");
4411     case CISS_CMD_STATUS_INVALID_COMMAND:
4412 	return("invalid command");
4413     case CISS_CMD_STATUS_PROTOCOL_ERROR:
4414 	return("protocol error");
4415     case CISS_CMD_STATUS_HARDWARE_ERROR:
4416 	return("hardware error");
4417     case CISS_CMD_STATUS_CONNECTION_LOST:
4418 	return("connection lost");
4419     case CISS_CMD_STATUS_ABORTED:
4420 	return("aborted");
4421     case CISS_CMD_STATUS_ABORT_FAILED:
4422 	return("abort failed");
4423     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
4424 	return("unsolicited abort");
4425     case CISS_CMD_STATUS_TIMEOUT:
4426 	return("timeout");
4427     case CISS_CMD_STATUS_UNABORTABLE:
4428 	return("unabortable");
4429     }
4430     return("unknown status");
4431 }
4432 
4433 /************************************************************************
4434  * Handle an open on the control device.
4435  */
4436 static int
4437 ciss_open(struct cdev *dev, int flags, int fmt, d_thread_t *p)
4438 {
4439     struct ciss_softc	*sc;
4440 
4441     debug_called(1);
4442 
4443     sc = (struct ciss_softc *)dev->si_drv1;
4444 
4445     /* we might want to veto if someone already has us open */
4446 
4447     mtx_lock(&sc->ciss_mtx);
4448     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
4449     mtx_unlock(&sc->ciss_mtx);
4450     return(0);
4451 }
4452 
4453 /************************************************************************
4454  * Handle the last close on the control device.
4455  */
4456 static int
4457 ciss_close(struct cdev *dev, int flags, int fmt, d_thread_t *p)
4458 {
4459     struct ciss_softc	*sc;
4460 
4461     debug_called(1);
4462 
4463     sc = (struct ciss_softc *)dev->si_drv1;
4464 
4465     mtx_lock(&sc->ciss_mtx);
4466     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
4467     mtx_unlock(&sc->ciss_mtx);
4468     return (0);
4469 }
4470 
4471 /********************************************************************************
4472  * Handle adapter-specific control operations.
4473  *
4474  * Note that the API here is compatible with the Linux driver, in order to
4475  * simplify the porting of Compaq's userland tools.
4476  */
4477 static int
4478 ciss_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *p)
4479 {
4480     struct ciss_softc		*sc;
4481     IOCTL_Command_struct	*ioc	= (IOCTL_Command_struct *)addr;
4482 #ifdef __amd64__
4483     IOCTL_Command_struct32	*ioc32	= (IOCTL_Command_struct32 *)addr;
4484     IOCTL_Command_struct	ioc_swab;
4485 #endif
4486     int				error;
4487 
4488     debug_called(1);
4489 
4490     sc = (struct ciss_softc *)dev->si_drv1;
4491     error = 0;
4492     mtx_lock(&sc->ciss_mtx);
4493 
4494     switch(cmd) {
4495     case CCISS_GETQSTATS:
4496     {
4497 	union ciss_statrequest *cr = (union ciss_statrequest *)addr;
4498 
4499 	switch (cr->cs_item) {
4500 	case CISSQ_FREE:
4501 	case CISSQ_NOTIFY:
4502 	    bcopy(&sc->ciss_qstat[cr->cs_item], &cr->cs_qstat,
4503 		sizeof(struct ciss_qstat));
4504 	    break;
4505 	default:
4506 	    error = ENOIOCTL;
4507 	    break;
4508 	}
4509 
4510 	break;
4511     }
4512 
4513     case CCISS_GETPCIINFO:
4514     {
4515 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4516 
4517 	pis->bus = pci_get_bus(sc->ciss_dev);
4518 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4519 	pis->board_id = pci_get_devid(sc->ciss_dev);
4520 
4521 	break;
4522     }
4523 
4524     case CCISS_GETINTINFO:
4525     {
4526 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4527 
4528 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4529 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4530 
4531 	break;
4532     }
4533 
4534     case CCISS_SETINTINFO:
4535     {
4536 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4537 
4538 	if ((cis->delay == 0) && (cis->count == 0)) {
4539 	    error = EINVAL;
4540 	    break;
4541 	}
4542 
4543 	/*
4544 	 * XXX apparently this is only safe if the controller is idle,
4545 	 *     we should suspend it before doing this.
4546 	 */
4547 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4548 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4549 
4550 	if (ciss_update_config(sc))
4551 	    error = EIO;
4552 
4553 	/* XXX resume the controller here */
4554 	break;
4555     }
4556 
4557     case CCISS_GETNODENAME:
4558 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4559 	      sizeof(NodeName_type));
4560 	break;
4561 
4562     case CCISS_SETNODENAME:
4563 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4564 	      sizeof(NodeName_type));
4565 	if (ciss_update_config(sc))
4566 	    error = EIO;
4567 	break;
4568 
4569     case CCISS_GETHEARTBEAT:
4570 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4571 	break;
4572 
4573     case CCISS_GETBUSTYPES:
4574 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4575 	break;
4576 
4577     case CCISS_GETFIRMVER:
4578 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4579 	      sizeof(FirmwareVer_type));
4580 	break;
4581 
4582     case CCISS_GETDRIVERVER:
4583 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4584 	break;
4585 
4586     case CCISS_REVALIDVOLS:
4587 	/*
4588 	 * This is a bit ugly; to do it "right" we really need
4589 	 * to find any disks that have changed, kick CAM off them,
4590 	 * then rescan only these disks.  It'd be nice if they
4591 	 * a) told us which disk(s) they were going to play with,
4592 	 * and b) which ones had arrived. 8(
4593 	 */
4594 	break;
4595 
4596 #ifdef __amd64__
4597     case CCISS_PASSTHRU32:
4598 	ioc_swab.LUN_info	= ioc32->LUN_info;
4599 	ioc_swab.Request	= ioc32->Request;
4600 	ioc_swab.error_info	= ioc32->error_info;
4601 	ioc_swab.buf_size	= ioc32->buf_size;
4602 	ioc_swab.buf		= (u_int8_t *)(uintptr_t)ioc32->buf;
4603 	ioc			= &ioc_swab;
4604 	/* FALLTHROUGH */
4605 #endif
4606 
4607     case CCISS_PASSTHRU:
4608 	error = ciss_user_command(sc, ioc);
4609 	break;
4610 
4611     default:
4612 	debug(0, "unknown ioctl 0x%lx", cmd);
4613 
4614 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4615 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4616 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4617 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4618 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4619 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4620 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4621 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4622 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4623 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4624 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4625 
4626 	error = ENOIOCTL;
4627 	break;
4628     }
4629 
4630     mtx_unlock(&sc->ciss_mtx);
4631     return(error);
4632 }
4633