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