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