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