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