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