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