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