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