xref: /freebsd/sys/dev/ciss/ciss.c (revision c0b9f4fe659b6839541970eb5675e57f4d814969)
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;
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 	    free(sc->ciss_logical[i], CISS_MALLOC_CLASS);
1730 	free(sc->ciss_logical, CISS_MALLOC_CLASS);
1731     }
1732 
1733     if (sc->ciss_physical) {
1734 	for (i = 0; i < sc->ciss_max_physical_bus; i++)
1735 	    free(sc->ciss_physical[i], CISS_MALLOC_CLASS);
1736 	free(sc->ciss_physical, CISS_MALLOC_CLASS);
1737     }
1738 
1739     if (sc->ciss_controllers)
1740 	free(sc->ciss_controllers, CISS_MALLOC_CLASS);
1741 }
1742 
1743 /************************************************************************
1744  * Give a command to the adapter.
1745  *
1746  * Note that this uses the simple transport layer directly.  If we
1747  * want to add support for other layers, we'll need a switch of some
1748  * sort.
1749  *
1750  * Note that the simple transport layer has no way of refusing a
1751  * command; we only have as many request structures as the adapter
1752  * supports commands, so we don't have to check (this presumes that
1753  * the adapter can handle commands as fast as we throw them at it).
1754  */
1755 static int
1756 ciss_start(struct ciss_request *cr)
1757 {
1758     struct ciss_command	*cc;	/* XXX debugging only */
1759     int			error;
1760 
1761     cc = CISS_FIND_COMMAND(cr);
1762     debug(2, "post command %d tag %d ", cr->cr_tag, cc->header.host_tag);
1763 
1764     /*
1765      * Map the request's data.
1766      */
1767     if ((error = ciss_map_request(cr)))
1768 	return(error);
1769 
1770 #if 0
1771     ciss_print_request(cr);
1772 #endif
1773 
1774     return(0);
1775 }
1776 
1777 /************************************************************************
1778  * Fetch completed request(s) from the adapter, queue them for
1779  * completion handling.
1780  *
1781  * Note that this uses the simple transport layer directly.  If we
1782  * want to add support for other layers, we'll need a switch of some
1783  * sort.
1784  *
1785  * Note that the simple transport mechanism does not require any
1786  * reentrancy protection; the OPQ read is atomic.  If there is a
1787  * chance of a race with something else that might move the request
1788  * off the busy list, then we will have to lock against that
1789  * (eg. timeouts, etc.)
1790  */
1791 static void
1792 ciss_done(struct ciss_softc *sc)
1793 {
1794     struct ciss_request	*cr;
1795     struct ciss_command	*cc;
1796     u_int32_t		tag, index;
1797     int			complete;
1798 
1799     debug_called(3);
1800 
1801     /*
1802      * Loop quickly taking requests from the adapter and moving them
1803      * from the busy queue to the completed queue.
1804      */
1805     complete = 0;
1806     for (;;) {
1807 
1808 	/* see if the OPQ contains anything */
1809 	if (!CISS_TL_SIMPLE_OPQ_INTERRUPT(sc))
1810 	    break;
1811 
1812 	tag = CISS_TL_SIMPLE_FETCH_CMD(sc);
1813 	if (tag == CISS_TL_SIMPLE_OPQ_EMPTY)
1814 	    break;
1815 	index = tag >> 2;
1816 	debug(2, "completed command %d%s", index,
1817 	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
1818 	if (index >= sc->ciss_max_requests) {
1819 	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
1820 	    continue;
1821 	}
1822 	cr = &(sc->ciss_request[index]);
1823 	cc = CISS_FIND_COMMAND(cr);
1824 	cc->header.host_tag = tag;	/* not updated by adapter */
1825 	if (ciss_remove_busy(cr)) {
1826 	    /* assume this is garbage out of the adapter */
1827 	    ciss_printf(sc, "completed nonbusy request %d\n", index);
1828 	} else {
1829 	    ciss_enqueue_complete(cr);
1830 	}
1831 	complete = 1;
1832     }
1833 
1834     /*
1835      * Invoke completion processing.  If we can defer this out of
1836      * interrupt context, that'd be good.
1837      */
1838     if (complete)
1839 	ciss_complete(sc);
1840 }
1841 
1842 /************************************************************************
1843  * Take an interrupt from the adapter.
1844  */
1845 static void
1846 ciss_intr(void *arg)
1847 {
1848     struct ciss_softc	*sc = (struct ciss_softc *)arg;
1849 
1850     /*
1851      * The only interrupt we recognise indicates that there are
1852      * entries in the outbound post queue.
1853      */
1854     ciss_done(sc);
1855 }
1856 
1857 /************************************************************************
1858  * Process completed requests.
1859  *
1860  * Requests can be completed in three fashions:
1861  *
1862  * - by invoking a callback function (cr_complete is non-null)
1863  * - by waking up a sleeper (cr_flags has CISS_REQ_SLEEP set)
1864  * - by clearing the CISS_REQ_POLL flag in interrupt/timeout context
1865  */
1866 static void
1867 ciss_complete(struct ciss_softc *sc)
1868 {
1869     struct ciss_request	*cr;
1870 
1871     debug_called(2);
1872 
1873     /*
1874      * Loop taking requests off the completed queue and performing
1875      * completion processing on them.
1876      */
1877     for (;;) {
1878 	if ((cr = ciss_dequeue_complete(sc)) == NULL)
1879 	    break;
1880 	ciss_unmap_request(cr);
1881 
1882 	/*
1883 	 * If the request has a callback, invoke it.
1884 	 */
1885 	if (cr->cr_complete != NULL) {
1886 	    cr->cr_complete(cr);
1887 	    continue;
1888 	}
1889 
1890 	/*
1891 	 * If someone is sleeping on this request, wake them up.
1892 	 */
1893 	if (cr->cr_flags & CISS_REQ_SLEEP) {
1894 	    cr->cr_flags &= ~CISS_REQ_SLEEP;
1895 	    wakeup(cr);
1896 	    continue;
1897 	}
1898 
1899 	/*
1900 	 * If someone is polling this request for completion, signal.
1901 	 */
1902 	if (cr->cr_flags & CISS_REQ_POLL) {
1903 	    cr->cr_flags &= ~CISS_REQ_POLL;
1904 	    continue;
1905 	}
1906 
1907 	/*
1908 	 * Give up and throw the request back on the free queue.  This
1909 	 * should never happen; resources will probably be lost.
1910 	 */
1911 	ciss_printf(sc, "WARNING: completed command with no submitter\n");
1912 	ciss_enqueue_free(cr);
1913     }
1914 }
1915 
1916 /************************************************************************
1917  * Report on the completion status of a request, and pass back SCSI
1918  * and command status values.
1919  */
1920 static int
1921 ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status)
1922 {
1923     struct ciss_command		*cc;
1924     struct ciss_error_info	*ce;
1925 
1926     debug_called(2);
1927 
1928     cc = CISS_FIND_COMMAND(cr);
1929     ce = (struct ciss_error_info *)&(cc->sg[0]);
1930 
1931     /*
1932      * We don't consider data under/overrun an error for the Report
1933      * Logical/Physical LUNs commands.
1934      */
1935     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) &&
1936 	((ce->command_status == CISS_CMD_STATUS_DATA_OVERRUN) ||
1937 	 (ce->command_status == CISS_CMD_STATUS_DATA_UNDERRUN)) &&
1938 	((cc->cdb.cdb[0] == CISS_OPCODE_REPORT_LOGICAL_LUNS) ||
1939 	 (cc->cdb.cdb[0] == CISS_OPCODE_REPORT_PHYSICAL_LUNS) ||
1940 	 (cc->cdb.cdb[0] == INQUIRY))) {
1941 	cc->header.host_tag &= ~CISS_HDR_HOST_TAG_ERROR;
1942 	debug(2, "ignoring irrelevant under/overrun error");
1943     }
1944 
1945     /*
1946      * Check the command's error bit, if clear, there's no status and
1947      * everything is OK.
1948      */
1949     if (!(cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR)) {
1950 	if (scsi_status != NULL)
1951 	    *scsi_status = SCSI_STATUS_OK;
1952 	if (command_status != NULL)
1953 	    *command_status = CISS_CMD_STATUS_SUCCESS;
1954 	return(0);
1955     } else {
1956 	if (command_status != NULL)
1957 	    *command_status = ce->command_status;
1958 	if (scsi_status != NULL) {
1959 	    if (ce->command_status == CISS_CMD_STATUS_TARGET_STATUS) {
1960 		*scsi_status = ce->scsi_status;
1961 	    } else {
1962 		*scsi_status = -1;
1963 	    }
1964 	}
1965 	if (bootverbose)
1966 	    ciss_printf(cr->cr_sc, "command status 0x%x (%s) scsi status 0x%x\n",
1967 			ce->command_status, ciss_name_command_status(ce->command_status),
1968 			ce->scsi_status);
1969 	if (ce->command_status == CISS_CMD_STATUS_INVALID_COMMAND) {
1970 	    ciss_printf(cr->cr_sc, "invalid command, offense size %d at %d, value 0x%x\n",
1971 			ce->additional_error_info.invalid_command.offense_size,
1972 			ce->additional_error_info.invalid_command.offense_offset,
1973 			ce->additional_error_info.invalid_command.offense_value);
1974 	}
1975     }
1976 #if 0
1977     ciss_print_request(cr);
1978 #endif
1979     return(1);
1980 }
1981 
1982 /************************************************************************
1983  * Issue a request and don't return until it's completed.
1984  *
1985  * Depending on adapter status, we may poll or sleep waiting for
1986  * completion.
1987  */
1988 static int
1989 ciss_synch_request(struct ciss_request *cr, int timeout)
1990 {
1991     if (cr->cr_sc->ciss_flags & CISS_FLAG_RUNNING) {
1992 	return(ciss_wait_request(cr, timeout));
1993     } else {
1994 	return(ciss_poll_request(cr, timeout));
1995     }
1996 }
1997 
1998 /************************************************************************
1999  * Issue a request and poll for completion.
2000  *
2001  * Timeout in milliseconds.
2002  */
2003 static int
2004 ciss_poll_request(struct ciss_request *cr, int timeout)
2005 {
2006     int		error;
2007 
2008     debug_called(2);
2009 
2010     cr->cr_flags |= CISS_REQ_POLL;
2011     if ((error = ciss_start(cr)) != 0)
2012 	return(error);
2013 
2014     do {
2015 	ciss_done(cr->cr_sc);
2016 	if (!(cr->cr_flags & CISS_REQ_POLL))
2017 	    return(0);
2018 	DELAY(1000);
2019     } while (timeout-- >= 0);
2020     return(EWOULDBLOCK);
2021 }
2022 
2023 /************************************************************************
2024  * Issue a request and sleep waiting for completion.
2025  *
2026  * Timeout in milliseconds.  Note that a spurious wakeup will reset
2027  * the timeout.
2028  */
2029 static int
2030 ciss_wait_request(struct ciss_request *cr, int timeout)
2031 {
2032     int		s, error;
2033 
2034     debug_called(2);
2035 
2036     cr->cr_flags |= CISS_REQ_SLEEP;
2037     if ((error = ciss_start(cr)) != 0)
2038 	return(error);
2039 
2040     s = splcam();
2041     while ((cr->cr_flags & CISS_REQ_SLEEP) && (error != EWOULDBLOCK)) {
2042 	error = tsleep(cr, PRIBIO, "cissREQ", (timeout * hz) / 1000);
2043     }
2044     splx(s);
2045     return(error);
2046 }
2047 
2048 #if 0
2049 /************************************************************************
2050  * Abort a request.  Note that a potential exists here to race the
2051  * request being completed; the caller must deal with this.
2052  */
2053 static int
2054 ciss_abort_request(struct ciss_request *ar)
2055 {
2056     struct ciss_request		*cr;
2057     struct ciss_command		*cc;
2058     struct ciss_message_cdb	*cmc;
2059     int				error;
2060 
2061     debug_called(1);
2062 
2063     /* get a request */
2064     if ((error = ciss_get_request(ar->cr_sc, &cr)) != 0)
2065 	return(error);
2066 
2067     /* build the abort command */
2068     cc = CISS_FIND_COMMAND(cr);
2069     cc->header.address.mode.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;	/* addressing? */
2070     cc->header.address.physical.target = 0;
2071     cc->header.address.physical.bus = 0;
2072     cc->cdb.cdb_length = sizeof(*cmc);
2073     cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
2074     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2075     cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2076     cc->cdb.timeout = 30;
2077 
2078     cmc = (struct ciss_message_cdb *)&(cc->cdb.cdb[0]);
2079     cmc->opcode = CISS_OPCODE_MESSAGE_ABORT;
2080     cmc->type = CISS_MESSAGE_ABORT_TASK;
2081     cmc->abort_tag = ar->cr_tag;	/* endianness?? */
2082 
2083     /*
2084      * Send the request and wait for a response.  If we believe we
2085      * aborted the request OK, clear the flag that indicates it's
2086      * running.
2087      */
2088     error = ciss_synch_request(cr, 35 * 1000);
2089     if (!error)
2090 	error = ciss_report_request(cr, NULL, NULL);
2091     ciss_release_request(cr);
2092 
2093     return(error);
2094 }
2095 #endif
2096 
2097 
2098 /************************************************************************
2099  * Fetch and initialise a request
2100  */
2101 static int
2102 ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp)
2103 {
2104     struct ciss_request *cr;
2105 
2106     debug_called(2);
2107 
2108     /*
2109      * Get a request and clean it up.
2110      */
2111     if ((cr = ciss_dequeue_free(sc)) == NULL)
2112 	return(ENOMEM);
2113 
2114     cr->cr_data = NULL;
2115     cr->cr_flags = 0;
2116     cr->cr_complete = NULL;
2117     cr->cr_private = NULL;
2118 
2119     ciss_preen_command(cr);
2120     *crp = cr;
2121     return(0);
2122 }
2123 
2124 static void
2125 ciss_preen_command(struct ciss_request *cr)
2126 {
2127     struct ciss_command	*cc;
2128     u_int32_t		cmdphys;
2129 
2130     /*
2131      * Clean up the command structure.
2132      *
2133      * Note that we set up the error_info structure here, since the
2134      * length can be overwritten by any command.
2135      */
2136     cc = CISS_FIND_COMMAND(cr);
2137     cc->header.sg_in_list = 0;		/* kinda inefficient this way */
2138     cc->header.sg_total = 0;
2139     cc->header.host_tag = cr->cr_tag << 2;
2140     cc->header.host_tag_zeroes = 0;
2141     cmdphys = CISS_FIND_COMMANDPHYS(cr);
2142     cc->error_info.error_info_address = cmdphys + sizeof(struct ciss_command);
2143     cc->error_info.error_info_length = CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command);
2144 }
2145 
2146 /************************************************************************
2147  * Release a request to the free list.
2148  */
2149 static void
2150 ciss_release_request(struct ciss_request *cr)
2151 {
2152     struct ciss_softc	*sc;
2153 
2154     debug_called(2);
2155 
2156     sc = cr->cr_sc;
2157 
2158     /* release the request to the free queue */
2159     ciss_requeue_free(cr);
2160 }
2161 
2162 /************************************************************************
2163  * Allocate a request that will be used to send a BMIC command.  Do some
2164  * of the common setup here to avoid duplicating it everywhere else.
2165  */
2166 static int
2167 ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
2168 		      int opcode, void **bufp, size_t bufsize)
2169 {
2170     struct ciss_request		*cr;
2171     struct ciss_command		*cc;
2172     struct ciss_bmic_cdb	*cbc;
2173     void			*buf;
2174     int				error;
2175     int				dataout;
2176 
2177     debug_called(2);
2178 
2179     cr = NULL;
2180     buf = NULL;
2181 
2182     /*
2183      * Get a request.
2184      */
2185     if ((error = ciss_get_request(sc, &cr)) != 0)
2186 	goto out;
2187 
2188     /*
2189      * Allocate data storage if requested, determine the data direction.
2190      */
2191     dataout = 0;
2192     if ((bufsize > 0) && (bufp != NULL)) {
2193 	if (*bufp == NULL) {
2194 	    if ((buf = malloc(bufsize, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
2195 		error = ENOMEM;
2196 		goto out;
2197 	    }
2198 	} else {
2199 	    buf = *bufp;
2200 	    dataout = 1;	/* we are given a buffer, so we are writing */
2201 	}
2202     }
2203 
2204     /*
2205      * Build a CISS BMIC command to get the logical drive ID.
2206      */
2207     cr->cr_data = buf;
2208     cr->cr_length = bufsize;
2209     if (!dataout)
2210 	cr->cr_flags = CISS_REQ_DATAIN;
2211 
2212     cc = CISS_FIND_COMMAND(cr);
2213     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2214     cc->header.address.physical.bus = 0;
2215     cc->header.address.physical.target = 0;
2216     cc->cdb.cdb_length = sizeof(*cbc);
2217     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2218     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2219     cc->cdb.direction = dataout ? CISS_CDB_DIRECTION_WRITE : CISS_CDB_DIRECTION_READ;
2220     cc->cdb.timeout = 0;
2221 
2222     cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
2223     bzero(cbc, sizeof(*cbc));
2224     cbc->opcode = dataout ? CISS_ARRAY_CONTROLLER_WRITE : CISS_ARRAY_CONTROLLER_READ;
2225     cbc->bmic_opcode = opcode;
2226     cbc->size = htons((u_int16_t)bufsize);
2227 
2228 out:
2229     if (error) {
2230 	if (cr != NULL)
2231 	    ciss_release_request(cr);
2232     } else {
2233 	*crp = cr;
2234 	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
2235 	    *bufp = buf;
2236     }
2237     return(error);
2238 }
2239 
2240 /************************************************************************
2241  * Handle a command passed in from userspace.
2242  */
2243 static int
2244 ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
2245 {
2246     struct ciss_request		*cr;
2247     struct ciss_command		*cc;
2248     struct ciss_error_info	*ce;
2249     int				error = 0;
2250 
2251     debug_called(1);
2252 
2253     cr = NULL;
2254 
2255     /*
2256      * Get a request.
2257      */
2258     if ((error = ciss_get_request(sc, &cr)) != 0)
2259 	goto out;
2260     cc = CISS_FIND_COMMAND(cr);
2261 
2262     /*
2263      * Allocate an in-kernel databuffer if required, copy in user data.
2264      */
2265     cr->cr_length = ioc->buf_size;
2266     if (ioc->buf_size > 0) {
2267 	if ((cr->cr_data = malloc(ioc->buf_size, CISS_MALLOC_CLASS, M_WAITOK)) == NULL) {
2268 	    error = ENOMEM;
2269 	    goto out;
2270 	}
2271 	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
2272 	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2273 	    goto out;
2274 	}
2275     }
2276 
2277     /*
2278      * Build the request based on the user command.
2279      */
2280     bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
2281     bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
2282 
2283     /* XXX anything else to populate here? */
2284 
2285     /*
2286      * Run the command.
2287      */
2288     if ((error = ciss_synch_request(cr, 60 * 1000))) {
2289 	debug(0, "request failed - %d", error);
2290 	goto out;
2291     }
2292 
2293     /*
2294      * Check to see if the command succeeded.
2295      */
2296     ce = (struct ciss_error_info *)&(cc->sg[0]);
2297     if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) == 0)
2298 	bzero(ce, sizeof(*ce));
2299 
2300     /*
2301      * Copy the results back to the user.
2302      */
2303     bcopy(ce, &ioc->error_info, sizeof(*ce));
2304     if ((ioc->buf_size > 0) &&
2305 	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
2306 	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
2307 	goto out;
2308     }
2309 
2310     /* done OK */
2311     error = 0;
2312 
2313 out:
2314     if ((cr != NULL) && (cr->cr_data != NULL))
2315 	free(cr->cr_data, CISS_MALLOC_CLASS);
2316     if (cr != NULL)
2317 	ciss_release_request(cr);
2318     return(error);
2319 }
2320 
2321 /************************************************************************
2322  * Map a request into bus-visible space, initialise the scatter/gather
2323  * list.
2324  */
2325 static int
2326 ciss_map_request(struct ciss_request *cr)
2327 {
2328     struct ciss_softc	*sc;
2329     int			error = 0;
2330 
2331     debug_called(2);
2332 
2333     sc = cr->cr_sc;
2334 
2335     /* check that mapping is necessary */
2336     if (cr->cr_flags & CISS_REQ_MAPPED)
2337 	return(0);
2338 
2339     cr->cr_flags |= CISS_REQ_MAPPED;
2340 
2341     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2342 		    BUS_DMASYNC_PREWRITE);
2343 
2344     if (cr->cr_data != NULL) {
2345 	error = bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap,
2346 				cr->cr_data, cr->cr_length,
2347 				ciss_request_map_helper, cr, 0);
2348 	if (error != 0)
2349 	    return (error);
2350     } else {
2351 	/*
2352 	 * Post the command to the adapter.
2353 	 */
2354 	ciss_enqueue_busy(cr);
2355 	CISS_TL_SIMPLE_POST_CMD(cr->cr_sc, CISS_FIND_COMMANDPHYS(cr));
2356     }
2357 
2358     return(0);
2359 }
2360 
2361 static void
2362 ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2363 {
2364     struct ciss_command	*cc;
2365     struct ciss_request *cr;
2366     struct ciss_softc	*sc;
2367     int			i;
2368 
2369     debug_called(2);
2370 
2371     cr = (struct ciss_request *)arg;
2372     sc = cr->cr_sc;
2373     cc = CISS_FIND_COMMAND(cr);
2374 
2375     for (i = 0; i < nseg; i++) {
2376 	cc->sg[i].address = segs[i].ds_addr;
2377 	cc->sg[i].length = segs[i].ds_len;
2378 	cc->sg[i].extension = 0;
2379     }
2380     /* we leave the s/g table entirely within the command */
2381     cc->header.sg_in_list = nseg;
2382     cc->header.sg_total = nseg;
2383 
2384     if (cr->cr_flags & CISS_REQ_DATAIN)
2385 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2386     if (cr->cr_flags & CISS_REQ_DATAOUT)
2387 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2388 
2389     /*
2390      * Post the command to the adapter.
2391      */
2392     ciss_enqueue_busy(cr);
2393     CISS_TL_SIMPLE_POST_CMD(cr->cr_sc, CISS_FIND_COMMANDPHYS(cr));
2394 }
2395 
2396 /************************************************************************
2397  * Unmap a request from bus-visible space.
2398  */
2399 static void
2400 ciss_unmap_request(struct ciss_request *cr)
2401 {
2402     struct ciss_softc	*sc;
2403 
2404     debug_called(2);
2405 
2406     sc = cr->cr_sc;
2407 
2408     /* check that unmapping is necessary */
2409     if ((cr->cr_flags & CISS_REQ_MAPPED) == 0)
2410 	return;
2411 
2412     bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2413 		    BUS_DMASYNC_POSTWRITE);
2414 
2415     if (cr->cr_data == NULL)
2416 	goto out;
2417 
2418     if (cr->cr_flags & CISS_REQ_DATAIN)
2419 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2420     if (cr->cr_flags & CISS_REQ_DATAOUT)
2421 	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2422 
2423     bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2424 out:
2425     cr->cr_flags &= ~CISS_REQ_MAPPED;
2426 }
2427 
2428 /************************************************************************
2429  * Attach the driver to CAM.
2430  *
2431  * We put all the logical drives on a single SCSI bus.
2432  */
2433 static int
2434 ciss_cam_init(struct ciss_softc *sc)
2435 {
2436     int			i, maxbus;
2437 
2438     debug_called(1);
2439 
2440     /*
2441      * Allocate a devq.  We can reuse this for the masked physical
2442      * devices if we decide to export these as well.
2443      */
2444     if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests)) == NULL) {
2445 	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2446 	return(ENOMEM);
2447     }
2448 
2449     /*
2450      * Create a SIM.
2451      *
2452      * This naturally wastes a bit of memory.  The alternative is to allocate
2453      * and register each bus as it is found, and then track them on a linked
2454      * list.  Unfortunately, the driver has a few places where it needs to
2455      * look up the SIM based solely on bus number, and it's unclear whether
2456      * a list traversal would work for these situations.
2457      */
2458     maxbus = max(sc->ciss_max_logical_bus, sc->ciss_max_physical_bus +
2459 		 CISS_PHYSICAL_BASE);
2460     sc->ciss_cam_sim = malloc(maxbus * sizeof(struct cam_sim*),
2461 			      CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO);
2462     if (sc->ciss_cam_sim == NULL) {
2463 	ciss_printf(sc, "can't allocate memory for controller SIM\n");
2464 	return(ENOMEM);
2465     }
2466 
2467     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
2468 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2469 						 "ciss", sc,
2470 						 device_get_unit(sc->ciss_dev),
2471 						 sc->ciss_max_requests - 2,
2472 						 1,
2473 						 sc->ciss_cam_devq)) == NULL) {
2474 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2475 	    return(ENOMEM);
2476 	}
2477 
2478 	/*
2479 	 * Register bus with this SIM.
2480 	 */
2481 	if (i == 0 || sc->ciss_controllers[i].physical.bus != 0) {
2482 	    if (xpt_bus_register(sc->ciss_cam_sim[i], i) != 0) {
2483 		ciss_printf(sc, "can't register SCSI bus %d\n", i);
2484 		return (ENXIO);
2485 	    }
2486 	}
2487     }
2488 
2489     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2490 	 CISS_PHYSICAL_BASE; i++) {
2491 	if ((sc->ciss_cam_sim[i] = cam_sim_alloc(ciss_cam_action, ciss_cam_poll,
2492 						 "ciss", sc,
2493 						 device_get_unit(sc->ciss_dev),
2494 						 sc->ciss_max_requests - 2,
2495 						 1,
2496 						 sc->ciss_cam_devq)) == NULL) {
2497 	    ciss_printf(sc, "can't allocate CAM SIM for controller %d\n", i);
2498 	    return (ENOMEM);
2499 	}
2500 
2501 	if (xpt_bus_register(sc->ciss_cam_sim[i], i) != 0) {
2502 	    ciss_printf(sc, "can't register SCSI bus %d\n", i);
2503 	    return (ENXIO);
2504 	}
2505     }
2506 
2507     /*
2508      * Initiate a rescan of the bus.
2509      */
2510     ciss_cam_rescan_all(sc);
2511 
2512     return(0);
2513 }
2514 
2515 /************************************************************************
2516  * Initiate a rescan of the 'logical devices' SIM
2517  */
2518 static void
2519 ciss_cam_rescan_target(struct ciss_softc *sc, int bus, int target)
2520 {
2521     struct cam_path	*path;
2522     union ccb		*ccb;
2523 
2524     debug_called(1);
2525 
2526     if ((ccb = malloc(sizeof(union ccb), M_TEMP, M_WAITOK | M_ZERO)) == NULL) {
2527 	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2528 	return;
2529     }
2530 
2531     if (xpt_create_path(&path, xpt_periph, cam_sim_path(sc->ciss_cam_sim[bus]),
2532 			target, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2533 	ciss_printf(sc, "rescan failed (can't create path)\n");
2534 	free(ccb, M_TEMP);
2535 	return;
2536     }
2537 
2538     xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
2539     ccb->ccb_h.func_code = XPT_SCAN_BUS;
2540     ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2541     ccb->crcn.flags = CAM_FLAG_NONE;
2542     xpt_action(ccb);
2543 
2544     /* scan is now in progress */
2545 }
2546 
2547 static void
2548 ciss_cam_rescan_all(struct ciss_softc *sc)
2549 {
2550     int i;
2551 
2552     /* Rescan the logical buses */
2553     for (i = 0; i < sc->ciss_max_logical_bus; i++)
2554 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2555     /* Rescan the physical buses */
2556     for (i = CISS_PHYSICAL_BASE; i < sc->ciss_max_physical_bus +
2557 	 CISS_PHYSICAL_BASE; i++)
2558 	ciss_cam_rescan_target(sc, i, CAM_TARGET_WILDCARD);
2559 }
2560 
2561 static void
2562 ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2563 {
2564     xpt_free_path(ccb->ccb_h.path);
2565     free(ccb, M_TEMP);
2566 }
2567 
2568 /************************************************************************
2569  * Handle requests coming from CAM
2570  */
2571 static void
2572 ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2573 {
2574     struct ciss_softc	*sc;
2575     struct ccb_scsiio	*csio;
2576     int			bus, target;
2577     int			physical;
2578 
2579     sc = cam_sim_softc(sim);
2580     bus = cam_sim_bus(sim);
2581     csio = (struct ccb_scsiio *)&ccb->csio;
2582     target = csio->ccb_h.target_id;
2583     physical = CISS_IS_PHYSICAL(bus);
2584 
2585     switch (ccb->ccb_h.func_code) {
2586 
2587 	/* perform SCSI I/O */
2588     case XPT_SCSI_IO:
2589 	if (!ciss_cam_action_io(sim, csio))
2590 	    return;
2591 	break;
2592 
2593 	/* perform geometry calculations */
2594     case XPT_CALC_GEOMETRY:
2595     {
2596 	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2597 	struct ciss_ldrive		*ld;
2598 
2599 	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2600 
2601 	ld = NULL;
2602 	if (!physical)
2603 	    ld = &sc->ciss_logical[bus][target];
2604 
2605 	/*
2606 	 * Use the cached geometry settings unless the fault tolerance
2607 	 * is invalid.
2608 	 */
2609 	if (physical || ld->cl_geometry.fault_tolerance == 0xFF) {
2610 	    u_int32_t			secs_per_cylinder;
2611 
2612 	    ccg->heads = 255;
2613 	    ccg->secs_per_track = 32;
2614 	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2615 	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2616 	} else {
2617 	    ccg->heads = ld->cl_geometry.heads;
2618 	    ccg->secs_per_track = ld->cl_geometry.sectors;
2619 	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2620 	}
2621 	ccb->ccb_h.status = CAM_REQ_CMP;
2622         break;
2623     }
2624 
2625 	/* handle path attribute inquiry */
2626     case XPT_PATH_INQ:
2627     {
2628 	struct ccb_pathinq	*cpi = &ccb->cpi;
2629 
2630 	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2631 
2632 	cpi->version_num = 1;
2633 	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2634 	cpi->target_sprt = 0;
2635 	cpi->hba_misc = 0;
2636 	cpi->max_target = CISS_MAX_LOGICAL;
2637 	cpi->max_lun = 0;		/* 'logical drive' channel only */
2638 	cpi->initiator_id = CISS_MAX_LOGICAL;
2639 	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2640         strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2641         strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2642         cpi->unit_number = cam_sim_unit(sim);
2643         cpi->bus_id = cam_sim_bus(sim);
2644 	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2645 	ccb->ccb_h.status = CAM_REQ_CMP;
2646 	break;
2647     }
2648 
2649     case XPT_GET_TRAN_SETTINGS:
2650     {
2651 	struct ccb_trans_settings	*cts = &ccb->cts;
2652 	int				bus, target;
2653 
2654 	bus = cam_sim_bus(sim);
2655 	target = cts->ccb_h.target_id;
2656 
2657 	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2658 	cts->valid = 0;
2659 
2660 	/* disconnect always OK */
2661 	cts->flags |= CCB_TRANS_DISC_ENB;
2662 	cts->valid |= CCB_TRANS_DISC_VALID;
2663 
2664 	cts->ccb_h.status = CAM_REQ_CMP;
2665 	break;
2666     }
2667 
2668     default:		/* we can't do this */
2669 	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
2670 	ccb->ccb_h.status = CAM_REQ_INVALID;
2671 	break;
2672     }
2673 
2674     xpt_done(ccb);
2675 }
2676 
2677 /************************************************************************
2678  * Handle a CAM SCSI I/O request.
2679  */
2680 static int
2681 ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
2682 {
2683     struct ciss_softc	*sc;
2684     int			bus, target;
2685     struct ciss_request	*cr;
2686     struct ciss_command	*cc;
2687     int			error;
2688 
2689     sc = cam_sim_softc(sim);
2690     bus = cam_sim_bus(sim);
2691     target = csio->ccb_h.target_id;
2692 
2693     debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
2694 
2695     /* firmware does not support commands > 10 bytes */
2696     if (csio->cdb_len > 12/*CISS_CDB_BUFFER_SIZE*/) {
2697 	debug(3, "  command too large (%d > %d)", csio->cdb_len, CISS_CDB_BUFFER_SIZE);
2698 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2699     }
2700 
2701     /* check that the CDB pointer is not to a physical address */
2702     if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
2703 	debug(3, "  CDB pointer is to physical address");
2704 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2705     }
2706 
2707     /* if there is data transfer, it must be to/from a virtual address */
2708     if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2709 	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
2710 	    debug(3, "  data pointer is to physical address");
2711 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2712 	}
2713 	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
2714 	    debug(3, "  data has premature s/g setup");
2715 	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2716 	}
2717     }
2718 
2719     /* abandon aborted ccbs or those that have failed validation */
2720     if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2721 	debug(3, "abandoning CCB due to abort/validation failure");
2722 	return(EINVAL);
2723     }
2724 
2725     /* handle emulation of some SCSI commands ourself */
2726     if (ciss_cam_emulate(sc, csio))
2727 	return(0);
2728 
2729     /*
2730      * Get a request to manage this command.  If we can't, return the
2731      * ccb, freeze the queue and flag so that we unfreeze it when a
2732      * request completes.
2733      */
2734     if ((error = ciss_get_request(sc, &cr)) != 0) {
2735 	xpt_freeze_simq(sim, 1);
2736 	csio->ccb_h.status |= CAM_REQUEUE_REQ;
2737 	return(error);
2738     }
2739 
2740     /*
2741      * Build the command.
2742      */
2743     cc = CISS_FIND_COMMAND(cr);
2744     cr->cr_data = csio->data_ptr;
2745     cr->cr_length = csio->dxfer_len;
2746     cr->cr_complete = ciss_cam_complete;
2747     cr->cr_private = csio;
2748 
2749     /*
2750      * Target the right logical volume.
2751      */
2752     if (CISS_IS_PHYSICAL(bus))
2753 	cc->header.address =
2754 	    sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_address;
2755     else
2756 	cc->header.address =
2757 	    sc->ciss_logical[bus][target].cl_address;
2758     cc->cdb.cdb_length = csio->cdb_len;
2759     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2760     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
2761     if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2762 	cr->cr_flags = CISS_REQ_DATAOUT;
2763 	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
2764     } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2765 	cr->cr_flags = CISS_REQ_DATAIN;
2766 	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2767     } else {
2768 	cr->cr_flags = 0;
2769 	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2770     }
2771     cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
2772     if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2773 	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
2774     } else {
2775 	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
2776     }
2777 
2778     /*
2779      * Submit the request to the adapter.
2780      *
2781      * Note that this may fail if we're unable to map the request (and
2782      * if we ever learn a transport layer other than simple, may fail
2783      * if the adapter rejects the command).
2784      */
2785     if ((error = ciss_start(cr)) != 0) {
2786 	xpt_freeze_simq(sim, 1);
2787 	if (error == EINPROGRESS) {
2788 	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2789 	    error = 0;
2790 	} else {
2791 	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
2792 	    ciss_release_request(cr);
2793 	}
2794 	return(error);
2795     }
2796 
2797     return(0);
2798 }
2799 
2800 /************************************************************************
2801  * Emulate SCSI commands the adapter doesn't handle as we might like.
2802  */
2803 static int
2804 ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
2805 {
2806     int		bus, target;
2807     u_int8_t	opcode;
2808 
2809     target = csio->ccb_h.target_id;
2810     bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
2811     opcode = (csio->ccb_h.flags & CAM_CDB_POINTER) ?
2812 	*(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0];
2813 
2814     if (CISS_IS_PHYSICAL(bus)) {
2815 	if (sc->ciss_physical[CISS_CAM_TO_PBUS(bus)][target].cp_online != 1) {
2816 	    csio->ccb_h.status = CAM_SEL_TIMEOUT;
2817 	    xpt_done((union ccb *)csio);
2818 	    return(1);
2819 	} else
2820 	    return(0);
2821     }
2822 
2823     /*
2824      * Handle requests for volumes that don't exist or are not online.
2825      * A selection timeout is slightly better than an illegal request.
2826      * Other errors might be better.
2827      */
2828     if (sc->ciss_logical[bus][target].cl_status != CISS_LD_ONLINE) {
2829 	csio->ccb_h.status = CAM_SEL_TIMEOUT;
2830 	xpt_done((union ccb *)csio);
2831 	return(1);
2832     }
2833 
2834     /* if we have to fake Synchronise Cache */
2835     if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
2836 	/*
2837 	 * If this is a Synchronise Cache command, typically issued when
2838 	 * a device is closed, flush the adapter and complete now.
2839 	 */
2840 	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2841 	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
2842 	    ciss_flush_adapter(sc);
2843 	    csio->ccb_h.status = CAM_REQ_CMP;
2844 	    xpt_done((union ccb *)csio);
2845 	    return(1);
2846 	}
2847     }
2848 
2849     return(0);
2850 }
2851 
2852 /************************************************************************
2853  * Check for possibly-completed commands.
2854  */
2855 static void
2856 ciss_cam_poll(struct cam_sim *sim)
2857 {
2858     struct ciss_softc	*sc = cam_sim_softc(sim);
2859 
2860     debug_called(2);
2861 
2862     ciss_done(sc);
2863 }
2864 
2865 /************************************************************************
2866  * Handle completion of a command - pass results back through the CCB
2867  */
2868 static void
2869 ciss_cam_complete(struct ciss_request *cr)
2870 {
2871     struct ciss_softc		*sc;
2872     struct ciss_command		*cc;
2873     struct ciss_error_info	*ce;
2874     struct ccb_scsiio		*csio;
2875     int				scsi_status;
2876     int				command_status;
2877 
2878     debug_called(2);
2879 
2880     sc = cr->cr_sc;
2881     cc = CISS_FIND_COMMAND(cr);
2882     ce = (struct ciss_error_info *)&(cc->sg[0]);
2883     csio = (struct ccb_scsiio *)cr->cr_private;
2884 
2885     /*
2886      * Extract status values from request.
2887      */
2888     ciss_report_request(cr, &command_status, &scsi_status);
2889     csio->scsi_status = scsi_status;
2890 
2891     /*
2892      * Handle specific SCSI status values.
2893      */
2894     switch(scsi_status) {
2895 	/* no status due to adapter error */
2896     case -1:
2897 	debug(0, "adapter error");
2898 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2899 	break;
2900 
2901 	/* no status due to command completed OK */
2902     case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
2903 	debug(2, "SCSI_STATUS_OK");
2904 	csio->ccb_h.status = CAM_REQ_CMP;
2905 	break;
2906 
2907 	/* check condition, sense data included */
2908     case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
2909 	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d\n",
2910 	      ce->sense_length, ce->residual_count);
2911 	bzero(&csio->sense_data, SSD_FULL_SIZE);
2912 	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
2913 	csio->sense_len = ce->sense_length;
2914 	csio->resid = ce->residual_count;
2915 	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
2916 #ifdef CISS_DEBUG
2917 	{
2918 	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
2919 	    debug(0, "sense key %x", sns->flags & SSD_KEY);
2920 	}
2921 #endif
2922 	break;
2923 
2924     case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
2925 	debug(0, "SCSI_STATUS_BUSY");
2926 	csio->ccb_h.status = CAM_SCSI_BUSY;
2927 	break;
2928 
2929     default:
2930 	debug(0, "unknown status 0x%x", csio->scsi_status);
2931 	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2932 	break;
2933     }
2934 
2935     /* handle post-command fixup */
2936     ciss_cam_complete_fixup(sc, csio);
2937 
2938     /* tell CAM we're ready for more commands */
2939     csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2940 
2941     xpt_done((union ccb *)csio);
2942     ciss_release_request(cr);
2943 }
2944 
2945 /********************************************************************************
2946  * Fix up the result of some commands here.
2947  */
2948 static void
2949 ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
2950 {
2951     struct scsi_inquiry_data	*inq;
2952     struct ciss_ldrive		*cl;
2953     int				bus, target;
2954 
2955     if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2956 	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
2957 
2958 	inq = (struct scsi_inquiry_data *)csio->data_ptr;
2959 	target = csio->ccb_h.target_id;
2960 	bus = cam_sim_bus(xpt_path_sim(csio->ccb_h.path));
2961 
2962 	/*
2963 	 * Don't let hard drives be seen by the DA driver.  They will still be
2964 	 * attached by the PASS driver.
2965 	 */
2966 	if (CISS_IS_PHYSICAL(bus)) {
2967 	    if (SID_TYPE(inq) == T_DIRECT)
2968 		inq->device = (inq->device & 0xe0) | T_NODEVICE;
2969 	    return;
2970 	}
2971 
2972 	cl = &sc->ciss_logical[bus][target];
2973 
2974 	padstr(inq->vendor, "COMPAQ", 8);
2975 	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
2976 	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
2977     }
2978 }
2979 
2980 
2981 /********************************************************************************
2982  * Find a peripheral attached at (target)
2983  */
2984 static struct cam_periph *
2985 ciss_find_periph(struct ciss_softc *sc, int bus, int target)
2986 {
2987     struct cam_periph	*periph;
2988     struct cam_path	*path;
2989     int			status;
2990 
2991     status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim[bus]),
2992 			     target, 0);
2993     if (status == CAM_REQ_CMP) {
2994 	periph = cam_periph_find(path, NULL);
2995 	xpt_free_path(path);
2996     } else {
2997 	periph = NULL;
2998     }
2999     return(periph);
3000 }
3001 
3002 /********************************************************************************
3003  * Name the device at (target)
3004  *
3005  * XXX is this strictly correct?
3006  */
3007 static int
3008 ciss_name_device(struct ciss_softc *sc, int bus, int target)
3009 {
3010     struct cam_periph	*periph;
3011 
3012     if (CISS_IS_PHYSICAL(bus))
3013 	return (0);
3014     if ((periph = ciss_find_periph(sc, bus, target)) != NULL) {
3015 	sprintf(sc->ciss_logical[bus][target].cl_name, "%s%d",
3016 		periph->periph_name, periph->unit_number);
3017 	return(0);
3018     }
3019     sc->ciss_logical[bus][target].cl_name[0] = 0;
3020     return(ENOENT);
3021 }
3022 
3023 /************************************************************************
3024  * Periodic status monitoring.
3025  */
3026 static void
3027 ciss_periodic(void *arg)
3028 {
3029     struct ciss_softc	*sc;
3030 
3031     debug_called(1);
3032 
3033     sc = (struct ciss_softc *)arg;
3034 
3035     /*
3036      * Check the adapter heartbeat.
3037      */
3038     if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
3039 	sc->ciss_heart_attack++;
3040 	debug(0, "adapter heart attack in progress 0x%x/%d",
3041 	      sc->ciss_heartbeat, sc->ciss_heart_attack);
3042 	if (sc->ciss_heart_attack == 3) {
3043 	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
3044 	    /* XXX should reset adapter here */
3045 	}
3046     } else {
3047 	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
3048 	sc->ciss_heart_attack = 0;
3049 	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
3050     }
3051 
3052     /*
3053      * If the notify event request has died for some reason, or has
3054      * not started yet, restart it.
3055      */
3056     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
3057 	debug(0, "(re)starting Event Notify chain");
3058 	ciss_notify_event(sc);
3059     }
3060 
3061     /*
3062      * Reschedule.
3063      */
3064     if (!(sc->ciss_flags & CISS_FLAG_ABORTING))
3065 	sc->ciss_periodic = timeout(ciss_periodic, sc, CISS_HEARTBEAT_RATE * hz);
3066 }
3067 
3068 /************************************************************************
3069  * Request a notification response from the adapter.
3070  *
3071  * If (cr) is NULL, this is the first request of the adapter, so
3072  * reset the adapter's message pointer and start with the oldest
3073  * message available.
3074  */
3075 static void
3076 ciss_notify_event(struct ciss_softc *sc)
3077 {
3078     struct ciss_request		*cr;
3079     struct ciss_command		*cc;
3080     struct ciss_notify_cdb	*cnc;
3081     int				error;
3082 
3083     debug_called(1);
3084 
3085     cr = sc->ciss_periodic_notify;
3086 
3087     /* get a request if we don't already have one */
3088     if (cr == NULL) {
3089 	if ((error = ciss_get_request(sc, &cr)) != 0) {
3090 	    debug(0, "can't get notify event request");
3091 	    goto out;
3092 	}
3093 	sc->ciss_periodic_notify = cr;
3094 	cr->cr_complete = ciss_notify_complete;
3095 	debug(1, "acquired request %d", cr->cr_tag);
3096     }
3097 
3098     /*
3099      * Get a databuffer if we don't already have one, note that the
3100      * adapter command wants a larger buffer than the actual
3101      * structure.
3102      */
3103     if (cr->cr_data == NULL) {
3104 	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3105 	    debug(0, "can't get notify event request buffer");
3106 	    error = ENOMEM;
3107 	    goto out;
3108 	}
3109 	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3110     }
3111 
3112     /* re-setup the request's command (since we never release it) XXX overkill*/
3113     ciss_preen_command(cr);
3114 
3115     /* (re)build the notify event command */
3116     cc = CISS_FIND_COMMAND(cr);
3117     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3118     cc->header.address.physical.bus = 0;
3119     cc->header.address.physical.target = 0;
3120 
3121     cc->cdb.cdb_length = sizeof(*cnc);
3122     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3123     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3124     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3125     cc->cdb.timeout = 0;	/* no timeout, we hope */
3126 
3127     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3128     bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
3129     cnc->opcode = CISS_OPCODE_READ;
3130     cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
3131     cnc->timeout = 0;		/* no timeout, we hope */
3132     cnc->synchronous = 0;
3133     cnc->ordered = 0;
3134     cnc->seek_to_oldest = 0;
3135     if ((sc->ciss_flags & CISS_FLAG_RUNNING) == 0)
3136 	cnc->new_only = 1;
3137     else
3138 	cnc->new_only = 0;
3139     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3140 
3141     /* submit the request */
3142     error = ciss_start(cr);
3143 
3144  out:
3145     if (error) {
3146 	if (cr != NULL) {
3147 	    if (cr->cr_data != NULL)
3148 		free(cr->cr_data, CISS_MALLOC_CLASS);
3149 	    ciss_release_request(cr);
3150 	}
3151 	sc->ciss_periodic_notify = NULL;
3152 	debug(0, "can't submit notify event request");
3153 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3154     } else {
3155 	debug(1, "notify event submitted");
3156 	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
3157     }
3158 }
3159 
3160 static void
3161 ciss_notify_complete(struct ciss_request *cr)
3162 {
3163     struct ciss_command	*cc;
3164     struct ciss_notify	*cn;
3165     struct ciss_softc	*sc;
3166     int			scsi_status;
3167     int			command_status;
3168     debug_called(1);
3169 
3170     cc = CISS_FIND_COMMAND(cr);
3171     cn = (struct ciss_notify *)cr->cr_data;
3172     sc = cr->cr_sc;
3173 
3174     /*
3175      * Report request results, decode status.
3176      */
3177     ciss_report_request(cr, &command_status, &scsi_status);
3178 
3179     /*
3180      * Abort the chain on a fatal error.
3181      *
3182      * XXX which of these are actually errors?
3183      */
3184     if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
3185 	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
3186 	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
3187 	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
3188 		    ciss_name_command_status(command_status));
3189 	ciss_release_request(cr);
3190 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3191 	return;
3192     }
3193 
3194     /*
3195      * If the adapter gave us a text message, print it.
3196      */
3197     if (cn->message[0] != 0)
3198 	ciss_printf(sc, "*** %.80s\n", cn->message);
3199 
3200     debug(0, "notify event class %d subclass %d detail %d",
3201 		cn->class, cn->subclass, cn->detail);
3202 
3203     /*
3204      * If the response indicates that the notifier has been aborted,
3205      * release the notifier command.
3206      */
3207     if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
3208 	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
3209 	(cn->detail == 1)) {
3210 	debug(0, "notifier exiting");
3211 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3212 	ciss_release_request(cr);
3213 	sc->ciss_periodic_notify = NULL;
3214 	wakeup(&sc->ciss_periodic_notify);
3215     } else {
3216 	/* Handle notify events in a kernel thread */
3217 	ciss_enqueue_notify(cr);
3218 	sc->ciss_periodic_notify = NULL;
3219 	wakeup(&sc->ciss_periodic_notify);
3220 	wakeup(&sc->ciss_notify);
3221     }
3222     /*
3223      * Send a new notify event command, if we're not aborting.
3224      */
3225     if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
3226 	ciss_notify_event(sc);
3227     }
3228 }
3229 
3230 /************************************************************************
3231  * Abort the Notify Event chain.
3232  *
3233  * Note that we can't just abort the command in progress; we have to
3234  * explicitly issue an Abort Notify Event command in order for the
3235  * adapter to clean up correctly.
3236  *
3237  * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
3238  * the chain will not restart itself.
3239  */
3240 static int
3241 ciss_notify_abort(struct ciss_softc *sc)
3242 {
3243     struct ciss_request		*cr;
3244     struct ciss_command		*cc;
3245     struct ciss_notify_cdb	*cnc;
3246     int				error, s, command_status, scsi_status;
3247 
3248     debug_called(1);
3249 
3250     cr = NULL;
3251     error = 0;
3252 
3253     /* verify that there's an outstanding command */
3254     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3255 	goto out;
3256 
3257     /* get a command to issue the abort with */
3258     if ((error = ciss_get_request(sc, &cr)))
3259 	goto out;
3260 
3261     /* get a buffer for the result */
3262     if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
3263 	debug(0, "can't get notify event request buffer");
3264 	error = ENOMEM;
3265 	goto out;
3266     }
3267     cr->cr_length = CISS_NOTIFY_DATA_SIZE;
3268 
3269     /* build the CDB */
3270     cc = CISS_FIND_COMMAND(cr);
3271     cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
3272     cc->header.address.physical.bus = 0;
3273     cc->header.address.physical.target = 0;
3274     cc->cdb.cdb_length = sizeof(*cnc);
3275     cc->cdb.type = CISS_CDB_TYPE_COMMAND;
3276     cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
3277     cc->cdb.direction = CISS_CDB_DIRECTION_READ;
3278     cc->cdb.timeout = 0;	/* no timeout, we hope */
3279 
3280     cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
3281     bzero(cnc, sizeof(*cnc));
3282     cnc->opcode = CISS_OPCODE_WRITE;
3283     cnc->command = CISS_COMMAND_ABORT_NOTIFY;
3284     cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
3285 
3286     ciss_print_request(cr);
3287 
3288     /*
3289      * Submit the request and wait for it to complete.
3290      */
3291     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3292 	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
3293 	goto out;
3294     }
3295 
3296     /*
3297      * Check response.
3298      */
3299     ciss_report_request(cr, &command_status, &scsi_status);
3300     switch(command_status) {
3301     case CISS_CMD_STATUS_SUCCESS:
3302 	break;
3303     case CISS_CMD_STATUS_INVALID_COMMAND:
3304 	/*
3305 	 * Some older adapters don't support the CISS version of this
3306 	 * command.  Fall back to using the BMIC version.
3307 	 */
3308 	error = ciss_notify_abort_bmic(sc);
3309 	if (error != 0)
3310 	    goto out;
3311 	break;
3312 
3313     case CISS_CMD_STATUS_TARGET_STATUS:
3314 	/*
3315 	 * This can happen if the adapter thinks there wasn't an outstanding
3316 	 * Notify Event command but we did.  We clean up here.
3317 	 */
3318 	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
3319 	    if (sc->ciss_periodic_notify != NULL)
3320 		ciss_release_request(sc->ciss_periodic_notify);
3321 	    error = 0;
3322 	    goto out;
3323 	}
3324 	/* FALLTHROUGH */
3325 
3326     default:
3327 	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
3328 		    ciss_name_command_status(command_status));
3329 	error = EIO;
3330 	goto out;
3331     }
3332 
3333     /*
3334      * Sleep waiting for the notifier command to complete.  Note
3335      * that if it doesn't, we may end up in a bad situation, since
3336      * the adapter may deliver it later.  Also note that the adapter
3337      * requires the Notify Event command to be cancelled in order to
3338      * maintain internal bookkeeping.
3339      */
3340     s = splcam();
3341     while (sc->ciss_periodic_notify != NULL) {
3342 	error = tsleep(&sc->ciss_periodic_notify, 0, "cissNEA", hz * 5);
3343 	if (error == EWOULDBLOCK) {
3344 	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
3345 	    break;
3346 	}
3347     }
3348     splx(s);
3349 
3350  out:
3351     /* release the cancel request */
3352     if (cr != NULL) {
3353 	if (cr->cr_data != NULL)
3354 	    free(cr->cr_data, CISS_MALLOC_CLASS);
3355 	ciss_release_request(cr);
3356     }
3357     if (error == 0)
3358 	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
3359     return(error);
3360 }
3361 
3362 /************************************************************************
3363  * Abort the Notify Event chain using a BMIC command.
3364  */
3365 static int
3366 ciss_notify_abort_bmic(struct ciss_softc *sc)
3367 {
3368     struct ciss_request			*cr;
3369     int					error, command_status;
3370 
3371     debug_called(1);
3372 
3373     cr = NULL;
3374     error = 0;
3375 
3376     /* verify that there's an outstanding command */
3377     if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3378 	goto out;
3379 
3380     /*
3381      * Build a BMIC command to cancel the Notify on Event command.
3382      *
3383      * Note that we are sending a CISS opcode here.  Odd.
3384      */
3385     if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3386 				       NULL, 0)) != 0)
3387 	goto out;
3388 
3389     /*
3390      * Submit the request and wait for it to complete.
3391      */
3392     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3393 	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3394 	goto out;
3395     }
3396 
3397     /*
3398      * Check response.
3399      */
3400     ciss_report_request(cr, &command_status, NULL);
3401     switch(command_status) {
3402     case CISS_CMD_STATUS_SUCCESS:
3403 	break;
3404     default:
3405 	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3406 		    ciss_name_command_status(command_status));
3407 	error = EIO;
3408 	goto out;
3409     }
3410 
3411 out:
3412     if (cr != NULL)
3413 	ciss_release_request(cr);
3414     return(error);
3415 }
3416 
3417 /************************************************************************
3418  * Handle rescanning all the logical volumes when a notify event
3419  * causes the drives to come online or offline.
3420  */
3421 static void
3422 ciss_notify_rescan_logical(struct ciss_softc *sc)
3423 {
3424     struct ciss_lun_report      *cll;
3425     struct ciss_ldrive		*ld;
3426     int                         i, j, ndrives;
3427 
3428     /*
3429      * We must rescan all logical volumes to get the right logical
3430      * drive address.
3431      */
3432     cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_LOGICAL_LUNS,
3433                            CISS_MAX_LOGICAL);
3434     if (cll == NULL)
3435         return;
3436 
3437     ndrives = (ntohl(cll->list_size) / sizeof(union ciss_device_address));
3438 
3439     /*
3440      * Delete any of the drives which were destroyed by the
3441      * firmware.
3442      */
3443     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3444 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3445 	    ld = &sc->ciss_logical[i][j];
3446 
3447 	    if (ld->cl_update == 0)
3448 		continue;
3449 
3450 	    if (ld->cl_status != CISS_LD_ONLINE) {
3451 		ciss_cam_rescan_target(sc, i, j);
3452 		ld->cl_update = 0;
3453 		if (ld->cl_ldrive)
3454 		    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
3455 		if (ld->cl_lstatus)
3456 		    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
3457 
3458 		ld->cl_ldrive = NULL;
3459 		ld->cl_lstatus = NULL;
3460 	    }
3461 	}
3462     }
3463 
3464     /*
3465      * Scan for new drives.
3466      */
3467     for (i = 0; i < ndrives; i++) {
3468 	int	bus, target;
3469 
3470 	bus 	= CISS_LUN_TO_BUS(cll->lun[i].logical.lun);
3471 	target	= CISS_LUN_TO_TARGET(cll->lun[i].logical.lun);
3472 	ld	= &sc->ciss_logical[bus][target];
3473 
3474 	if (ld->cl_update == 0)
3475 		continue;
3476 
3477 	ld->cl_update		= 0;
3478 	ld->cl_address		= cll->lun[i];
3479 	ld->cl_controller	= &sc->ciss_controllers[bus];
3480 	if (ciss_identify_logical(sc, ld) == 0) {
3481 	    ciss_cam_rescan_target(sc, bus, target);
3482 	}
3483     }
3484     free(cll, CISS_MALLOC_CLASS);
3485 }
3486 
3487 /************************************************************************
3488  * Handle a notify event relating to the status of a logical drive.
3489  *
3490  * XXX need to be able to defer some of these to properly handle
3491  *     calling the "ID Physical drive" command, unless the 'extended'
3492  *     drive IDs are always in BIG_MAP format.
3493  */
3494 static void
3495 ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3496 {
3497     struct ciss_ldrive	*ld;
3498     int			ostatus, bus, target;
3499 
3500     debug_called(2);
3501 
3502     bus		= cn->device.physical.bus;
3503     target	= cn->data.logical_status.logical_drive;
3504     ld		= &sc->ciss_logical[bus][target];
3505 
3506     switch (cn->subclass) {
3507     case CISS_NOTIFY_LOGICAL_STATUS:
3508 	switch (cn->detail) {
3509 	case 0:
3510 	    ciss_name_device(sc, bus, target);
3511 	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3512 			cn->data.logical_status.logical_drive, ld->cl_name,
3513 			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3514 			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3515 			cn->data.logical_status.spare_state,
3516 			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3517 
3518 	    /*
3519 	     * Update our idea of the drive's status.
3520 	     */
3521 	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3522 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3523 	    if (ld->cl_lstatus != NULL)
3524 		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3525 
3526 	    /*
3527 	     * Have CAM rescan the drive if its status has changed.
3528 	     */
3529 	    if (ostatus != ld->cl_status) {
3530 		ld->cl_update = 1;
3531 		ciss_notify_rescan_logical(sc);
3532 	    }
3533 
3534 	    break;
3535 
3536 	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3537 	    ciss_name_device(sc, bus, target);
3538 	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3539 			cn->data.logical_status.logical_drive, ld->cl_name);
3540 	    ciss_accept_media(sc, ld);
3541 
3542 	    ld->cl_update = 1;
3543 	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3544 	    ciss_notify_rescan_logical(sc);
3545 	    break;
3546 
3547 	case 2:
3548 	case 3:
3549 	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3550 			cn->data.rebuild_aborted.logical_drive,
3551 			ld->cl_name,
3552 			(cn->detail == 2) ? "read" : "write");
3553 	    break;
3554 	}
3555 	break;
3556 
3557     case CISS_NOTIFY_LOGICAL_ERROR:
3558 	if (cn->detail == 0) {
3559 	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3560 			cn->data.io_error.logical_drive,
3561 			ld->cl_name,
3562 			cn->data.io_error.failure_bus,
3563 			cn->data.io_error.failure_drive);
3564 	    /* XXX should we take the drive down at this point, or will we be told? */
3565 	}
3566 	break;
3567 
3568     case CISS_NOTIFY_LOGICAL_SURFACE:
3569 	if (cn->detail == 0)
3570 	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
3571 			cn->data.consistency_completed.logical_drive,
3572 			ld->cl_name);
3573 	break;
3574     }
3575 }
3576 
3577 /************************************************************************
3578  * Handle a notify event relating to the status of a physical drive.
3579  */
3580 static void
3581 ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
3582 {
3583 }
3584 
3585 /************************************************************************
3586  * Handle a notify event relating to the status of a physical drive.
3587  */
3588 static void
3589 ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn)
3590 {
3591     struct ciss_lun_report *cll;
3592     int bus, target;
3593     int s;
3594 
3595     switch (cn->subclass) {
3596     case CISS_NOTIFY_HOTPLUG_PHYSICAL:
3597     case CISS_NOTIFY_HOTPLUG_NONDISK:
3598 	bus = CISS_BIG_MAP_BUS(sc, cn->data.drive.big_physical_drive_number);
3599 	target =
3600 	    CISS_BIG_MAP_TARGET(sc, cn->data.drive.big_physical_drive_number);
3601 
3602 	s = splcam();
3603 	if (cn->detail == 0) {
3604 	    /*
3605 	     * Mark the device offline so that it'll start producing selection
3606 	     * timeouts to the upper layer.
3607 	     */
3608 	    if ((bus >= 0) && (target >= 0))
3609 		sc->ciss_physical[bus][target].cp_online = 0;
3610 	} else {
3611 	    /*
3612 	     * Rescan the physical lun list for new items
3613 	     */
3614 	    cll = ciss_report_luns(sc, CISS_OPCODE_REPORT_PHYSICAL_LUNS,
3615 				   CISS_MAX_PHYSICAL);
3616 	    if (cll == NULL) {
3617 		ciss_printf(sc, "Warning, cannot get physical lun list\n");
3618 		break;
3619 	    }
3620 	    ciss_filter_physical(sc, cll);
3621 	}
3622 	splx(s);
3623 	break;
3624 
3625     default:
3626 	ciss_printf(sc, "Unknown hotplug event %d\n", cn->subclass);
3627 	return;
3628     }
3629 }
3630 
3631 /************************************************************************
3632  * Handle deferred processing of notify events.  Notify events may need
3633  * sleep which is unsafe during an interrupt.
3634  */
3635 static void
3636 ciss_notify_thread(void *arg)
3637 {
3638     struct ciss_softc		*sc;
3639     struct ciss_request		*cr;
3640     struct ciss_notify		*cn;
3641     int				s;
3642 
3643 #if __FreeBSD_version >= 500000
3644     mtx_lock(&Giant);
3645 #endif
3646     sc = (struct ciss_softc *)arg;
3647 
3648     s = splcam();
3649     for (;;) {
3650 	if (TAILQ_EMPTY(&sc->ciss_notify) != 0 &&
3651 	    (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
3652 	    tsleep(&sc->ciss_notify, PUSER, "idle", 0);
3653 	}
3654 
3655 	if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
3656 	    break;
3657 
3658 	cr = ciss_dequeue_notify(sc);
3659 	splx(s);
3660 
3661 	if (cr == NULL)
3662 		panic("cr null");
3663 	cn = (struct ciss_notify *)cr->cr_data;
3664 
3665 	switch (cn->class) {
3666 	case CISS_NOTIFY_HOTPLUG:
3667 	    ciss_notify_hotplug(sc, cn);
3668 	    break;
3669 	case CISS_NOTIFY_LOGICAL:
3670 	    ciss_notify_logical(sc, cn);
3671 	    break;
3672 	case CISS_NOTIFY_PHYSICAL:
3673 	    ciss_notify_physical(sc, cn);
3674 	    break;
3675 	}
3676 
3677 	ciss_release_request(cr);
3678 
3679 	s = splcam();
3680     }
3681     sc->ciss_notify_thread = NULL;
3682     wakeup(&sc->ciss_notify_thread);
3683     splx(s);
3684 
3685 #if __FreeBSD_version >= 500000
3686     mtx_unlock(&Giant);
3687 #endif
3688     kthread_exit(0);
3689 }
3690 
3691 /************************************************************************
3692  * Start the notification kernel thread.
3693  */
3694 static void
3695 ciss_spawn_notify_thread(struct ciss_softc *sc)
3696 {
3697 
3698 #if __FreeBSD_version > 500005
3699     if (kthread_create((void(*)(void *))ciss_notify_thread, sc,
3700 		       &sc->ciss_notify_thread, 0, 0, "ciss_notify%d",
3701 		       device_get_unit(sc->ciss_dev)))
3702 #else
3703     if (kthread_create((void(*)(void *))ciss_notify_thread, sc,
3704 		       &sc->ciss_notify_thread, "ciss_notify%d",
3705 		       device_get_unit(sc->ciss_dev)))
3706 #endif
3707 	panic("Could not create notify thread\n");
3708 }
3709 
3710 /************************************************************************
3711  * Kill the notification kernel thread.
3712  */
3713 static void
3714 ciss_kill_notify_thread(struct ciss_softc *sc)
3715 {
3716 
3717     if (sc->ciss_notify_thread == NULL)
3718 	return;
3719 
3720     sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
3721     wakeup(&sc->ciss_notify);
3722     tsleep(&sc->ciss_notify_thread, PUSER, "thtrm", 0);
3723 }
3724 
3725 /************************************************************************
3726  * Print a request.
3727  */
3728 static void
3729 ciss_print_request(struct ciss_request *cr)
3730 {
3731     struct ciss_softc	*sc;
3732     struct ciss_command	*cc;
3733     int			i;
3734 
3735     sc = cr->cr_sc;
3736     cc = CISS_FIND_COMMAND(cr);
3737 
3738     ciss_printf(sc, "REQUEST @ %p\n", cr);
3739     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
3740 	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
3741 	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
3742     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
3743 		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
3744     switch(cc->header.address.mode.mode) {
3745     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
3746     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
3747 	ciss_printf(sc, "  physical bus %d target %d\n",
3748 		    cc->header.address.physical.bus, cc->header.address.physical.target);
3749 	break;
3750     case CISS_HDR_ADDRESS_MODE_LOGICAL:
3751 	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
3752 	break;
3753     }
3754     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
3755 		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
3756 		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
3757 		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
3758 		cc->cdb.cdb_length,
3759 		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
3760 		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
3761 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
3762 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
3763 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
3764 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
3765 		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
3766     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
3767 
3768     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
3769 	/* XXX print error info */
3770     } else {
3771 	/* since we don't use chained s/g, don't support it here */
3772 	for (i = 0; i < cc->header.sg_in_list; i++) {
3773 	    if ((i % 4) == 0)
3774 		ciss_printf(sc, "   ");
3775 	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
3776 	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
3777 		printf("\n");
3778 	}
3779     }
3780 }
3781 
3782 /************************************************************************
3783  * Print information about the status of a logical drive.
3784  */
3785 static void
3786 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
3787 {
3788     int		bus, target, i;
3789 
3790     if (ld->cl_lstatus == NULL) {
3791 	printf("does not exist\n");
3792 	return;
3793     }
3794 
3795     /* print drive status */
3796     switch(ld->cl_lstatus->status) {
3797     case CISS_LSTATUS_OK:
3798 	printf("online\n");
3799 	break;
3800     case CISS_LSTATUS_INTERIM_RECOVERY:
3801 	printf("in interim recovery mode\n");
3802 	break;
3803     case CISS_LSTATUS_READY_RECOVERY:
3804 	printf("ready to begin recovery\n");
3805 	break;
3806     case CISS_LSTATUS_RECOVERING:
3807 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3808 	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3809 	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
3810 	       bus, target, ld->cl_lstatus->blocks_to_recover);
3811 	break;
3812     case CISS_LSTATUS_EXPANDING:
3813 	printf("being expanded, %u blocks remaining\n",
3814 	       ld->cl_lstatus->blocks_to_recover);
3815 	break;
3816     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3817 	printf("queued for expansion\n");
3818 	break;
3819     case CISS_LSTATUS_FAILED:
3820 	printf("queued for expansion\n");
3821 	break;
3822     case CISS_LSTATUS_WRONG_PDRIVE:
3823 	printf("wrong physical drive inserted\n");
3824 	break;
3825     case CISS_LSTATUS_MISSING_PDRIVE:
3826 	printf("missing a needed physical drive\n");
3827 	break;
3828     case CISS_LSTATUS_BECOMING_READY:
3829 	printf("becoming ready\n");
3830 	break;
3831     }
3832 
3833     /* print failed physical drives */
3834     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
3835 	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
3836 	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
3837 	if (bus == -1)
3838 	    continue;
3839 	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
3840 		    ld->cl_lstatus->drive_failure_map[i]);
3841     }
3842 }
3843 
3844 #ifdef CISS_DEBUG
3845 /************************************************************************
3846  * Print information about the controller/driver.
3847  */
3848 static void
3849 ciss_print_adapter(struct ciss_softc *sc)
3850 {
3851     int		i, j;
3852 
3853     ciss_printf(sc, "ADAPTER:\n");
3854     for (i = 0; i < CISSQ_COUNT; i++) {
3855 	ciss_printf(sc, "%s     %d/%d\n",
3856 	    i == 0 ? "free" :
3857 	    i == 1 ? "busy" : "complete",
3858 	    sc->ciss_qstat[i].q_length,
3859 	    sc->ciss_qstat[i].q_max);
3860     }
3861     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
3862     ciss_printf(sc, "flags %b\n", sc->ciss_flags,
3863 	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
3864 
3865     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3866 	for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3867 	    ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
3868 	    ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
3869 	}
3870     }
3871 
3872     /* XXX Should physical drives be printed out here? */
3873 
3874     for (i = 1; i < sc->ciss_max_requests; i++)
3875 	ciss_print_request(sc->ciss_request + i);
3876 }
3877 
3878 /* DDB hook */
3879 static void
3880 ciss_print0(void)
3881 {
3882     struct ciss_softc	*sc;
3883 
3884     sc = devclass_get_softc(devclass_find("ciss"), 0);
3885     if (sc == NULL) {
3886 	printf("no ciss controllers\n");
3887     } else {
3888 	ciss_print_adapter(sc);
3889     }
3890 }
3891 #endif
3892 
3893 /************************************************************************
3894  * Return a name for a logical drive status value.
3895  */
3896 static const char *
3897 ciss_name_ldrive_status(int status)
3898 {
3899     switch (status) {
3900     case CISS_LSTATUS_OK:
3901 	return("OK");
3902     case CISS_LSTATUS_FAILED:
3903 	return("failed");
3904     case CISS_LSTATUS_NOT_CONFIGURED:
3905 	return("not configured");
3906     case CISS_LSTATUS_INTERIM_RECOVERY:
3907 	return("interim recovery");
3908     case CISS_LSTATUS_READY_RECOVERY:
3909 	return("ready for recovery");
3910     case CISS_LSTATUS_RECOVERING:
3911 	return("recovering");
3912     case CISS_LSTATUS_WRONG_PDRIVE:
3913 	return("wrong physical drive inserted");
3914     case CISS_LSTATUS_MISSING_PDRIVE:
3915 	return("missing physical drive");
3916     case CISS_LSTATUS_EXPANDING:
3917 	return("expanding");
3918     case CISS_LSTATUS_BECOMING_READY:
3919 	return("becoming ready");
3920     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3921 	return("queued for expansion");
3922     }
3923     return("unknown status");
3924 }
3925 
3926 /************************************************************************
3927  * Return an online/offline/nonexistent value for a logical drive
3928  * status value.
3929  */
3930 static int
3931 ciss_decode_ldrive_status(int status)
3932 {
3933     switch(status) {
3934     case CISS_LSTATUS_NOT_CONFIGURED:
3935 	return(CISS_LD_NONEXISTENT);
3936 
3937     case CISS_LSTATUS_OK:
3938     case CISS_LSTATUS_INTERIM_RECOVERY:
3939     case CISS_LSTATUS_READY_RECOVERY:
3940     case CISS_LSTATUS_RECOVERING:
3941     case CISS_LSTATUS_EXPANDING:
3942     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3943 	return(CISS_LD_ONLINE);
3944 
3945     case CISS_LSTATUS_FAILED:
3946     case CISS_LSTATUS_WRONG_PDRIVE:
3947     case CISS_LSTATUS_MISSING_PDRIVE:
3948     case CISS_LSTATUS_BECOMING_READY:
3949     default:
3950 	return(CISS_LD_OFFLINE);
3951     }
3952 }
3953 
3954 
3955 /************************************************************************
3956  * Return a name for a logical drive's organisation.
3957  */
3958 static const char *
3959 ciss_name_ldrive_org(int org)
3960 {
3961     switch(org) {
3962     case CISS_LDRIVE_RAID0:
3963 	return("RAID 0");
3964     case CISS_LDRIVE_RAID1:
3965 	return("RAID 1");
3966     case CISS_LDRIVE_RAID4:
3967 	return("RAID 4");
3968     case CISS_LDRIVE_RAID5:
3969 	return("RAID 5");
3970     case CISS_LDRIVE_RAID51:
3971 	return("RAID 5+1");
3972     case CISS_LDRIVE_RAIDADG:
3973 	return("RAID ADG");
3974     }
3975     return("unkown");
3976 }
3977 
3978 /************************************************************************
3979  * Return a name for a command status value.
3980  */
3981 static const char *
3982 ciss_name_command_status(int status)
3983 {
3984     switch(status) {
3985     case CISS_CMD_STATUS_SUCCESS:
3986 	return("success");
3987     case CISS_CMD_STATUS_TARGET_STATUS:
3988 	return("target status");
3989     case CISS_CMD_STATUS_DATA_UNDERRUN:
3990 	return("data underrun");
3991     case CISS_CMD_STATUS_DATA_OVERRUN:
3992 	return("data overrun");
3993     case CISS_CMD_STATUS_INVALID_COMMAND:
3994 	return("invalid command");
3995     case CISS_CMD_STATUS_PROTOCOL_ERROR:
3996 	return("protocol error");
3997     case CISS_CMD_STATUS_HARDWARE_ERROR:
3998 	return("hardware error");
3999     case CISS_CMD_STATUS_CONNECTION_LOST:
4000 	return("connection lost");
4001     case CISS_CMD_STATUS_ABORTED:
4002 	return("aborted");
4003     case CISS_CMD_STATUS_ABORT_FAILED:
4004 	return("abort failed");
4005     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
4006 	return("unsolicited abort");
4007     case CISS_CMD_STATUS_TIMEOUT:
4008 	return("timeout");
4009     case CISS_CMD_STATUS_UNABORTABLE:
4010 	return("unabortable");
4011     }
4012     return("unknown status");
4013 }
4014 
4015 /************************************************************************
4016  * Handle an open on the control device.
4017  */
4018 static int
4019 ciss_open(struct cdev *dev, int flags, int fmt, d_thread_t *p)
4020 {
4021     struct ciss_softc	*sc;
4022 
4023     debug_called(1);
4024 
4025     sc = (struct ciss_softc *)dev->si_drv1;
4026 
4027     /* we might want to veto if someone already has us open */
4028 
4029     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
4030     return(0);
4031 }
4032 
4033 /************************************************************************
4034  * Handle the last close on the control device.
4035  */
4036 static int
4037 ciss_close(struct cdev *dev, int flags, int fmt, d_thread_t *p)
4038 {
4039     struct ciss_softc	*sc;
4040 
4041     debug_called(1);
4042 
4043     sc = (struct ciss_softc *)dev->si_drv1;
4044 
4045     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
4046     return (0);
4047 }
4048 
4049 /********************************************************************************
4050  * Handle adapter-specific control operations.
4051  *
4052  * Note that the API here is compatible with the Linux driver, in order to
4053  * simplify the porting of Compaq's userland tools.
4054  */
4055 static int
4056 ciss_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *p)
4057 {
4058     struct ciss_softc		*sc;
4059     IOCTL_Command_struct	*ioc	= (IOCTL_Command_struct *)addr;
4060 #ifdef __amd64__
4061     IOCTL_Command_struct32	*ioc32	= (IOCTL_Command_struct32 *)addr;
4062     IOCTL_Command_struct	ioc_swab;
4063 #endif
4064     int				error;
4065 
4066     debug_called(1);
4067 
4068     sc = (struct ciss_softc *)dev->si_drv1;
4069     error = 0;
4070 
4071     switch(cmd) {
4072     case CCISS_GETPCIINFO:
4073     {
4074 	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
4075 
4076 	pis->bus = pci_get_bus(sc->ciss_dev);
4077 	pis->dev_fn = pci_get_slot(sc->ciss_dev);
4078 	pis->board_id = pci_get_devid(sc->ciss_dev);
4079 
4080 	break;
4081     }
4082 
4083     case CCISS_GETINTINFO:
4084     {
4085 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4086 
4087 	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
4088 	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
4089 
4090 	break;
4091     }
4092 
4093     case CCISS_SETINTINFO:
4094     {
4095 	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
4096 
4097 	if ((cis->delay == 0) && (cis->count == 0)) {
4098 	    error = EINVAL;
4099 	    break;
4100 	}
4101 
4102 	/*
4103 	 * XXX apparently this is only safe if the controller is idle,
4104 	 *     we should suspend it before doing this.
4105 	 */
4106 	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
4107 	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
4108 
4109 	if (ciss_update_config(sc))
4110 	    error = EIO;
4111 
4112 	/* XXX resume the controller here */
4113 	break;
4114     }
4115 
4116     case CCISS_GETNODENAME:
4117 	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
4118 	      sizeof(NodeName_type));
4119 	break;
4120 
4121     case CCISS_SETNODENAME:
4122 	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
4123 	      sizeof(NodeName_type));
4124 	if (ciss_update_config(sc))
4125 	    error = EIO;
4126 	break;
4127 
4128     case CCISS_GETHEARTBEAT:
4129 	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
4130 	break;
4131 
4132     case CCISS_GETBUSTYPES:
4133 	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
4134 	break;
4135 
4136     case CCISS_GETFIRMVER:
4137 	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
4138 	      sizeof(FirmwareVer_type));
4139 	break;
4140 
4141     case CCISS_GETDRIVERVER:
4142 	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
4143 	break;
4144 
4145     case CCISS_REVALIDVOLS:
4146 	/*
4147 	 * This is a bit ugly; to do it "right" we really need
4148 	 * to find any disks that have changed, kick CAM off them,
4149 	 * then rescan only these disks.  It'd be nice if they
4150 	 * a) told us which disk(s) they were going to play with,
4151 	 * and b) which ones had arrived. 8(
4152 	 */
4153 	break;
4154 
4155 #ifdef __amd64__
4156     case CCISS_PASSTHRU32:
4157 	ioc_swab.LUN_info	= ioc32->LUN_info;
4158 	ioc_swab.Request	= ioc32->Request;
4159 	ioc_swab.error_info	= ioc32->error_info;
4160 	ioc_swab.buf_size	= ioc32->buf_size;
4161 	ioc_swab.buf		= (u_int8_t *)(uintptr_t)ioc32->buf;
4162 	ioc			= &ioc_swab;
4163 	/* FALLTHROUGH */
4164 #endif
4165 
4166     case CCISS_PASSTHRU:
4167 	error = ciss_user_command(sc, ioc);
4168 	break;
4169 
4170     default:
4171 	debug(0, "unknown ioctl 0x%lx", cmd);
4172 
4173 	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4174 	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4175 	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4176 	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4177 	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4178 	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4179 	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4180 	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4181 	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4182 	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4183 	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4184 
4185 	error = ENOIOCTL;
4186 	break;
4187     }
4188 
4189     return(error);
4190 }
4191