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