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