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