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