xref: /dragonfly/sys/dev/raid/ciss/ciss.c (revision 7bcb6caf)
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%pb%i\n",
1217 		    "\20\1READY\2simple\3performant\4MEMQ\n",
1218 		    sc->ciss_cfg->supported_methods);
1219 	ciss_printf(sc, "  active I/O method 0x%pb%i\n",
1220 		    "\20\2simple\3performant\4MEMQ\n",
1221 		    sc->ciss_cfg->active_method);
1222 	ciss_printf(sc, "  4G page base 0x%08x\n",
1223 		    sc->ciss_cfg->command_physlimit);
1224 	ciss_printf(sc, "  interrupt coalesce delay %dus\n",
1225 		    sc->ciss_cfg->interrupt_coalesce_delay);
1226 	ciss_printf(sc, "  interrupt coalesce count %d\n",
1227 		    sc->ciss_cfg->interrupt_coalesce_count);
1228 	ciss_printf(sc, "  max outstanding commands %d\n",
1229 		    sc->ciss_cfg->max_outstanding_commands);
1230 	ciss_printf(sc, "  bus types 0x%pb%i\n",
1231 		    "\20\1ultra2\2ultra3\10fibre1\11fibre2\n",
1232 		    sc->ciss_cfg->bus_types);
1233 	ciss_printf(sc, "  server name '%.16s'\n", sc->ciss_cfg->server_name);
1234 	ciss_printf(sc, "  heartbeat 0x%x\n", sc->ciss_cfg->heartbeat);
1235     }
1236 
1237 out:
1238     if (error) {
1239 	if (sc->ciss_id != NULL) {
1240 	    kfree(sc->ciss_id, CISS_MALLOC_CLASS);
1241 	    sc->ciss_id = NULL;
1242 	}
1243     }
1244     if (cr != NULL)
1245 	ciss_release_request(cr);
1246     return(error);
1247 }
1248 
1249 /************************************************************************
1250  * Helper routine for generating a list of logical and physical luns.
1251  */
1252 static struct ciss_lun_report *
1253 ciss_report_luns(struct ciss_softc *sc, int opcode, int nunits)
1254 {
1255     struct ciss_request		*cr;
1256     struct ciss_command		*cc;
1257     struct ciss_report_cdb	*crc;
1258     struct ciss_lun_report	*cll;
1259     int				command_status;
1260     int				report_size;
1261     int				error = 0;
1262 
1263     debug_called(1);
1264 
1265     cr = NULL;
1266     cll = NULL;
1267 
1268     /*
1269      * Get a request, allocate storage for the address list.
1270      */
1271     if ((error = ciss_get_request(sc, &cr)) != 0)
1272 	goto out;
1273     report_size = sizeof(*cll) + nunits * sizeof(union ciss_device_address);
1274     cll = kmalloc(report_size, CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
1275 
1276     /*
1277      * Build the Report Logical/Physical LUNs command.
1278      */
1279     cc = cr->cr_cc;
1280     cr->cr_data = cll;
1281     cr->cr_length = report_size;
1282     cr->cr_flags = CISS_REQ_DATAIN;
1283 
1284     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
1285     cc->header.address.physical.bus = 0;
1286     cc->header.address.physical.target = 0;
1287     cc->cdb.cdb_length = sizeof(*crc);
1288     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1289     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1290     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
1291     cc->cdb.timeout = 30;	/* XXX better suggestions? */
1292 
1293     crc = (struct ciss_report_cdb *)&(cc->cdb.cdb[0]);
1294     bzero(crc, sizeof(*crc));
1295     crc->opcode = opcode;
1296     crc->length = htonl(report_size);			/* big-endian field */
1297     cll->list_size = htonl(report_size - sizeof(*cll));	/* big-endian field */
1298 
1299     /*
1300      * Submit the request and wait for it to complete.  (timeout
1301      * here should be much greater than above)
1302      */
1303     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1304 	ciss_printf(sc, "error sending %d LUN command (%d)\n", opcode, error);
1305 	goto out;
1306     }
1307 
1308     /*
1309      * Check response.  Note that data over/underrun is OK.
1310      */
1311     ciss_report_request(cr, &command_status, NULL);
1312     switch(command_status) {
1313     case CISS_CMD_STATUS_SUCCESS:	/* buffer right size */
1314     case CISS_CMD_STATUS_DATA_UNDERRUN:	/* buffer too large, not bad */
1315 	break;
1316     case CISS_CMD_STATUS_DATA_OVERRUN:
1317 	ciss_printf(sc, "WARNING: more units than driver limit (%d)\n",
1318 		    CISS_MAX_LOGICAL);
1319 	break;
1320     default:
1321 	ciss_printf(sc, "error detecting logical drive configuration (%s)\n",
1322 		    ciss_name_command_status(command_status));
1323 	error = EIO;
1324 	goto out;
1325     }
1326     ciss_release_request(cr);
1327     cr = NULL;
1328 
1329 out:
1330     if (cr != NULL)
1331 	ciss_release_request(cr);
1332     if (error && cll != NULL) {
1333 	kfree(cll, CISS_MALLOC_CLASS);
1334 	cll = NULL;
1335     }
1336     return(cll);
1337 }
1338 
1339 /************************************************************************
1340  * Find logical drives on the adapter.
1341  */
1342 static int
1343 ciss_init_logical(struct ciss_softc *sc)
1344 {
1345     struct ciss_lun_report	*cll;
1346     int				error = 0, i, j;
1347     int				ndrives;
1348 
1349     debug_called(1);
1350 
1351     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
1352 			   CISS_MAX_LOGICAL);
1353     if (cll == NULL) {
1354 	error = ENXIO;
1355 	goto out;
1356     }
1357 
1358     /* sanity-check reply */
1359     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1360     if ((ndrives < 0) || (ndrives > CISS_MAX_LOGICAL)) {
1361 	ciss_printf(sc, "adapter claims to report absurd number of logical drives (%d > %d)\n",
1362 		    ndrives, CISS_MAX_LOGICAL);
1363 	error = ENXIO;
1364 	goto out;
1365     }
1366 
1367     /*
1368      * Save logical drive information.
1369      */
1370     if (bootverbose) {
1371 	ciss_printf(sc, "%d logical drive%s\n",
1372 	    ndrives, (ndrives > 1 || ndrives == 0) ? "s" : "");
1373     }
1374 
1375     sc->ciss_logical =
1376 	kmalloc(sc->ciss_max_logical_bus * sizeof(struct ciss_ldrive *),
1377 		CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
1378 
1379     for (i = 0; i <= sc->ciss_max_logical_bus; i++) {
1380 	sc->ciss_logical[i] =
1381 	    kmalloc(CISS_MAX_LOGICAL * sizeof(struct ciss_ldrive),
1382 		    CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
1383 
1384 	for (j = 0; j < CISS_MAX_LOGICAL; j++)
1385 	    sc->ciss_logical[i][j].cl_status = CISS_LD_NONEXISTENT;
1386     }
1387 
1388 
1389     for (i = 0; i < CISS_MAX_LOGICAL; i++) {
1390 	if (i < ndrives) {
1391 	    struct ciss_ldrive	*ld;
1392 	    int			bus, target;
1393 
1394 	    bus		= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
1395 	    target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
1396 	    ld		= &sc->ciss_logical[bus][target];
1397 
1398 	    ld->cl_address	= cll->lun[i];
1399 	    ld->cl_controller	= &sc->ciss_controllers[bus];
1400 	    if (ciss_identify_logical(sc, ld) != 0)
1401 		continue;
1402 	    /*
1403 	     * If the drive has had media exchanged, we should bring it online.
1404 	     */
1405 	    if (ld->cl_lstatus->media_exchanged)
1406 		ciss_accept_media(sc, ld);
1407 
1408 	}
1409     }
1410 
1411  out:
1412     if (cll != NULL)
1413 	kfree(cll, CISS_MALLOC_CLASS);
1414     return(error);
1415 }
1416 
1417 static int
1418 ciss_init_physical(struct ciss_softc *sc)
1419 {
1420     struct ciss_lun_report	*cll;
1421     int				error = 0, i;
1422     int				nphys;
1423     int				bus;
1424 
1425     debug_called(1);
1426 
1427     bus = 0;
1428 
1429     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
1430 			   CISS_MAX_PHYSICAL);
1431     if (cll == NULL) {
1432 	error = ENXIO;
1433 	goto out;
1434     }
1435 
1436     nphys = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1437 
1438     if (bootverbose) {
1439 	ciss_printf(sc, "%d physical device%s\n",
1440 	    nphys, (nphys > 1 || nphys == 0) ? "s" : "");
1441     }
1442 
1443     /*
1444      * Figure out the bus mapping.
1445      * Logical buses include both the local logical bus for local arrays and
1446      * proxy buses for remote arrays.  Physical buses are numbered by the
1447      * controller and represent physical buses that hold physical devices.
1448      * We shift these bus numbers so that everything fits into a single flat
1449      * numbering space for CAM.  Logical buses occupy the first 32 CAM bus
1450      * numbers, and the physical bus numbers are shifted to be above that.
1451      * This results in the various driver arrays being indexed as follows:
1452      *
1453      * ciss_controllers[] - indexed by logical bus
1454      * ciss_cam_sim[]     - indexed by both logical and physical, with physical
1455      *                      being shifted by 32.
1456      * ciss_logical[][]   - indexed by logical bus
1457      * ciss_physical[][]  - indexed by physical bus
1458      *
1459      * XXX This is getting more and more hackish.  CISS really doesn't play
1460      *     well with a standard SCSI model; devices are addressed via magic
1461      *     cookies, not via b/t/l addresses.  Since there is no way to store
1462      *     the cookie in the CAM device object, we have to keep these lookup
1463      *     tables handy so that the devices can be found quickly at the cost
1464      *     of wasting memory and having a convoluted lookup scheme.  This
1465      *     driver should probably be converted to block interface.
1466      */
1467     /*
1468      * If the L2 and L3 SCSI addresses are 0, this signifies a proxy
1469      * controller. A proxy controller is another physical controller
1470      * behind the primary PCI controller. We need to know about this
1471      * so that BMIC commands can be properly targeted.  There can be
1472      * proxy controllers attached to a single PCI controller, so
1473      * find the highest numbered one so the array can be properly
1474      * sized.
1475      */
1476     sc->ciss_max_logical_bus = 1;
1477     for (i = 0; i < nphys; i++) {
1478 	if (cll->lun[i].physical.extra_address == 0) {
1479 	    bus = cll->lun[i].physical.bus;
1480 	    sc->ciss_max_logical_bus = max(sc->ciss_max_logical_bus, bus) + 1;
1481 	} else {
1482 	    bus = CISS_EXTRA_BUS2(cll->lun[i].physical.extra_address);
1483 	    sc->ciss_max_physical_bus = max(sc->ciss_max_physical_bus, bus);
1484 	}
1485     }
1486 
1487     sc->ciss_controllers =
1488 	kmalloc(sc->ciss_max_logical_bus * sizeof (union ciss_device_address),
1489 		CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
1490 
1491     /* setup a map of controller addresses */
1492     for (i = 0; i < nphys; i++) {
1493 	if (cll->lun[i].physical.extra_address == 0) {
1494 	    sc->ciss_controllers[cll->lun[i].physical.bus] = cll->lun[i];
1495 	}
1496     }
1497 
1498     sc->ciss_physical =
1499 	kmalloc(sc->ciss_max_physical_bus * sizeof(struct ciss_pdrive *),
1500 		CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
1501 
1502     for (i = 0; i < sc->ciss_max_physical_bus; i++) {
1503 	sc->ciss_physical[i] =
1504 	    kmalloc(sizeof(struct ciss_pdrive) * CISS_MAX_PHYSTGT,
1505 		    CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
1506     }
1507 
1508     ciss_filter_physical(sc, cll);
1509 
1510 out:
1511     if (cll != NULL)
1512 	kfree(cll, CISS_MALLOC_CLASS);
1513 
1514     return(error);
1515 }
1516 
1517 static int
1518 ciss_filter_physical(struct ciss_softc *sc, struct ciss_lun_report *cll)
1519 {
1520     u_int32_t ea;
1521     int i, nphys;
1522     int	bus, target;
1523 
1524     nphys = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
1525     for (i = 0; i < nphys; i++) {
1526 	if (cll->lun[i].physical.extra_address == 0)
1527 	    continue;
1528 
1529 	/*
1530 	 * Filter out devices that we don't want.  Level 3 LUNs could
1531 	 * probably be supported, but the docs don't give enough of a
1532 	 * hint to know how.
1533 	 *
1534 	 * The mode field of the physical address is likely set to have
1535 	 * hard disks masked out.  Honor it unless the user has overridden
1536 	 * us with the tunable.  We also munge the inquiry data for these
1537 	 * disks so that they only show up as passthrough devices.  Keeping
1538 	 * them visible in this fashion is useful for doing things like
1539 	 * flashing firmware.
1540 	 */
1541 	ea = cll->lun[i].physical.extra_address;
1542 	if ((CISS_EXTRA_BUS3(ea) != 0) || (CISS_EXTRA_TARGET3(ea) != 0) ||
1543 	    (CISS_EXTRA_MODE2(ea) == 0x3))
1544 	    continue;
1545 	if ((ciss_expose_hidden_physical == 0) &&
1546 	   (cll->lun[i].physical.mode == CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL))
1547 	    continue;
1548 
1549 	/*
1550 	 * Note: CISS firmware numbers physical busses starting at '1', not
1551 	 *       '0'.  This numbering is internal to the firmware and is only
1552 	 *       used as a hint here.
1553 	 */
1554 	bus = CISS_EXTRA_BUS2(ea) - 1;
1555 	target = CISS_EXTRA_TARGET2(ea);
1556 	sc->ciss_physical[bus][target].cp_address = cll->lun[i];
1557 	sc->ciss_physical[bus][target].cp_online = 1;
1558     }
1559 
1560     return (0);
1561 }
1562 
1563 static int
1564 ciss_inquiry_logical(struct ciss_softc *sc, struct ciss_ldrive *ld)
1565 {
1566     struct ciss_request			*cr;
1567     struct ciss_command			*cc;
1568     struct scsi_inquiry			*inq;
1569     int					error;
1570     int					command_status;
1571 
1572     cr = NULL;
1573 
1574     bzero(&ld->cl_geometry, sizeof(ld->cl_geometry));
1575 
1576     if ((error = ciss_get_request(sc, &cr)) != 0)
1577 	goto out;
1578 
1579     cc = cr->cr_cc;
1580     cr->cr_data = &ld->cl_geometry;
1581     cr->cr_length = sizeof(ld->cl_geometry);
1582     cr->cr_flags = CISS_REQ_DATAIN;
1583 
1584     cc->header.address = ld->cl_address;
1585     cc->cdb.cdb_length = 6;
1586     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1587     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1588     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
1589     cc->cdb.timeout = 30;
1590 
1591     inq = (struct scsi_inquiry *)&(cc->cdb.cdb[0]);
1592     inq->opcode = INQUIRY;
1593     inq->byte2 = SI_EVPD;
1594     inq->page_code = CISS_VPD_LOGICAL_DRIVE_GEOMETRY;
1595     inq->length = sizeof(ld->cl_geometry);
1596 
1597     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1598 	ciss_printf(sc, "error getting geometry (%d)\n", error);
1599 	goto out;
1600     }
1601 
1602     ciss_report_request(cr, &command_status, NULL);
1603     switch(command_status) {
1604     case CISS_CMD_STATUS_SUCCESS:
1605     case CISS_CMD_STATUS_DATA_UNDERRUN:
1606 	break;
1607     case CISS_CMD_STATUS_DATA_OVERRUN:
1608 	ciss_printf(sc, "WARNING: Data overrun\n");
1609 	break;
1610     default:
1611 	ciss_printf(sc, "Error detecting logical drive geometry (%s)\n",
1612 		    ciss_name_command_status(command_status));
1613 	break;
1614     }
1615 
1616 out:
1617     if (cr != NULL)
1618 	ciss_release_request(cr);
1619     return(error);
1620 }
1621 /************************************************************************
1622  * Identify a logical drive, initialise state related to it.
1623  */
1624 static int
1625 ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld)
1626 {
1627     struct ciss_request		*cr;
1628     struct ciss_command		*cc;
1629     struct ciss_bmic_cdb	*cbc;
1630     int				error, command_status;
1631 
1632     debug_called(1);
1633 
1634     cr = NULL;
1635 
1636     /*
1637      * Build a BMIC request to fetch the drive ID.
1638      */
1639     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LDRIVE,
1640 				       (void **)&ld->cl_ldrive,
1641 				       sizeof(*ld->cl_ldrive))) != 0)
1642 	goto out;
1643     cc = cr->cr_cc;
1644     cc->header.address = *ld->cl_controller;	/* target controller */
1645     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1646     cbc->log_drive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1647 
1648     /*
1649      * Submit the request and wait for it to complete.
1650      */
1651     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1652 	ciss_printf(sc, "error sending BMIC LDRIVE command (%d)\n", error);
1653 	goto out;
1654     }
1655 
1656     /*
1657      * Check response.
1658      */
1659     ciss_report_request(cr, &command_status, NULL);
1660     switch(command_status) {
1661     case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1662 	break;
1663     case CISS_CMD_STATUS_DATA_UNDERRUN:
1664     case CISS_CMD_STATUS_DATA_OVERRUN:
1665 	ciss_printf(sc, "data over/underrun reading logical drive ID\n");
1666     default:
1667 	ciss_printf(sc, "error reading logical drive ID (%s)\n",
1668 		    ciss_name_command_status(command_status));
1669 	error = EIO;
1670 	goto out;
1671     }
1672     ciss_release_request(cr);
1673     cr = NULL;
1674 
1675     /*
1676      * Build a CISS BMIC command to get the logical drive status.
1677      */
1678     if ((error = ciss_get_ldrive_status(sc, ld)) != 0)
1679 	goto out;
1680 
1681     /*
1682      * Get the logical drive geometry.
1683      */
1684     if ((error = ciss_inquiry_logical(sc, ld)) != 0)
1685 	goto out;
1686 
1687     /*
1688      * Print the drive's basic characteristics.
1689      */
1690     if (bootverbose) {
1691 	ciss_printf(sc, "logical drive (b%dt%d): %s, %dMB ",
1692 		    CISS_LUN_TO_BUS(ld->cl_address.logical.lun),
1693 		    CISS_LUN_TO_TARGET(ld->cl_address.logical.lun),
1694 		    ciss_name_ldrive_org(ld->cl_ldrive->fault_tolerance),
1695 		    ((ld->cl_ldrive->blocks_available / (1024 * 1024)) *
1696 		     ld->cl_ldrive->block_size));
1697 
1698 	ciss_print_ldrive(sc, ld);
1699     }
1700 out:
1701     if (error != 0) {
1702 	/* make the drive not-exist */
1703 	ld->cl_status = CISS_LD_NONEXISTENT;
1704 	if (ld->cl_ldrive != NULL) {
1705 	    kfree(ld->cl_ldrive, CISS_MALLOC_CLASS);
1706 	    ld->cl_ldrive = NULL;
1707 	}
1708 	if (ld->cl_lstatus != NULL) {
1709 	    kfree(ld->cl_lstatus, CISS_MALLOC_CLASS);
1710 	    ld->cl_lstatus = NULL;
1711 	}
1712     }
1713     if (cr != NULL)
1714 	ciss_release_request(cr);
1715 
1716     return(error);
1717 }
1718 
1719 /************************************************************************
1720  * Get status for a logical drive.
1721  *
1722  * XXX should we also do this in response to Test Unit Ready?
1723  */
1724 static int
1725 ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld)
1726 {
1727     struct ciss_request		*cr;
1728     struct ciss_command		*cc;
1729     struct ciss_bmic_cdb	*cbc;
1730     int				error, command_status;
1731 
1732     /*
1733      * Build a CISS BMIC command to get the logical drive status.
1734      */
1735     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LSTATUS,
1736 				       (void **)&ld->cl_lstatus,
1737 				       sizeof(*ld->cl_lstatus))) != 0)
1738 	goto out;
1739     cc = cr->cr_cc;
1740     cc->header.address = *ld->cl_controller;	/* target controller */
1741     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1742     cbc->log_drive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1743 
1744     /*
1745      * Submit the request and wait for it to complete.
1746      */
1747     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1748 	ciss_printf(sc, "error sending BMIC LSTATUS command (%d)\n", error);
1749 	goto out;
1750     }
1751 
1752     /*
1753      * Check response.
1754      */
1755     ciss_report_request(cr, &command_status, NULL);
1756     switch(command_status) {
1757     case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1758 	break;
1759     case CISS_CMD_STATUS_DATA_UNDERRUN:
1760     case CISS_CMD_STATUS_DATA_OVERRUN:
1761 	ciss_printf(sc, "data over/underrun reading logical drive status\n");
1762     default:
1763 	ciss_printf(sc, "error reading logical drive status (%s)\n",
1764 		    ciss_name_command_status(command_status));
1765 	error = EIO;
1766 	goto out;
1767     }
1768 
1769     /*
1770      * Set the drive's summary status based on the returned status.
1771      *
1772      * XXX testing shows that a failed JBOD drive comes back at next
1773      * boot in "queued for expansion" mode.  WTF?
1774      */
1775     ld->cl_status = ciss_decode_ldrive_status(ld->cl_lstatus->status);
1776 
1777 out:
1778     if (cr != NULL)
1779 	ciss_release_request(cr);
1780     return(error);
1781 }
1782 
1783 /************************************************************************
1784  * Notify the adapter of a config update.
1785  */
1786 static int
1787 ciss_update_config(struct ciss_softc *sc)
1788 {
1789     int		i;
1790 
1791     debug_called(1);
1792 
1793     CISS_TL_SIMPLE_WRITE(sc, CISS_TL_SIMPLE_IDBR, CISS_TL_SIMPLE_IDBR_CFG_TABLE);
1794     for (i = 0; i < 1000; i++) {
1795 	if (!(CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR) &
1796 	      CISS_TL_SIMPLE_IDBR_CFG_TABLE)) {
1797 	    return(0);
1798 	}
1799 	DELAY(1000);
1800     }
1801     return(1);
1802 }
1803 
1804 /************************************************************************
1805  * Accept new media into a logical drive.
1806  *
1807  * XXX The drive has previously been offline; it would be good if we
1808  *     could make sure it's not open right now.
1809  */
1810 static int
1811 ciss_accept_media(struct ciss_softc *sc, struct ciss_ldrive *ld)
1812 {
1813     struct ciss_request		*cr;
1814     struct ciss_command		*cc;
1815     struct ciss_bmic_cdb	*cbc;
1816     int				command_status;
1817     int				error = 0, ldrive;
1818 
1819     ldrive = CISS_LUN_TO_TARGET(ld->cl_address.logical.lun);
1820 
1821     debug(0, "bringing logical drive %d back online", ldrive);
1822 
1823     /*
1824      * Build a CISS BMIC command to bring the drive back online.
1825      */
1826     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ACCEPT_MEDIA,
1827 				       NULL, 0)) != 0)
1828 	goto out;
1829     cc = cr->cr_cc;
1830     cc->header.address = *ld->cl_controller;	/* target controller */
1831     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1832     cbc->log_drive = ldrive;
1833 
1834     /*
1835      * Submit the request and wait for it to complete.
1836      */
1837     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1838 	ciss_printf(sc, "error sending BMIC ACCEPT MEDIA command (%d)\n", error);
1839 	goto out;
1840     }
1841 
1842     /*
1843      * Check response.
1844      */
1845     ciss_report_request(cr, &command_status, NULL);
1846     switch(command_status) {
1847     case CISS_CMD_STATUS_SUCCESS:		/* all OK */
1848 	/* we should get a logical drive status changed event here */
1849 	break;
1850     default:
1851 	ciss_printf(cr->cr_sc, "error accepting media into failed logical drive (%s)\n",
1852 		    ciss_name_command_status(command_status));
1853 	break;
1854     }
1855 
1856 out:
1857     if (cr != NULL)
1858 	ciss_release_request(cr);
1859     return(error);
1860 }
1861 
1862 /************************************************************************
1863  * Release adapter resources.
1864  */
1865 static void
1866 ciss_free(struct ciss_softc *sc)
1867 {
1868     struct ciss_request *cr;
1869     int			i, j;
1870 
1871     debug_called(1);
1872 
1873     /* we're going away */
1874     sc->ciss_flags |= CISS_FLAG_ABORTING;
1875 
1876     /* terminate the periodic heartbeat routine */
1877     callout_stop(&sc->ciss_periodic);
1878 
1879     /* cancel the Event Notify chain */
1880     ciss_notify_abort(sc);
1881 
1882     ciss_kill_notify_thread(sc);
1883 
1884     /* disconnect from CAM */
1885     if (sc->ciss_cam_sim) {
1886 	for (i = 0; i < sc->ciss_max_logical_bus; i++) {
1887 	    if (sc->ciss_cam_sim[i]) {
1888 		xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim[i]));
1889 		cam_sim_free(sc->ciss_cam_sim[i]);
1890 	    }
1891 	}
1892 	for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
1893 	     CISS_PHYSICAL_BASE; i++) {
1894 	    if (sc->ciss_cam_sim[i]) {
1895 		xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim[i]));
1896 		cam_sim_free(sc->ciss_cam_sim[i]);
1897 	    }
1898 	}
1899 	kfree(sc->ciss_cam_sim, CISS_MALLOC_CLASS);
1900     }
1901     if (sc->ciss_cam_devq)
1902 	cam_simq_release(sc->ciss_cam_devq);
1903 
1904     /* remove the control device */
1905     lockmgr(&sc->ciss_lock, LK_RELEASE);
1906     if (sc->ciss_dev_t != NULL)
1907 	destroy_dev(sc->ciss_dev_t);
1908 
1909     /* Final cleanup of the callout. */
1910     callout_stop_sync(&sc->ciss_periodic);
1911     lockuninit(&sc->ciss_lock);
1912 
1913     /* free the controller data */
1914     if (sc->ciss_id != NULL)
1915 	kfree(sc->ciss_id, CISS_MALLOC_CLASS);
1916 
1917     /* release I/O resources */
1918     if (sc->ciss_regs_resource != NULL)
1919 	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1920 			     sc->ciss_regs_rid, sc->ciss_regs_resource);
1921     if (sc->ciss_cfg_resource != NULL)
1922 	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1923 			     sc->ciss_cfg_rid, sc->ciss_cfg_resource);
1924     if (sc->ciss_intr != NULL)
1925 	bus_teardown_intr(sc->ciss_dev, sc->ciss_irq_resource, sc->ciss_intr);
1926     if (sc->ciss_irq_resource != NULL)
1927 	bus_release_resource(sc->ciss_dev, SYS_RES_IRQ,
1928 			     sc->ciss_irq_rid[0], sc->ciss_irq_resource);
1929     if (sc->ciss_irq_type == PCI_INTR_TYPE_MSI)
1930 	pci_release_msi(sc->ciss_dev);
1931 
1932     while ((cr = ciss_dequeue_free(sc)) != NULL)
1933 	bus_dmamap_destroy(sc->ciss_buffer_dmat, cr->cr_datamap);
1934     if (sc->ciss_buffer_dmat)
1935 	bus_dma_tag_destroy(sc->ciss_buffer_dmat);
1936 
1937     /* destroy command memory and DMA tag */
1938     if (sc->ciss_command != NULL) {
1939 	bus_dmamap_unload(sc->ciss_command_dmat, sc->ciss_command_map);
1940 	bus_dmamem_free(sc->ciss_command_dmat, sc->ciss_command, sc->ciss_command_map);
1941     }
1942     if (sc->ciss_command_dmat)
1943 	bus_dma_tag_destroy(sc->ciss_command_dmat);
1944 
1945     if (sc->ciss_reply) {
1946 	bus_dmamap_unload(sc->ciss_reply_dmat, sc->ciss_reply_map);
1947 	bus_dmamem_free(sc->ciss_reply_dmat, sc->ciss_reply, sc->ciss_reply_map);
1948     }
1949     if (sc->ciss_reply_dmat)
1950 	bus_dma_tag_destroy(sc->ciss_reply_dmat);
1951 
1952     /* destroy DMA tags */
1953     if (sc->ciss_parent_dmat)
1954 	bus_dma_tag_destroy(sc->ciss_parent_dmat);
1955     if (sc->ciss_logical) {
1956 	for (i = 0; i <= sc->ciss_max_logical_bus; i++) {
1957 	    for (j = 0; j < CISS_MAX_LOGICAL; j++) {
1958 		if (sc->ciss_logical[i][j].cl_ldrive)
1959 		    kfree(sc->ciss_logical[i][j].cl_ldrive, CISS_MALLOC_CLASS);
1960 		if (sc->ciss_logical[i][j].cl_lstatus)
1961 		    kfree(sc->ciss_logical[i][j].cl_lstatus, CISS_MALLOC_CLASS);
1962 	    }
1963 	    kfree(sc->ciss_logical[i], CISS_MALLOC_CLASS);
1964 	}
1965 	kfree(sc->ciss_logical, CISS_MALLOC_CLASS);
1966     }
1967 
1968     if (sc->ciss_physical) {
1969 	for (i = 0; i < sc->ciss_max_physical_bus; i++)
1970 	    kfree(sc->ciss_physical[i], CISS_MALLOC_CLASS);
1971 	kfree(sc->ciss_physical, CISS_MALLOC_CLASS);
1972     }
1973 
1974     if (sc->ciss_controllers)
1975 	kfree(sc->ciss_controllers, CISS_MALLOC_CLASS);
1976 }
1977 
1978 /************************************************************************
1979  * Give a command to the adapter.
1980  *
1981  * Note that this uses the simple transport layer directly.  If we
1982  * want to add support for other layers, we'll need a switch of some
1983  * sort.
1984  *
1985  * Note that the simple transport layer has no way of refusing a
1986  * command; we only have as many request structures as the adapter
1987  * supports commands, so we don't have to check (this presumes that
1988  * the adapter can handle commands as fast as we throw them at it).
1989  */
1990 static int
1991 ciss_start(struct ciss_request *cr)
1992 {
1993 #ifdef CISS_DEBUG
1994     struct ciss_command	*cc;
1995 #endif
1996     int			error;
1997 
1998 #ifdef CISS_DEBUG
1999     cc = cr->cr_cc;
2000 #endif
2001     debug(2, "post command %d tag %d ", cr->cr_tag, cc->header.host_tag);
2002 
2003     /*
2004      * Map the request's data.
2005      */
2006     if ((error = ciss_map_request(cr)))
2007 	return(error);
2008 
2009 #if 0
2010     ciss_print_request(cr);
2011 #endif
2012 
2013     return(0);
2014 }
2015 
2016 /************************************************************************
2017  * Fetch completed request(s) from the adapter, queue them for
2018  * completion handling.
2019  *
2020  * Note that this uses the simple transport layer directly.  If we
2021  * want to add support for other layers, we'll need a switch of some
2022  * sort.
2023  *
2024  * Note that the simple transport mechanism does not require any
2025  * reentrancy protection; the OPQ read is atomic.  If there is a
2026  * chance of a race with something else that might move the request
2027  * off the busy list, then we will have to lock against that
2028  * (eg. timeouts, etc.)
2029  */
2030 static void
2031 ciss_done(struct ciss_softc *sc, cr_qhead_t *qh)
2032 {
2033     struct ciss_request	*cr;
2034     struct ciss_command	*cc;
2035     u_int32_t		tag, index;
2036 
2037     debug_called(3);
2038 
2039     /*
2040      * Loop quickly taking requests from the adapter and moving them
2041      * to the completed queue.
2042      */
2043     for (;;) {
2044 
2045 	tag = CISS_TL_SIMPLE_FETCH_CMD(sc);
2046 	if (tag == CISS_TL_SIMPLE_OPQ_EMPTY)
2047 	    break;
2048 	index = tag >> 2;
2049 	debug(2, "completed command %d%s", index,
2050 	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2051 	if (index >= sc->ciss_max_requests) {
2052 	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2053 	    continue;
2054 	}
2055 	cr = &(sc->ciss_request[index]);
2056 	cc = cr->cr_cc;
2057 	cc->header.host_tag = tag;	/* not updated by adapter */
2058 	ciss_enqueue_complete(cr, qh);
2059     }
2060 
2061 }
2062 
2063 static void
2064 ciss_perf_done(struct ciss_softc *sc, cr_qhead_t *qh)
2065 {
2066     struct ciss_request	*cr;
2067     struct ciss_command	*cc;
2068     u_int32_t		tag, index;
2069 
2070     debug_called(3);
2071 
2072     /*
2073      * Loop quickly taking requests from the adapter and moving them
2074      * to the completed queue.
2075      */
2076     for (;;) {
2077 	tag = sc->ciss_reply[sc->ciss_rqidx];
2078 	if ((tag & CISS_CYCLE_MASK) != sc->ciss_cycle)
2079 	    break;
2080 	index = tag >> 2;
2081 	debug(2, "completed command %d%s\n", index,
2082 	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
2083 	if (index < sc->ciss_max_requests) {
2084 	    cr = &(sc->ciss_request[index]);
2085 	    cc = cr->cr_cc;
2086 	    cc->header.host_tag = tag;	/* not updated by adapter */
2087 	    ciss_enqueue_complete(cr, qh);
2088 	} else {
2089 	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
2090 	}
2091 	if (++sc->ciss_rqidx == sc->ciss_max_requests) {
2092 	    sc->ciss_rqidx = 0;
2093 	    sc->ciss_cycle ^= 1;
2094 	}
2095     }
2096 
2097 }
2098 
2099 /************************************************************************
2100  * Take an interrupt from the adapter.
2101  */
2102 static void
2103 ciss_intr(void *arg)
2104 {
2105     cr_qhead_t qh;
2106     struct ciss_softc	*sc = (struct ciss_softc *)arg;
2107 
2108     /*
2109      * The only interrupt we recognise indicates that there are
2110      * entries in the outbound post queue.
2111      */
2112     STAILQ_INIT(&qh);
2113     ciss_done(sc, &qh);
2114     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
2115     ciss_complete(sc, &qh);
2116     lockmgr(&sc->ciss_lock, LK_RELEASE);
2117 }
2118 
2119 static void
2120 ciss_perf_intr(void *arg)
2121 {
2122     struct ciss_softc	*sc = (struct ciss_softc *)arg;
2123 
2124     /* Clear the interrupt and flush the bridges.  Docs say that the flush
2125      * needs to be done twice, which doesn't seem right.
2126      */
2127     CISS_TL_PERF_CLEAR_INT(sc);
2128     CISS_TL_PERF_FLUSH_INT(sc);
2129 
2130     ciss_perf_msi_intr(sc);
2131 }
2132 
2133 static void
2134 ciss_perf_msi_intr(void *arg)
2135 {
2136     cr_qhead_t qh;
2137     struct ciss_softc	*sc = (struct ciss_softc *)arg;
2138 
2139     STAILQ_INIT(&qh);
2140     ciss_perf_done(sc, &qh);
2141     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
2142     ciss_complete(sc, &qh);
2143     lockmgr(&sc->ciss_lock, LK_RELEASE);
2144 }
2145 
2146 
2147 /************************************************************************
2148  * Process completed requests.
2149  *
2150  * Requests can be completed in three fashions:
2151  *
2152  * - by invoking a callback function (cr_complete is non-null)
2153  * - by waking up a sleeper (cr_flags has CISS_REQ_SLEEP set)
2154  * - by clearing the CISS_REQ_POLL flag in interrupt/timeout context
2155  */
2156 static void
2157 ciss_complete(struct ciss_softc *sc, cr_qhead_t *qh)
2158 {
2159     struct ciss_request	*cr;
2160 
2161     debug_called(2);
2162 
2163     /*
2164      * Loop taking requests off the completed queue and performing
2165      * completion processing on them.
2166      */
2167     for (;;) {
2168 	if ((cr = ciss_dequeue_complete(sc, qh)) == NULL)
2169 	    break;
2170 	ciss_unmap_request(cr);
2171 
2172 	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
2173 	    ciss_printf(sc, "WARNING: completing non-busy request\n");
2174 	cr->cr_flags &= ~CISS_REQ_BUSY;
2175 
2176 	/*
2177 	 * If the request has a callback, invoke it.
2178 	 */
2179 	if (cr->cr_complete != NULL) {
2180 	    cr->cr_complete(cr);
2181 	    continue;
2182 	}
2183 
2184 	/*
2185 	 * If someone is sleeping on this request, wake them up.
2186 	 */
2187 	if (cr->cr_flags & CISS_REQ_SLEEP) {
2188 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
2189 	    wakeup(cr);
2190 	    continue;
2191 	}
2192 
2193 	/*
2194 	 * If someone is polling this request for completion, signal.
2195 	 */
2196 	if (cr->cr_flags & CISS_REQ_POLL) {
2197 	    cr->cr_flags &= ~CISS_REQ_POLL;
2198 	    continue;
2199 	}
2200 
2201 	/*
2202 	 * Give up and throw the request back on the free queue.  This
2203 	 * should never happen; resources will probably be lost.
2204 	 */
2205 	ciss_printf(sc, "WARNING: completed command with no submitter\n");
2206 	ciss_enqueue_free(cr);
2207     }
2208 }
2209 
2210 /************************************************************************
2211  * Report on the completion status of a request, and pass back SCSI
2212  * and command status values.
2213  */
2214 static int
2215 _ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status, const char *func)
2216 {
2217     struct ciss_command		*cc;
2218     struct ciss_error_info	*ce;
2219 
2220     debug_called(2);
2221 
2222     cc = cr->cr_cc;
2223     ce = (struct ciss_error_info *)&(cc->sg[0]);
2224 
2225     /*
2226      * We don't consider data under/overrun an error for the Report
2227      * Logical/Physical LUNs commands.
2228      */
2229     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) &&
2230 	((ce->command_status == CISS_CMD_STATUS_DATA_OVERRUN) ||
2231 	 (ce->command_status == CISS_CMD_STATUS_DATA_UNDERRUN)) &&
2232 	((cc->cdb.cdb[0] == CISS_OPCODE_REPORT_LOGICAL_LUNS) ||
2233 	 (cc->cdb.cdb[0] == CISS_OPCODE_REPORT_PHYSICAL_LUNS) ||
2234 	 (cc->cdb.cdb[0] == INQUIRY))) {
2235 	cc->header.host_tag &= ~CISS_HDR_HOST_TAG_ERROR;
2236 	debug(2, "ignoring irrelevant under/overrun error");
2237     }
2238 
2239     /*
2240      * Check the command's error bit, if clear, there's no status and
2241      * everything is OK.
2242      */
2243     if (!(cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR)) {
2244 	if (scsi_status != NULL)
2245 	    *scsi_status = SCSI_STATUS_OK;
2246 	if (command_status != NULL)
2247 	    *command_status = CISS_CMD_STATUS_SUCCESS;
2248 	return(0);
2249     } else {
2250 	if (command_status != NULL)
2251 	    *command_status = ce->command_status;
2252 	if (scsi_status != NULL) {
2253 	    if (ce->command_status == CISS_CMD_STATUS_TARGET_STATUS) {
2254 		*scsi_status = ce->scsi_status;
2255 	    } else {
2256 		*scsi_status = -1;
2257 	    }
2258 	}
2259 	if (bootverbose)
2260 	    ciss_printf(cr->cr_sc, "command status 0x%x (%s) scsi status 0x%x\n",
2261 			ce->command_status, ciss_name_command_status(ce->command_status),
2262 			ce->scsi_status);
2263 	if (ce->command_status == CISS_CMD_STATUS_INVALID_COMMAND) {
2264 	    ciss_printf(cr->cr_sc, "invalid command, offense size %d at %d, value 0x%x, function %s\n",
2265 			ce->additional_error_info.invalid_command.offense_size,
2266 			ce->additional_error_info.invalid_command.offense_offset,
2267 			ce->additional_error_info.invalid_command.offense_value,
2268 			func);
2269 	}
2270     }
2271 #if 0
2272     ciss_print_request(cr);
2273 #endif
2274     return(1);
2275 }
2276 
2277 /************************************************************************
2278  * Issue a request and don't return until it's completed.
2279  *
2280  * Depending on adapter status, we may poll or sleep waiting for
2281  * completion.
2282  */
2283 static int
2284 ciss_synch_request(struct ciss_request *cr, int timeout)
2285 {
2286     if (cr->cr_sc->ciss_flags & CISS_FLAG_RUNNING) {
2287 	return(ciss_wait_request(cr, timeout));
2288     } else {
2289 	return(ciss_poll_request(cr, timeout));
2290     }
2291 }
2292 
2293 /************************************************************************
2294  * Issue a request and poll for completion.
2295  *
2296  * Timeout in milliseconds.
2297  */
2298 static int
2299 ciss_poll_request(struct ciss_request *cr, int timeout)
2300 {
2301     cr_qhead_t qh;
2302     struct ciss_softc *sc;
2303     int		error;
2304 
2305     debug_called(2);
2306 
2307     STAILQ_INIT(&qh);
2308     sc = cr->cr_sc;
2309     cr->cr_flags |= CISS_REQ_POLL;
2310     if ((error = ciss_start(cr)) != 0)
2311 	return(error);
2312 
2313     do {
2314 	if (sc->ciss_perf)
2315 	    ciss_perf_done(sc, &qh);
2316 	else
2317 	    ciss_done(sc, &qh);
2318 	ciss_complete(sc, &qh);
2319 	if (!(cr->cr_flags & CISS_REQ_POLL))
2320 	    return(0);
2321 	DELAY(1000);
2322     } while (timeout-- >= 0);
2323     return(EWOULDBLOCK);
2324 }
2325 
2326 /************************************************************************
2327  * Issue a request and sleep waiting for completion.
2328  *
2329  * Timeout in milliseconds.  Note that a spurious wakeup will reset
2330  * the timeout.
2331  */
2332 static int
2333 ciss_wait_request(struct ciss_request *cr, int timeout)
2334 {
2335     int		error;
2336 
2337     debug_called(2);
2338 
2339     cr->cr_flags |= CISS_REQ_SLEEP;
2340     if ((error = ciss_start(cr)) != 0)
2341 	return(error);
2342 
2343     while ((cr->cr_flags & CISS_REQ_SLEEP) && (error != EWOULDBLOCK)) {
2344 	error = lksleep(cr, &cr->cr_sc->ciss_lock, 0, "cissREQ", (timeout * hz) / 1000);
2345     }
2346     return(error);
2347 }
2348 
2349 #if 0
2350 /************************************************************************
2351  * Abort a request.  Note that a potential exists here to race the
2352  * request being completed; the caller must deal with this.
2353  */
2354 static int
2355 ciss_abort_request(struct ciss_request *ar)
2356 {
2357     struct ciss_request		*cr;
2358     struct ciss_command		*cc;
2359     struct ciss_message_cdb	*cmc;
2360     int				error;
2361 
2362     debug_called(1);
2363 
2364     /* get a request */
2365     if ((error = ciss_get_request(ar->cr_sc, &cr)) != 0)
2366 	return(error);
2367 
2368     /* build the abort command */
2369     cc = cr->cr_cc;
2370     cc->header.address.mode.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;	/* addressing? */
2371     cc->header.address.physical.target = 0;
2372     cc->header.address.physical.bus = 0;
2373     cc->cdb.cdb_length = sizeof(*cmc);
2374     cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
2375     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2376     cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2377     cc->cdb.timeout = 30;
2378 
2379     cmc = (struct ciss_message_cdb *)&(cc->cdb.cdb[0]);
2380     cmc->opcode = CISS_OPCODE_MESSAGE_ABORT;
2381     cmc->type = CISS_MESSAGE_ABORT_TASK;
2382     cmc->abort_tag = ar->cr_tag;	/* endianness?? */
2383 
2384     /*
2385      * Send the request and wait for a response.  If we believe we
2386      * aborted the request OK, clear the flag that indicates it's
2387      * running.
2388      */
2389     error = ciss_synch_request(cr, 35 * 1000);
2390     if (!error)
2391 	error = ciss_report_request(cr, NULL, NULL);
2392     ciss_release_request(cr);
2393 
2394     return(error);
2395 }
2396 #endif
2397 
2398 
2399 /************************************************************************
2400  * Fetch and initialise a request
2401  */
2402 static int
2403 ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp)
2404 {
2405     struct ciss_request *cr;
2406 
2407     debug_called(2);
2408 
2409     /*
2410      * Get a request and clean it up.
2411      */
2412     if ((cr = ciss_dequeue_free(sc)) == NULL)
2413 	return(ENOMEM);
2414 
2415     cr->cr_data = NULL;
2416     cr->cr_flags = 0;
2417     cr->cr_complete = NULL;
2418     cr->cr_private = NULL;
2419     cr->cr_sg_tag = CISS_SG_MAX;	/* Backstop to prevent accidents */
2420 
2421     ciss_preen_command(cr);
2422     *crp = cr;
2423     return(0);
2424 }
2425 
2426 static void
2427 ciss_preen_command(struct ciss_request *cr)
2428 {
2429     struct ciss_command	*cc;
2430     u_int32_t		cmdphys;
2431 
2432     /*
2433      * Clean up the command structure.
2434      *
2435      * Note that we set up the error_info structure here, since the
2436      * length can be overwritten by any command.
2437      */
2438     cc = cr->cr_cc;
2439     cc->header.sg_in_list = 0;		/* kinda inefficient this way */
2440     cc->header.sg_total = 0;
2441     cc->header.host_tag = cr->cr_tag << 2;
2442     cc->header.host_tag_zeroes = 0;
2443     cmdphys = cr->cr_ccphys;
2444     cc->error_info.error_info_address = cmdphys + sizeof(struct ciss_command);
2445     cc->error_info.error_info_length = CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command);
2446 }
2447 
2448 /************************************************************************
2449  * Release a request to the free list.
2450  */
2451 static void
2452 ciss_release_request(struct ciss_request *cr)
2453 {
2454     debug_called(2);
2455 
2456     /* release the request to the free queue */
2457     ciss_requeue_free(cr);
2458 }
2459 
2460 /************************************************************************
2461  * Allocate a request that will be used to send a BMIC command.  Do some
2462  * of the common setup here to avoid duplicating it everywhere else.
2463  */
2464 static int
2465 ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
2466 		      int opcode, void **bufp, size_t bufsize)
2467 {
2468     struct ciss_request		*cr;
2469     struct ciss_command		*cc;
2470     struct ciss_bmic_cdb	*cbc;
2471     void			*buf;
2472     int				error;
2473     int				dataout;
2474 
2475     debug_called(2);
2476 
2477     *crp = NULL;	/* avoid gcc warnings */
2478     cr = NULL;
2479     buf = NULL;
2480 
2481     /*
2482      * Get a request.
2483      */
2484     if ((error = ciss_get_request(sc, &cr)) != 0)
2485 	goto out;
2486 
2487     /*
2488      * Allocate data storage if requested, determine the data direction.
2489      */
2490     dataout = 0;
2491     if ((bufsize > 0) && (bufp != NULL)) {
2492 	if (*bufp == NULL) {
2493 	    buf = kmalloc(bufsize, CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
2494 	} else {
2495 	    buf = *bufp;
2496 	    dataout = 1;	/* we are given a buffer, so we are writing */
2497 	}
2498     }
2499 
2500     /*
2501      * Build a CISS BMIC command to get the logical drive ID.
2502      */
2503     cr->cr_data = buf;
2504     cr->cr_length = bufsize;
2505     if (!dataout)
2506 	cr->cr_flags = CISS_REQ_DATAIN;
2507 
2508     cc = cr->cr_cc;
2509     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2510     cc->header.address.physical.bus = 0;
2511     cc->header.address.physical.target = 0;
2512     cc->cdb.cdb_length = sizeof(*cbc);
2513     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2514     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2515     cc->cdb.direction = dataout ? CISS_CDB_DIRECTION_WRITE : CISS_CDB_DIRECTION_READ;
2516     cc->cdb.timeout = 0;
2517 
2518     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
2519     bzero(cbc, sizeof(*cbc));
2520     cbc->opcode = dataout ? CISS_ARRAY_CONTROLLER_WRITE : CISS_ARRAY_CONTROLLER_READ;
2521     cbc->bmic_opcode = opcode;
2522     cbc->size = htons((u_int16_t)bufsize);
2523 
2524 out:
2525     if (error) {
2526 	if (cr != NULL)
2527 	    ciss_release_request(cr);
2528     } else {
2529 	*crp = cr;
2530 	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
2531 	    *bufp = buf;
2532     }
2533     return(error);
2534 }
2535 
2536 /************************************************************************
2537  * Handle a command passed in from userspace.
2538  */
2539 static int
2540 ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
2541 {
2542     struct ciss_request		*cr;
2543     struct ciss_command		*cc;
2544     struct ciss_error_info	*ce;
2545     int				error = 0;
2546 
2547     debug_called(1);
2548 
2549     cr = NULL;
2550 
2551     /*
2552      * Get a request.
2553      */
2554     while (ciss_get_request(sc, &cr) != 0)
2555 	lksleep(sc, &sc->ciss_lock, 0, "cissREQ", hz);
2556     cc = cr->cr_cc;
2557 
2558     /*
2559      * Allocate an in-kernel databuffer if required, copy in user data.
2560      */
2561     lockmgr(&sc->ciss_lock, LK_RELEASE);
2562     cr->cr_length = ioc->buf_size;
2563     if (ioc->buf_size > 0) {
2564 	cr->cr_data = kmalloc(ioc->buf_size, CISS_MALLOC_CLASS, M_WAITOK);
2565 	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
2566 	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2567 	    goto out_unlocked;
2568 	}
2569     }
2570 
2571     /*
2572      * Build the request based on the user command.
2573      */
2574     bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
2575     bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
2576 
2577     /* XXX anything else to populate here? */
2578     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
2579 
2580     /*
2581      * Run the command.
2582      */
2583     if ((error = ciss_synch_request(cr, 60 * 1000))) {
2584 	debug(0, "request failed - %d", error);
2585 	goto out;
2586     }
2587 
2588     /*
2589      * Check to see if the command succeeded.
2590      */
2591     ce = (struct ciss_error_info *)&(cc->sg[0]);
2592     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) == 0)
2593 	bzero(ce, sizeof(*ce));
2594 
2595     /*
2596      * Copy the results back to the user.
2597      */
2598     bcopy(ce, &ioc->error_info, sizeof(*ce));
2599     lockmgr(&sc->ciss_lock, LK_RELEASE);
2600     if ((ioc->buf_size > 0) &&
2601 	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
2602 	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2603 	goto out_unlocked;
2604     }
2605 
2606     /* done OK */
2607     error = 0;
2608 
2609 out_unlocked:
2610     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
2611 
2612 out:
2613     if ((cr != NULL) && (cr->cr_data != NULL))
2614 	kfree(cr->cr_data, CISS_MALLOC_CLASS);
2615     if (cr != NULL)
2616 	ciss_release_request(cr);
2617     return(error);
2618 }
2619 
2620 /************************************************************************
2621  * Map a request into bus-visible space, initialise the scatter/gather
2622  * list.
2623  */
2624 static int
2625 ciss_map_request(struct ciss_request *cr)
2626 {
2627     struct ciss_softc	*sc;
2628     int			error = 0;
2629 
2630     debug_called(2);
2631 
2632     sc = cr->cr_sc;
2633 
2634     /* check that mapping is necessary */
2635     if (cr->cr_flags & CISS_REQ_MAPPED)
2636 	return(0);
2637 
2638     cr->cr_flags |= CISS_REQ_MAPPED;
2639 
2640     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2641 		    BUS_DMASYNC_PREWRITE);
2642 
2643     if (cr->cr_data != NULL) {
2644 	error = bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap,
2645 				cr->cr_data, cr->cr_length,
2646 				ciss_request_map_helper, cr, 0);
2647 	if (error != 0)
2648 	    return (error);
2649     } else {
2650 	/*
2651 	 * Post the command to the adapter.
2652 	 */
2653 	cr->cr_sg_tag = CISS_SG_NONE;
2654 	cr->cr_flags |= CISS_REQ_BUSY;
2655 	if (sc->ciss_perf)
2656 	    CISS_TL_PERF_POST_CMD(sc, cr);
2657 	else
2658 	    CISS_TL_SIMPLE_POST_CMD(sc, cr->cr_ccphys);
2659     }
2660 
2661     return(0);
2662 }
2663 
2664 static void
2665 ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2666 {
2667     struct ciss_command	*cc;
2668     struct ciss_request *cr;
2669     struct ciss_softc	*sc;
2670     int			i;
2671 
2672     debug_called(2);
2673 
2674     cr = (struct ciss_request *)arg;
2675     sc = cr->cr_sc;
2676     cc = cr->cr_cc;
2677 
2678     for (i = 0; i < nseg; i++) {
2679 	cc->sg[i].address = segs[i].ds_addr;
2680 	cc->sg[i].length = segs[i].ds_len;
2681 	cc->sg[i].extension = 0;
2682     }
2683     /* we leave the s/g table entirely within the command */
2684     cc->header.sg_in_list = nseg;
2685     cc->header.sg_total = nseg;
2686 
2687     if (cr->cr_flags & CISS_REQ_DATAIN)
2688 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2689     if (cr->cr_flags & CISS_REQ_DATAOUT)
2690 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2691 
2692     if (nseg == 0)
2693 	cr->cr_sg_tag = CISS_SG_NONE;
2694     else if (nseg == 1)
2695 	cr->cr_sg_tag = CISS_SG_1;
2696     else if (nseg == 2)
2697 	cr->cr_sg_tag = CISS_SG_2;
2698     else if (nseg <= 4)
2699 	cr->cr_sg_tag = CISS_SG_4;
2700     else if (nseg <= 8)
2701 	cr->cr_sg_tag = CISS_SG_8;
2702     else if (nseg <= 16)
2703 	cr->cr_sg_tag = CISS_SG_16;
2704     else if (nseg <= 32)
2705 	cr->cr_sg_tag = CISS_SG_32;
2706     else
2707 	cr->cr_sg_tag = CISS_SG_MAX;
2708 
2709     /*
2710      * Post the command to the adapter.
2711      */
2712     cr->cr_flags |= CISS_REQ_BUSY;
2713     if (sc->ciss_perf)
2714 	CISS_TL_PERF_POST_CMD(sc, cr);
2715     else
2716 	CISS_TL_SIMPLE_POST_CMD(sc, cr->cr_ccphys);
2717 }
2718 
2719 /************************************************************************
2720  * Unmap a request from bus-visible space.
2721  */
2722 static void
2723 ciss_unmap_request(struct ciss_request *cr)
2724 {
2725     struct ciss_softc	*sc;
2726 
2727     debug_called(2);
2728 
2729     sc = cr->cr_sc;
2730 
2731     /* check that unmapping is necessary */
2732     if ((cr->cr_flags & CISS_REQ_MAPPED) == 0)
2733 	return;
2734 
2735     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2736 		    BUS_DMASYNC_POSTWRITE);
2737 
2738     if (cr->cr_data == NULL)
2739 	goto out;
2740 
2741     if (cr->cr_flags & CISS_REQ_DATAIN)
2742 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2743     if (cr->cr_flags & CISS_REQ_DATAOUT)
2744 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2745 
2746     bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2747 out:
2748     cr->cr_flags &= ~CISS_REQ_MAPPED;
2749 }
2750 
2751 /************************************************************************
2752  * Attach the driver to CAM.
2753  *
2754  * We put all the logical drives on a single SCSI bus.
2755  */
2756 static int
2757 ciss_cam_init(struct ciss_softc *sc)
2758 {
2759     int			i, maxbus;
2760 
2761     debug_called(1);
2762 
2763     /*
2764      * Allocate a devq.  We can reuse this for the masked physical
2765      * devices if we decide to export these as well.
2766      */
2767     if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests - 2)) == NULL) {
2768 	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2769 	return(ENOMEM);
2770     }
2771 
2772     /*
2773      * Create a SIM.
2774      *
2775      * This naturally wastes a bit of memory.  The alternative is to allocate
2776      * and register each bus as it is found, and then track them on a linked
2777      * list.  Unfortunately, the driver has a few places where it needs to
2778      * look up the SIM based solely on bus number, and it's unclear whether
2779      * a list traversal would work for these situations.
2780      */
2781     maxbus = max(sc->ciss_max_logical_bus, sc->ciss_max_physical_bus +
2782 		 CISS_PHYSICAL_BASE);
2783     sc->ciss_cam_sim = kmalloc(maxbus * sizeof(struct cam_sim*),
2784 			       CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
2785 
2786     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
2787 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2788 						 "ciss", sc,
2789 						 device_get_unit(sc->ciss_dev),
2790 						 &sc->ciss_lock,
2791 						 2,
2792 						 sc->ciss_max_requests - 2,
2793 						 sc->ciss_cam_devq)) == NULL) {
2794 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2795 	    return(ENOMEM);
2796 	}
2797 
2798 	/*
2799 	 * Register bus with this SIM.
2800 	 */
2801 	lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
2802 	if (i == 0 || sc->ciss_controllers[i].physical.bus != 0) {
2803 	    if (xpt_bus_register(sc->ciss_cam_sim[i], i) != 0) {
2804 		ciss_printf(sc, "can't register SCSI bus %d\n", i);
2805 		lockmgr(&sc->ciss_lock, LK_RELEASE);
2806 		return (ENXIO);
2807 	    }
2808 	}
2809 	lockmgr(&sc->ciss_lock, LK_RELEASE);
2810     }
2811 
2812     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2813 	 CISS_PHYSICAL_BASE; i++) {
2814 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2815 						 "ciss", sc,
2816 						 device_get_unit(sc->ciss_dev),
2817 						 &sc->ciss_lock, 1,
2818 						 sc->ciss_max_requests - 2,
2819 						 sc->ciss_cam_devq)) == NULL) {
2820 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2821 	    return (ENOMEM);
2822 	}
2823 
2824 	lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
2825 	if (xpt_bus_register(sc->ciss_cam_sim[i], i) != 0) {
2826 	    ciss_printf(sc, "can't register SCSI bus %d\n", i);
2827 	    lockmgr(&sc->ciss_lock, LK_RELEASE);
2828 	    return (ENXIO);
2829 	}
2830 	lockmgr(&sc->ciss_lock, LK_RELEASE);
2831     }
2832 
2833     /*
2834      * Initiate a rescan of the bus.
2835      */
2836     ciss_cam_rescan_all(sc);
2837 
2838     return(0);
2839 }
2840 
2841 /************************************************************************
2842  * Initiate a rescan of the 'logical devices' SIM
2843  */
2844 static void
2845 ciss_cam_rescan_target(struct ciss_softc *sc, int bus, int target)
2846 {
2847     union ccb		*ccb;
2848 
2849     debug_called(1);
2850 
2851     ccb = kmalloc(sizeof(union ccb), M_TEMP, M_WAITOK | M_ZERO);
2852 
2853     if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
2854 	    cam_sim_path(sc->ciss_cam_sim[bus]),
2855 	    target, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2856 	ciss_printf(sc, "rescan failed (can't create path)\n");
2857 	kfree(ccb, M_TEMP);
2858 	return;
2859     }
2860 
2861     xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path, 5/*priority (low)*/);
2862     ccb->ccb_h.func_code = XPT_SCAN_BUS;
2863     ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2864     ccb->crcn.flags = CAM_FLAG_NONE;
2865     xpt_action(ccb);
2866 
2867     /* scan is now in progress */
2868 }
2869 
2870 static void
2871 ciss_cam_rescan_all(struct ciss_softc *sc)
2872 {
2873     int i;
2874 
2875     /* Rescan the logical buses */
2876     for (i = 0; i < sc->ciss_max_logical_bus; i++)
2877 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2878     /* Rescan the physical buses */
2879     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2880 	 CISS_PHYSICAL_BASE; i++)
2881 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2882 }
2883 
2884 static void
2885 ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2886 {
2887     xpt_free_path(ccb->ccb_h.path);
2888     kfree(ccb, M_TEMP);
2889 }
2890 
2891 /************************************************************************
2892  * Handle requests coming from CAM
2893  */
2894 static void
2895 ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2896 {
2897     struct ciss_softc	*sc;
2898     struct ccb_scsiio	*csio;
2899     int			bus, target;
2900     int			physical;
2901 
2902     sc = cam_sim_softc(sim);
2903     bus = cam_sim_bus(sim);
2904     csio = (struct ccb_scsiio *)&ccb->csio;
2905     target = csio->ccb_h.target_id;
2906     physical = CISS_IS_PHYSICAL(bus);
2907 
2908     switch (ccb->ccb_h.func_code) {
2909 
2910 	/* perform SCSI I/O */
2911     case XPT_SCSI_IO:
2912 	if (!ciss_cam_action_io(sim, csio))
2913 	    return;
2914 	break;
2915 
2916 	/* perform geometry calculations */
2917     case XPT_CALC_GEOMETRY:
2918     {
2919 	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2920 	struct ciss_ldrive		*ld;
2921 
2922 	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2923 
2924 	ld = NULL;
2925 	if (!physical)
2926 	    ld = &sc->ciss_logical[bus][target];
2927 
2928 	/*
2929 	 * Use the cached geometry settings unless the fault tolerance
2930 	 * is invalid.
2931 	 */
2932 	if (physical || ld->cl_geometry.fault_tolerance == 0xFF) {
2933 	    u_int32_t			secs_per_cylinder;
2934 
2935 	    ccg->heads = 255;
2936 	    ccg->secs_per_track = 32;
2937 	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2938 	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2939 	} else {
2940 	    ccg->heads = ld->cl_geometry.heads;
2941 	    ccg->secs_per_track = ld->cl_geometry.sectors;
2942 	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2943 	}
2944 	ccb->ccb_h.status = CAM_REQ_CMP;
2945         break;
2946     }
2947 
2948 	/* handle path attribute inquiry */
2949     case XPT_PATH_INQ:
2950     {
2951 	struct ccb_pathinq	*cpi = &ccb->cpi;
2952 
2953 	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2954 
2955 	cpi->version_num = 1;
2956 	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2957 	cpi->target_sprt = 0;
2958 	cpi->hba_misc = 0;
2959 	cpi->max_target = CISS_MAX_LOGICAL;
2960 	cpi->max_lun = 0;		/* 'logical drive' channel only */
2961 	cpi->initiator_id = CISS_MAX_LOGICAL;
2962 	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2963         strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2964         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2965         cpi->unit_number = cam_sim_unit(sim);
2966         cpi->bus_id = cam_sim_bus(sim);
2967 	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2968 	cpi->transport = XPORT_SPI;
2969 	cpi->transport_version = 2;
2970 	cpi->protocol = PROTO_SCSI;
2971 	cpi->protocol_version = SCSI_REV_2;
2972 #if 0 /* XXX swildner */
2973 	cpi->maxio = (CISS_MAX_SG_ELEMENTS - 1) * PAGE_SIZE;
2974 #endif
2975 	ccb->ccb_h.status = CAM_REQ_CMP;
2976 	break;
2977     }
2978 
2979     case XPT_GET_TRAN_SETTINGS:
2980     {
2981 	struct ccb_trans_settings	*cts = &ccb->cts;
2982 #ifdef CISS_DEBUG
2983 	int				bus, target;
2984 #endif
2985 	struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
2986 	struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
2987 
2988 #ifdef CISS_DEBUG
2989 	bus = cam_sim_bus(sim);
2990 	target = cts->ccb_h.target_id;
2991 #endif
2992 
2993 	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2994 	/* disconnect always OK */
2995 	cts->protocol = PROTO_SCSI;
2996 	cts->protocol_version = SCSI_REV_2;
2997 	cts->transport = XPORT_SPI;
2998 	cts->transport_version = 2;
2999 
3000 	spi->valid = CTS_SPI_VALID_DISC;
3001 	spi->flags = CTS_SPI_FLAGS_DISC_ENB;
3002 
3003 	scsi->valid = CTS_SCSI_VALID_TQ;
3004 	scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3005 
3006 	cts->ccb_h.status = CAM_REQ_CMP;
3007 	break;
3008     }
3009 
3010     default:		/* we can't do this */
3011 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
3012 	ccb->ccb_h.status = CAM_REQ_INVALID;
3013 	break;
3014     }
3015 
3016     xpt_done(ccb);
3017 }
3018 
3019 /************************************************************************
3020  * Handle a CAM SCSI I/O request.
3021  */
3022 static int
3023 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
3024 {
3025     struct ciss_softc	*sc;
3026     int			bus, target;
3027     struct ciss_request	*cr;
3028     struct ciss_command	*cc;
3029     int			error;
3030 
3031     sc = cam_sim_softc(sim);
3032     bus = cam_sim_bus(sim);
3033     target = csio->ccb_h.target_id;
3034 
3035     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
3036 
3037     /* check that the CDB pointer is not to a physical address */
3038     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
3039 	debug(3, "  CDB pointer is to physical address");
3040 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3041     }
3042 
3043     /* if there is data transfer, it must be to/from a virtual address */
3044     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
3045 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
3046 	    debug(3, "  data pointer is to physical address");
3047 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3048 	}
3049 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
3050 	    debug(3, "  data has premature s/g setup");
3051 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3052 	}
3053     }
3054 
3055     /* abandon aborted ccbs or those that have failed validation */
3056     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3057 	debug(3, "abandoning CCB due to abort/validation failure");
3058 	return(EINVAL);
3059     }
3060 
3061     /* handle emulation of some SCSI commands ourself */
3062     if (ciss_cam_emulate(sc, csio))
3063 	return(0);
3064 
3065     /*
3066      * Get a request to manage this command.  If we can't, return the
3067      * ccb, freeze the queue and flag so that we unfreeze it when a
3068      * request completes.
3069      */
3070     if ((error = ciss_get_request(sc, &cr)) != 0) {
3071 	xpt_freeze_simq(sim, 1);
3072 	sc->ciss_flags |= CISS_FLAG_BUSY;
3073 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
3074 	return(error);
3075     }
3076 
3077     /*
3078      * Build the command.
3079      */
3080     cc = cr->cr_cc;
3081     cr->cr_data = csio->data_ptr;
3082     cr->cr_length = csio->dxfer_len;
3083     cr->cr_complete = ciss_cam_complete;
3084     cr->cr_private = csio;
3085 
3086     /*
3087      * Target the right logical volume.
3088      */
3089     if (CISS_IS_PHYSICAL(bus))
3090 	cc->header.address =
3091 	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
3092     else
3093 	cc->header.address =
3094 	    sc->ciss_logical[bus][target].cl_address;
3095     cc->cdb.cdb_length = csio->cdb_len;
3096     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3097     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
3098     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
3099 	cr->cr_flags = CISS_REQ_DATAOUT;
3100 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3101     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
3102 	cr->cr_flags = CISS_REQ_DATAIN;
3103 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3104     } else {
3105 	cr->cr_flags = 0;
3106 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
3107     }
3108     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
3109     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
3110 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
3111     } else {
3112 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
3113     }
3114 
3115     /*
3116      * Submit the request to the adapter.
3117      *
3118      * Note that this may fail if we're unable to map the request (and
3119      * if we ever learn a transport layer other than simple, may fail
3120      * if the adapter rejects the command).
3121      */
3122     if ((error = ciss_start(cr)) != 0) {
3123 	xpt_freeze_simq(sim, 1);
3124 	csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3125 	if (error == EINPROGRESS) {
3126 	    error = 0;
3127 	} else {
3128 	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
3129 	    ciss_release_request(cr);
3130 	}
3131 	return(error);
3132     }
3133 
3134     return(0);
3135 }
3136 
3137 /************************************************************************
3138  * Emulate SCSI commands the adapter doesn't handle as we might like.
3139  */
3140 static int
3141 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
3142 {
3143     int		bus, target;
3144 
3145     target = csio->ccb_h.target_id;
3146     bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3147 
3148     if (CISS_IS_PHYSICAL(bus)) {
3149 	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
3150 	    csio->ccb_h.status |= CAM_SEL_TIMEOUT;
3151 	    xpt_done((union ccb *)csio);
3152 	    return(1);
3153 	} else
3154 	    return(0);
3155     }
3156 
3157     /*
3158      * Handle requests for volumes that don't exist or are not online.
3159      * A selection timeout is slightly better than an illegal request.
3160      * Other errors might be better.
3161      */
3162     if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
3163 	csio->ccb_h.status |= CAM_SEL_TIMEOUT;
3164 	xpt_done((union ccb *)csio);
3165 	return(1);
3166     }
3167 
3168     /* if we have to fake Synchronise Cache */
3169     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
3170 	/*
3171 	 * If this is a Synchronise Cache command, typically issued when
3172 	 * a device is closed, flush the adapter and complete now.
3173 	 */
3174 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3175 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
3176 	    ciss_flush_adapter(sc);
3177 	    csio->ccb_h.status |= CAM_REQ_CMP;
3178 	    xpt_done((union ccb *)csio);
3179 	    return(1);
3180 	}
3181     }
3182 
3183     return(0);
3184 }
3185 
3186 /************************************************************************
3187  * Check for possibly-completed commands.
3188  */
3189 static void
3190 ciss_cam_poll(struct cam_sim *sim)
3191 {
3192     cr_qhead_t qh;
3193     struct ciss_softc	*sc = cam_sim_softc(sim);
3194 
3195     debug_called(2);
3196 
3197     STAILQ_INIT(&qh);
3198     if (sc->ciss_perf)
3199 	ciss_perf_done(sc, &qh);
3200     else
3201 	ciss_done(sc, &qh);
3202     ciss_complete(sc, &qh);
3203 }
3204 
3205 /************************************************************************
3206  * Handle completion of a command - pass results back through the CCB
3207  */
3208 static void
3209 ciss_cam_complete(struct ciss_request *cr)
3210 {
3211     struct ciss_softc		*sc;
3212     struct ciss_command		*cc;
3213     struct ciss_error_info	*ce;
3214     struct ccb_scsiio		*csio;
3215     int				scsi_status;
3216     int				command_status;
3217 
3218     debug_called(2);
3219 
3220     sc = cr->cr_sc;
3221     cc = cr->cr_cc;
3222     ce = (struct ciss_error_info *)&(cc->sg[0]);
3223     csio = (struct ccb_scsiio *)cr->cr_private;
3224 
3225     /*
3226      * Extract status values from request.
3227      */
3228     ciss_report_request(cr, &command_status, &scsi_status);
3229     csio->scsi_status = scsi_status;
3230 
3231     /*
3232      * Handle specific SCSI status values.
3233      */
3234     switch(scsi_status) {
3235 	/* no status due to adapter error */
3236     case -1:
3237 	debug(0, "adapter error");
3238 	csio->ccb_h.status |= CAM_REQ_CMP_ERR;
3239 	break;
3240 
3241 	/* no status due to command completed OK */
3242     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
3243 	debug(2, "SCSI_STATUS_OK");
3244 	csio->ccb_h.status |= CAM_REQ_CMP;
3245 	break;
3246 
3247 	/* check condition, sense data included */
3248     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
3249 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
3250 	      ce->sense_length, ce->residual_count);
3251 	bzero(&csio->sense_data, SSD_FULL_SIZE);
3252 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
3253 	if (csio->sense_len > ce->sense_length)
3254 		csio->sense_resid = csio->sense_len - ce->sense_length;
3255 	else
3256 		csio->sense_resid = 0;
3257 	csio->resid = ce->residual_count;
3258 	csio->ccb_h.status |= CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
3259 #ifdef CISS_DEBUG
3260 	{
3261 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
3262 	    debug(0, "sense key %x", sns->flags & SSD_KEY);
3263 	}
3264 #endif
3265 	break;
3266 
3267     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
3268 	debug(0, "SCSI_STATUS_BUSY");
3269 	csio->ccb_h.status |= CAM_SCSI_BUSY;
3270 	break;
3271 
3272     default:
3273 	debug(0, "unknown status 0x%x", csio->scsi_status);
3274 	csio->ccb_h.status |= CAM_REQ_CMP_ERR;
3275 	break;
3276     }
3277 
3278     /* handle post-command fixup */
3279     ciss_cam_complete_fixup(sc, csio);
3280 
3281     ciss_release_request(cr);
3282     if (sc->ciss_flags & CISS_FLAG_BUSY) {
3283 	sc->ciss_flags &= ~CISS_FLAG_BUSY;
3284 	if (csio->ccb_h.status & CAM_RELEASE_SIMQ)
3285 	    xpt_release_simq(xpt_path_sim(csio->ccb_h.path), 0);
3286 	else
3287 	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3288     }
3289     xpt_done((union ccb *)csio);
3290 }
3291 
3292 /********************************************************************************
3293  * Fix up the result of some commands here.
3294  */
3295 static void
3296 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
3297 {
3298     struct scsi_inquiry_data	*inq;
3299     struct ciss_ldrive		*cl;
3300     uint8_t			*cdb;
3301     int				bus, target;
3302 
3303     cdb = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3304 	 (uint8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes;
3305     if (cdb[0] == INQUIRY &&
3306 	(cdb[1] & SI_EVPD) == 0 &&
3307 	(csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN &&
3308 	csio->dxfer_len >= SHORT_INQUIRY_LENGTH) {
3309 
3310 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
3311 	target = csio->ccb_h.target_id;
3312 	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3313 
3314 	/*
3315 	 * Don't let hard drives be seen by the DA driver.  They will still be
3316 	 * attached by the PASS driver.
3317 	 */
3318 	if (CISS_IS_PHYSICAL(bus)) {
3319 	    if (SID_TYPE(inq) == T_DIRECT)
3320 		inq->device = (inq->device & 0xe0) | T_NODEVICE;
3321 	    return;
3322 	}
3323 
3324 	cl = &sc->ciss_logical[bus][target];
3325 
3326 	padstr(inq->vendor, "COMPAQ", 8);
3327 	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
3328 	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
3329     }
3330 }
3331 
3332 
3333 /********************************************************************************
3334  * Find a peripheral attached at (target)
3335  */
3336 static struct cam_periph *
3337 ciss_find_periph(struct ciss_softc *sc, int bus, int target)
3338 {
3339     struct cam_periph	*periph;
3340     struct cam_path	*path;
3341     int			status;
3342 
3343     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
3344 			     target, 0);
3345     if (status == CAM_REQ_CMP) {
3346 	periph = cam_periph_find(path, NULL);
3347 	xpt_free_path(path);
3348     } else {
3349 	periph = NULL;
3350     }
3351     return(periph);
3352 }
3353 
3354 /********************************************************************************
3355  * Name the device at (target)
3356  *
3357  * XXX is this strictly correct?
3358  */
3359 static int
3360 ciss_name_device(struct ciss_softc *sc, int bus, int target)
3361 {
3362     struct cam_periph	*periph;
3363 
3364     if (CISS_IS_PHYSICAL(bus))
3365 	return (0);
3366     if ((periph = ciss_find_periph(sc, bus, target)) != NULL) {
3367 	ksprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
3368 		periph->periph_name, periph->unit_number);
3369 	return(0);
3370     }
3371     sc->ciss_logical[bus][target].cl_name[0] = 0;
3372     return(ENOENT);
3373 }
3374 
3375 /************************************************************************
3376  * Periodic status monitoring.
3377  */
3378 static void
3379 ciss_periodic(void *arg)
3380 {
3381     struct ciss_softc	*sc = (struct ciss_softc *)arg;
3382     struct ciss_request	*cr = NULL;
3383     struct ciss_command	*cc = NULL;
3384     int			error = 0;
3385 
3386     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
3387     debug_called(1);
3388 
3389     /*
3390      * Check the adapter heartbeat.
3391      */
3392     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
3393 	sc->ciss_heart_attack++;
3394 	debug(0, "adapter heart attack in progress 0x%x/%d",
3395 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
3396 	if (sc->ciss_heart_attack == 3) {
3397 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
3398 	    ciss_disable_adapter(sc);
3399 	    lockmgr(&sc->ciss_lock, LK_RELEASE);
3400 	    return;
3401 	}
3402     } else {
3403 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
3404 	sc->ciss_heart_attack = 0;
3405 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
3406     }
3407 
3408     /*
3409      * Send the NOP message and wait for a response.
3410      */
3411     if (ciss_nop_message_heartbeat != 0 && (error = ciss_get_request(sc, &cr)) == 0) {
3412 	cc = cr->cr_cc;
3413 	cr->cr_complete = ciss_nop_complete;
3414 	cc->cdb.cdb_length = 1;
3415 	cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
3416 	cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3417 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3418 	cc->cdb.timeout = 0;
3419 	cc->cdb.cdb[0] = CISS_OPCODE_MESSAGE_NOP;
3420 
3421 	if ((error = ciss_start(cr)) != 0) {
3422 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED\n");
3423 	}
3424     }
3425 
3426     /*
3427      * If the notify event request has died for some reason, or has
3428      * not started yet, restart it.
3429      */
3430     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
3431 	debug(0, "(re)starting Event Notify chain");
3432 	ciss_notify_event(sc);
3433     }
3434     lockmgr(&sc->ciss_lock, LK_RELEASE);
3435 
3436     /*
3437      * Reschedule.
3438      */
3439     callout_reset(&sc->ciss_periodic, CISS_HEARTBEAT_RATE * hz, ciss_periodic, sc);
3440 }
3441 
3442 static void
3443 ciss_nop_complete(struct ciss_request *cr)
3444 {
3445     struct ciss_softc		*sc;
3446     static int			first_time = 1;
3447 
3448     sc = cr->cr_sc;
3449     if (ciss_report_request(cr, NULL, NULL) != 0) {
3450 	if (first_time == 1) {
3451 	    first_time = 0;
3452 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED (not logging anymore)\n");
3453 	}
3454     }
3455 
3456     ciss_release_request(cr);
3457 }
3458 
3459 /************************************************************************
3460  * Disable the adapter.
3461  *
3462  * The all requests in completed queue is failed with hardware error.
3463  * This will cause failover in a multipath configuration.
3464  */
3465 static void
3466 ciss_disable_adapter(struct ciss_softc *sc)
3467 {
3468     cr_qhead_t			qh;
3469     struct ciss_request		*cr;
3470     struct ciss_command		*cc;
3471     struct ciss_error_info	*ce;
3472     int				i;
3473 
3474     CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
3475     pci_disable_busmaster(sc->ciss_dev);
3476     sc->ciss_flags &= ~CISS_FLAG_RUNNING;
3477 
3478     for (i = 1; i < sc->ciss_max_requests; i++) {
3479 	cr = &sc->ciss_request[i];
3480 	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
3481 	    continue;
3482 
3483 	cc = cr->cr_cc;
3484 	ce = (struct ciss_error_info *)&(cc->sg[0]);
3485 	ce->command_status = CISS_CMD_STATUS_HARDWARE_ERROR;
3486 	ciss_enqueue_complete(cr, &qh);
3487     }
3488 
3489     for (;;) {
3490 	if ((cr = ciss_dequeue_complete(sc, &qh)) == NULL)
3491 	    break;
3492 
3493 	/*
3494 	 * If the request has a callback, invoke it.
3495 	 */
3496 	if (cr->cr_complete != NULL) {
3497 	    cr->cr_complete(cr);
3498 	    continue;
3499 	}
3500 
3501 	/*
3502 	 * If someone is sleeping on this request, wake them up.
3503 	 */
3504 	if (cr->cr_flags & CISS_REQ_SLEEP) {
3505 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
3506 	    wakeup(cr);
3507 	    continue;
3508 	}
3509     }
3510 }
3511 
3512 /************************************************************************
3513  * Request a notification response from the adapter.
3514  *
3515  * If (cr) is NULL, this is the first request of the adapter, so
3516  * reset the adapter's message pointer and start with the oldest
3517  * message available.
3518  */
3519 static void
3520 ciss_notify_event(struct ciss_softc *sc)
3521 {
3522     struct ciss_request		*cr;
3523     struct ciss_command		*cc;
3524     struct ciss_notify_cdb	*cnc;
3525     int				error;
3526 
3527     debug_called(1);
3528 
3529     cr = sc->ciss_periodic_notify;
3530 
3531     /* get a request if we don't already have one */
3532     if (cr == NULL) {
3533 	if ((error = ciss_get_request(sc, &cr)) != 0) {
3534 	    debug(0, "can't get notify event request");
3535 	    goto out;
3536 	}
3537 	sc->ciss_periodic_notify = cr;
3538 	cr->cr_complete = ciss_notify_complete;
3539 	debug(1, "acquired request %d", cr->cr_tag);
3540     }
3541 
3542     /*
3543      * Get a databuffer if we don't already have one, note that the
3544      * adapter command wants a larger buffer than the actual
3545      * structure.
3546      */
3547     if (cr->cr_data == NULL) {
3548 	cr->cr_data = kmalloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_INTWAIT);
3549 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3550     }
3551 
3552     /* re-setup the request's command (since we never release it) XXX overkill*/
3553     ciss_preen_command(cr);
3554 
3555     /* (re)build the notify event command */
3556     cc = cr->cr_cc;
3557     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3558     cc->header.address.physical.bus = 0;
3559     cc->header.address.physical.target = 0;
3560 
3561     cc->cdb.cdb_length = sizeof(*cnc);
3562     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3563     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3564     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3565     cc->cdb.timeout = 0;	/* no timeout, we hope */
3566 
3567     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3568     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3569     cnc->opcode = CISS_OPCODE_READ;
3570     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3571     cnc->timeout = 0;		/* no timeout, we hope */
3572     cnc->synchronous = 0;
3573     cnc->ordered = 0;
3574     cnc->seek_to_oldest = 0;
3575     if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3576 	cnc->new_only = 1;
3577     else
3578 	cnc->new_only = 0;
3579     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3580 
3581     /* submit the request */
3582     error = ciss_start(cr);
3583 
3584  out:
3585     if (error) {
3586 	if (cr != NULL) {
3587 	    if (cr->cr_data != NULL)
3588 		kfree(cr->cr_data, CISS_MALLOC_CLASS);
3589 	    ciss_release_request(cr);
3590 	}
3591 	sc->ciss_periodic_notify = NULL;
3592 	debug(0, "can't submit notify event request");
3593 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3594     } else {
3595 	debug(1, "notify event submitted");
3596 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3597     }
3598 }
3599 
3600 static void
3601 ciss_notify_complete(struct ciss_request *cr)
3602 {
3603     struct ciss_notify	*cn;
3604     struct ciss_softc	*sc;
3605     int			scsi_status;
3606     int			command_status;
3607     debug_called(1);
3608 
3609     cn = (struct ciss_notify *)cr->cr_data;
3610     sc = cr->cr_sc;
3611 
3612     /*
3613      * Report request results, decode status.
3614      */
3615     ciss_report_request(cr, &command_status, &scsi_status);
3616 
3617     /*
3618      * Abort the chain on a fatal error.
3619      *
3620      * XXX which of these are actually errors?
3621      */
3622     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3623 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3624 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3625 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3626 		    ciss_name_command_status(command_status));
3627 	ciss_release_request(cr);
3628 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3629 	return;
3630     }
3631 
3632     /*
3633      * If the adapter gave us a text message, print it.
3634      */
3635     if (cn->message[0] != 0)
3636 	ciss_printf(sc, "*** %.80s\n", cn->message);
3637 
3638     debug(0, "notify event class %d subclass %d detail %d",
3639 		cn->class, cn->subclass, cn->detail);
3640 
3641     /*
3642      * If the response indicates that the notifier has been aborted,
3643      * release the notifier command.
3644      */
3645     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3646 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3647 	(cn->detail == 1)) {
3648 	debug(0, "notifier exiting");
3649 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3650 	ciss_release_request(cr);
3651 	sc->ciss_periodic_notify = NULL;
3652 	wakeup(&sc->ciss_periodic_notify);
3653     } else {
3654 	/* Handle notify events in a kernel thread */
3655 	ciss_enqueue_notify(cr);
3656 	sc->ciss_periodic_notify = NULL;
3657 	wakeup(&sc->ciss_periodic_notify);
3658 	wakeup(&sc->ciss_notify);
3659     }
3660     /*
3661      * Send a new notify event command, if we're not aborting.
3662      */
3663     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3664 	ciss_notify_event(sc);
3665     }
3666 }
3667 
3668 /************************************************************************
3669  * Abort the Notify Event chain.
3670  *
3671  * Note that we can't just abort the command in progress; we have to
3672  * explicitly issue an Abort Notify Event command in order for the
3673  * adapter to clean up correctly.
3674  *
3675  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3676  * the chain will not restart itself.
3677  */
3678 static int
3679 ciss_notify_abort(struct ciss_softc *sc)
3680 {
3681     struct ciss_request		*cr;
3682     struct ciss_command		*cc;
3683     struct ciss_notify_cdb	*cnc;
3684     int				error, command_status, scsi_status;
3685 
3686     debug_called(1);
3687 
3688     cr = NULL;
3689     error = 0;
3690 
3691     /* verify that there's an outstanding command */
3692     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3693 	goto out;
3694 
3695     /* get a command to issue the abort with */
3696     if ((error = ciss_get_request(sc, &cr)))
3697 	goto out;
3698 
3699     /* get a buffer for the result */
3700     cr->cr_data = kmalloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_INTWAIT);
3701     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3702 
3703     /* build the CDB */
3704     cc = cr->cr_cc;
3705     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3706     cc->header.address.physical.bus = 0;
3707     cc->header.address.physical.target = 0;
3708     cc->cdb.cdb_length = sizeof(*cnc);
3709     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3710     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3711     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3712     cc->cdb.timeout = 0;	/* no timeout, we hope */
3713 
3714     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3715     bzero(cnc, sizeof(*cnc));
3716     cnc->opcode = CISS_OPCODE_WRITE;
3717     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3718     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3719 
3720     ciss_print_request(cr);
3721 
3722     /*
3723      * Submit the request and wait for it to complete.
3724      */
3725     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3726 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3727 	goto out;
3728     }
3729 
3730     /*
3731      * Check response.
3732      */
3733     ciss_report_request(cr, &command_status, &scsi_status);
3734     switch(command_status) {
3735     case CISS_CMD_STATUS_SUCCESS:
3736 	break;
3737     case CISS_CMD_STATUS_INVALID_COMMAND:
3738 	/*
3739 	 * Some older adapters don't support the CISS version of this
3740 	 * command.  Fall back to using the BMIC version.
3741 	 */
3742 	error = ciss_notify_abort_bmic(sc);
3743 	if (error != 0)
3744 	    goto out;
3745 	break;
3746 
3747     case CISS_CMD_STATUS_TARGET_STATUS:
3748 	/*
3749 	 * This can happen if the adapter thinks there wasn't an outstanding
3750 	 * Notify Event command but we did.  We clean up here.
3751 	 */
3752 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3753 	    if (sc->ciss_periodic_notify != NULL)
3754 		ciss_release_request(sc->ciss_periodic_notify);
3755 	    error = 0;
3756 	    goto out;
3757 	}
3758 	/* FALLTHROUGH */
3759 
3760     default:
3761 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3762 		    ciss_name_command_status(command_status));
3763 	error = EIO;
3764 	goto out;
3765     }
3766 
3767     /*
3768      * Sleep waiting for the notifier command to complete.  Note
3769      * that if it doesn't, we may end up in a bad situation, since
3770      * the adapter may deliver it later.  Also note that the adapter
3771      * requires the Notify Event command to be cancelled in order to
3772      * maintain internal bookkeeping.
3773      */
3774     while (sc->ciss_periodic_notify != NULL) {
3775 	error = lksleep(&sc->ciss_periodic_notify, &sc->ciss_lock, 0, "cissNEA", hz * 5);
3776 	if (error == EWOULDBLOCK) {
3777 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3778 	    break;
3779 	}
3780     }
3781 
3782  out:
3783     /* release the cancel request */
3784     if (cr != NULL) {
3785 	if (cr->cr_data != NULL)
3786 	    kfree(cr->cr_data, CISS_MALLOC_CLASS);
3787 	ciss_release_request(cr);
3788     }
3789     if (error == 0)
3790 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3791     return(error);
3792 }
3793 
3794 /************************************************************************
3795  * Abort the Notify Event chain using a BMIC command.
3796  */
3797 static int
3798 ciss_notify_abort_bmic(struct ciss_softc *sc)
3799 {
3800     struct ciss_request			*cr;
3801     int					error, command_status;
3802 
3803     debug_called(1);
3804 
3805     cr = NULL;
3806     error = 0;
3807 
3808     /* verify that there's an outstanding command */
3809     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3810 	goto out;
3811 
3812     /*
3813      * Build a BMIC command to cancel the Notify on Event command.
3814      *
3815      * Note that we are sending a CISS opcode here.  Odd.
3816      */
3817     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3818 				       NULL, 0)) != 0)
3819 	goto out;
3820 
3821     /*
3822      * Submit the request and wait for it to complete.
3823      */
3824     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3825 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3826 	goto out;
3827     }
3828 
3829     /*
3830      * Check response.
3831      */
3832     ciss_report_request(cr, &command_status, NULL);
3833     switch(command_status) {
3834     case CISS_CMD_STATUS_SUCCESS:
3835 	break;
3836     default:
3837 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3838 		    ciss_name_command_status(command_status));
3839 	error = EIO;
3840 	goto out;
3841     }
3842 
3843 out:
3844     if (cr != NULL)
3845 	ciss_release_request(cr);
3846     return(error);
3847 }
3848 
3849 /************************************************************************
3850  * Handle rescanning all the logical volumes when a notify event
3851  * causes the drives to come online or offline.
3852  */
3853 static void
3854 ciss_notify_rescan_logical(struct ciss_softc *sc)
3855 {
3856     struct ciss_lun_report      *cll;
3857     struct ciss_ldrive		*ld;
3858     int                         i, j, ndrives;
3859 
3860     /*
3861      * We must rescan all logical volumes to get the right logical
3862      * drive address.
3863      */
3864     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3865                            CISS_MAX_LOGICAL);
3866     if (cll == NULL)
3867         return;
3868 
3869     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3870 
3871     /*
3872      * Delete any of the drives which were destroyed by the
3873      * firmware.
3874      */
3875     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3876 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3877 	    ld = &sc->ciss_logical[i][j];
3878 
3879 	    if (ld->cl_update == 0)
3880 		continue;
3881 
3882 	    if (ld->cl_status != CISS_LD_ONLINE) {
3883 		ciss_cam_rescan_target(sc, i, j);
3884 		ld->cl_update = 0;
3885 		if (ld->cl_ldrive)
3886 		    kfree(ld->cl_ldrive, CISS_MALLOC_CLASS);
3887 		if (ld->cl_lstatus)
3888 		    kfree(ld->cl_lstatus, CISS_MALLOC_CLASS);
3889 
3890 		ld->cl_ldrive = NULL;
3891 		ld->cl_lstatus = NULL;
3892 	    }
3893 	}
3894     }
3895 
3896     /*
3897      * Scan for new drives.
3898      */
3899     for (i = 0; i < ndrives; i++) {
3900 	int	bus, target;
3901 
3902 	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3903 	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3904 	ld	= &sc->ciss_logical[bus][target];
3905 
3906 	if (ld->cl_update == 0)
3907 		continue;
3908 
3909 	ld->cl_update		= 0;
3910 	ld->cl_address		= cll->lun[i];
3911 	ld->cl_controller	= &sc->ciss_controllers[bus];
3912 	if (ciss_identify_logical(sc, ld) == 0) {
3913 	    ciss_cam_rescan_target(sc, bus, target);
3914 	}
3915     }
3916     kfree(cll, CISS_MALLOC_CLASS);
3917 }
3918 
3919 /************************************************************************
3920  * Handle a notify event relating to the status of a logical drive.
3921  *
3922  * XXX need to be able to defer some of these to properly handle
3923  *     calling the "ID Physical drive" command, unless the 'extended'
3924  *     drive IDs are always in BIG_MAP format.
3925  */
3926 static void
3927 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3928 {
3929     struct ciss_ldrive	*ld;
3930     int			ostatus, bus, target;
3931 
3932     debug_called(2);
3933 
3934     bus		= cn->device.physical.bus;
3935     target	= cn->data.logical_status.logical_drive;
3936     ld		= &sc->ciss_logical[bus][target];
3937 
3938     switch (cn->subclass) {
3939     case CISS_NOTIFY_LOGICAL_STATUS:
3940 	switch (cn->detail) {
3941 	case 0:
3942 	    ciss_name_device(sc, bus, target);
3943 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%pb%i\n",
3944 			cn->data.logical_status.logical_drive, ld->cl_name,
3945 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3946 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3947 			"\20\1configured\2rebuilding\3failed\4in use\5available\n",
3948 			cn->data.logical_status.spare_state);
3949 
3950 	    /*
3951 	     * Update our idea of the drive's status.
3952 	     */
3953 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3954 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3955 	    if (ld->cl_lstatus != NULL)
3956 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3957 
3958 	    /*
3959 	     * Have CAM rescan the drive if its status has changed.
3960 	     */
3961 	    if (ostatus != ld->cl_status) {
3962 		ld->cl_update = 1;
3963 		ciss_notify_rescan_logical(sc);
3964 	    }
3965 
3966 	    break;
3967 
3968 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3969 	    ciss_name_device(sc, bus, target);
3970 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3971 			cn->data.logical_status.logical_drive, ld->cl_name);
3972 	    ciss_accept_media(sc, ld);
3973 
3974 	    ld->cl_update = 1;
3975 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3976 	    ciss_notify_rescan_logical(sc);
3977 	    break;
3978 
3979 	case 2:
3980 	case 3:
3981 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3982 			cn->data.rebuild_aborted.logical_drive,
3983 			ld->cl_name,
3984 			(cn->detail == 2) ? "read" : "write");
3985 	    break;
3986 	}
3987 	break;
3988 
3989     case CISS_NOTIFY_LOGICAL_ERROR:
3990 	if (cn->detail == 0) {
3991 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3992 			cn->data.io_error.logical_drive,
3993 			ld->cl_name,
3994 			cn->data.io_error.failure_bus,
3995 			cn->data.io_error.failure_drive);
3996 	    /* XXX should we take the drive down at this point, or will we be told? */
3997 	}
3998 	break;
3999 
4000     case CISS_NOTIFY_LOGICAL_SURFACE:
4001 	if (cn->detail == 0)
4002 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
4003 			cn->data.consistency_completed.logical_drive,
4004 			ld->cl_name);
4005 	break;
4006     }
4007 }
4008 
4009 /************************************************************************
4010  * Handle a notify event relating to the status of a physical drive.
4011  */
4012 static void
4013 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
4014 {
4015 }
4016 
4017 /************************************************************************
4018  * Handle a notify event relating to the status of a physical drive.
4019  */
4020 static void
4021 ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
4022 {
4023     struct ciss_lun_report *cll = NULL;
4024     int bus, target;
4025 
4026     switch (cn->subclass) {
4027     case CISS_NOTIFY_HOTPLUG_PHYSICAL:
4028     case CISS_NOTIFY_HOTPLUG_NONDISK:
4029 	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
4030 	target =
4031 	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
4032 
4033 	if (cn->detail == 0) {
4034 	    /*
4035 	     * Mark the device offline so that it'll start producing selection
4036 	     * timeouts to the upper layer.
4037 	     */
4038 	    if ((bus >= 0) && (target >= 0))
4039 		sc->ciss_physical[bus][target].cp_online = 0;
4040 	} else {
4041 	    /*
4042 	     * Rescan the physical lun list for new items
4043 	     */
4044 	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
4045 				   CISS_MAX_PHYSICAL);
4046 	    if (cll == NULL) {
4047 		ciss_printf(sc, "Warning, cannot get physical lun list\n");
4048 		break;
4049 	    }
4050 	    ciss_filter_physical(sc, cll);
4051 	}
4052 	break;
4053 
4054     default:
4055 	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
4056 	return;
4057     }
4058 
4059     if (cll != NULL)
4060 	kfree(cll, CISS_MALLOC_CLASS);
4061 }
4062 
4063 /************************************************************************
4064  * Handle deferred processing of notify events.  Notify events may need
4065  * sleep which is unsafe during an interrupt.
4066  */
4067 static void
4068 ciss_notify_thread(void *arg)
4069 {
4070     struct ciss_softc		*sc;
4071     struct ciss_request		*cr;
4072     struct ciss_notify		*cn;
4073 
4074     sc = (struct ciss_softc *)arg;
4075     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
4076 
4077     for (;;) {
4078 	if (STAILQ_EMPTY(&sc->ciss_notify) != 0 &&
4079 	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
4080 	    lksleep(&sc->ciss_notify, &sc->ciss_lock, 0, "idle", 0);
4081 	}
4082 
4083 	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
4084 	    break;
4085 
4086 	cr = ciss_dequeue_notify(sc);
4087 
4088 	if (cr == NULL)
4089 		panic("cr null");
4090 	cn = (struct ciss_notify *)cr->cr_data;
4091 
4092 	switch (cn->class) {
4093 	case CISS_NOTIFY_HOTPLUG:
4094 	    ciss_notify_hotplug(sc, cn);
4095 	    break;
4096 	case CISS_NOTIFY_LOGICAL:
4097 	    ciss_notify_logical(sc, cn);
4098 	    break;
4099 	case CISS_NOTIFY_PHYSICAL:
4100 	    ciss_notify_physical(sc, cn);
4101 	    break;
4102 	}
4103 
4104 	ciss_release_request(cr);
4105 
4106     }
4107     sc->ciss_notify_thread = NULL;
4108     wakeup(&sc->ciss_notify_thread);
4109 
4110     lockmgr(&sc->ciss_lock, LK_RELEASE);
4111     kthread_exit();
4112 }
4113 
4114 /************************************************************************
4115  * Start the notification kernel thread.
4116  */
4117 static void
4118 ciss_spawn_notify_thread(struct ciss_softc *sc)
4119 {
4120 
4121     if (kthread_create((void(*)(void *))ciss_notify_thread, sc,
4122 		       &sc->ciss_notify_thread, "ciss_notify%d",
4123 		       device_get_unit(sc->ciss_dev)))
4124 	panic("Could not create notify thread\n");
4125 }
4126 
4127 /************************************************************************
4128  * Kill the notification kernel thread.
4129  */
4130 static void
4131 ciss_kill_notify_thread(struct ciss_softc *sc)
4132 {
4133 
4134     if (sc->ciss_notify_thread == NULL)
4135 	return;
4136 
4137     sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
4138     wakeup(&sc->ciss_notify);
4139     lksleep(&sc->ciss_notify_thread, &sc->ciss_lock, 0, "thtrm", 0);
4140 }
4141 
4142 /************************************************************************
4143  * Print a request.
4144  */
4145 static void
4146 ciss_print_request(struct ciss_request *cr)
4147 {
4148     struct ciss_softc	*sc;
4149     struct ciss_command	*cc;
4150     int			i;
4151     char		hexstr[HEX_NCPYLEN(CISS_CDB_BUFFER_SIZE)];
4152 
4153     sc = cr->cr_sc;
4154     cc = cr->cr_cc;
4155 
4156     ciss_printf(sc, "REQUEST @ %p\n", cr);
4157     ciss_printf(sc, "  data %p/%d  tag %d  flags %pb%i\n",
4158 	      cr->cr_data, cr->cr_length, cr->cr_tag,
4159 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n", cr->cr_flags);
4160     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
4161 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
4162     switch(cc->header.address.mode.mode) {
4163     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
4164     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
4165 	ciss_printf(sc, "  physical bus %d target %d\n",
4166 		    cc->header.address.physical.bus, cc->header.address.physical.target);
4167 	break;
4168     case CISS_HDR_ADDRESS_MODE_LOGICAL:
4169 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
4170 	break;
4171     }
4172     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
4173 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
4174 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
4175 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
4176 		cc->cdb.cdb_length,
4177 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
4178 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
4179 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
4180 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
4181 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
4182 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
4183 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
4184     ciss_printf(sc, "  %s\n", hexncpy(&cc->cdb.cdb[0], cc->cdb.cdb_length,
4185 	    hexstr, HEX_NCPYLEN(cc->cdb.cdb_length), " "));
4186 
4187     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
4188 	/* XXX print error info */
4189     } else {
4190 	/* since we don't use chained s/g, don't support it here */
4191 	for (i = 0; i < cc->header.sg_in_list; i++) {
4192 	    if ((i % 4) == 0)
4193 		ciss_printf(sc, "   ");
4194 	    kprintf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
4195 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
4196 		kprintf("\n");
4197 	}
4198     }
4199 }
4200 
4201 /************************************************************************
4202  * Print information about the status of a logical drive.
4203  */
4204 static void
4205 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
4206 {
4207     int		bus, target, i;
4208 
4209     if (ld->cl_lstatus == NULL) {
4210 	kprintf("does not exist\n");
4211 	return;
4212     }
4213 
4214     /* print drive status */
4215     switch(ld->cl_lstatus->status) {
4216     case CISS_LSTATUS_OK:
4217 	kprintf("online\n");
4218 	break;
4219     case CISS_LSTATUS_INTERIM_RECOVERY:
4220 	kprintf("in interim recovery mode\n");
4221 	break;
4222     case CISS_LSTATUS_READY_RECOVERY:
4223 	kprintf("ready to begin recovery\n");
4224 	break;
4225     case CISS_LSTATUS_RECOVERING:
4226 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4227 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4228 	kprintf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
4229 	       bus, target, ld->cl_lstatus->blocks_to_recover);
4230 	break;
4231     case CISS_LSTATUS_EXPANDING:
4232 	kprintf("being expanded, %u blocks remaining\n",
4233 	       ld->cl_lstatus->blocks_to_recover);
4234 	break;
4235     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4236 	kprintf("queued for expansion\n");
4237 	break;
4238     case CISS_LSTATUS_FAILED:
4239 	kprintf("queued for expansion\n");
4240 	break;
4241     case CISS_LSTATUS_WRONG_PDRIVE:
4242 	kprintf("wrong physical drive inserted\n");
4243 	break;
4244     case CISS_LSTATUS_MISSING_PDRIVE:
4245 	kprintf("missing a needed physical drive\n");
4246 	break;
4247     case CISS_LSTATUS_BECOMING_READY:
4248 	kprintf("becoming ready\n");
4249 	break;
4250     }
4251 
4252     /* print failed physical drives */
4253     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
4254 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
4255 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
4256 	if (bus == -1)
4257 	    continue;
4258 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
4259 		    ld->cl_lstatus->drive_failure_map[i]);
4260     }
4261 }
4262 
4263 #ifdef CISS_DEBUG
4264 #include "opt_ddb.h"
4265 #ifdef DDB
4266 #include <ddb/ddb.h>
4267 /************************************************************************
4268  * Print information about the controller/driver.
4269  */
4270 static void
4271 ciss_print_adapter(struct ciss_softc *sc)
4272 {
4273     int		i, j;
4274 
4275     ciss_printf(sc, "ADAPTER:\n");
4276     for (i = 0; i < CISSQ_COUNT; i++) {
4277 	ciss_printf(sc, "%s     %d/%d\n",
4278 	    i == 0 ? "free" :
4279 	    i == 1 ? "busy" : "complete",
4280 	    sc->ciss_qstat[i].q_length,
4281 	    sc->ciss_qstat[i].q_max);
4282     }
4283     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
4284     ciss_printf(sc, "flags %pb%i\n",
4285 	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n",
4286 	sc->ciss_flags);
4287 
4288     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
4289 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
4290 	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
4291 	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
4292 	}
4293     }
4294 
4295     /* XXX Should physical drives be printed out here? */
4296 
4297     for (i = 1; i < sc->ciss_max_requests; i++)
4298 	ciss_print_request(sc->ciss_request + i);
4299 }
4300 
4301 /* DDB hook */
4302 DB_COMMAND(ciss_prt, db_ciss_prt)
4303 {
4304     struct ciss_softc	*sc;
4305 
4306     sc = devclass_get_softc(devclass_find("ciss"), 0);
4307     if (sc == NULL) {
4308 	kprintf("no ciss controllers\n");
4309     } else {
4310 	ciss_print_adapter(sc);
4311     }
4312 }
4313 #endif
4314 #endif
4315 
4316 /************************************************************************
4317  * Return a name for a logical drive status value.
4318  */
4319 static const char *
4320 ciss_name_ldrive_status(int status)
4321 {
4322     switch (status) {
4323     case CISS_LSTATUS_OK:
4324 	return("OK");
4325     case CISS_LSTATUS_FAILED:
4326 	return("failed");
4327     case CISS_LSTATUS_NOT_CONFIGURED:
4328 	return("not configured");
4329     case CISS_LSTATUS_INTERIM_RECOVERY:
4330 	return("interim recovery");
4331     case CISS_LSTATUS_READY_RECOVERY:
4332 	return("ready for recovery");
4333     case CISS_LSTATUS_RECOVERING:
4334 	return("recovering");
4335     case CISS_LSTATUS_WRONG_PDRIVE:
4336 	return("wrong physical drive inserted");
4337     case CISS_LSTATUS_MISSING_PDRIVE:
4338 	return("missing physical drive");
4339     case CISS_LSTATUS_EXPANDING:
4340 	return("expanding");
4341     case CISS_LSTATUS_BECOMING_READY:
4342 	return("becoming ready");
4343     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4344 	return("queued for expansion");
4345     }
4346     return("unknown status");
4347 }
4348 
4349 /************************************************************************
4350  * Return an online/offline/nonexistent value for a logical drive
4351  * status value.
4352  */
4353 static int
4354 ciss_decode_ldrive_status(int status)
4355 {
4356     switch(status) {
4357     case CISS_LSTATUS_NOT_CONFIGURED:
4358 	return(CISS_LD_NONEXISTENT);
4359 
4360     case CISS_LSTATUS_OK:
4361     case CISS_LSTATUS_INTERIM_RECOVERY:
4362     case CISS_LSTATUS_READY_RECOVERY:
4363     case CISS_LSTATUS_RECOVERING:
4364     case CISS_LSTATUS_EXPANDING:
4365     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4366 	return(CISS_LD_ONLINE);
4367 
4368     case CISS_LSTATUS_FAILED:
4369     case CISS_LSTATUS_WRONG_PDRIVE:
4370     case CISS_LSTATUS_MISSING_PDRIVE:
4371     case CISS_LSTATUS_BECOMING_READY:
4372     default:
4373 	return(CISS_LD_OFFLINE);
4374     }
4375 }
4376 
4377 
4378 /************************************************************************
4379  * Return a name for a logical drive's organisation.
4380  */
4381 static const char *
4382 ciss_name_ldrive_org(int org)
4383 {
4384     switch(org) {
4385     case CISS_LDRIVE_RAID0:
4386 	return("RAID 0");
4387     case CISS_LDRIVE_RAID1:
4388 	return("RAID 1(1+0)");
4389     case CISS_LDRIVE_RAID4:
4390 	return("RAID 4");
4391     case CISS_LDRIVE_RAID5:
4392 	return("RAID 5");
4393     case CISS_LDRIVE_RAID51:
4394 	return("RAID 5+1");
4395     case CISS_LDRIVE_RAIDADG:
4396 	return("RAID ADG");
4397     }
4398     return("unknown");
4399 }
4400 
4401 /************************************************************************
4402  * Return a name for a command status value.
4403  */
4404 static const char *
4405 ciss_name_command_status(int status)
4406 {
4407     switch(status) {
4408     case CISS_CMD_STATUS_SUCCESS:
4409 	return("success");
4410     case CISS_CMD_STATUS_TARGET_STATUS:
4411 	return("target status");
4412     case CISS_CMD_STATUS_DATA_UNDERRUN:
4413 	return("data underrun");
4414     case CISS_CMD_STATUS_DATA_OVERRUN:
4415 	return("data overrun");
4416     case CISS_CMD_STATUS_INVALID_COMMAND:
4417 	return("invalid command");
4418     case CISS_CMD_STATUS_PROTOCOL_ERROR:
4419 	return("protocol error");
4420     case CISS_CMD_STATUS_HARDWARE_ERROR:
4421 	return("hardware error");
4422     case CISS_CMD_STATUS_CONNECTION_LOST:
4423 	return("connection lost");
4424     case CISS_CMD_STATUS_ABORTED:
4425 	return("aborted");
4426     case CISS_CMD_STATUS_ABORT_FAILED:
4427 	return("abort failed");
4428     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
4429 	return("unsolicited abort");
4430     case CISS_CMD_STATUS_TIMEOUT:
4431 	return("timeout");
4432     case CISS_CMD_STATUS_UNABORTABLE:
4433 	return("unabortable");
4434     }
4435     return("unknown status");
4436 }
4437 
4438 /************************************************************************
4439  * Handle an open on the control device.
4440  */
4441 static int
4442 ciss_open(struct dev_open_args *ap)
4443 {
4444     cdev_t dev = ap->a_head.a_dev;
4445     struct ciss_softc	*sc;
4446 
4447     debug_called(1);
4448 
4449     sc = (struct ciss_softc *)dev->si_drv1;
4450 
4451     /* we might want to veto if someone already has us open */
4452 
4453     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
4454     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
4455     lockmgr(&sc->ciss_lock, LK_RELEASE);
4456     return(0);
4457 }
4458 
4459 /************************************************************************
4460  * Handle the last close on the control device.
4461  */
4462 static int
4463 ciss_close(struct dev_close_args *ap)
4464 {
4465     cdev_t dev = ap->a_head.a_dev;
4466     struct ciss_softc	*sc;
4467 
4468     debug_called(1);
4469 
4470     sc = (struct ciss_softc *)dev->si_drv1;
4471 
4472     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
4473     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
4474     lockmgr(&sc->ciss_lock, LK_RELEASE);
4475     return (0);
4476 }
4477 
4478 /********************************************************************************
4479  * Handle adapter-specific control operations.
4480  *
4481  * Note that the API here is compatible with the Linux driver, in order to
4482  * simplify the porting of Compaq's userland tools.
4483  */
4484 static int
4485 ciss_ioctl(struct dev_ioctl_args *ap)
4486 {
4487     caddr_t addr = ap->a_data;
4488     cdev_t dev = ap->a_head.a_dev;
4489     u_long cmd = ap->a_cmd;
4490     struct ciss_softc		*sc;
4491     IOCTL_Command_struct	*ioc	= (IOCTL_Command_struct *)addr;
4492 #ifdef __x86_64__
4493     IOCTL_Command_struct32	*ioc32	= (IOCTL_Command_struct32 *)addr;
4494     IOCTL_Command_struct	ioc_swab;
4495 #endif
4496     int				error;
4497 
4498     debug_called(1);
4499 
4500     sc = (struct ciss_softc *)dev->si_drv1;
4501     error = 0;
4502     lockmgr(&sc->ciss_lock, LK_EXCLUSIVE);
4503 
4504     switch(cmd) {
4505     case CCISS_GETQSTATS:
4506     {
4507 	union ciss_statrequest *cr = (union ciss_statrequest *)addr;
4508 
4509 	switch (cr->cs_item) {
4510 	case CISSQ_FREE:
4511 	case CISSQ_NOTIFY:
4512 	    bcopy(&sc->ciss_qstat[cr->cs_item], &cr->cs_qstat,
4513 		sizeof(struct ciss_qstat));
4514 	    break;
4515 	default:
4516 	    error = ENOIOCTL;
4517 	    break;
4518 	}
4519 
4520 	break;
4521     }
4522 
4523     case CCISS_GETPCIINFO:
4524     {
4525 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4526 
4527 	pis->bus = pci_get_bus(sc->ciss_dev);
4528 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4529         pis->board_id = (pci_get_subvendor(sc->ciss_dev) << 16) |
4530                 pci_get_subdevice(sc->ciss_dev);
4531 
4532 	break;
4533     }
4534 
4535     case CCISS_GETINTINFO:
4536     {
4537 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4538 
4539 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4540 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4541 
4542 	break;
4543     }
4544 
4545     case CCISS_SETINTINFO:
4546     {
4547 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4548 
4549 	if ((cis->delay == 0) && (cis->count == 0)) {
4550 	    error = EINVAL;
4551 	    break;
4552 	}
4553 
4554 	/*
4555 	 * XXX apparently this is only safe if the controller is idle,
4556 	 *     we should suspend it before doing this.
4557 	 */
4558 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4559 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4560 
4561 	if (ciss_update_config(sc))
4562 	    error = EIO;
4563 
4564 	/* XXX resume the controller here */
4565 	break;
4566     }
4567 
4568     case CCISS_GETNODENAME:
4569 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4570 	      sizeof(NodeName_type));
4571 	break;
4572 
4573     case CCISS_SETNODENAME:
4574 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4575 	      sizeof(NodeName_type));
4576 	if (ciss_update_config(sc))
4577 	    error = EIO;
4578 	break;
4579 
4580     case CCISS_GETHEARTBEAT:
4581 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4582 	break;
4583 
4584     case CCISS_GETBUSTYPES:
4585 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4586 	break;
4587 
4588     case CCISS_GETFIRMVER:
4589 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4590 	      sizeof(FirmwareVer_type));
4591 	break;
4592 
4593     case CCISS_GETDRIVERVER:
4594 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4595 	break;
4596 
4597     case CCISS_REVALIDVOLS:
4598 	/*
4599 	 * This is a bit ugly; to do it "right" we really need
4600 	 * to find any disks that have changed, kick CAM off them,
4601 	 * then rescan only these disks.  It'd be nice if they
4602 	 * a) told us which disk(s) they were going to play with,
4603 	 * and b) which ones had arrived. 8(
4604 	 */
4605 	break;
4606 
4607 #ifdef __x86_64__
4608     case CCISS_PASSTHRU32:
4609 	ioc_swab.LUN_info	= ioc32->LUN_info;
4610 	ioc_swab.Request	= ioc32->Request;
4611 	ioc_swab.error_info	= ioc32->error_info;
4612 	ioc_swab.buf_size	= ioc32->buf_size;
4613 	ioc_swab.buf		= (u_int8_t *)(uintptr_t)ioc32->buf;
4614 	ioc			= &ioc_swab;
4615 	/* FALLTHROUGH */
4616 #endif
4617 
4618     case CCISS_PASSTHRU:
4619 	error = ciss_user_command(sc, ioc);
4620 	break;
4621 
4622     default:
4623 	debug(0, "unknown ioctl 0x%lx", cmd);
4624 
4625 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4626 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4627 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4628 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4629 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4630 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4631 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4632 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4633 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4634 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4635 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4636 
4637 	error = ENOIOCTL;
4638 	break;
4639     }
4640 
4641     lockmgr(&sc->ciss_lock, LK_RELEASE);
4642     return(error);
4643 }
4644