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