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