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