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