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