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