xref: /freebsd/sys/dev/ciss/ciss.c (revision 54ebdd631db8c0bba2baab0155f603a8b5cf014a)
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 =
2985 	    &cts->xport_specific.spi;
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 	cts->ccb_h.status = CAM_REQ_CMP;
3001 	break;
3002     }
3003 
3004     default:		/* we can't do this */
3005 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
3006 	ccb->ccb_h.status = CAM_REQ_INVALID;
3007 	break;
3008     }
3009 
3010     xpt_done(ccb);
3011 }
3012 
3013 /************************************************************************
3014  * Handle a CAM SCSI I/O request.
3015  */
3016 static int
3017 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
3018 {
3019     struct ciss_softc	*sc;
3020     int			bus, target;
3021     struct ciss_request	*cr;
3022     struct ciss_command	*cc;
3023     int			error;
3024 
3025     sc = cam_sim_softc(sim);
3026     bus = cam_sim_bus(sim);
3027     target = csio->ccb_h.target_id;
3028 
3029     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
3030 
3031     /* check that the CDB pointer is not to a physical address */
3032     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
3033 	debug(3, "  CDB pointer is to physical address");
3034 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3035     }
3036 
3037     /* if there is data transfer, it must be to/from a virtual address */
3038     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
3039 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
3040 	    debug(3, "  data pointer is to physical address");
3041 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3042 	}
3043 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
3044 	    debug(3, "  data has premature s/g setup");
3045 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3046 	}
3047     }
3048 
3049     /* abandon aborted ccbs or those that have failed validation */
3050     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3051 	debug(3, "abandoning CCB due to abort/validation failure");
3052 	return(EINVAL);
3053     }
3054 
3055     /* handle emulation of some SCSI commands ourself */
3056     if (ciss_cam_emulate(sc, csio))
3057 	return(0);
3058 
3059     /*
3060      * Get a request to manage this command.  If we can't, return the
3061      * ccb, freeze the queue and flag so that we unfreeze it when a
3062      * request completes.
3063      */
3064     if ((error = ciss_get_request(sc, &cr)) != 0) {
3065 	xpt_freeze_simq(sim, 1);
3066 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
3067 	return(error);
3068     }
3069 
3070     /*
3071      * Build the command.
3072      */
3073     cc = CISS_FIND_COMMAND(cr);
3074     cr->cr_data = csio->data_ptr;
3075     cr->cr_length = csio->dxfer_len;
3076     cr->cr_complete = ciss_cam_complete;
3077     cr->cr_private = csio;
3078 
3079     /*
3080      * Target the right logical volume.
3081      */
3082     if (CISS_IS_PHYSICAL(bus))
3083 	cc->header.address =
3084 	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
3085     else
3086 	cc->header.address =
3087 	    sc->ciss_logical[bus][target].cl_address;
3088     cc->cdb.cdb_length = csio->cdb_len;
3089     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3090     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
3091     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
3092 	cr->cr_flags = CISS_REQ_DATAOUT;
3093 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3094     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
3095 	cr->cr_flags = CISS_REQ_DATAIN;
3096 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3097     } else {
3098 	cr->cr_flags = 0;
3099 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
3100     }
3101     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
3102     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
3103 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
3104     } else {
3105 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
3106     }
3107 
3108     /*
3109      * Submit the request to the adapter.
3110      *
3111      * Note that this may fail if we're unable to map the request (and
3112      * if we ever learn a transport layer other than simple, may fail
3113      * if the adapter rejects the command).
3114      */
3115     if ((error = ciss_start(cr)) != 0) {
3116 	xpt_freeze_simq(sim, 1);
3117 	if (error == EINPROGRESS) {
3118 	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3119 	    error = 0;
3120 	} else {
3121 	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
3122 	    ciss_release_request(cr);
3123 	}
3124 	return(error);
3125     }
3126 
3127     return(0);
3128 }
3129 
3130 /************************************************************************
3131  * Emulate SCSI commands the adapter doesn't handle as we might like.
3132  */
3133 static int
3134 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
3135 {
3136     int		bus, target;
3137     u_int8_t	opcode;
3138 
3139     target = csio->ccb_h.target_id;
3140     bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3141     opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3142 	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
3143 
3144     if (CISS_IS_PHYSICAL(bus)) {
3145 	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
3146 	    csio->ccb_h.status = CAM_SEL_TIMEOUT;
3147 	    xpt_done((union ccb *)csio);
3148 	    return(1);
3149 	} else
3150 	    return(0);
3151     }
3152 
3153     /*
3154      * Handle requests for volumes that don't exist or are not online.
3155      * A selection timeout is slightly better than an illegal request.
3156      * Other errors might be better.
3157      */
3158     if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
3159 	csio->ccb_h.status = CAM_SEL_TIMEOUT;
3160 	xpt_done((union ccb *)csio);
3161 	return(1);
3162     }
3163 
3164     /* if we have to fake Synchronise Cache */
3165     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
3166 	/*
3167 	 * If this is a Synchronise Cache command, typically issued when
3168 	 * a device is closed, flush the adapter and complete now.
3169 	 */
3170 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3171 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
3172 	    ciss_flush_adapter(sc);
3173 	    csio->ccb_h.status = CAM_REQ_CMP;
3174 	    xpt_done((union ccb *)csio);
3175 	    return(1);
3176 	}
3177     }
3178 
3179     return(0);
3180 }
3181 
3182 /************************************************************************
3183  * Check for possibly-completed commands.
3184  */
3185 static void
3186 ciss_cam_poll(struct cam_sim *sim)
3187 {
3188     cr_qhead_t qh;
3189     struct ciss_softc	*sc = cam_sim_softc(sim);
3190 
3191     debug_called(2);
3192 
3193     STAILQ_INIT(&qh);
3194     if (sc->ciss_perf)
3195 	ciss_perf_done(sc, &qh);
3196     else
3197 	ciss_done(sc, &qh);
3198     ciss_complete(sc, &qh);
3199 }
3200 
3201 /************************************************************************
3202  * Handle completion of a command - pass results back through the CCB
3203  */
3204 static void
3205 ciss_cam_complete(struct ciss_request *cr)
3206 {
3207     struct ciss_softc		*sc;
3208     struct ciss_command		*cc;
3209     struct ciss_error_info	*ce;
3210     struct ccb_scsiio		*csio;
3211     int				scsi_status;
3212     int				command_status;
3213 
3214     debug_called(2);
3215 
3216     sc = cr->cr_sc;
3217     cc = CISS_FIND_COMMAND(cr);
3218     ce = (struct ciss_error_info *)&(cc->sg[0]);
3219     csio = (struct ccb_scsiio *)cr->cr_private;
3220 
3221     /*
3222      * Extract status values from request.
3223      */
3224     ciss_report_request(cr, &command_status, &scsi_status);
3225     csio->scsi_status = scsi_status;
3226 
3227     /*
3228      * Handle specific SCSI status values.
3229      */
3230     switch(scsi_status) {
3231 	/* no status due to adapter error */
3232     case -1:
3233 	debug(0, "adapter error");
3234 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3235 	break;
3236 
3237 	/* no status due to command completed OK */
3238     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
3239 	debug(2, "SCSI_STATUS_OK");
3240 	csio->ccb_h.status = CAM_REQ_CMP;
3241 	break;
3242 
3243 	/* check condition, sense data included */
3244     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
3245 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
3246 	      ce->sense_length, ce->residual_count);
3247 	bzero(&csio->sense_data, SSD_FULL_SIZE);
3248 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
3249 	csio->sense_len = ce->sense_length;
3250 	csio->resid = ce->residual_count;
3251 	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
3252 #ifdef CISS_DEBUG
3253 	{
3254 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
3255 	    debug(0, "sense key %x", sns->flags & SSD_KEY);
3256 	}
3257 #endif
3258 	break;
3259 
3260     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
3261 	debug(0, "SCSI_STATUS_BUSY");
3262 	csio->ccb_h.status = CAM_SCSI_BUSY;
3263 	break;
3264 
3265     default:
3266 	debug(0, "unknown status 0x%x", csio->scsi_status);
3267 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3268 	break;
3269     }
3270 
3271     /* handle post-command fixup */
3272     ciss_cam_complete_fixup(sc, csio);
3273 
3274     /* tell CAM we're ready for more commands */
3275     csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3276 
3277     ciss_release_request(cr);
3278     xpt_done((union ccb *)csio);
3279 }
3280 
3281 /********************************************************************************
3282  * Fix up the result of some commands here.
3283  */
3284 static void
3285 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
3286 {
3287     struct scsi_inquiry_data	*inq;
3288     struct ciss_ldrive		*cl;
3289     int				bus, target;
3290 
3291     if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3292 	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
3293 
3294 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
3295 	target = csio->ccb_h.target_id;
3296 	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3297 
3298 	/*
3299 	 * Don't let hard drives be seen by the DA driver.  They will still be
3300 	 * attached by the PASS driver.
3301 	 */
3302 	if (CISS_IS_PHYSICAL(bus)) {
3303 	    if (SID_TYPE(inq) == T_DIRECT)
3304 		inq->device = (inq->device & 0xe0) | T_NODEVICE;
3305 	    return;
3306 	}
3307 
3308 	cl = &sc->ciss_logical[bus][target];
3309 
3310 	padstr(inq->vendor, "COMPAQ", 8);
3311 	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
3312 	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
3313     }
3314 }
3315 
3316 
3317 /********************************************************************************
3318  * Find a peripheral attached at (target)
3319  */
3320 static struct cam_periph *
3321 ciss_find_periph(struct ciss_softc *sc, int bus, int target)
3322 {
3323     struct cam_periph	*periph;
3324     struct cam_path	*path;
3325     int			status;
3326 
3327     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
3328 			     target, 0);
3329     if (status == CAM_REQ_CMP) {
3330 	periph = cam_periph_find(path, NULL);
3331 	xpt_free_path(path);
3332     } else {
3333 	periph = NULL;
3334     }
3335     return(periph);
3336 }
3337 
3338 /********************************************************************************
3339  * Name the device at (target)
3340  *
3341  * XXX is this strictly correct?
3342  */
3343 static int
3344 ciss_name_device(struct ciss_softc *sc, int bus, int target)
3345 {
3346     struct cam_periph	*periph;
3347 
3348     if (CISS_IS_PHYSICAL(bus))
3349 	return (0);
3350     if ((periph = ciss_find_periph(sc, bus, target)) != NULL) {
3351 	sprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
3352 		periph->periph_name, periph->unit_number);
3353 	return(0);
3354     }
3355     sc->ciss_logical[bus][target].cl_name[0] = 0;
3356     return(ENOENT);
3357 }
3358 
3359 /************************************************************************
3360  * Periodic status monitoring.
3361  */
3362 static void
3363 ciss_periodic(void *arg)
3364 {
3365     struct ciss_softc	*sc;
3366     struct ciss_request	*cr = NULL;
3367     struct ciss_command	*cc = NULL;
3368     int			error = 0;
3369 
3370     debug_called(1);
3371 
3372     sc = (struct ciss_softc *)arg;
3373 
3374     /*
3375      * Check the adapter heartbeat.
3376      */
3377     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
3378 	sc->ciss_heart_attack++;
3379 	debug(0, "adapter heart attack in progress 0x%x/%d",
3380 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
3381 	if (sc->ciss_heart_attack == 3) {
3382 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
3383 	    ciss_disable_adapter(sc);
3384 	    return;
3385 	}
3386     } else {
3387 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
3388 	sc->ciss_heart_attack = 0;
3389 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
3390     }
3391 
3392     /*
3393      * Send the NOP message and wait for a response.
3394      */
3395     if (ciss_nop_message_heartbeat != 0 && (error = ciss_get_request(sc, &cr)) == 0) {
3396 	cc = CISS_FIND_COMMAND(cr);
3397 	cr->cr_complete = ciss_nop_complete;
3398 	cc->cdb.cdb_length = 1;
3399 	cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
3400 	cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3401 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3402 	cc->cdb.timeout = 0;
3403 	cc->cdb.cdb[0] = CISS_OPCODE_MESSAGE_NOP;
3404 
3405 	if ((error = ciss_start(cr)) != 0) {
3406 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED\n");
3407 	}
3408     }
3409 
3410     /*
3411      * If the notify event request has died for some reason, or has
3412      * not started yet, restart it.
3413      */
3414     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
3415 	debug(0, "(re)starting Event Notify chain");
3416 	ciss_notify_event(sc);
3417     }
3418 
3419     /*
3420      * Reschedule.
3421      */
3422     callout_reset(&sc->ciss_periodic, CISS_HEARTBEAT_RATE * hz, ciss_periodic, sc);
3423 }
3424 
3425 static void
3426 ciss_nop_complete(struct ciss_request *cr)
3427 {
3428     struct ciss_softc		*sc;
3429     static int			first_time = 1;
3430 
3431     sc = cr->cr_sc;
3432     if (ciss_report_request(cr, NULL, NULL) != 0) {
3433 	if (first_time == 1) {
3434 	    first_time = 0;
3435 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED (not logging anymore)\n");
3436 	}
3437     }
3438 
3439     ciss_release_request(cr);
3440 }
3441 
3442 /************************************************************************
3443  * Disable the adapter.
3444  *
3445  * The all requests in completed queue is failed with hardware error.
3446  * This will cause failover in a multipath configuration.
3447  */
3448 static void
3449 ciss_disable_adapter(struct ciss_softc *sc)
3450 {
3451     cr_qhead_t			qh;
3452     struct ciss_request		*cr;
3453     struct ciss_command		*cc;
3454     struct ciss_error_info	*ce;
3455     int				i;
3456 
3457     CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
3458     pci_disable_busmaster(sc->ciss_dev);
3459     sc->ciss_flags &= ~CISS_FLAG_RUNNING;
3460 
3461     for (i = 1; i < sc->ciss_max_requests; i++) {
3462 	cr = &sc->ciss_request[i];
3463 	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
3464 	    continue;
3465 
3466 	cc = CISS_FIND_COMMAND(cr);
3467 	ce = (struct ciss_error_info *)&(cc->sg[0]);
3468 	ce->command_status = CISS_CMD_STATUS_HARDWARE_ERROR;
3469 	ciss_enqueue_complete(cr, &qh);
3470     }
3471 
3472     for (;;) {
3473 	if ((cr = ciss_dequeue_complete(sc, &qh)) == NULL)
3474 	    break;
3475 
3476 	/*
3477 	 * If the request has a callback, invoke it.
3478 	 */
3479 	if (cr->cr_complete != NULL) {
3480 	    cr->cr_complete(cr);
3481 	    continue;
3482 	}
3483 
3484 	/*
3485 	 * If someone is sleeping on this request, wake them up.
3486 	 */
3487 	if (cr->cr_flags & CISS_REQ_SLEEP) {
3488 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
3489 	    wakeup(cr);
3490 	    continue;
3491 	}
3492     }
3493 }
3494 
3495 /************************************************************************
3496  * Request a notification response from the adapter.
3497  *
3498  * If (cr) is NULL, this is the first request of the adapter, so
3499  * reset the adapter's message pointer and start with the oldest
3500  * message available.
3501  */
3502 static void
3503 ciss_notify_event(struct ciss_softc *sc)
3504 {
3505     struct ciss_request		*cr;
3506     struct ciss_command		*cc;
3507     struct ciss_notify_cdb	*cnc;
3508     int				error;
3509 
3510     debug_called(1);
3511 
3512     cr = sc->ciss_periodic_notify;
3513 
3514     /* get a request if we don't already have one */
3515     if (cr == NULL) {
3516 	if ((error = ciss_get_request(sc, &cr)) != 0) {
3517 	    debug(0, "can't get notify event request");
3518 	    goto out;
3519 	}
3520 	sc->ciss_periodic_notify = cr;
3521 	cr->cr_complete = ciss_notify_complete;
3522 	debug(1, "acquired request %d", cr->cr_tag);
3523     }
3524 
3525     /*
3526      * Get a databuffer if we don't already have one, note that the
3527      * adapter command wants a larger buffer than the actual
3528      * structure.
3529      */
3530     if (cr->cr_data == NULL) {
3531 	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3532 	    debug(0, "can't get notify event request buffer");
3533 	    error = ENOMEM;
3534 	    goto out;
3535 	}
3536 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3537     }
3538 
3539     /* re-setup the request's command (since we never release it) XXX overkill*/
3540     ciss_preen_command(cr);
3541 
3542     /* (re)build the notify event command */
3543     cc = CISS_FIND_COMMAND(cr);
3544     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3545     cc->header.address.physical.bus = 0;
3546     cc->header.address.physical.target = 0;
3547 
3548     cc->cdb.cdb_length = sizeof(*cnc);
3549     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3550     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3551     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3552     cc->cdb.timeout = 0;	/* no timeout, we hope */
3553 
3554     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3555     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3556     cnc->opcode = CISS_OPCODE_READ;
3557     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3558     cnc->timeout = 0;		/* no timeout, we hope */
3559     cnc->synchronous = 0;
3560     cnc->ordered = 0;
3561     cnc->seek_to_oldest = 0;
3562     if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3563 	cnc->new_only = 1;
3564     else
3565 	cnc->new_only = 0;
3566     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3567 
3568     /* submit the request */
3569     error = ciss_start(cr);
3570 
3571  out:
3572     if (error) {
3573 	if (cr != NULL) {
3574 	    if (cr->cr_data != NULL)
3575 		free(cr->cr_data, CISS_MALLOC_CLASS);
3576 	    ciss_release_request(cr);
3577 	}
3578 	sc->ciss_periodic_notify = NULL;
3579 	debug(0, "can't submit notify event request");
3580 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3581     } else {
3582 	debug(1, "notify event submitted");
3583 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3584     }
3585 }
3586 
3587 static void
3588 ciss_notify_complete(struct ciss_request *cr)
3589 {
3590     struct ciss_command	*cc;
3591     struct ciss_notify	*cn;
3592     struct ciss_softc	*sc;
3593     int			scsi_status;
3594     int			command_status;
3595     debug_called(1);
3596 
3597     cc = CISS_FIND_COMMAND(cr);
3598     cn = (struct ciss_notify *)cr->cr_data;
3599     sc = cr->cr_sc;
3600 
3601     /*
3602      * Report request results, decode status.
3603      */
3604     ciss_report_request(cr, &command_status, &scsi_status);
3605 
3606     /*
3607      * Abort the chain on a fatal error.
3608      *
3609      * XXX which of these are actually errors?
3610      */
3611     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3612 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3613 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3614 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3615 		    ciss_name_command_status(command_status));
3616 	ciss_release_request(cr);
3617 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3618 	return;
3619     }
3620 
3621     /*
3622      * If the adapter gave us a text message, print it.
3623      */
3624     if (cn->message[0] != 0)
3625 	ciss_printf(sc, "*** %.80s\n", cn->message);
3626 
3627     debug(0, "notify event class %d subclass %d detail %d",
3628 		cn->class, cn->subclass, cn->detail);
3629 
3630     /*
3631      * If the response indicates that the notifier has been aborted,
3632      * release the notifier command.
3633      */
3634     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3635 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3636 	(cn->detail == 1)) {
3637 	debug(0, "notifier exiting");
3638 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3639 	ciss_release_request(cr);
3640 	sc->ciss_periodic_notify = NULL;
3641 	wakeup(&sc->ciss_periodic_notify);
3642     } else {
3643 	/* Handle notify events in a kernel thread */
3644 	ciss_enqueue_notify(cr);
3645 	sc->ciss_periodic_notify = NULL;
3646 	wakeup(&sc->ciss_periodic_notify);
3647 	wakeup(&sc->ciss_notify);
3648     }
3649     /*
3650      * Send a new notify event command, if we're not aborting.
3651      */
3652     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3653 	ciss_notify_event(sc);
3654     }
3655 }
3656 
3657 /************************************************************************
3658  * Abort the Notify Event chain.
3659  *
3660  * Note that we can't just abort the command in progress; we have to
3661  * explicitly issue an Abort Notify Event command in order for the
3662  * adapter to clean up correctly.
3663  *
3664  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3665  * the chain will not restart itself.
3666  */
3667 static int
3668 ciss_notify_abort(struct ciss_softc *sc)
3669 {
3670     struct ciss_request		*cr;
3671     struct ciss_command		*cc;
3672     struct ciss_notify_cdb	*cnc;
3673     int				error, command_status, scsi_status;
3674 
3675     debug_called(1);
3676 
3677     cr = NULL;
3678     error = 0;
3679 
3680     /* verify that there's an outstanding command */
3681     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3682 	goto out;
3683 
3684     /* get a command to issue the abort with */
3685     if ((error = ciss_get_request(sc, &cr)))
3686 	goto out;
3687 
3688     /* get a buffer for the result */
3689     if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3690 	debug(0, "can't get notify event request buffer");
3691 	error = ENOMEM;
3692 	goto out;
3693     }
3694     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3695 
3696     /* build the CDB */
3697     cc = CISS_FIND_COMMAND(cr);
3698     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3699     cc->header.address.physical.bus = 0;
3700     cc->header.address.physical.target = 0;
3701     cc->cdb.cdb_length = sizeof(*cnc);
3702     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3703     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3704     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3705     cc->cdb.timeout = 0;	/* no timeout, we hope */
3706 
3707     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3708     bzero(cnc, sizeof(*cnc));
3709     cnc->opcode = CISS_OPCODE_WRITE;
3710     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3711     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3712 
3713     ciss_print_request(cr);
3714 
3715     /*
3716      * Submit the request and wait for it to complete.
3717      */
3718     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3719 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3720 	goto out;
3721     }
3722 
3723     /*
3724      * Check response.
3725      */
3726     ciss_report_request(cr, &command_status, &scsi_status);
3727     switch(command_status) {
3728     case CISS_CMD_STATUS_SUCCESS:
3729 	break;
3730     case CISS_CMD_STATUS_INVALID_COMMAND:
3731 	/*
3732 	 * Some older adapters don't support the CISS version of this
3733 	 * command.  Fall back to using the BMIC version.
3734 	 */
3735 	error = ciss_notify_abort_bmic(sc);
3736 	if (error != 0)
3737 	    goto out;
3738 	break;
3739 
3740     case CISS_CMD_STATUS_TARGET_STATUS:
3741 	/*
3742 	 * This can happen if the adapter thinks there wasn't an outstanding
3743 	 * Notify Event command but we did.  We clean up here.
3744 	 */
3745 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3746 	    if (sc->ciss_periodic_notify != NULL)
3747 		ciss_release_request(sc->ciss_periodic_notify);
3748 	    error = 0;
3749 	    goto out;
3750 	}
3751 	/* FALLTHROUGH */
3752 
3753     default:
3754 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3755 		    ciss_name_command_status(command_status));
3756 	error = EIO;
3757 	goto out;
3758     }
3759 
3760     /*
3761      * Sleep waiting for the notifier command to complete.  Note
3762      * that if it doesn't, we may end up in a bad situation, since
3763      * the adapter may deliver it later.  Also note that the adapter
3764      * requires the Notify Event command to be cancelled in order to
3765      * maintain internal bookkeeping.
3766      */
3767     while (sc->ciss_periodic_notify != NULL) {
3768 	error = msleep(&sc->ciss_periodic_notify, &sc->ciss_mtx, PRIBIO, "cissNEA", hz * 5);
3769 	if (error == EWOULDBLOCK) {
3770 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3771 	    break;
3772 	}
3773     }
3774 
3775  out:
3776     /* release the cancel request */
3777     if (cr != NULL) {
3778 	if (cr->cr_data != NULL)
3779 	    free(cr->cr_data, CISS_MALLOC_CLASS);
3780 	ciss_release_request(cr);
3781     }
3782     if (error == 0)
3783 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3784     return(error);
3785 }
3786 
3787 /************************************************************************
3788  * Abort the Notify Event chain using a BMIC command.
3789  */
3790 static int
3791 ciss_notify_abort_bmic(struct ciss_softc *sc)
3792 {
3793     struct ciss_request			*cr;
3794     int					error, command_status;
3795 
3796     debug_called(1);
3797 
3798     cr = NULL;
3799     error = 0;
3800 
3801     /* verify that there's an outstanding command */
3802     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3803 	goto out;
3804 
3805     /*
3806      * Build a BMIC command to cancel the Notify on Event command.
3807      *
3808      * Note that we are sending a CISS opcode here.  Odd.
3809      */
3810     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3811 				       NULL, 0)) != 0)
3812 	goto out;
3813 
3814     /*
3815      * Submit the request and wait for it to complete.
3816      */
3817     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3818 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3819 	goto out;
3820     }
3821 
3822     /*
3823      * Check response.
3824      */
3825     ciss_report_request(cr, &command_status, NULL);
3826     switch(command_status) {
3827     case CISS_CMD_STATUS_SUCCESS:
3828 	break;
3829     default:
3830 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3831 		    ciss_name_command_status(command_status));
3832 	error = EIO;
3833 	goto out;
3834     }
3835 
3836 out:
3837     if (cr != NULL)
3838 	ciss_release_request(cr);
3839     return(error);
3840 }
3841 
3842 /************************************************************************
3843  * Handle rescanning all the logical volumes when a notify event
3844  * causes the drives to come online or offline.
3845  */
3846 static void
3847 ciss_notify_rescan_logical(struct ciss_softc *sc)
3848 {
3849     struct ciss_lun_report      *cll;
3850     struct ciss_ldrive		*ld;
3851     int                         i, j, ndrives;
3852 
3853     /*
3854      * We must rescan all logical volumes to get the right logical
3855      * drive address.
3856      */
3857     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3858                            CISS_MAX_LOGICAL);
3859     if (cll == NULL)
3860         return;
3861 
3862     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3863 
3864     /*
3865      * Delete any of the drives which were destroyed by the
3866      * firmware.
3867      */
3868     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3869 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3870 	    ld = &sc->ciss_logical[i][j];
3871 
3872 	    if (ld->cl_update == 0)
3873 		continue;
3874 
3875 	    if (ld->cl_status != CISS_LD_ONLINE) {
3876 		ciss_cam_rescan_target(sc, i, j);
3877 		ld->cl_update = 0;
3878 		if (ld->cl_ldrive)
3879 		    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
3880 		if (ld->cl_lstatus)
3881 		    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
3882 
3883 		ld->cl_ldrive = NULL;
3884 		ld->cl_lstatus = NULL;
3885 	    }
3886 	}
3887     }
3888 
3889     /*
3890      * Scan for new drives.
3891      */
3892     for (i = 0; i < ndrives; i++) {
3893 	int	bus, target;
3894 
3895 	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3896 	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3897 	ld	= &sc->ciss_logical[bus][target];
3898 
3899 	if (ld->cl_update == 0)
3900 		continue;
3901 
3902 	ld->cl_update		= 0;
3903 	ld->cl_address		= cll->lun[i];
3904 	ld->cl_controller	= &sc->ciss_controllers[bus];
3905 	if (ciss_identify_logical(sc, ld) == 0) {
3906 	    ciss_cam_rescan_target(sc, bus, target);
3907 	}
3908     }
3909     free(cll, CISS_MALLOC_CLASS);
3910 }
3911 
3912 /************************************************************************
3913  * Handle a notify event relating to the status of a logical drive.
3914  *
3915  * XXX need to be able to defer some of these to properly handle
3916  *     calling the "ID Physical drive" command, unless the 'extended'
3917  *     drive IDs are always in BIG_MAP format.
3918  */
3919 static void
3920 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3921 {
3922     struct ciss_ldrive	*ld;
3923     int			ostatus, bus, target;
3924 
3925     debug_called(2);
3926 
3927     bus		= cn->device.physical.bus;
3928     target	= cn->data.logical_status.logical_drive;
3929     ld		= &sc->ciss_logical[bus][target];
3930 
3931     switch (cn->subclass) {
3932     case CISS_NOTIFY_LOGICAL_STATUS:
3933 	switch (cn->detail) {
3934 	case 0:
3935 	    ciss_name_device(sc, bus, target);
3936 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3937 			cn->data.logical_status.logical_drive, ld->cl_name,
3938 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3939 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3940 			cn->data.logical_status.spare_state,
3941 			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3942 
3943 	    /*
3944 	     * Update our idea of the drive's status.
3945 	     */
3946 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3947 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3948 	    if (ld->cl_lstatus != NULL)
3949 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3950 
3951 	    /*
3952 	     * Have CAM rescan the drive if its status has changed.
3953 	     */
3954 	    if (ostatus != ld->cl_status) {
3955 		ld->cl_update = 1;
3956 		ciss_notify_rescan_logical(sc);
3957 	    }
3958 
3959 	    break;
3960 
3961 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3962 	    ciss_name_device(sc, bus, target);
3963 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3964 			cn->data.logical_status.logical_drive, ld->cl_name);
3965 	    ciss_accept_media(sc, ld);
3966 
3967 	    ld->cl_update = 1;
3968 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3969 	    ciss_notify_rescan_logical(sc);
3970 	    break;
3971 
3972 	case 2:
3973 	case 3:
3974 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3975 			cn->data.rebuild_aborted.logical_drive,
3976 			ld->cl_name,
3977 			(cn->detail == 2) ? "read" : "write");
3978 	    break;
3979 	}
3980 	break;
3981 
3982     case CISS_NOTIFY_LOGICAL_ERROR:
3983 	if (cn->detail == 0) {
3984 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3985 			cn->data.io_error.logical_drive,
3986 			ld->cl_name,
3987 			cn->data.io_error.failure_bus,
3988 			cn->data.io_error.failure_drive);
3989 	    /* XXX should we take the drive down at this point, or will we be told? */
3990 	}
3991 	break;
3992 
3993     case CISS_NOTIFY_LOGICAL_SURFACE:
3994 	if (cn->detail == 0)
3995 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
3996 			cn->data.consistency_completed.logical_drive,
3997 			ld->cl_name);
3998 	break;
3999     }
4000 }
4001 
4002 /************************************************************************
4003  * Handle a notify event relating to the status of a physical drive.
4004  */
4005 static void
4006 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
4007 {
4008 }
4009 
4010 /************************************************************************
4011  * Handle a notify event relating to the status of a physical drive.
4012  */
4013 static void
4014 ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
4015 {
4016     struct ciss_lun_report *cll = NULL;
4017     int bus, target;
4018 
4019     switch (cn->subclass) {
4020     case CISS_NOTIFY_HOTPLUG_PHYSICAL:
4021     case CISS_NOTIFY_HOTPLUG_NONDISK:
4022 	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
4023 	target =
4024 	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
4025 
4026 	if (cn->detail == 0) {
4027 	    /*
4028 	     * Mark the device offline so that it'll start producing selection
4029 	     * timeouts to the upper layer.
4030 	     */
4031 	    if ((bus >= 0) && (target >= 0))
4032 		sc->ciss_physical[bus][target].cp_online = 0;
4033 	} else {
4034 	    /*
4035 	     * Rescan the physical lun list for new items
4036 	     */
4037 	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
4038 				   CISS_MAX_PHYSICAL);
4039 	    if (cll == NULL) {
4040 		ciss_printf(sc, "Warning, cannot get physical lun list\n");
4041 		break;
4042 	    }
4043 	    ciss_filter_physical(sc, cll);
4044 	}
4045 	break;
4046 
4047     default:
4048 	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
4049 	return;
4050     }
4051 
4052     if (cll != NULL)
4053 	free(cll, CISS_MALLOC_CLASS);
4054 }
4055 
4056 /************************************************************************
4057  * Handle deferred processing of notify events.  Notify events may need
4058  * sleep which is unsafe during an interrupt.
4059  */
4060 static void
4061 ciss_notify_thread(void *arg)
4062 {
4063     struct ciss_softc		*sc;
4064     struct ciss_request		*cr;
4065     struct ciss_notify		*cn;
4066 
4067     sc = (struct ciss_softc *)arg;
4068 #if __FreeBSD_version >= 500000
4069     mtx_lock(&sc->ciss_mtx);
4070 #endif
4071 
4072     for (;;) {
4073 	if (STAILQ_EMPTY(&sc->ciss_notify) != 0 &&
4074 	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
4075 	    msleep(&sc->ciss_notify, &sc->ciss_mtx, PUSER, "idle", 0);
4076 	}
4077 
4078 	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
4079 	    break;
4080 
4081 	cr = ciss_dequeue_notify(sc);
4082 
4083 	if (cr == NULL)
4084 		panic("cr null");
4085 	cn = (struct ciss_notify *)cr->cr_data;
4086 
4087 	switch (cn->class) {
4088 	case CISS_NOTIFY_HOTPLUG:
4089 	    ciss_notify_hotplug(sc, cn);
4090 	    break;
4091 	case CISS_NOTIFY_LOGICAL:
4092 	    ciss_notify_logical(sc, cn);
4093 	    break;
4094 	case CISS_NOTIFY_PHYSICAL:
4095 	    ciss_notify_physical(sc, cn);
4096 	    break;
4097 	}
4098 
4099 	ciss_release_request(cr);
4100 
4101     }
4102     sc->ciss_notify_thread = NULL;
4103     wakeup(&sc->ciss_notify_thread);
4104 
4105 #if __FreeBSD_version >= 500000
4106     mtx_unlock(&sc->ciss_mtx);
4107 #endif
4108     kproc_exit(0);
4109 }
4110 
4111 /************************************************************************
4112  * Start the notification kernel thread.
4113  */
4114 static void
4115 ciss_spawn_notify_thread(struct ciss_softc *sc)
4116 {
4117 
4118 #if __FreeBSD_version > 500005
4119     if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4120 		       &sc->ciss_notify_thread, 0, 0, "ciss_notify%d",
4121 		       device_get_unit(sc->ciss_dev)))
4122 #else
4123     if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4124 		       &sc->ciss_notify_thread, "ciss_notify%d",
4125 		       device_get_unit(sc->ciss_dev)))
4126 #endif
4127 	panic("Could not create notify thread\n");
4128 }
4129 
4130 /************************************************************************
4131  * Kill the notification kernel thread.
4132  */
4133 static void
4134 ciss_kill_notify_thread(struct ciss_softc *sc)
4135 {
4136 
4137     if (sc->ciss_notify_thread == NULL)
4138 	return;
4139 
4140     sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
4141     wakeup(&sc->ciss_notify);
4142     msleep(&sc->ciss_notify_thread, &sc->ciss_mtx, PUSER, "thtrm", 0);
4143 }
4144 
4145 /************************************************************************
4146  * Print a request.
4147  */
4148 static void
4149 ciss_print_request(struct ciss_request *cr)
4150 {
4151     struct ciss_softc	*sc;
4152     struct ciss_command	*cc;
4153     int			i;
4154 
4155     sc = cr->cr_sc;
4156     cc = CISS_FIND_COMMAND(cr);
4157 
4158     ciss_printf(sc, "REQUEST @ %p\n", cr);
4159     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
4160 	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
4161 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
4162     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
4163 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
4164     switch(cc->header.address.mode.mode) {
4165     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
4166     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
4167 	ciss_printf(sc, "  physical bus %d target %d\n",
4168 		    cc->header.address.physical.bus, cc->header.address.physical.target);
4169 	break;
4170     case CISS_HDR_ADDRESS_MODE_LOGICAL:
4171 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
4172 	break;
4173     }
4174     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
4175 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
4176 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
4177 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
4178 		cc->cdb.cdb_length,
4179 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
4180 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
4181 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
4182 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
4183 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
4184 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
4185 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
4186     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
4187 
4188     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
4189 	/* XXX print error info */
4190     } else {
4191 	/* since we don't use chained s/g, don't support it here */
4192 	for (i = 0; i < cc->header.sg_in_list; i++) {
4193 	    if ((i % 4) == 0)
4194 		ciss_printf(sc, "   ");
4195 	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
4196 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
4197 		printf("\n");
4198 	}
4199     }
4200 }
4201 
4202 /************************************************************************
4203  * Print information about the status of a logical drive.
4204  */
4205 static void
4206 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
4207 {
4208     int		bus, target, i;
4209 
4210     if (ld->cl_lstatus == NULL) {
4211 	printf("does not exist\n");
4212 	return;
4213     }
4214 
4215     /* print drive status */
4216     switch(ld->cl_lstatus->status) {
4217     case CISS_LSTATUS_OK:
4218 	printf("online\n");
4219 	break;
4220     case CISS_LSTATUS_INTERIM_RECOVERY:
4221 	printf("in interim recovery mode\n");
4222 	break;
4223     case CISS_LSTATUS_READY_RECOVERY:
4224 	printf("ready to begin recovery\n");
4225 	break;
4226     case CISS_LSTATUS_RECOVERING:
4227 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4228 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4229 	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
4230 	       bus, target, ld->cl_lstatus->blocks_to_recover);
4231 	break;
4232     case CISS_LSTATUS_EXPANDING:
4233 	printf("being expanded, %u blocks remaining\n",
4234 	       ld->cl_lstatus->blocks_to_recover);
4235 	break;
4236     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4237 	printf("queued for expansion\n");
4238 	break;
4239     case CISS_LSTATUS_FAILED:
4240 	printf("queued for expansion\n");
4241 	break;
4242     case CISS_LSTATUS_WRONG_PDRIVE:
4243 	printf("wrong physical drive inserted\n");
4244 	break;
4245     case CISS_LSTATUS_MISSING_PDRIVE:
4246 	printf("missing a needed physical drive\n");
4247 	break;
4248     case CISS_LSTATUS_BECOMING_READY:
4249 	printf("becoming ready\n");
4250 	break;
4251     }
4252 
4253     /* print failed physical drives */
4254     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
4255 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
4256 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
4257 	if (bus == -1)
4258 	    continue;
4259 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
4260 		    ld->cl_lstatus->drive_failure_map[i]);
4261     }
4262 }
4263 
4264 #ifdef CISS_DEBUG
4265 /************************************************************************
4266  * Print information about the controller/driver.
4267  */
4268 static void
4269 ciss_print_adapter(struct ciss_softc *sc)
4270 {
4271     int		i, j;
4272 
4273     ciss_printf(sc, "ADAPTER:\n");
4274     for (i = 0; i < CISSQ_COUNT; i++) {
4275 	ciss_printf(sc, "%s     %d/%d\n",
4276 	    i == 0 ? "free" :
4277 	    i == 1 ? "busy" : "complete",
4278 	    sc->ciss_qstat[i].q_length,
4279 	    sc->ciss_qstat[i].q_max);
4280     }
4281     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
4282     ciss_printf(sc, "flags %b\n", sc->ciss_flags,
4283 	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
4284 
4285     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
4286 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
4287 	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
4288 	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
4289 	}
4290     }
4291 
4292     /* XXX Should physical drives be printed out here? */
4293 
4294     for (i = 1; i < sc->ciss_max_requests; i++)
4295 	ciss_print_request(sc->ciss_request + i);
4296 }
4297 
4298 /* DDB hook */
4299 static void
4300 ciss_print0(void)
4301 {
4302     struct ciss_softc	*sc;
4303 
4304     sc = devclass_get_softc(devclass_find("ciss"), 0);
4305     if (sc == NULL) {
4306 	printf("no ciss controllers\n");
4307     } else {
4308 	ciss_print_adapter(sc);
4309     }
4310 }
4311 #endif
4312 
4313 /************************************************************************
4314  * Return a name for a logical drive status value.
4315  */
4316 static const char *
4317 ciss_name_ldrive_status(int status)
4318 {
4319     switch (status) {
4320     case CISS_LSTATUS_OK:
4321 	return("OK");
4322     case CISS_LSTATUS_FAILED:
4323 	return("failed");
4324     case CISS_LSTATUS_NOT_CONFIGURED:
4325 	return("not configured");
4326     case CISS_LSTATUS_INTERIM_RECOVERY:
4327 	return("interim recovery");
4328     case CISS_LSTATUS_READY_RECOVERY:
4329 	return("ready for recovery");
4330     case CISS_LSTATUS_RECOVERING:
4331 	return("recovering");
4332     case CISS_LSTATUS_WRONG_PDRIVE:
4333 	return("wrong physical drive inserted");
4334     case CISS_LSTATUS_MISSING_PDRIVE:
4335 	return("missing physical drive");
4336     case CISS_LSTATUS_EXPANDING:
4337 	return("expanding");
4338     case CISS_LSTATUS_BECOMING_READY:
4339 	return("becoming ready");
4340     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4341 	return("queued for expansion");
4342     }
4343     return("unknown status");
4344 }
4345 
4346 /************************************************************************
4347  * Return an online/offline/nonexistent value for a logical drive
4348  * status value.
4349  */
4350 static int
4351 ciss_decode_ldrive_status(int status)
4352 {
4353     switch(status) {
4354     case CISS_LSTATUS_NOT_CONFIGURED:
4355 	return(CISS_LD_NONEXISTENT);
4356 
4357     case CISS_LSTATUS_OK:
4358     case CISS_LSTATUS_INTERIM_RECOVERY:
4359     case CISS_LSTATUS_READY_RECOVERY:
4360     case CISS_LSTATUS_RECOVERING:
4361     case CISS_LSTATUS_EXPANDING:
4362     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4363 	return(CISS_LD_ONLINE);
4364 
4365     case CISS_LSTATUS_FAILED:
4366     case CISS_LSTATUS_WRONG_PDRIVE:
4367     case CISS_LSTATUS_MISSING_PDRIVE:
4368     case CISS_LSTATUS_BECOMING_READY:
4369     default:
4370 	return(CISS_LD_OFFLINE);
4371     }
4372 }
4373 
4374 
4375 /************************************************************************
4376  * Return a name for a logical drive's organisation.
4377  */
4378 static const char *
4379 ciss_name_ldrive_org(int org)
4380 {
4381     switch(org) {
4382     case CISS_LDRIVE_RAID0:
4383 	return("RAID 0");
4384     case CISS_LDRIVE_RAID1:
4385 	return("RAID 1");
4386     case CISS_LDRIVE_RAID4:
4387 	return("RAID 4");
4388     case CISS_LDRIVE_RAID5:
4389 	return("RAID 5");
4390     case CISS_LDRIVE_RAID51:
4391 	return("RAID 5+1");
4392     case CISS_LDRIVE_RAIDADG:
4393 	return("RAID ADG");
4394     }
4395     return("unkown");
4396 }
4397 
4398 /************************************************************************
4399  * Return a name for a command status value.
4400  */
4401 static const char *
4402 ciss_name_command_status(int status)
4403 {
4404     switch(status) {
4405     case CISS_CMD_STATUS_SUCCESS:
4406 	return("success");
4407     case CISS_CMD_STATUS_TARGET_STATUS:
4408 	return("target status");
4409     case CISS_CMD_STATUS_DATA_UNDERRUN:
4410 	return("data underrun");
4411     case CISS_CMD_STATUS_DATA_OVERRUN:
4412 	return("data overrun");
4413     case CISS_CMD_STATUS_INVALID_COMMAND:
4414 	return("invalid command");
4415     case CISS_CMD_STATUS_PROTOCOL_ERROR:
4416 	return("protocol error");
4417     case CISS_CMD_STATUS_HARDWARE_ERROR:
4418 	return("hardware error");
4419     case CISS_CMD_STATUS_CONNECTION_LOST:
4420 	return("connection lost");
4421     case CISS_CMD_STATUS_ABORTED:
4422 	return("aborted");
4423     case CISS_CMD_STATUS_ABORT_FAILED:
4424 	return("abort failed");
4425     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
4426 	return("unsolicited abort");
4427     case CISS_CMD_STATUS_TIMEOUT:
4428 	return("timeout");
4429     case CISS_CMD_STATUS_UNABORTABLE:
4430 	return("unabortable");
4431     }
4432     return("unknown status");
4433 }
4434 
4435 /************************************************************************
4436  * Handle an open on the control device.
4437  */
4438 static int
4439 ciss_open(struct cdev *dev, int flags, int fmt, d_thread_t *p)
4440 {
4441     struct ciss_softc	*sc;
4442 
4443     debug_called(1);
4444 
4445     sc = (struct ciss_softc *)dev->si_drv1;
4446 
4447     /* we might want to veto if someone already has us open */
4448 
4449     mtx_lock(&sc->ciss_mtx);
4450     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
4451     mtx_unlock(&sc->ciss_mtx);
4452     return(0);
4453 }
4454 
4455 /************************************************************************
4456  * Handle the last close on the control device.
4457  */
4458 static int
4459 ciss_close(struct cdev *dev, int flags, int fmt, d_thread_t *p)
4460 {
4461     struct ciss_softc	*sc;
4462 
4463     debug_called(1);
4464 
4465     sc = (struct ciss_softc *)dev->si_drv1;
4466 
4467     mtx_lock(&sc->ciss_mtx);
4468     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
4469     mtx_unlock(&sc->ciss_mtx);
4470     return (0);
4471 }
4472 
4473 /********************************************************************************
4474  * Handle adapter-specific control operations.
4475  *
4476  * Note that the API here is compatible with the Linux driver, in order to
4477  * simplify the porting of Compaq's userland tools.
4478  */
4479 static int
4480 ciss_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *p)
4481 {
4482     struct ciss_softc		*sc;
4483     IOCTL_Command_struct	*ioc	= (IOCTL_Command_struct *)addr;
4484 #ifdef __amd64__
4485     IOCTL_Command_struct32	*ioc32	= (IOCTL_Command_struct32 *)addr;
4486     IOCTL_Command_struct	ioc_swab;
4487 #endif
4488     int				error;
4489 
4490     debug_called(1);
4491 
4492     sc = (struct ciss_softc *)dev->si_drv1;
4493     error = 0;
4494     mtx_lock(&sc->ciss_mtx);
4495 
4496     switch(cmd) {
4497     case CCISS_GETQSTATS:
4498     {
4499 	union ciss_statrequest *cr = (union ciss_statrequest *)addr;
4500 
4501 	switch (cr->cs_item) {
4502 	case CISSQ_FREE:
4503 	case CISSQ_NOTIFY:
4504 	    bcopy(&sc->ciss_qstat[cr->cs_item], &cr->cs_qstat,
4505 		sizeof(struct ciss_qstat));
4506 	    break;
4507 	default:
4508 	    error = ENOIOCTL;
4509 	    break;
4510 	}
4511 
4512 	break;
4513     }
4514 
4515     case CCISS_GETPCIINFO:
4516     {
4517 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4518 
4519 	pis->bus = pci_get_bus(sc->ciss_dev);
4520 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4521 	pis->board_id = pci_get_devid(sc->ciss_dev);
4522 
4523 	break;
4524     }
4525 
4526     case CCISS_GETINTINFO:
4527     {
4528 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4529 
4530 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4531 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4532 
4533 	break;
4534     }
4535 
4536     case CCISS_SETINTINFO:
4537     {
4538 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4539 
4540 	if ((cis->delay == 0) && (cis->count == 0)) {
4541 	    error = EINVAL;
4542 	    break;
4543 	}
4544 
4545 	/*
4546 	 * XXX apparently this is only safe if the controller is idle,
4547 	 *     we should suspend it before doing this.
4548 	 */
4549 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4550 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4551 
4552 	if (ciss_update_config(sc))
4553 	    error = EIO;
4554 
4555 	/* XXX resume the controller here */
4556 	break;
4557     }
4558 
4559     case CCISS_GETNODENAME:
4560 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4561 	      sizeof(NodeName_type));
4562 	break;
4563 
4564     case CCISS_SETNODENAME:
4565 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4566 	      sizeof(NodeName_type));
4567 	if (ciss_update_config(sc))
4568 	    error = EIO;
4569 	break;
4570 
4571     case CCISS_GETHEARTBEAT:
4572 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4573 	break;
4574 
4575     case CCISS_GETBUSTYPES:
4576 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4577 	break;
4578 
4579     case CCISS_GETFIRMVER:
4580 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4581 	      sizeof(FirmwareVer_type));
4582 	break;
4583 
4584     case CCISS_GETDRIVERVER:
4585 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4586 	break;
4587 
4588     case CCISS_REVALIDVOLS:
4589 	/*
4590 	 * This is a bit ugly; to do it "right" we really need
4591 	 * to find any disks that have changed, kick CAM off them,
4592 	 * then rescan only these disks.  It'd be nice if they
4593 	 * a) told us which disk(s) they were going to play with,
4594 	 * and b) which ones had arrived. 8(
4595 	 */
4596 	break;
4597 
4598 #ifdef __amd64__
4599     case CCISS_PASSTHRU32:
4600 	ioc_swab.LUN_info	= ioc32->LUN_info;
4601 	ioc_swab.Request	= ioc32->Request;
4602 	ioc_swab.error_info	= ioc32->error_info;
4603 	ioc_swab.buf_size	= ioc32->buf_size;
4604 	ioc_swab.buf		= (u_int8_t *)(uintptr_t)ioc32->buf;
4605 	ioc			= &ioc_swab;
4606 	/* FALLTHROUGH */
4607 #endif
4608 
4609     case CCISS_PASSTHRU:
4610 	error = ciss_user_command(sc, ioc);
4611 	break;
4612 
4613     default:
4614 	debug(0, "unknown ioctl 0x%lx", cmd);
4615 
4616 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4617 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4618 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4619 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4620 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4621 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4622 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4623 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4624 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4625 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4626 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4627 
4628 	error = ENOIOCTL;
4629 	break;
4630     }
4631 
4632     mtx_unlock(&sc->ciss_mtx);
4633     return(error);
4634 }
4635