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