xref: /freebsd/sys/dev/ciss/ciss.c (revision 8fa0b743820f61c661ba5f3ea0e3be0dc137910e)
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 static MALLOC_DEFINE(CISS_MALLOC_CLASS, "ciss_data",
109     "ciss internal data buffers");
110 
111 /* pci interface */
112 static int	ciss_lookup(device_t dev);
113 static int	ciss_probe(device_t dev);
114 static int	ciss_attach(device_t dev);
115 static int	ciss_detach(device_t dev);
116 static int	ciss_shutdown(device_t dev);
117 
118 /* (de)initialisation functions, control wrappers */
119 static int	ciss_init_pci(struct ciss_softc *sc);
120 static int	ciss_setup_msix(struct ciss_softc *sc);
121 static int	ciss_init_perf(struct ciss_softc *sc);
122 static int	ciss_wait_adapter(struct ciss_softc *sc);
123 static int	ciss_flush_adapter(struct ciss_softc *sc);
124 static int	ciss_init_requests(struct ciss_softc *sc);
125 static void	ciss_command_map_helper(void *arg, bus_dma_segment_t *segs,
126 					int nseg, int error);
127 static int	ciss_identify_adapter(struct ciss_softc *sc);
128 static int	ciss_init_logical(struct ciss_softc *sc);
129 static int	ciss_init_physical(struct ciss_softc *sc);
130 static int	ciss_filter_physical(struct ciss_softc *sc, struct ciss_lun_report *cll);
131 static int	ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld);
132 static int	ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld);
133 static int	ciss_update_config(struct ciss_softc *sc);
134 static int	ciss_accept_media(struct ciss_softc *sc, struct ciss_ldrive *ld);
135 static void	ciss_init_sysctl(struct ciss_softc *sc);
136 static void	ciss_soft_reset(struct ciss_softc *sc);
137 static void	ciss_free(struct ciss_softc *sc);
138 static void	ciss_spawn_notify_thread(struct ciss_softc *sc);
139 static void	ciss_kill_notify_thread(struct ciss_softc *sc);
140 
141 /* request submission/completion */
142 static int	ciss_start(struct ciss_request *cr);
143 static void	ciss_done(struct ciss_softc *sc, cr_qhead_t *qh);
144 static void	ciss_perf_done(struct ciss_softc *sc, cr_qhead_t *qh);
145 static void	ciss_intr(void *arg);
146 static void	ciss_perf_intr(void *arg);
147 static void	ciss_perf_msi_intr(void *arg);
148 static void	ciss_complete(struct ciss_softc *sc, cr_qhead_t *qh);
149 static int	_ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status, const char *func);
150 static int	ciss_synch_request(struct ciss_request *cr, int timeout);
151 static int	ciss_poll_request(struct ciss_request *cr, int timeout);
152 static int	ciss_wait_request(struct ciss_request *cr, int timeout);
153 #if 0
154 static int	ciss_abort_request(struct ciss_request *cr);
155 #endif
156 
157 /* request queueing */
158 static int	ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp);
159 static void	ciss_preen_command(struct ciss_request *cr);
160 static void 	ciss_release_request(struct ciss_request *cr);
161 
162 /* request helpers */
163 static int	ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
164 				      int opcode, void **bufp, size_t bufsize);
165 static int	ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc);
166 
167 /* DMA map/unmap */
168 static int	ciss_map_request(struct ciss_request *cr);
169 static void	ciss_request_map_helper(void *arg, bus_dma_segment_t *segs,
170 					int nseg, int error);
171 static void	ciss_unmap_request(struct ciss_request *cr);
172 
173 /* CAM interface */
174 static int	ciss_cam_init(struct ciss_softc *sc);
175 static void	ciss_cam_rescan_target(struct ciss_softc *sc,
176 				       int bus, int target);
177 static void	ciss_cam_action(struct cam_sim *sim, union ccb *ccb);
178 static int	ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio);
179 static int	ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio);
180 static void	ciss_cam_poll(struct cam_sim *sim);
181 static void	ciss_cam_complete(struct ciss_request *cr);
182 static void	ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio);
183 static struct cam_periph *ciss_find_periph(struct ciss_softc *sc,
184 					   int bus, int target);
185 static int	ciss_name_device(struct ciss_softc *sc, int bus, int target);
186 
187 /* periodic status monitoring */
188 static void	ciss_periodic(void *arg);
189 static void	ciss_nop_complete(struct ciss_request *cr);
190 static void	ciss_disable_adapter(struct ciss_softc *sc);
191 static void	ciss_notify_event(struct ciss_softc *sc);
192 static void	ciss_notify_complete(struct ciss_request *cr);
193 static int	ciss_notify_abort(struct ciss_softc *sc);
194 static int	ciss_notify_abort_bmic(struct ciss_softc *sc);
195 static void	ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn);
196 static void	ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn);
197 static void	ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn);
198 
199 /* debugging output */
200 static void	ciss_print_request(struct ciss_request *cr);
201 static void	ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld);
202 static const char *ciss_name_ldrive_status(int status);
203 static int	ciss_decode_ldrive_status(int status);
204 static const char *ciss_name_ldrive_org(int org);
205 static const char *ciss_name_command_status(int status);
206 
207 /*
208  * PCI bus interface.
209  */
210 static device_method_t ciss_methods[] = {
211     /* Device interface */
212     DEVMETHOD(device_probe,	ciss_probe),
213     DEVMETHOD(device_attach,	ciss_attach),
214     DEVMETHOD(device_detach,	ciss_detach),
215     DEVMETHOD(device_shutdown,	ciss_shutdown),
216     { 0, 0 }
217 };
218 
219 static driver_t ciss_pci_driver = {
220     "ciss",
221     ciss_methods,
222     sizeof(struct ciss_softc)
223 };
224 
225 static devclass_t	ciss_devclass;
226 DRIVER_MODULE(ciss, pci, ciss_pci_driver, ciss_devclass, 0, 0);
227 MODULE_DEPEND(ciss, cam, 1, 1, 1);
228 MODULE_DEPEND(ciss, pci, 1, 1, 1);
229 
230 /*
231  * Control device interface.
232  */
233 static d_open_t		ciss_open;
234 static d_close_t	ciss_close;
235 static d_ioctl_t	ciss_ioctl;
236 
237 static struct cdevsw ciss_cdevsw = {
238 	.d_version =	D_VERSION,
239 	.d_flags =	0,
240 	.d_open =	ciss_open,
241 	.d_close =	ciss_close,
242 	.d_ioctl =	ciss_ioctl,
243 	.d_name =	"ciss",
244 };
245 
246 /*
247  * This tunable can be set at boot time and controls whether physical devices
248  * that are marked hidden by the firmware should be exposed anyways.
249  */
250 static unsigned int ciss_expose_hidden_physical = 0;
251 TUNABLE_INT("hw.ciss.expose_hidden_physical", &ciss_expose_hidden_physical);
252 
253 static unsigned int ciss_nop_message_heartbeat = 0;
254 TUNABLE_INT("hw.ciss.nop_message_heartbeat", &ciss_nop_message_heartbeat);
255 
256 /*
257  * This tunable can force a particular transport to be used:
258  * <= 0 : use default
259  *    1 : force simple
260  *    2 : force performant
261  */
262 static int ciss_force_transport = 0;
263 TUNABLE_INT("hw.ciss.force_transport", &ciss_force_transport);
264 
265 /*
266  * This tunable can force a particular interrupt delivery method to be used:
267  * <= 0 : use default
268  *    1 : force INTx
269  *    2 : force MSIX
270  */
271 static int ciss_force_interrupt = 0;
272 TUNABLE_INT("hw.ciss.force_interrupt", &ciss_force_interrupt);
273 
274 /************************************************************************
275  * CISS adapters amazingly don't have a defined programming interface
276  * value.  (One could say some very despairing things about PCI and
277  * people just not getting the general idea.)  So we are forced to
278  * stick with matching against subvendor/subdevice, and thus have to
279  * be updated for every new CISS adapter that appears.
280  */
281 #define CISS_BOARD_UNKNWON	0
282 #define CISS_BOARD_SA5		1
283 #define CISS_BOARD_SA5B		2
284 #define CISS_BOARD_NOMSI	(1<<4)
285 
286 static struct
287 {
288     u_int16_t	subvendor;
289     u_int16_t	subdevice;
290     int		flags;
291     char	*desc;
292 } ciss_vendor_data[] = {
293     { 0x0e11, 0x4070, CISS_BOARD_SA5|CISS_BOARD_NOMSI,	"Compaq Smart Array 5300" },
294     { 0x0e11, 0x4080, CISS_BOARD_SA5B|CISS_BOARD_NOMSI,	"Compaq Smart Array 5i" },
295     { 0x0e11, 0x4082, CISS_BOARD_SA5B|CISS_BOARD_NOMSI,	"Compaq Smart Array 532" },
296     { 0x0e11, 0x4083, CISS_BOARD_SA5B|CISS_BOARD_NOMSI,	"HP Smart Array 5312" },
297     { 0x0e11, 0x4091, CISS_BOARD_SA5,	"HP Smart Array 6i" },
298     { 0x0e11, 0x409A, CISS_BOARD_SA5,	"HP Smart Array 641" },
299     { 0x0e11, 0x409B, CISS_BOARD_SA5,	"HP Smart Array 642" },
300     { 0x0e11, 0x409C, CISS_BOARD_SA5,	"HP Smart Array 6400" },
301     { 0x0e11, 0x409D, CISS_BOARD_SA5,	"HP Smart Array 6400 EM" },
302     { 0x103C, 0x3211, CISS_BOARD_SA5,	"HP Smart Array E200i" },
303     { 0x103C, 0x3212, CISS_BOARD_SA5,	"HP Smart Array E200" },
304     { 0x103C, 0x3213, CISS_BOARD_SA5,	"HP Smart Array E200i" },
305     { 0x103C, 0x3214, CISS_BOARD_SA5,	"HP Smart Array E200i" },
306     { 0x103C, 0x3215, CISS_BOARD_SA5,	"HP Smart Array E200i" },
307     { 0x103C, 0x3220, CISS_BOARD_SA5,	"HP Smart Array" },
308     { 0x103C, 0x3222, CISS_BOARD_SA5,	"HP Smart Array" },
309     { 0x103C, 0x3223, CISS_BOARD_SA5,	"HP Smart Array P800" },
310     { 0x103C, 0x3225, CISS_BOARD_SA5,	"HP Smart Array P600" },
311     { 0x103C, 0x3230, CISS_BOARD_SA5,	"HP Smart Array" },
312     { 0x103C, 0x3231, CISS_BOARD_SA5,	"HP Smart Array" },
313     { 0x103C, 0x3232, CISS_BOARD_SA5,	"HP Smart Array" },
314     { 0x103C, 0x3233, CISS_BOARD_SA5,	"HP Smart Array" },
315     { 0x103C, 0x3234, CISS_BOARD_SA5,	"HP Smart Array P400" },
316     { 0x103C, 0x3235, CISS_BOARD_SA5,	"HP Smart Array P400i" },
317     { 0x103C, 0x3236, CISS_BOARD_SA5,	"HP Smart Array" },
318     { 0x103C, 0x3237, CISS_BOARD_SA5,	"HP Smart Array E500" },
319     { 0x103C, 0x3238, CISS_BOARD_SA5,	"HP Smart Array" },
320     { 0x103C, 0x3239, CISS_BOARD_SA5,	"HP Smart Array" },
321     { 0x103C, 0x323A, CISS_BOARD_SA5,	"HP Smart Array" },
322     { 0x103C, 0x323B, CISS_BOARD_SA5,	"HP Smart Array" },
323     { 0x103C, 0x323C, CISS_BOARD_SA5,	"HP Smart Array" },
324     { 0x103C, 0x323D, CISS_BOARD_SA5,	"HP Smart Array P700m" },
325     { 0x103C, 0x3241, CISS_BOARD_SA5,	"HP Smart Array P212" },
326     { 0x103C, 0x3243, CISS_BOARD_SA5,	"HP Smart Array P410" },
327     { 0x103C, 0x3245, CISS_BOARD_SA5,	"HP Smart Array P410i" },
328     { 0x103C, 0x3247, CISS_BOARD_SA5,	"HP Smart Array P411" },
329     { 0x103C, 0x3249, CISS_BOARD_SA5,	"HP Smart Array P812" },
330     { 0x103C, 0x324A, CISS_BOARD_SA5,	"HP Smart Array P712m" },
331     { 0x103C, 0x324B, CISS_BOARD_SA5,	"HP Smart Array" },
332     { 0x103C, 0x3351, CISS_BOARD_SA5,	"HP Smart Array P420" },
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     callout_init_mtx(&sc->ciss_periodic, &sc->ciss_mtx, 0);
423 
424     /*
425      * Do PCI-specific init.
426      */
427     if ((error = ciss_init_pci(sc)) != 0)
428 	goto out;
429 
430     /*
431      * Initialise driver queues.
432      */
433     ciss_initq_free(sc);
434     ciss_initq_notify(sc);
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     scsi_ulto2b(sizeof(ld->cl_geometry), inq->length);
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 - 2)) == 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     return(0);
2867 }
2868 
2869 /************************************************************************
2870  * Initiate a rescan of the 'logical devices' SIM
2871  */
2872 static void
2873 ciss_cam_rescan_target(struct ciss_softc *sc, int bus, int target)
2874 {
2875     union ccb		*ccb;
2876 
2877     debug_called(1);
2878 
2879     if ((ccb = xpt_alloc_ccb_nowait()) == NULL) {
2880 	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2881 	return;
2882     }
2883 
2884     if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
2885 	    cam_sim_path(sc->ciss_cam_sim[bus]),
2886 	    target, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2887 	ciss_printf(sc, "rescan failed (can't create path)\n");
2888 	xpt_free_ccb(ccb);
2889 	return;
2890     }
2891     xpt_rescan(ccb);
2892     /* scan is now in progress */
2893 }
2894 
2895 /************************************************************************
2896  * Handle requests coming from CAM
2897  */
2898 static void
2899 ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2900 {
2901     struct ciss_softc	*sc;
2902     struct ccb_scsiio	*csio;
2903     int			bus, target;
2904     int			physical;
2905 
2906     sc = cam_sim_softc(sim);
2907     bus = cam_sim_bus(sim);
2908     csio = (struct ccb_scsiio *)&ccb->csio;
2909     target = csio->ccb_h.target_id;
2910     physical = CISS_IS_PHYSICAL(bus);
2911 
2912     switch (ccb->ccb_h.func_code) {
2913 
2914 	/* perform SCSI I/O */
2915     case XPT_SCSI_IO:
2916 	if (!ciss_cam_action_io(sim, csio))
2917 	    return;
2918 	break;
2919 
2920 	/* perform geometry calculations */
2921     case XPT_CALC_GEOMETRY:
2922     {
2923 	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2924 	struct ciss_ldrive		*ld;
2925 
2926 	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2927 
2928 	ld = NULL;
2929 	if (!physical)
2930 	    ld = &sc->ciss_logical[bus][target];
2931 
2932 	/*
2933 	 * Use the cached geometry settings unless the fault tolerance
2934 	 * is invalid.
2935 	 */
2936 	if (physical || ld->cl_geometry.fault_tolerance == 0xFF) {
2937 	    u_int32_t			secs_per_cylinder;
2938 
2939 	    ccg->heads = 255;
2940 	    ccg->secs_per_track = 32;
2941 	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2942 	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2943 	} else {
2944 	    ccg->heads = ld->cl_geometry.heads;
2945 	    ccg->secs_per_track = ld->cl_geometry.sectors;
2946 	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2947 	}
2948 	ccb->ccb_h.status = CAM_REQ_CMP;
2949         break;
2950     }
2951 
2952 	/* handle path attribute inquiry */
2953     case XPT_PATH_INQ:
2954     {
2955 	struct ccb_pathinq	*cpi = &ccb->cpi;
2956 
2957 	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2958 
2959 	cpi->version_num = 1;
2960 	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2961 	cpi->target_sprt = 0;
2962 	cpi->hba_misc = 0;
2963 	cpi->max_target = CISS_MAX_LOGICAL;
2964 	cpi->max_lun = 0;		/* 'logical drive' channel only */
2965 	cpi->initiator_id = CISS_MAX_LOGICAL;
2966 	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2967         strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2968         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2969         cpi->unit_number = cam_sim_unit(sim);
2970         cpi->bus_id = cam_sim_bus(sim);
2971 	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2972 	cpi->transport = XPORT_SPI;
2973 	cpi->transport_version = 2;
2974 	cpi->protocol = PROTO_SCSI;
2975 	cpi->protocol_version = SCSI_REV_2;
2976 	cpi->maxio = (CISS_MAX_SG_ELEMENTS - 1) * PAGE_SIZE;
2977 	ccb->ccb_h.status = CAM_REQ_CMP;
2978 	break;
2979     }
2980 
2981     case XPT_GET_TRAN_SETTINGS:
2982     {
2983 	struct ccb_trans_settings	*cts = &ccb->cts;
2984 	int				bus, target;
2985 	struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
2986 	struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
2987 
2988 	bus = cam_sim_bus(sim);
2989 	target = cts->ccb_h.target_id;
2990 
2991 	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2992 	/* disconnect always OK */
2993 	cts->protocol = PROTO_SCSI;
2994 	cts->protocol_version = SCSI_REV_2;
2995 	cts->transport = XPORT_SPI;
2996 	cts->transport_version = 2;
2997 
2998 	spi->valid = CTS_SPI_VALID_DISC;
2999 	spi->flags = CTS_SPI_FLAGS_DISC_ENB;
3000 
3001 	scsi->valid = CTS_SCSI_VALID_TQ;
3002 	scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3003 
3004 	cts->ccb_h.status = CAM_REQ_CMP;
3005 	break;
3006     }
3007 
3008     default:		/* we can't do this */
3009 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
3010 	ccb->ccb_h.status = CAM_REQ_INVALID;
3011 	break;
3012     }
3013 
3014     xpt_done(ccb);
3015 }
3016 
3017 /************************************************************************
3018  * Handle a CAM SCSI I/O request.
3019  */
3020 static int
3021 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
3022 {
3023     struct ciss_softc	*sc;
3024     int			bus, target;
3025     struct ciss_request	*cr;
3026     struct ciss_command	*cc;
3027     int			error;
3028 
3029     sc = cam_sim_softc(sim);
3030     bus = cam_sim_bus(sim);
3031     target = csio->ccb_h.target_id;
3032 
3033     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
3034 
3035     /* check that the CDB pointer is not to a physical address */
3036     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
3037 	debug(3, "  CDB pointer is to physical address");
3038 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
3039     }
3040 
3041     /* if there is data transfer, it must be to/from a virtual address */
3042     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
3043 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
3044 	    debug(3, "  data pointer is to physical address");
3045 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3046 	}
3047 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
3048 	    debug(3, "  data has premature s/g setup");
3049 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
3050 	}
3051     }
3052 
3053     /* abandon aborted ccbs or those that have failed validation */
3054     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3055 	debug(3, "abandoning CCB due to abort/validation failure");
3056 	return(EINVAL);
3057     }
3058 
3059     /* handle emulation of some SCSI commands ourself */
3060     if (ciss_cam_emulate(sc, csio))
3061 	return(0);
3062 
3063     /*
3064      * Get a request to manage this command.  If we can't, return the
3065      * ccb, freeze the queue and flag so that we unfreeze it when a
3066      * request completes.
3067      */
3068     if ((error = ciss_get_request(sc, &cr)) != 0) {
3069 	xpt_freeze_simq(sim, 1);
3070 	sc->ciss_flags |= CISS_FLAG_BUSY;
3071 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
3072 	return(error);
3073     }
3074 
3075     /*
3076      * Build the command.
3077      */
3078     cc = cr->cr_cc;
3079     cr->cr_data = csio->data_ptr;
3080     cr->cr_length = csio->dxfer_len;
3081     cr->cr_complete = ciss_cam_complete;
3082     cr->cr_private = csio;
3083 
3084     /*
3085      * Target the right logical volume.
3086      */
3087     if (CISS_IS_PHYSICAL(bus))
3088 	cc->header.address =
3089 	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
3090     else
3091 	cc->header.address =
3092 	    sc->ciss_logical[bus][target].cl_address;
3093     cc->cdb.cdb_length = csio->cdb_len;
3094     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3095     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
3096     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
3097 	cr->cr_flags = CISS_REQ_DATAOUT;
3098 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3099     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
3100 	cr->cr_flags = CISS_REQ_DATAIN;
3101 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3102     } else {
3103 	cr->cr_flags = 0;
3104 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
3105     }
3106     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
3107     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
3108 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
3109     } else {
3110 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
3111     }
3112 
3113     /*
3114      * Submit the request to the adapter.
3115      *
3116      * Note that this may fail if we're unable to map the request (and
3117      * if we ever learn a transport layer other than simple, may fail
3118      * if the adapter rejects the command).
3119      */
3120     if ((error = ciss_start(cr)) != 0) {
3121 	xpt_freeze_simq(sim, 1);
3122 	csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3123 	if (error == EINPROGRESS) {
3124 	    error = 0;
3125 	} else {
3126 	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
3127 	    ciss_release_request(cr);
3128 	}
3129 	return(error);
3130     }
3131 
3132     return(0);
3133 }
3134 
3135 /************************************************************************
3136  * Emulate SCSI commands the adapter doesn't handle as we might like.
3137  */
3138 static int
3139 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
3140 {
3141     int		bus, target;
3142     u_int8_t	opcode;
3143 
3144     target = csio->ccb_h.target_id;
3145     bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3146     opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3147 	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
3148 
3149     if (CISS_IS_PHYSICAL(bus)) {
3150 	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
3151 	    csio->ccb_h.status |= CAM_SEL_TIMEOUT;
3152 	    xpt_done((union ccb *)csio);
3153 	    return(1);
3154 	} else
3155 	    return(0);
3156     }
3157 
3158     /*
3159      * Handle requests for volumes that don't exist or are not online.
3160      * A selection timeout is slightly better than an illegal request.
3161      * Other errors might be better.
3162      */
3163     if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
3164 	csio->ccb_h.status |= CAM_SEL_TIMEOUT;
3165 	xpt_done((union ccb *)csio);
3166 	return(1);
3167     }
3168 
3169     /* if we have to fake Synchronise Cache */
3170     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
3171 	/*
3172 	 * If this is a Synchronise Cache command, typically issued when
3173 	 * a device is closed, flush the adapter and complete now.
3174 	 */
3175 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
3176 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
3177 	    ciss_flush_adapter(sc);
3178 	    csio->ccb_h.status |= CAM_REQ_CMP;
3179 	    xpt_done((union ccb *)csio);
3180 	    return(1);
3181 	}
3182     }
3183 
3184     return(0);
3185 }
3186 
3187 /************************************************************************
3188  * Check for possibly-completed commands.
3189  */
3190 static void
3191 ciss_cam_poll(struct cam_sim *sim)
3192 {
3193     cr_qhead_t qh;
3194     struct ciss_softc	*sc = cam_sim_softc(sim);
3195 
3196     debug_called(2);
3197 
3198     STAILQ_INIT(&qh);
3199     if (sc->ciss_perf)
3200 	ciss_perf_done(sc, &qh);
3201     else
3202 	ciss_done(sc, &qh);
3203     ciss_complete(sc, &qh);
3204 }
3205 
3206 /************************************************************************
3207  * Handle completion of a command - pass results back through the CCB
3208  */
3209 static void
3210 ciss_cam_complete(struct ciss_request *cr)
3211 {
3212     struct ciss_softc		*sc;
3213     struct ciss_command		*cc;
3214     struct ciss_error_info	*ce;
3215     struct ccb_scsiio		*csio;
3216     int				scsi_status;
3217     int				command_status;
3218 
3219     debug_called(2);
3220 
3221     sc = cr->cr_sc;
3222     cc = cr->cr_cc;
3223     ce = (struct ciss_error_info *)&(cc->sg[0]);
3224     csio = (struct ccb_scsiio *)cr->cr_private;
3225 
3226     /*
3227      * Extract status values from request.
3228      */
3229     ciss_report_request(cr, &command_status, &scsi_status);
3230     csio->scsi_status = scsi_status;
3231 
3232     /*
3233      * Handle specific SCSI status values.
3234      */
3235     switch(scsi_status) {
3236 	/* no status due to adapter error */
3237     case -1:
3238 	debug(0, "adapter error");
3239 	csio->ccb_h.status |= CAM_REQ_CMP_ERR;
3240 	break;
3241 
3242 	/* no status due to command completed OK */
3243     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
3244 	debug(2, "SCSI_STATUS_OK");
3245 	csio->ccb_h.status |= CAM_REQ_CMP;
3246 	break;
3247 
3248 	/* check condition, sense data included */
3249     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
3250 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
3251 	      ce->sense_length, ce->residual_count);
3252 	bzero(&csio->sense_data, SSD_FULL_SIZE);
3253 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
3254 	if (csio->sense_len > ce->sense_length)
3255 		csio->sense_resid = csio->sense_len - ce->sense_length;
3256 	else
3257 		csio->sense_resid = 0;
3258 	csio->resid = ce->residual_count;
3259 	csio->ccb_h.status |= CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
3260 #ifdef CISS_DEBUG
3261 	{
3262 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
3263 	    debug(0, "sense key %x", scsi_get_sense_key(sns, csio->sense_len -
3264 		  csio->sense_resid, /*show_errors*/ 1));
3265 	}
3266 #endif
3267 	break;
3268 
3269     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
3270 	debug(0, "SCSI_STATUS_BUSY");
3271 	csio->ccb_h.status |= CAM_SCSI_BUSY;
3272 	break;
3273 
3274     default:
3275 	debug(0, "unknown status 0x%x", csio->scsi_status);
3276 	csio->ccb_h.status |= CAM_REQ_CMP_ERR;
3277 	break;
3278     }
3279 
3280     /* handle post-command fixup */
3281     ciss_cam_complete_fixup(sc, csio);
3282 
3283     ciss_release_request(cr);
3284     if (sc->ciss_flags & CISS_FLAG_BUSY) {
3285 	sc->ciss_flags &= ~CISS_FLAG_BUSY;
3286 	if (csio->ccb_h.status & CAM_RELEASE_SIMQ)
3287 	    xpt_release_simq(xpt_path_sim(csio->ccb_h.path), 0);
3288 	else
3289 	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
3290     }
3291     xpt_done((union ccb *)csio);
3292 }
3293 
3294 /********************************************************************************
3295  * Fix up the result of some commands here.
3296  */
3297 static void
3298 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
3299 {
3300     struct scsi_inquiry_data	*inq;
3301     struct ciss_ldrive		*cl;
3302     uint8_t			*cdb;
3303     int				bus, target;
3304 
3305     cdb = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
3306 	 (uint8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes;
3307     if (cdb[0] == INQUIRY &&
3308 	(cdb[1] & SI_EVPD) == 0 &&
3309 	(csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN &&
3310 	csio->dxfer_len >= SHORT_INQUIRY_LENGTH) {
3311 
3312 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
3313 	target = csio->ccb_h.target_id;
3314 	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
3315 
3316 	/*
3317 	 * Don't let hard drives be seen by the DA driver.  They will still be
3318 	 * attached by the PASS driver.
3319 	 */
3320 	if (CISS_IS_PHYSICAL(bus)) {
3321 	    if (SID_TYPE(inq) == T_DIRECT)
3322 		inq->device = (inq->device & 0xe0) | T_NODEVICE;
3323 	    return;
3324 	}
3325 
3326 	cl = &sc->ciss_logical[bus][target];
3327 
3328 	padstr(inq->vendor, "COMPAQ", 8);
3329 	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
3330 	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
3331     }
3332 }
3333 
3334 
3335 /********************************************************************************
3336  * Find a peripheral attached at (target)
3337  */
3338 static struct cam_periph *
3339 ciss_find_periph(struct ciss_softc *sc, int bus, int target)
3340 {
3341     struct cam_periph	*periph;
3342     struct cam_path	*path;
3343     int			status;
3344 
3345     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
3346 			     target, 0);
3347     if (status == CAM_REQ_CMP) {
3348 	periph = cam_periph_find(path, NULL);
3349 	xpt_free_path(path);
3350     } else {
3351 	periph = NULL;
3352     }
3353     return(periph);
3354 }
3355 
3356 /********************************************************************************
3357  * Name the device at (target)
3358  *
3359  * XXX is this strictly correct?
3360  */
3361 static int
3362 ciss_name_device(struct ciss_softc *sc, int bus, int target)
3363 {
3364     struct cam_periph	*periph;
3365 
3366     if (CISS_IS_PHYSICAL(bus))
3367 	return (0);
3368     if ((periph = ciss_find_periph(sc, bus, target)) != NULL) {
3369 	sprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
3370 		periph->periph_name, periph->unit_number);
3371 	return(0);
3372     }
3373     sc->ciss_logical[bus][target].cl_name[0] = 0;
3374     return(ENOENT);
3375 }
3376 
3377 /************************************************************************
3378  * Periodic status monitoring.
3379  */
3380 static void
3381 ciss_periodic(void *arg)
3382 {
3383     struct ciss_softc	*sc;
3384     struct ciss_request	*cr = NULL;
3385     struct ciss_command	*cc = NULL;
3386     int			error = 0;
3387 
3388     debug_called(1);
3389 
3390     sc = (struct ciss_softc *)arg;
3391 
3392     /*
3393      * Check the adapter heartbeat.
3394      */
3395     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
3396 	sc->ciss_heart_attack++;
3397 	debug(0, "adapter heart attack in progress 0x%x/%d",
3398 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
3399 	if (sc->ciss_heart_attack == 3) {
3400 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
3401 	    ciss_disable_adapter(sc);
3402 	    return;
3403 	}
3404     } else {
3405 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
3406 	sc->ciss_heart_attack = 0;
3407 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
3408     }
3409 
3410     /*
3411      * Send the NOP message and wait for a response.
3412      */
3413     if (ciss_nop_message_heartbeat != 0 && (error = ciss_get_request(sc, &cr)) == 0) {
3414 	cc = cr->cr_cc;
3415 	cr->cr_complete = ciss_nop_complete;
3416 	cc->cdb.cdb_length = 1;
3417 	cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
3418 	cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3419 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
3420 	cc->cdb.timeout = 0;
3421 	cc->cdb.cdb[0] = CISS_OPCODE_MESSAGE_NOP;
3422 
3423 	if ((error = ciss_start(cr)) != 0) {
3424 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED\n");
3425 	}
3426     }
3427 
3428     /*
3429      * If the notify event request has died for some reason, or has
3430      * not started yet, restart it.
3431      */
3432     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
3433 	debug(0, "(re)starting Event Notify chain");
3434 	ciss_notify_event(sc);
3435     }
3436 
3437     /*
3438      * Reschedule.
3439      */
3440     callout_reset(&sc->ciss_periodic, CISS_HEARTBEAT_RATE * hz, ciss_periodic, sc);
3441 }
3442 
3443 static void
3444 ciss_nop_complete(struct ciss_request *cr)
3445 {
3446     struct ciss_softc		*sc;
3447     static int			first_time = 1;
3448 
3449     sc = cr->cr_sc;
3450     if (ciss_report_request(cr, NULL, NULL) != 0) {
3451 	if (first_time == 1) {
3452 	    first_time = 0;
3453 	    ciss_printf(sc, "SENDING NOP MESSAGE FAILED (not logging anymore)\n");
3454 	}
3455     }
3456 
3457     ciss_release_request(cr);
3458 }
3459 
3460 /************************************************************************
3461  * Disable the adapter.
3462  *
3463  * The all requests in completed queue is failed with hardware error.
3464  * This will cause failover in a multipath configuration.
3465  */
3466 static void
3467 ciss_disable_adapter(struct ciss_softc *sc)
3468 {
3469     cr_qhead_t			qh;
3470     struct ciss_request		*cr;
3471     struct ciss_command		*cc;
3472     struct ciss_error_info	*ce;
3473     int				i;
3474 
3475     CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
3476     pci_disable_busmaster(sc->ciss_dev);
3477     sc->ciss_flags &= ~CISS_FLAG_RUNNING;
3478 
3479     for (i = 1; i < sc->ciss_max_requests; i++) {
3480 	cr = &sc->ciss_request[i];
3481 	if ((cr->cr_flags & CISS_REQ_BUSY) == 0)
3482 	    continue;
3483 
3484 	cc = cr->cr_cc;
3485 	ce = (struct ciss_error_info *)&(cc->sg[0]);
3486 	ce->command_status = CISS_CMD_STATUS_HARDWARE_ERROR;
3487 	ciss_enqueue_complete(cr, &qh);
3488     }
3489 
3490     for (;;) {
3491 	if ((cr = ciss_dequeue_complete(sc, &qh)) == NULL)
3492 	    break;
3493 
3494 	/*
3495 	 * If the request has a callback, invoke it.
3496 	 */
3497 	if (cr->cr_complete != NULL) {
3498 	    cr->cr_complete(cr);
3499 	    continue;
3500 	}
3501 
3502 	/*
3503 	 * If someone is sleeping on this request, wake them up.
3504 	 */
3505 	if (cr->cr_flags & CISS_REQ_SLEEP) {
3506 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
3507 	    wakeup(cr);
3508 	    continue;
3509 	}
3510     }
3511 }
3512 
3513 /************************************************************************
3514  * Request a notification response from the adapter.
3515  *
3516  * If (cr) is NULL, this is the first request of the adapter, so
3517  * reset the adapter's message pointer and start with the oldest
3518  * message available.
3519  */
3520 static void
3521 ciss_notify_event(struct ciss_softc *sc)
3522 {
3523     struct ciss_request		*cr;
3524     struct ciss_command		*cc;
3525     struct ciss_notify_cdb	*cnc;
3526     int				error;
3527 
3528     debug_called(1);
3529 
3530     cr = sc->ciss_periodic_notify;
3531 
3532     /* get a request if we don't already have one */
3533     if (cr == NULL) {
3534 	if ((error = ciss_get_request(sc, &cr)) != 0) {
3535 	    debug(0, "can't get notify event request");
3536 	    goto out;
3537 	}
3538 	sc->ciss_periodic_notify = cr;
3539 	cr->cr_complete = ciss_notify_complete;
3540 	debug(1, "acquired request %d", cr->cr_tag);
3541     }
3542 
3543     /*
3544      * Get a databuffer if we don't already have one, note that the
3545      * adapter command wants a larger buffer than the actual
3546      * structure.
3547      */
3548     if (cr->cr_data == NULL) {
3549 	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3550 	    debug(0, "can't get notify event request buffer");
3551 	    error = ENOMEM;
3552 	    goto out;
3553 	}
3554 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3555     }
3556 
3557     /* re-setup the request's command (since we never release it) XXX overkill*/
3558     ciss_preen_command(cr);
3559 
3560     /* (re)build the notify event command */
3561     cc = cr->cr_cc;
3562     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3563     cc->header.address.physical.bus = 0;
3564     cc->header.address.physical.target = 0;
3565 
3566     cc->cdb.cdb_length = sizeof(*cnc);
3567     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3568     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3569     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3570     cc->cdb.timeout = 0;	/* no timeout, we hope */
3571 
3572     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3573     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3574     cnc->opcode = CISS_OPCODE_READ;
3575     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3576     cnc->timeout = 0;		/* no timeout, we hope */
3577     cnc->synchronous = 0;
3578     cnc->ordered = 0;
3579     cnc->seek_to_oldest = 0;
3580     if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3581 	cnc->new_only = 1;
3582     else
3583 	cnc->new_only = 0;
3584     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3585 
3586     /* submit the request */
3587     error = ciss_start(cr);
3588 
3589  out:
3590     if (error) {
3591 	if (cr != NULL) {
3592 	    if (cr->cr_data != NULL)
3593 		free(cr->cr_data, CISS_MALLOC_CLASS);
3594 	    ciss_release_request(cr);
3595 	}
3596 	sc->ciss_periodic_notify = NULL;
3597 	debug(0, "can't submit notify event request");
3598 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3599     } else {
3600 	debug(1, "notify event submitted");
3601 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3602     }
3603 }
3604 
3605 static void
3606 ciss_notify_complete(struct ciss_request *cr)
3607 {
3608     struct ciss_command	*cc;
3609     struct ciss_notify	*cn;
3610     struct ciss_softc	*sc;
3611     int			scsi_status;
3612     int			command_status;
3613     debug_called(1);
3614 
3615     cc = cr->cr_cc;
3616     cn = (struct ciss_notify *)cr->cr_data;
3617     sc = cr->cr_sc;
3618 
3619     /*
3620      * Report request results, decode status.
3621      */
3622     ciss_report_request(cr, &command_status, &scsi_status);
3623 
3624     /*
3625      * Abort the chain on a fatal error.
3626      *
3627      * XXX which of these are actually errors?
3628      */
3629     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3630 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3631 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3632 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3633 		    ciss_name_command_status(command_status));
3634 	ciss_release_request(cr);
3635 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3636 	return;
3637     }
3638 
3639     /*
3640      * If the adapter gave us a text message, print it.
3641      */
3642     if (cn->message[0] != 0)
3643 	ciss_printf(sc, "*** %.80s\n", cn->message);
3644 
3645     debug(0, "notify event class %d subclass %d detail %d",
3646 		cn->class, cn->subclass, cn->detail);
3647 
3648     /*
3649      * If the response indicates that the notifier has been aborted,
3650      * release the notifier command.
3651      */
3652     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3653 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3654 	(cn->detail == 1)) {
3655 	debug(0, "notifier exiting");
3656 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3657 	ciss_release_request(cr);
3658 	sc->ciss_periodic_notify = NULL;
3659 	wakeup(&sc->ciss_periodic_notify);
3660     } else {
3661 	/* Handle notify events in a kernel thread */
3662 	ciss_enqueue_notify(cr);
3663 	sc->ciss_periodic_notify = NULL;
3664 	wakeup(&sc->ciss_periodic_notify);
3665 	wakeup(&sc->ciss_notify);
3666     }
3667     /*
3668      * Send a new notify event command, if we're not aborting.
3669      */
3670     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3671 	ciss_notify_event(sc);
3672     }
3673 }
3674 
3675 /************************************************************************
3676  * Abort the Notify Event chain.
3677  *
3678  * Note that we can't just abort the command in progress; we have to
3679  * explicitly issue an Abort Notify Event command in order for the
3680  * adapter to clean up correctly.
3681  *
3682  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3683  * the chain will not restart itself.
3684  */
3685 static int
3686 ciss_notify_abort(struct ciss_softc *sc)
3687 {
3688     struct ciss_request		*cr;
3689     struct ciss_command		*cc;
3690     struct ciss_notify_cdb	*cnc;
3691     int				error, command_status, scsi_status;
3692 
3693     debug_called(1);
3694 
3695     cr = NULL;
3696     error = 0;
3697 
3698     /* verify that there's an outstanding command */
3699     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3700 	goto out;
3701 
3702     /* get a command to issue the abort with */
3703     if ((error = ciss_get_request(sc, &cr)))
3704 	goto out;
3705 
3706     /* get a buffer for the result */
3707     if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3708 	debug(0, "can't get notify event request buffer");
3709 	error = ENOMEM;
3710 	goto out;
3711     }
3712     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3713 
3714     /* build the CDB */
3715     cc = cr->cr_cc;
3716     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3717     cc->header.address.physical.bus = 0;
3718     cc->header.address.physical.target = 0;
3719     cc->cdb.cdb_length = sizeof(*cnc);
3720     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3721     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3722     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3723     cc->cdb.timeout = 0;	/* no timeout, we hope */
3724 
3725     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3726     bzero(cnc, sizeof(*cnc));
3727     cnc->opcode = CISS_OPCODE_WRITE;
3728     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3729     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3730 
3731     ciss_print_request(cr);
3732 
3733     /*
3734      * Submit the request and wait for it to complete.
3735      */
3736     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3737 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3738 	goto out;
3739     }
3740 
3741     /*
3742      * Check response.
3743      */
3744     ciss_report_request(cr, &command_status, &scsi_status);
3745     switch(command_status) {
3746     case CISS_CMD_STATUS_SUCCESS:
3747 	break;
3748     case CISS_CMD_STATUS_INVALID_COMMAND:
3749 	/*
3750 	 * Some older adapters don't support the CISS version of this
3751 	 * command.  Fall back to using the BMIC version.
3752 	 */
3753 	error = ciss_notify_abort_bmic(sc);
3754 	if (error != 0)
3755 	    goto out;
3756 	break;
3757 
3758     case CISS_CMD_STATUS_TARGET_STATUS:
3759 	/*
3760 	 * This can happen if the adapter thinks there wasn't an outstanding
3761 	 * Notify Event command but we did.  We clean up here.
3762 	 */
3763 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3764 	    if (sc->ciss_periodic_notify != NULL)
3765 		ciss_release_request(sc->ciss_periodic_notify);
3766 	    error = 0;
3767 	    goto out;
3768 	}
3769 	/* FALLTHROUGH */
3770 
3771     default:
3772 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3773 		    ciss_name_command_status(command_status));
3774 	error = EIO;
3775 	goto out;
3776     }
3777 
3778     /*
3779      * Sleep waiting for the notifier command to complete.  Note
3780      * that if it doesn't, we may end up in a bad situation, since
3781      * the adapter may deliver it later.  Also note that the adapter
3782      * requires the Notify Event command to be cancelled in order to
3783      * maintain internal bookkeeping.
3784      */
3785     while (sc->ciss_periodic_notify != NULL) {
3786 	error = msleep(&sc->ciss_periodic_notify, &sc->ciss_mtx, PRIBIO, "cissNEA", hz * 5);
3787 	if (error == EWOULDBLOCK) {
3788 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3789 	    break;
3790 	}
3791     }
3792 
3793  out:
3794     /* release the cancel request */
3795     if (cr != NULL) {
3796 	if (cr->cr_data != NULL)
3797 	    free(cr->cr_data, CISS_MALLOC_CLASS);
3798 	ciss_release_request(cr);
3799     }
3800     if (error == 0)
3801 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3802     return(error);
3803 }
3804 
3805 /************************************************************************
3806  * Abort the Notify Event chain using a BMIC command.
3807  */
3808 static int
3809 ciss_notify_abort_bmic(struct ciss_softc *sc)
3810 {
3811     struct ciss_request			*cr;
3812     int					error, command_status;
3813 
3814     debug_called(1);
3815 
3816     cr = NULL;
3817     error = 0;
3818 
3819     /* verify that there's an outstanding command */
3820     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3821 	goto out;
3822 
3823     /*
3824      * Build a BMIC command to cancel the Notify on Event command.
3825      *
3826      * Note that we are sending a CISS opcode here.  Odd.
3827      */
3828     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3829 				       NULL, 0)) != 0)
3830 	goto out;
3831 
3832     /*
3833      * Submit the request and wait for it to complete.
3834      */
3835     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3836 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3837 	goto out;
3838     }
3839 
3840     /*
3841      * Check response.
3842      */
3843     ciss_report_request(cr, &command_status, NULL);
3844     switch(command_status) {
3845     case CISS_CMD_STATUS_SUCCESS:
3846 	break;
3847     default:
3848 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3849 		    ciss_name_command_status(command_status));
3850 	error = EIO;
3851 	goto out;
3852     }
3853 
3854 out:
3855     if (cr != NULL)
3856 	ciss_release_request(cr);
3857     return(error);
3858 }
3859 
3860 /************************************************************************
3861  * Handle rescanning all the logical volumes when a notify event
3862  * causes the drives to come online or offline.
3863  */
3864 static void
3865 ciss_notify_rescan_logical(struct ciss_softc *sc)
3866 {
3867     struct ciss_lun_report      *cll;
3868     struct ciss_ldrive		*ld;
3869     int                         i, j, ndrives;
3870 
3871     /*
3872      * We must rescan all logical volumes to get the right logical
3873      * drive address.
3874      */
3875     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3876                            CISS_MAX_LOGICAL);
3877     if (cll == NULL)
3878         return;
3879 
3880     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3881 
3882     /*
3883      * Delete any of the drives which were destroyed by the
3884      * firmware.
3885      */
3886     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3887 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3888 	    ld = &sc->ciss_logical[i][j];
3889 
3890 	    if (ld->cl_update == 0)
3891 		continue;
3892 
3893 	    if (ld->cl_status != CISS_LD_ONLINE) {
3894 		ciss_cam_rescan_target(sc, i, j);
3895 		ld->cl_update = 0;
3896 		if (ld->cl_ldrive)
3897 		    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
3898 		if (ld->cl_lstatus)
3899 		    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
3900 
3901 		ld->cl_ldrive = NULL;
3902 		ld->cl_lstatus = NULL;
3903 	    }
3904 	}
3905     }
3906 
3907     /*
3908      * Scan for new drives.
3909      */
3910     for (i = 0; i < ndrives; i++) {
3911 	int	bus, target;
3912 
3913 	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3914 	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3915 	ld	= &sc->ciss_logical[bus][target];
3916 
3917 	if (ld->cl_update == 0)
3918 		continue;
3919 
3920 	ld->cl_update		= 0;
3921 	ld->cl_address		= cll->lun[i];
3922 	ld->cl_controller	= &sc->ciss_controllers[bus];
3923 	if (ciss_identify_logical(sc, ld) == 0) {
3924 	    ciss_cam_rescan_target(sc, bus, target);
3925 	}
3926     }
3927     free(cll, CISS_MALLOC_CLASS);
3928 }
3929 
3930 /************************************************************************
3931  * Handle a notify event relating to the status of a logical drive.
3932  *
3933  * XXX need to be able to defer some of these to properly handle
3934  *     calling the "ID Physical drive" command, unless the 'extended'
3935  *     drive IDs are always in BIG_MAP format.
3936  */
3937 static void
3938 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3939 {
3940     struct ciss_ldrive	*ld;
3941     int			ostatus, bus, target;
3942 
3943     debug_called(2);
3944 
3945     bus		= cn->device.physical.bus;
3946     target	= cn->data.logical_status.logical_drive;
3947     ld		= &sc->ciss_logical[bus][target];
3948 
3949     switch (cn->subclass) {
3950     case CISS_NOTIFY_LOGICAL_STATUS:
3951 	switch (cn->detail) {
3952 	case 0:
3953 	    ciss_name_device(sc, bus, target);
3954 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3955 			cn->data.logical_status.logical_drive, ld->cl_name,
3956 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3957 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3958 			cn->data.logical_status.spare_state,
3959 			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3960 
3961 	    /*
3962 	     * Update our idea of the drive's status.
3963 	     */
3964 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3965 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3966 	    if (ld->cl_lstatus != NULL)
3967 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3968 
3969 	    /*
3970 	     * Have CAM rescan the drive if its status has changed.
3971 	     */
3972 	    if (ostatus != ld->cl_status) {
3973 		ld->cl_update = 1;
3974 		ciss_notify_rescan_logical(sc);
3975 	    }
3976 
3977 	    break;
3978 
3979 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3980 	    ciss_name_device(sc, bus, target);
3981 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3982 			cn->data.logical_status.logical_drive, ld->cl_name);
3983 	    ciss_accept_media(sc, ld);
3984 
3985 	    ld->cl_update = 1;
3986 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3987 	    ciss_notify_rescan_logical(sc);
3988 	    break;
3989 
3990 	case 2:
3991 	case 3:
3992 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3993 			cn->data.rebuild_aborted.logical_drive,
3994 			ld->cl_name,
3995 			(cn->detail == 2) ? "read" : "write");
3996 	    break;
3997 	}
3998 	break;
3999 
4000     case CISS_NOTIFY_LOGICAL_ERROR:
4001 	if (cn->detail == 0) {
4002 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
4003 			cn->data.io_error.logical_drive,
4004 			ld->cl_name,
4005 			cn->data.io_error.failure_bus,
4006 			cn->data.io_error.failure_drive);
4007 	    /* XXX should we take the drive down at this point, or will we be told? */
4008 	}
4009 	break;
4010 
4011     case CISS_NOTIFY_LOGICAL_SURFACE:
4012 	if (cn->detail == 0)
4013 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
4014 			cn->data.consistency_completed.logical_drive,
4015 			ld->cl_name);
4016 	break;
4017     }
4018 }
4019 
4020 /************************************************************************
4021  * Handle a notify event relating to the status of a physical drive.
4022  */
4023 static void
4024 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
4025 {
4026 }
4027 
4028 /************************************************************************
4029  * Handle a notify event relating to the status of a physical drive.
4030  */
4031 static void
4032 ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
4033 {
4034     struct ciss_lun_report *cll = NULL;
4035     int bus, target;
4036 
4037     switch (cn->subclass) {
4038     case CISS_NOTIFY_HOTPLUG_PHYSICAL:
4039     case CISS_NOTIFY_HOTPLUG_NONDISK:
4040 	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
4041 	target =
4042 	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
4043 
4044 	if (cn->detail == 0) {
4045 	    /*
4046 	     * Mark the device offline so that it'll start producing selection
4047 	     * timeouts to the upper layer.
4048 	     */
4049 	    if ((bus >= 0) && (target >= 0))
4050 		sc->ciss_physical[bus][target].cp_online = 0;
4051 	} else {
4052 	    /*
4053 	     * Rescan the physical lun list for new items
4054 	     */
4055 	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
4056 				   CISS_MAX_PHYSICAL);
4057 	    if (cll == NULL) {
4058 		ciss_printf(sc, "Warning, cannot get physical lun list\n");
4059 		break;
4060 	    }
4061 	    ciss_filter_physical(sc, cll);
4062 	}
4063 	break;
4064 
4065     default:
4066 	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
4067 	return;
4068     }
4069 
4070     if (cll != NULL)
4071 	free(cll, CISS_MALLOC_CLASS);
4072 }
4073 
4074 /************************************************************************
4075  * Handle deferred processing of notify events.  Notify events may need
4076  * sleep which is unsafe during an interrupt.
4077  */
4078 static void
4079 ciss_notify_thread(void *arg)
4080 {
4081     struct ciss_softc		*sc;
4082     struct ciss_request		*cr;
4083     struct ciss_notify		*cn;
4084 
4085     sc = (struct ciss_softc *)arg;
4086 #if __FreeBSD_version >= 500000
4087     mtx_lock(&sc->ciss_mtx);
4088 #endif
4089 
4090     for (;;) {
4091 	if (STAILQ_EMPTY(&sc->ciss_notify) != 0 &&
4092 	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
4093 	    msleep(&sc->ciss_notify, &sc->ciss_mtx, PUSER, "idle", 0);
4094 	}
4095 
4096 	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
4097 	    break;
4098 
4099 	cr = ciss_dequeue_notify(sc);
4100 
4101 	if (cr == NULL)
4102 		panic("cr null");
4103 	cn = (struct ciss_notify *)cr->cr_data;
4104 
4105 	switch (cn->class) {
4106 	case CISS_NOTIFY_HOTPLUG:
4107 	    ciss_notify_hotplug(sc, cn);
4108 	    break;
4109 	case CISS_NOTIFY_LOGICAL:
4110 	    ciss_notify_logical(sc, cn);
4111 	    break;
4112 	case CISS_NOTIFY_PHYSICAL:
4113 	    ciss_notify_physical(sc, cn);
4114 	    break;
4115 	}
4116 
4117 	ciss_release_request(cr);
4118 
4119     }
4120     sc->ciss_notify_thread = NULL;
4121     wakeup(&sc->ciss_notify_thread);
4122 
4123 #if __FreeBSD_version >= 500000
4124     mtx_unlock(&sc->ciss_mtx);
4125 #endif
4126     kproc_exit(0);
4127 }
4128 
4129 /************************************************************************
4130  * Start the notification kernel thread.
4131  */
4132 static void
4133 ciss_spawn_notify_thread(struct ciss_softc *sc)
4134 {
4135 
4136 #if __FreeBSD_version > 500005
4137     if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4138 		       &sc->ciss_notify_thread, 0, 0, "ciss_notify%d",
4139 		       device_get_unit(sc->ciss_dev)))
4140 #else
4141     if (kproc_create((void(*)(void *))ciss_notify_thread, sc,
4142 		       &sc->ciss_notify_thread, "ciss_notify%d",
4143 		       device_get_unit(sc->ciss_dev)))
4144 #endif
4145 	panic("Could not create notify thread\n");
4146 }
4147 
4148 /************************************************************************
4149  * Kill the notification kernel thread.
4150  */
4151 static void
4152 ciss_kill_notify_thread(struct ciss_softc *sc)
4153 {
4154 
4155     if (sc->ciss_notify_thread == NULL)
4156 	return;
4157 
4158     sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
4159     wakeup(&sc->ciss_notify);
4160     msleep(&sc->ciss_notify_thread, &sc->ciss_mtx, PUSER, "thtrm", 0);
4161 }
4162 
4163 /************************************************************************
4164  * Print a request.
4165  */
4166 static void
4167 ciss_print_request(struct ciss_request *cr)
4168 {
4169     struct ciss_softc	*sc;
4170     struct ciss_command	*cc;
4171     int			i;
4172 
4173     sc = cr->cr_sc;
4174     cc = cr->cr_cc;
4175 
4176     ciss_printf(sc, "REQUEST @ %p\n", cr);
4177     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
4178 	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
4179 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
4180     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
4181 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
4182     switch(cc->header.address.mode.mode) {
4183     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
4184     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
4185 	ciss_printf(sc, "  physical bus %d target %d\n",
4186 		    cc->header.address.physical.bus, cc->header.address.physical.target);
4187 	break;
4188     case CISS_HDR_ADDRESS_MODE_LOGICAL:
4189 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
4190 	break;
4191     }
4192     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
4193 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
4194 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
4195 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
4196 		cc->cdb.cdb_length,
4197 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
4198 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
4199 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
4200 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
4201 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
4202 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
4203 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
4204     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
4205 
4206     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
4207 	/* XXX print error info */
4208     } else {
4209 	/* since we don't use chained s/g, don't support it here */
4210 	for (i = 0; i < cc->header.sg_in_list; i++) {
4211 	    if ((i % 4) == 0)
4212 		ciss_printf(sc, "   ");
4213 	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
4214 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
4215 		printf("\n");
4216 	}
4217     }
4218 }
4219 
4220 /************************************************************************
4221  * Print information about the status of a logical drive.
4222  */
4223 static void
4224 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
4225 {
4226     int		bus, target, i;
4227 
4228     if (ld->cl_lstatus == NULL) {
4229 	printf("does not exist\n");
4230 	return;
4231     }
4232 
4233     /* print drive status */
4234     switch(ld->cl_lstatus->status) {
4235     case CISS_LSTATUS_OK:
4236 	printf("online\n");
4237 	break;
4238     case CISS_LSTATUS_INTERIM_RECOVERY:
4239 	printf("in interim recovery mode\n");
4240 	break;
4241     case CISS_LSTATUS_READY_RECOVERY:
4242 	printf("ready to begin recovery\n");
4243 	break;
4244     case CISS_LSTATUS_RECOVERING:
4245 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4246 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
4247 	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
4248 	       bus, target, ld->cl_lstatus->blocks_to_recover);
4249 	break;
4250     case CISS_LSTATUS_EXPANDING:
4251 	printf("being expanded, %u blocks remaining\n",
4252 	       ld->cl_lstatus->blocks_to_recover);
4253 	break;
4254     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4255 	printf("queued for expansion\n");
4256 	break;
4257     case CISS_LSTATUS_FAILED:
4258 	printf("queued for expansion\n");
4259 	break;
4260     case CISS_LSTATUS_WRONG_PDRIVE:
4261 	printf("wrong physical drive inserted\n");
4262 	break;
4263     case CISS_LSTATUS_MISSING_PDRIVE:
4264 	printf("missing a needed physical drive\n");
4265 	break;
4266     case CISS_LSTATUS_BECOMING_READY:
4267 	printf("becoming ready\n");
4268 	break;
4269     }
4270 
4271     /* print failed physical drives */
4272     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
4273 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
4274 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
4275 	if (bus == -1)
4276 	    continue;
4277 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
4278 		    ld->cl_lstatus->drive_failure_map[i]);
4279     }
4280 }
4281 
4282 #ifdef CISS_DEBUG
4283 /************************************************************************
4284  * Print information about the controller/driver.
4285  */
4286 static void
4287 ciss_print_adapter(struct ciss_softc *sc)
4288 {
4289     int		i, j;
4290 
4291     ciss_printf(sc, "ADAPTER:\n");
4292     for (i = 0; i < CISSQ_COUNT; i++) {
4293 	ciss_printf(sc, "%s     %d/%d\n",
4294 	    i == 0 ? "free" :
4295 	    i == 1 ? "busy" : "complete",
4296 	    sc->ciss_qstat[i].q_length,
4297 	    sc->ciss_qstat[i].q_max);
4298     }
4299     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
4300     ciss_printf(sc, "flags %b\n", sc->ciss_flags,
4301 	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
4302 
4303     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
4304 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
4305 	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
4306 	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
4307 	}
4308     }
4309 
4310     /* XXX Should physical drives be printed out here? */
4311 
4312     for (i = 1; i < sc->ciss_max_requests; i++)
4313 	ciss_print_request(sc->ciss_request + i);
4314 }
4315 
4316 /* DDB hook */
4317 static void
4318 ciss_print0(void)
4319 {
4320     struct ciss_softc	*sc;
4321 
4322     sc = devclass_get_softc(devclass_find("ciss"), 0);
4323     if (sc == NULL) {
4324 	printf("no ciss controllers\n");
4325     } else {
4326 	ciss_print_adapter(sc);
4327     }
4328 }
4329 #endif
4330 
4331 /************************************************************************
4332  * Return a name for a logical drive status value.
4333  */
4334 static const char *
4335 ciss_name_ldrive_status(int status)
4336 {
4337     switch (status) {
4338     case CISS_LSTATUS_OK:
4339 	return("OK");
4340     case CISS_LSTATUS_FAILED:
4341 	return("failed");
4342     case CISS_LSTATUS_NOT_CONFIGURED:
4343 	return("not configured");
4344     case CISS_LSTATUS_INTERIM_RECOVERY:
4345 	return("interim recovery");
4346     case CISS_LSTATUS_READY_RECOVERY:
4347 	return("ready for recovery");
4348     case CISS_LSTATUS_RECOVERING:
4349 	return("recovering");
4350     case CISS_LSTATUS_WRONG_PDRIVE:
4351 	return("wrong physical drive inserted");
4352     case CISS_LSTATUS_MISSING_PDRIVE:
4353 	return("missing physical drive");
4354     case CISS_LSTATUS_EXPANDING:
4355 	return("expanding");
4356     case CISS_LSTATUS_BECOMING_READY:
4357 	return("becoming ready");
4358     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4359 	return("queued for expansion");
4360     }
4361     return("unknown status");
4362 }
4363 
4364 /************************************************************************
4365  * Return an online/offline/nonexistent value for a logical drive
4366  * status value.
4367  */
4368 static int
4369 ciss_decode_ldrive_status(int status)
4370 {
4371     switch(status) {
4372     case CISS_LSTATUS_NOT_CONFIGURED:
4373 	return(CISS_LD_NONEXISTENT);
4374 
4375     case CISS_LSTATUS_OK:
4376     case CISS_LSTATUS_INTERIM_RECOVERY:
4377     case CISS_LSTATUS_READY_RECOVERY:
4378     case CISS_LSTATUS_RECOVERING:
4379     case CISS_LSTATUS_EXPANDING:
4380     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
4381 	return(CISS_LD_ONLINE);
4382 
4383     case CISS_LSTATUS_FAILED:
4384     case CISS_LSTATUS_WRONG_PDRIVE:
4385     case CISS_LSTATUS_MISSING_PDRIVE:
4386     case CISS_LSTATUS_BECOMING_READY:
4387     default:
4388 	return(CISS_LD_OFFLINE);
4389     }
4390 }
4391 
4392 
4393 /************************************************************************
4394  * Return a name for a logical drive's organisation.
4395  */
4396 static const char *
4397 ciss_name_ldrive_org(int org)
4398 {
4399     switch(org) {
4400     case CISS_LDRIVE_RAID0:
4401 	return("RAID 0");
4402     case CISS_LDRIVE_RAID1:
4403 	return("RAID 1(1+0)");
4404     case CISS_LDRIVE_RAID4:
4405 	return("RAID 4");
4406     case CISS_LDRIVE_RAID5:
4407 	return("RAID 5");
4408     case CISS_LDRIVE_RAID51:
4409 	return("RAID 5+1");
4410     case CISS_LDRIVE_RAIDADG:
4411 	return("RAID ADG");
4412     }
4413     return("unkown");
4414 }
4415 
4416 /************************************************************************
4417  * Return a name for a command status value.
4418  */
4419 static const char *
4420 ciss_name_command_status(int status)
4421 {
4422     switch(status) {
4423     case CISS_CMD_STATUS_SUCCESS:
4424 	return("success");
4425     case CISS_CMD_STATUS_TARGET_STATUS:
4426 	return("target status");
4427     case CISS_CMD_STATUS_DATA_UNDERRUN:
4428 	return("data underrun");
4429     case CISS_CMD_STATUS_DATA_OVERRUN:
4430 	return("data overrun");
4431     case CISS_CMD_STATUS_INVALID_COMMAND:
4432 	return("invalid command");
4433     case CISS_CMD_STATUS_PROTOCOL_ERROR:
4434 	return("protocol error");
4435     case CISS_CMD_STATUS_HARDWARE_ERROR:
4436 	return("hardware error");
4437     case CISS_CMD_STATUS_CONNECTION_LOST:
4438 	return("connection lost");
4439     case CISS_CMD_STATUS_ABORTED:
4440 	return("aborted");
4441     case CISS_CMD_STATUS_ABORT_FAILED:
4442 	return("abort failed");
4443     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
4444 	return("unsolicited abort");
4445     case CISS_CMD_STATUS_TIMEOUT:
4446 	return("timeout");
4447     case CISS_CMD_STATUS_UNABORTABLE:
4448 	return("unabortable");
4449     }
4450     return("unknown status");
4451 }
4452 
4453 /************************************************************************
4454  * Handle an open on the control device.
4455  */
4456 static int
4457 ciss_open(struct cdev *dev, int flags, int fmt, struct thread *p)
4458 {
4459     struct ciss_softc	*sc;
4460 
4461     debug_called(1);
4462 
4463     sc = (struct ciss_softc *)dev->si_drv1;
4464 
4465     /* we might want to veto if someone already has us open */
4466 
4467     mtx_lock(&sc->ciss_mtx);
4468     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
4469     mtx_unlock(&sc->ciss_mtx);
4470     return(0);
4471 }
4472 
4473 /************************************************************************
4474  * Handle the last close on the control device.
4475  */
4476 static int
4477 ciss_close(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     mtx_lock(&sc->ciss_mtx);
4486     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
4487     mtx_unlock(&sc->ciss_mtx);
4488     return (0);
4489 }
4490 
4491 /********************************************************************************
4492  * Handle adapter-specific control operations.
4493  *
4494  * Note that the API here is compatible with the Linux driver, in order to
4495  * simplify the porting of Compaq's userland tools.
4496  */
4497 static int
4498 ciss_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, struct thread *p)
4499 {
4500     struct ciss_softc		*sc;
4501     IOCTL_Command_struct	*ioc	= (IOCTL_Command_struct *)addr;
4502 #ifdef __amd64__
4503     IOCTL_Command_struct32	*ioc32	= (IOCTL_Command_struct32 *)addr;
4504     IOCTL_Command_struct	ioc_swab;
4505 #endif
4506     int				error;
4507 
4508     debug_called(1);
4509 
4510     sc = (struct ciss_softc *)dev->si_drv1;
4511     error = 0;
4512     mtx_lock(&sc->ciss_mtx);
4513 
4514     switch(cmd) {
4515     case CCISS_GETQSTATS:
4516     {
4517 	union ciss_statrequest *cr = (union ciss_statrequest *)addr;
4518 
4519 	switch (cr->cs_item) {
4520 	case CISSQ_FREE:
4521 	case CISSQ_NOTIFY:
4522 	    bcopy(&sc->ciss_qstat[cr->cs_item], &cr->cs_qstat,
4523 		sizeof(struct ciss_qstat));
4524 	    break;
4525 	default:
4526 	    error = ENOIOCTL;
4527 	    break;
4528 	}
4529 
4530 	break;
4531     }
4532 
4533     case CCISS_GETPCIINFO:
4534     {
4535 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4536 
4537 	pis->bus = pci_get_bus(sc->ciss_dev);
4538 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4539 	pis->board_id = pci_get_devid(sc->ciss_dev);
4540 
4541 	break;
4542     }
4543 
4544     case CCISS_GETINTINFO:
4545     {
4546 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4547 
4548 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4549 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4550 
4551 	break;
4552     }
4553 
4554     case CCISS_SETINTINFO:
4555     {
4556 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4557 
4558 	if ((cis->delay == 0) && (cis->count == 0)) {
4559 	    error = EINVAL;
4560 	    break;
4561 	}
4562 
4563 	/*
4564 	 * XXX apparently this is only safe if the controller is idle,
4565 	 *     we should suspend it before doing this.
4566 	 */
4567 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4568 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4569 
4570 	if (ciss_update_config(sc))
4571 	    error = EIO;
4572 
4573 	/* XXX resume the controller here */
4574 	break;
4575     }
4576 
4577     case CCISS_GETNODENAME:
4578 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4579 	      sizeof(NodeName_type));
4580 	break;
4581 
4582     case CCISS_SETNODENAME:
4583 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4584 	      sizeof(NodeName_type));
4585 	if (ciss_update_config(sc))
4586 	    error = EIO;
4587 	break;
4588 
4589     case CCISS_GETHEARTBEAT:
4590 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4591 	break;
4592 
4593     case CCISS_GETBUSTYPES:
4594 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4595 	break;
4596 
4597     case CCISS_GETFIRMVER:
4598 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4599 	      sizeof(FirmwareVer_type));
4600 	break;
4601 
4602     case CCISS_GETDRIVERVER:
4603 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4604 	break;
4605 
4606     case CCISS_REVALIDVOLS:
4607 	/*
4608 	 * This is a bit ugly; to do it "right" we really need
4609 	 * to find any disks that have changed, kick CAM off them,
4610 	 * then rescan only these disks.  It'd be nice if they
4611 	 * a) told us which disk(s) they were going to play with,
4612 	 * and b) which ones had arrived. 8(
4613 	 */
4614 	break;
4615 
4616 #ifdef __amd64__
4617     case CCISS_PASSTHRU32:
4618 	ioc_swab.LUN_info	= ioc32->LUN_info;
4619 	ioc_swab.Request	= ioc32->Request;
4620 	ioc_swab.error_info	= ioc32->error_info;
4621 	ioc_swab.buf_size	= ioc32->buf_size;
4622 	ioc_swab.buf		= (u_int8_t *)(uintptr_t)ioc32->buf;
4623 	ioc			= &ioc_swab;
4624 	/* FALLTHROUGH */
4625 #endif
4626 
4627     case CCISS_PASSTHRU:
4628 	error = ciss_user_command(sc, ioc);
4629 	break;
4630 
4631     default:
4632 	debug(0, "unknown ioctl 0x%lx", cmd);
4633 
4634 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4635 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4636 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4637 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4638 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4639 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4640 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4641 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4642 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4643 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4644 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4645 
4646 	error = ENOIOCTL;
4647 	break;
4648     }
4649 
4650     mtx_unlock(&sc->ciss_mtx);
4651     return(error);
4652 }
4653