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