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