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