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