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