DEVFS - remove dev_ops_add(), dev_ops_get(), and get_dev()
[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  *      $DragonFly: src/sys/dev/raid/ciss/ciss.c,v 1.28 2008/05/18 20:30:23 pavalos Exp $
29  */
30
31 /*
32  * Common Interface for SCSI-3 Support driver.
33  *
34  * CISS claims to provide a common interface between a generic SCSI
35  * transport and an intelligent host adapter.
36  *
37  * This driver supports CISS as defined in the document "CISS Command
38  * Interface for SCSI-3 Support Open Specification", Version 1.04,
39  * Valence Number 1, dated 20001127, produced by Compaq Computer
40  * Corporation.  This document appears to be a hastily and somewhat
41  * arbitrarlily cut-down version of a larger (and probably even more
42  * chaotic and inconsistent) Compaq internal document.  Various
43  * details were also gleaned from Compaq's "cciss" driver for Linux.
44  *
45  * We provide a shim layer between the CISS interface and CAM,
46  * offloading most of the queueing and being-a-disk chores onto CAM.
47  * Entry to the driver is via the PCI bus attachment (ciss_probe,
48  * ciss_attach, etc) and via the CAM interface (ciss_cam_action,
49  * ciss_cam_poll).  The Compaq CISS adapters are, however, poor SCSI
50  * citizens and we have to fake up some responses to get reasonable
51  * behaviour out of them.  In addition, the CISS command set is by no
52  * means adequate to support the functionality of a RAID controller,
53  * and thus the supported Compaq adapters utilise portions of the
54  * control protocol from earlier Compaq adapter families.
55  *
56  * Note that we only support the "simple" transport layer over PCI.
57  * This interface (ab)uses the I2O register set (specifically the post
58  * queues) to exchange commands with the adapter.  Other interfaces
59  * are available, but we aren't supposed to know about them, and it is
60  * dubious whether they would provide major performance improvements
61  * except under extreme load.
62  *
63  * Currently the only supported CISS adapters are the Compaq Smart
64  * Array 5* series (5300, 5i, 532).  Even with only three adapters,
65  * Compaq still manage to have interface variations.
66  *
67  *
68  * Thanks must go to Fred Harris and Darryl DeVinney at Compaq, as
69  * well as Paul Saab at Yahoo! for their assistance in making this
70  * driver happen.
71  *
72  * More thanks must go to John Cagle at HP for the countless hours
73  * spent making this driver "work" with the MSA* series storage
74  * enclosures.  Without his help (and nagging), this driver could not
75  * be used with these enclosures.
76  */
77
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/device.h>
81 #include <sys/malloc.h>
82 #include <sys/kernel.h>
83 #include <sys/bus.h>
84 #include <sys/conf.h>
85 #include <sys/devicestat.h>
86 #include <sys/stat.h>
87 #include <sys/kthread.h>
88 #include <sys/queue.h>
89 #include <sys/rman.h>
90
91 #include <bus/cam/cam.h>
92 #include <bus/cam/cam_ccb.h>
93 #include <bus/cam/cam_periph.h>
94 #include <bus/cam/cam_sim.h>
95 #include <bus/cam/cam_xpt_sim.h>
96 #include <bus/cam/scsi/scsi_all.h>
97 #include <bus/cam/scsi/scsi_message.h>
98
99 #include <machine/clock.h>
100 #include <machine/endian.h>
101
102 #include <bus/pci/pcireg.h>
103 #include <bus/pci/pcivar.h>
104
105 #include "cissreg.h"
106 #include "cissvar.h"
107 #include "cissio.h"
108
109 MALLOC_DEFINE(CISS_MALLOC_CLASS, "ciss_data", "ciss internal data buffers");
110
111 /* pci interface */
112 static int      ciss_lookup(device_t dev);
113 static int      ciss_probe(device_t dev);
114 static int      ciss_attach(device_t dev);
115 static int      ciss_detach(device_t dev);
116 static int      ciss_shutdown(device_t dev);
117
118 /* (de)initialisation functions, control wrappers */
119 static int      ciss_init_pci(struct ciss_softc *sc);
120 static int      ciss_wait_adapter(struct ciss_softc *sc);
121 static int      ciss_flush_adapter(struct ciss_softc *sc);
122 static int      ciss_init_requests(struct ciss_softc *sc);
123 static void     ciss_command_map_helper(void *arg, bus_dma_segment_t *segs,
124                                         int nseg, int error);
125 static int      ciss_identify_adapter(struct ciss_softc *sc);
126 static int      ciss_init_logical(struct ciss_softc *sc);
127 static int      ciss_init_physical(struct ciss_softc *sc);
128 static int      ciss_filter_physical(struct ciss_softc *sc, struct ciss_lun_report *cll);
129 static int      ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld);
130 static int      ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld);
131 static int      ciss_update_config(struct ciss_softc *sc);
132 static int      ciss_accept_media(struct ciss_softc *sc, struct ciss_ldrive *ld);
133 static void     ciss_free(struct ciss_softc *sc);
134 static void     ciss_spawn_notify_thread(struct ciss_softc *sc);
135 static void     ciss_kill_notify_thread(struct ciss_softc *sc);
136
137 /* request submission/completion */
138 static int      ciss_start(struct ciss_request *cr);
139 static void     ciss_done(struct ciss_softc *sc);
140 static void     ciss_intr(void *arg);
141 static void     ciss_complete(struct ciss_softc *sc);
142 static int      ciss_report_request(struct ciss_request *cr, int *command_status,
143                                     int *scsi_status);
144 static int      ciss_synch_request(struct ciss_request *cr, int timeout);
145 static int      ciss_poll_request(struct ciss_request *cr, int timeout);
146 static int      ciss_wait_request(struct ciss_request *cr, int timeout);
147 #if 0
148 static int      ciss_abort_request(struct ciss_request *cr);
149 #endif
150
151 /* request queueing */
152 static int      ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp);
153 static void     ciss_preen_command(struct ciss_request *cr);
154 static void     ciss_release_request(struct ciss_request *cr);
155
156 /* request helpers */
157 static int      ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
158                                       int opcode, void **bufp, size_t bufsize);
159 static int      ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc);
160
161 /* DMA map/unmap */
162 static int      ciss_map_request(struct ciss_request *cr);
163 static void     ciss_request_map_helper(void *arg, bus_dma_segment_t *segs,
164                                         int nseg, int error);
165 static void     ciss_unmap_request(struct ciss_request *cr);
166
167 /* CAM interface */
168 static int      ciss_cam_init(struct ciss_softc *sc);
169 static void     ciss_cam_rescan_target(struct ciss_softc *sc,
170                                        int bus, int target);
171 static void     ciss_cam_rescan_all(struct ciss_softc *sc);
172 static void     ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb);
173 static void     ciss_cam_action(struct cam_sim *sim, union ccb *ccb);
174 static int      ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio);
175 static int      ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio);
176 static void     ciss_cam_poll(struct cam_sim *sim);
177 static void     ciss_cam_complete(struct ciss_request *cr);
178 static void     ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio);
179 static struct cam_periph *ciss_find_periph(struct ciss_softc *sc,
180                                            int bus, int target);
181 static int      ciss_name_device(struct ciss_softc *sc, int bus, int target);
182
183 /* periodic status monitoring */
184 static void     ciss_periodic(void *arg);
185 static void     ciss_notify_event(struct ciss_softc *sc);
186 static void     ciss_notify_complete(struct ciss_request *cr);
187 static int      ciss_notify_abort(struct ciss_softc *sc);
188 static int      ciss_notify_abort_bmic(struct ciss_softc *sc);
189 static void     ciss_notify_hotplug(struct ciss_softc *sc, struct ciss_notify *cn);
190 static void     ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn);
191 static void     ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn);
192
193 /* debugging output */
194 static void     ciss_print_request(struct ciss_request *cr);
195 static void     ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld);
196 static const char *ciss_name_ldrive_status(int status);
197 static int      ciss_decode_ldrive_status(int status);
198 static const char *ciss_name_ldrive_org(int org);
199 static const char *ciss_name_command_status(int status);
200
201 /*
202  * PCI bus interface.
203  */
204 static device_method_t ciss_methods[] = {
205     /* Device interface */
206     DEVMETHOD(device_probe,     ciss_probe),
207     DEVMETHOD(device_attach,    ciss_attach),
208     DEVMETHOD(device_detach,    ciss_detach),
209     DEVMETHOD(device_shutdown,  ciss_shutdown),
210     { 0, 0 }
211 };
212
213 static driver_t ciss_pci_driver = {
214     "ciss",
215     ciss_methods,
216     sizeof(struct ciss_softc)
217 };
218
219 static devclass_t       ciss_devclass;
220
221 DECLARE_DUMMY_MODULE(ciss);
222 DRIVER_MODULE(ciss, pci, ciss_pci_driver, ciss_devclass, 0, 0);
223
224 /*
225  * Control device interface.
226  */
227 static d_open_t         ciss_open;
228 static d_close_t        ciss_close;
229 static d_ioctl_t        ciss_ioctl;
230
231 #define CISS_CDEV_MAJOR  166
232
233 static struct dev_ops ciss_ops = {
234     { "ciss", CISS_CDEV_MAJOR, 0 },
235     .d_open =           ciss_open,
236     .d_close =          ciss_close,
237     .d_ioctl =          ciss_ioctl
238 };
239
240 /*
241  * This tunable can be set at boot time and controls whether physical devices
242  * that are marked hidden by the firmware should be exposed anyways.
243  */
244 static unsigned int ciss_expose_hidden_physical = 0;
245 TUNABLE_INT("hw.ciss.expose_hidden_physical", &ciss_expose_hidden_physical);
246
247 /************************************************************************
248  * CISS adapters amazingly don't have a defined programming interface
249  * value.  (One could say some very despairing things about PCI and
250  * people just not getting the general idea.)  So we are forced to
251  * stick with matching against subvendor/subdevice, and thus have to
252  * be updated for every new CISS adapter that appears.
253  */
254 #define CISS_BOARD_SA5  (1<<0)
255 #define CISS_BOARD_SA5B (1<<1)
256
257 static struct
258 {
259     u_int16_t   subvendor;
260     u_int16_t   subdevice;
261     int         flags;
262     char        *desc;
263 } ciss_vendor_data[] = {
264     { 0x0e11, 0x4070, CISS_BOARD_SA5,   "Compaq Smart Array 5300" },
265     { 0x0e11, 0x4080, CISS_BOARD_SA5B,  "Compaq Smart Array 5i" },
266     { 0x0e11, 0x4082, CISS_BOARD_SA5B,  "Compaq Smart Array 532" },
267     { 0x0e11, 0x4083, CISS_BOARD_SA5B,  "HP Smart Array 5312" },
268     { 0x0e11, 0x4091, CISS_BOARD_SA5,   "HP Smart Array 6i" },
269     { 0x0e11, 0x409A, CISS_BOARD_SA5,   "HP Smart Array 641" },
270     { 0x0e11, 0x409B, CISS_BOARD_SA5,   "HP Smart Array 642" },
271     { 0x0e11, 0x409C, CISS_BOARD_SA5,   "HP Smart Array 6400" },
272     { 0x0e11, 0x409D, CISS_BOARD_SA5,   "HP Smart Array 6400 EM" },
273     { 0x103C, 0x3211, CISS_BOARD_SA5,   "HP Smart Array E200i" },
274     { 0x103C, 0x3212, CISS_BOARD_SA5,   "HP Smart Array E200" },
275     { 0x103C, 0x3213, CISS_BOARD_SA5,   "HP Smart Array E200i" },
276     { 0x103C, 0x3214, CISS_BOARD_SA5,   "HP Smart Array E200i" },
277     { 0x103C, 0x3215, CISS_BOARD_SA5,   "HP Smart Array E200i" },
278     { 0x103C, 0x3220, CISS_BOARD_SA5,   "HP Smart Array" },
279     { 0x103C, 0x3222, CISS_BOARD_SA5,   "HP Smart Array" },
280     { 0x103C, 0x3223, CISS_BOARD_SA5,   "HP Smart Array P800" },
281     { 0x103C, 0x3225, CISS_BOARD_SA5,   "HP Smart Array P600" },
282     { 0x103C, 0x3230, CISS_BOARD_SA5,   "HP Smart Array" },
283     { 0x103C, 0x3231, CISS_BOARD_SA5,   "HP Smart Array" },
284     { 0x103C, 0x3232, CISS_BOARD_SA5,   "HP Smart Array" },
285     { 0x103C, 0x3233, CISS_BOARD_SA5,   "HP Smart Array" },
286     { 0x103C, 0x3234, CISS_BOARD_SA5,   "HP Smart Array P400" },
287     { 0x103C, 0x3235, CISS_BOARD_SA5,   "HP Smart Array P400i" },
288     { 0x103C, 0x3236, CISS_BOARD_SA5,   "HP Smart Array" },
289     { 0x103C, 0x3237, CISS_BOARD_SA5,   "HP Smart Array" },
290     { 0x103C, 0x3238, CISS_BOARD_SA5,   "HP Smart Array" },
291     { 0x103C, 0x3239, CISS_BOARD_SA5,   "HP Smart Array" },
292     { 0x103C, 0x323A, CISS_BOARD_SA5,   "HP Smart Array" },
293     { 0x103C, 0x323B, CISS_BOARD_SA5,   "HP Smart Array" },
294     { 0x103C, 0x323C, CISS_BOARD_SA5,   "HP Smart Array" },
295     { 0x103C, 0x3241, CISS_BOARD_SA5,   "HP Smart Array P212" },
296     { 0x103C, 0x3243, CISS_BOARD_SA5,   "HP Smart Array P410" },
297     { 0x103C, 0x3245, CISS_BOARD_SA5,   "HP Smart Array P410i" },
298     { 0x103C, 0x3247, CISS_BOARD_SA5,   "HP Smart Array P411" },
299     { 0x103C, 0x3249, CISS_BOARD_SA5,   "HP Smart Array P812" },
300     { 0, 0, 0, NULL }
301 };
302
303 /************************************************************************
304  * Find a match for the device in our list of known adapters.
305  */
306 static int
307 ciss_lookup(device_t dev)
308 {
309     int         i;
310
311     for (i = 0; ciss_vendor_data[i].desc != NULL; i++)
312         if ((pci_get_subvendor(dev) == ciss_vendor_data[i].subvendor) &&
313             (pci_get_subdevice(dev) == ciss_vendor_data[i].subdevice)) {
314             return(i);
315         }
316     return(-1);
317 }
318
319 /************************************************************************
320  * Match a known CISS adapter.
321  */
322 static int
323 ciss_probe(device_t dev)
324 {
325     int         i;
326
327     i = ciss_lookup(dev);
328     if (i != -1) {
329         device_set_desc(dev, ciss_vendor_data[i].desc);
330         return(-10);
331     }
332     return(ENOENT);
333 }
334
335 /************************************************************************
336  * Attach the driver to this adapter.
337  */
338 static int
339 ciss_attach(device_t dev)
340 {
341     struct ciss_softc   *sc;
342     int                 i, error;
343
344     debug_called(1);
345
346 #ifdef CISS_DEBUG
347     /* print structure/union sizes */
348     debug_struct(ciss_command);
349     debug_struct(ciss_header);
350     debug_union(ciss_device_address);
351     debug_struct(ciss_cdb);
352     debug_struct(ciss_report_cdb);
353     debug_struct(ciss_notify_cdb);
354     debug_struct(ciss_notify);
355     debug_struct(ciss_message_cdb);
356     debug_struct(ciss_error_info_pointer);
357     debug_struct(ciss_error_info);
358     debug_struct(ciss_sg_entry);
359     debug_struct(ciss_config_table);
360     debug_struct(ciss_bmic_cdb);
361     debug_struct(ciss_bmic_id_ldrive);
362     debug_struct(ciss_bmic_id_lstatus);
363     debug_struct(ciss_bmic_id_table);
364     debug_struct(ciss_bmic_id_pdrive);
365     debug_struct(ciss_bmic_blink_pdrive);
366     debug_struct(ciss_bmic_flush_cache);
367     debug_const(CISS_MAX_REQUESTS);
368     debug_const(CISS_MAX_LOGICAL);
369     debug_const(CISS_INTERRUPT_COALESCE_DELAY);
370     debug_const(CISS_INTERRUPT_COALESCE_COUNT);
371     debug_const(CISS_COMMAND_ALLOC_SIZE);
372     debug_const(CISS_COMMAND_SG_LENGTH);
373
374     debug_type(cciss_pci_info_struct);
375     debug_type(cciss_coalint_struct);
376     debug_type(cciss_coalint_struct);
377     debug_type(NodeName_type);
378     debug_type(NodeName_type);
379     debug_type(Heartbeat_type);
380     debug_type(BusTypes_type);
381     debug_type(FirmwareVer_type);
382     debug_type(DriverVer_type);
383     debug_type(IOCTL_Command_struct);
384 #endif
385
386     sc = device_get_softc(dev);
387     sc->ciss_dev = dev;
388     callout_init(&sc->ciss_periodic);
389
390     /*
391      * Work out adapter type.
392      */
393     i = ciss_lookup(dev);
394     if (ciss_vendor_data[i].flags & CISS_BOARD_SA5) {
395         sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5;
396     } else if (ciss_vendor_data[i].flags & CISS_BOARD_SA5B) {
397         sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5B;
398     } else {
399         /* really an error on our part */
400         ciss_printf(sc, "unable to determine hardware type\n");
401         error = ENXIO;
402         goto out;
403     }
404
405     /*
406      * Do PCI-specific init.
407      */
408     if ((error = ciss_init_pci(sc)) != 0)
409         goto out;
410
411     /*
412      * Initialise driver queues.
413      */
414     ciss_initq_free(sc);
415     ciss_initq_busy(sc);
416     ciss_initq_complete(sc);
417     ciss_initq_notify(sc);
418
419     /*
420      * Initialise command/request pool.
421      */
422     if ((error = ciss_init_requests(sc)) != 0)
423         goto out;
424
425     /*
426      * Get adapter information.
427      */
428     if ((error = ciss_identify_adapter(sc)) != 0)
429         goto out;
430
431     /*
432      * Find all the physical devices.
433      */
434     if ((error = ciss_init_physical(sc)) != 0)
435         goto out;
436
437     /*
438      * Build our private table of logical devices.
439      */
440     if ((error = ciss_init_logical(sc)) != 0)
441         goto out;
442
443     /*
444      * Enable interrupts so that the CAM scan can complete.
445      */
446     CISS_TL_SIMPLE_ENABLE_INTERRUPTS(sc);
447
448     /*
449      * Initialise the CAM interface.
450      */
451     if ((error = ciss_cam_init(sc)) != 0)
452         goto out;
453
454     /*
455      * Start the heartbeat routine and event chain.
456      */
457     ciss_periodic(sc);
458
459     /*
460      * Create the control device.
461      */
462     sc->ciss_dev_t = make_dev(&ciss_ops, device_get_unit(sc->ciss_dev),
463                               UID_ROOT, GID_OPERATOR, S_IRUSR | S_IWUSR,
464                               "ciss%d", device_get_unit(sc->ciss_dev));
465     sc->ciss_dev_t->si_drv1 = sc;
466
467     /*
468      * The adapter is running; synchronous commands can now sleep
469      * waiting for an interrupt to signal completion.
470      */
471     sc->ciss_flags |= CISS_FLAG_RUNNING;
472
473     ciss_spawn_notify_thread(sc);
474
475     error = 0;
476  out:
477     if (error != 0)
478         ciss_free(sc);
479     return(error);
480 }
481
482 /************************************************************************
483  * Detach the driver from this adapter.
484  */
485 static int
486 ciss_detach(device_t dev)
487 {
488     struct ciss_softc   *sc = device_get_softc(dev);
489
490     debug_called(1);
491
492     if (sc->ciss_flags & CISS_FLAG_CONTROL_OPEN)
493         return (EBUSY);
494
495     /* flush adapter cache */
496     ciss_flush_adapter(sc);
497
498     /* release all resources */
499     ciss_free(sc);
500
501     return(0);
502 }
503
504 /************************************************************************
505  * Prepare adapter for system shutdown.
506  */
507 static int
508 ciss_shutdown(device_t dev)
509 {
510     struct ciss_softc   *sc = device_get_softc(dev);
511
512     debug_called(1);
513
514     /* flush adapter cache */
515     ciss_flush_adapter(sc);
516
517     return(0);
518 }
519
520 /************************************************************************
521  * Perform PCI-specific attachment actions.
522  */
523 static int
524 ciss_init_pci(struct ciss_softc *sc)
525 {
526     uintptr_t           cbase, csize, cofs;
527     int                 error;
528
529     debug_called(1);
530
531     /*
532      * Allocate register window first (we need this to find the config
533      * struct).
534      */
535     error = ENXIO;
536     sc->ciss_regs_rid = CISS_TL_SIMPLE_BAR_REGS;
537     if ((sc->ciss_regs_resource =
538          bus_alloc_resource(sc->ciss_dev, SYS_RES_MEMORY, &sc->ciss_regs_rid,
539                             0, ~0, 1, RF_ACTIVE)) == NULL) {
540         ciss_printf(sc, "can't allocate register window\n");
541         return(ENXIO);
542     }
543     sc->ciss_regs_bhandle = rman_get_bushandle(sc->ciss_regs_resource);
544     sc->ciss_regs_btag = rman_get_bustag(sc->ciss_regs_resource);
545
546     /*
547      * Find the BAR holding the config structure.  If it's not the one
548      * we already mapped for registers, map it too.
549      */
550     sc->ciss_cfg_rid = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_BAR) & 0xffff;
551     if (sc->ciss_cfg_rid != sc->ciss_regs_rid) {
552         if ((sc->ciss_cfg_resource =
553              bus_alloc_resource(sc->ciss_dev, SYS_RES_MEMORY, &sc->ciss_cfg_rid,
554                                 0, ~0, 1, RF_ACTIVE)) == NULL) {
555             ciss_printf(sc, "can't allocate config window\n");
556             return(ENXIO);
557         }
558         cbase = (uintptr_t)rman_get_virtual(sc->ciss_cfg_resource);
559         csize = rman_get_end(sc->ciss_cfg_resource) -
560             rman_get_start(sc->ciss_cfg_resource) + 1;
561     } else {
562         cbase = (uintptr_t)rman_get_virtual(sc->ciss_regs_resource);
563         csize = rman_get_end(sc->ciss_regs_resource) -
564             rman_get_start(sc->ciss_regs_resource) + 1;
565     }
566     cofs = CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_CFG_OFF);
567
568     /*
569      * Use the base/size/offset values we just calculated to
570      * sanity-check the config structure.  If it's OK, point to it.
571      */
572     if ((cofs + sizeof(struct ciss_config_table)) > csize) {
573         ciss_printf(sc, "config table outside window\n");
574         return(ENXIO);
575     }
576     sc->ciss_cfg = (struct ciss_config_table *)(cbase + cofs);
577     debug(1, "config struct at %p", sc->ciss_cfg);
578
579     /*
580      * Validate the config structure.  If we supported other transport
581      * methods, we could select amongst them at this point in time.
582      */
583     if (strncmp(sc->ciss_cfg->signature, "CISS", 4)) {
584         ciss_printf(sc, "config signature mismatch (got '%c%c%c%c')\n",
585                     sc->ciss_cfg->signature[0], sc->ciss_cfg->signature[1],
586                     sc->ciss_cfg->signature[2], sc->ciss_cfg->signature[3]);
587         return(ENXIO);
588     }
589
590     /*
591      * Put the board into simple mode, and tell it we're using the low
592      * 4GB of RAM.  Set the default interrupt coalescing options.
593      */
594     if (!(sc->ciss_cfg->supported_methods & CISS_TRANSPORT_METHOD_SIMPLE)) {
595         ciss_printf(sc, "adapter does not support 'simple' transport layer\n");
596         return(ENXIO);
597     }
598     sc->ciss_cfg->requested_method = CISS_TRANSPORT_METHOD_SIMPLE;
599     sc->ciss_cfg->command_physlimit = 0;
600     sc->ciss_cfg->interrupt_coalesce_delay = CISS_INTERRUPT_COALESCE_DELAY;
601     sc->ciss_cfg->interrupt_coalesce_count = CISS_INTERRUPT_COALESCE_COUNT;
602
603 #ifdef __i386__
604     sc->ciss_cfg->host_driver |= CISS_DRIVER_SCSI_PREFETCH;
605 #endif
606
607     if (ciss_update_config(sc)) {
608         ciss_printf(sc, "adapter refuses to accept config update (IDBR 0x%x)\n",
609                     CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR));
610         return(ENXIO);
611     }
612     if (!(sc->ciss_cfg->active_method != CISS_TRANSPORT_METHOD_SIMPLE)) {
613         ciss_printf(sc,
614                     "adapter refuses to go into 'simple' transport mode (0x%x, 0x%x)\n",
615                     sc->ciss_cfg->supported_methods, sc->ciss_cfg->active_method);
616         return(ENXIO);
617     }
618
619     /*
620      * Wait for the adapter to come ready.
621      */
622     if ((error = ciss_wait_adapter(sc)) != 0)
623         return(error);
624
625     /*
626      * Turn off interrupts before we go routing anything.
627      */
628     CISS_TL_SIMPLE_DISABLE_INTERRUPTS(sc);
629
630     /*
631      * Allocate and set up our interrupt.
632      */
633     sc->ciss_irq_rid = 0;
634     if ((sc->ciss_irq_resource =
635          bus_alloc_resource(sc->ciss_dev, SYS_RES_IRQ, &sc->ciss_irq_rid, 0, ~0, 1, 
636                             RF_ACTIVE | RF_SHAREABLE)) == NULL) {
637         ciss_printf(sc, "can't allocate interrupt\n");
638         return(ENXIO);
639     }
640     error = bus_setup_intr(sc->ciss_dev, sc->ciss_irq_resource, 
641                            0, ciss_intr, sc,
642                            &sc->ciss_intr, NULL);
643     if (error) {
644         ciss_printf(sc, "can't set up interrupt\n");
645         return(ENXIO);
646     }
647
648     /*
649      * Allocate the parent bus DMA tag appropriate for our PCI
650      * interface.
651      *
652      * Note that "simple" adapters can only address within a 32-bit
653      * span.
654      */
655     if (bus_dma_tag_create(NULL,                        /* parent */
656                            1, 0,                        /* alignment, boundary */
657                            BUS_SPACE_MAXADDR,           /* lowaddr */
658                            BUS_SPACE_MAXADDR,           /* highaddr */
659                            NULL, NULL,                  /* filter, filterarg */
660                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsize */
661                            CISS_COMMAND_SG_LENGTH,      /* nsegments */
662                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
663                            BUS_DMA_ALLOCNOW,            /* flags */
664                            &sc->ciss_parent_dmat)) {
665         ciss_printf(sc, "can't allocate parent DMA tag\n");
666         return(ENOMEM);
667     }
668
669     /*
670      * Create DMA tag for mapping buffers into adapter-addressable
671      * space.
672      */
673     if (bus_dma_tag_create(sc->ciss_parent_dmat,        /* parent */
674                            1, 0,                        /* alignment, boundary */
675                            BUS_SPACE_MAXADDR,           /* lowaddr */
676                            BUS_SPACE_MAXADDR,           /* highaddr */
677                            NULL, NULL,                  /* filter, filterarg */
678                            MAXBSIZE, CISS_COMMAND_SG_LENGTH,    /* maxsize, nsegments */
679                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
680                            0,                           /* flags */
681                            &sc->ciss_buffer_dmat)) {
682         ciss_printf(sc, "can't allocate buffer DMA tag\n");
683         return(ENOMEM);
684     }
685     return(0);
686 }
687
688 /************************************************************************
689  * Wait for the adapter to come ready.
690  */
691 static int
692 ciss_wait_adapter(struct ciss_softc *sc)
693 {
694     int         i;
695
696     debug_called(1);
697
698     /*
699      * Wait for the adapter to come ready.
700      */
701     if (!(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY)) {
702         ciss_printf(sc, "waiting for adapter to come ready...\n");
703         for (i = 0; !(sc->ciss_cfg->active_method & CISS_TRANSPORT_METHOD_READY); i++) {
704             DELAY(1000000);     /* one second */
705             if (i > 30) {
706                 ciss_printf(sc, "timed out waiting for adapter to come ready\n");
707                 return(EIO);
708             }
709         }
710     }
711     return(0);
712 }
713
714 /************************************************************************
715  * Flush the adapter cache.
716  */
717 static int
718 ciss_flush_adapter(struct ciss_softc *sc)
719 {
720     struct ciss_request                 *cr;
721     struct ciss_bmic_flush_cache        *cbfc;
722     int                                 error, command_status;
723
724     debug_called(1);
725
726     cr = NULL;
727     cbfc = NULL;
728
729     /*
730      * Build a BMIC request to flush the cache.  We don't disable
731      * it, as we may be going to do more I/O (eg. we are emulating
732      * the Synchronise Cache command).
733      */
734     cbfc = kmalloc(sizeof(*cbfc), CISS_MALLOC_CLASS, M_INTWAIT | M_ZERO);
735     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_FLUSH_CACHE,
736                                        (void **)&cbfc, sizeof(*cbfc))) != 0)
737         goto out;
738
739     /*
740      * Submit the request and wait for it to complete.
741      */
742     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
743         ciss_printf(sc, "error sending BMIC FLUSH_CACHE command (%d)\n", error);
744         goto out;
745     }
746
747     /*
748      * Check response.
749      */
750     ciss_report_request(cr, &command_status, NULL);
751     switch(command_status) {
752     case CISS_CMD_STATUS_SUCCESS:
753         break;
754     default:
755         ciss_printf(sc, "error flushing cache (%s)\n",
756                     ciss_name_command_status(command_status));
757         error = EIO;
758         goto out;
759     }
760
761 out:
762     if (cbfc != NULL)
763         kfree(cbfc, CISS_MALLOC_CLASS);
764     if (cr != NULL)
765         ciss_release_request(cr);
766     return(error);
767 }
768
769 /************************************************************************
770  * Allocate memory for the adapter command structures, initialise
771  * the request structures.
772  *
773  * Note that the entire set of commands are allocated in a single
774  * contiguous slab.
775  */
776 static int
777 ciss_init_requests(struct ciss_softc *sc)
778 {
779     struct ciss_request *cr;
780     int                 i;
781
782     debug_called(1);
783
784     /*
785      * Calculate the number of request structures/commands we are
786      * going to provide for this adapter.
787      */
788     sc->ciss_max_requests = min(CISS_MAX_REQUESTS, sc->ciss_cfg->max_outstanding_commands);
789
790     if (bootverbose)
791         ciss_printf(sc, "using %d of %d available commands\n",
792                     sc->ciss_max_requests, sc->ciss_cfg->max_outstanding_commands);
793
794     /*
795      * Create the DMA tag for commands.
796      */
797     if (bus_dma_tag_create(sc->ciss_parent_dmat,        /* parent */
798                            1, 0,                        /* alignment, boundary */
799                            BUS_SPACE_MAXADDR_32BIT,     /* lowaddr */
800                            BUS_SPACE_MAXADDR,           /* highaddr */
801                            NULL, NULL,                  /* filter, filterarg */
802                            CISS_COMMAND_ALLOC_SIZE *
803                            sc->ciss_max_requests, 1,    /* maxsize, nsegments */
804                            BUS_SPACE_MAXSIZE_32BIT,     /* maxsegsize */
805                            BUS_DMA_ALLOCNOW,            /* flags */
806                            &sc->ciss_command_dmat)) {
807         ciss_printf(sc, "can't allocate command DMA tag\n");
808         return(ENOMEM);
809     }
810     /*
811      * Allocate memory and make it available for DMA.
812      */
813     if (bus_dmamem_alloc(sc->ciss_command_dmat, (void **)&sc->ciss_command,
814                          BUS_DMA_NOWAIT, &sc->ciss_command_map)) {
815         ciss_printf(sc, "can't allocate command memory\n");
816         return(ENOMEM);
817     }
818     bus_dmamap_load(sc->ciss_command_dmat, sc->ciss_command_map, sc->ciss_command,
819                     CISS_COMMAND_ALLOC_SIZE * sc->ciss_max_requests,
820                     ciss_command_map_helper, sc, 0);
821     bzero(sc->ciss_command, CISS_COMMAND_ALLOC_SIZE * sc->ciss_max_requests);
822
823     /*
824      * Set up the request and command structures, push requests onto
825      * the free queue.
826      */
827     for (i = 1; i < sc->ciss_max_requests; i++) {
828         cr = &sc->ciss_request[i];
829         cr->cr_sc = sc;
830         cr->cr_tag = i;
831         bus_dmamap_create(sc->ciss_buffer_dmat, 0, &cr->cr_datamap);
832         ciss_enqueue_free(cr);
833     }
834     return(0);
835 }
836
837 static void
838 ciss_command_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
839 {
840     struct ciss_softc   *sc = (struct ciss_softc *)arg;
841
842     sc->ciss_command_phys = segs->ds_addr;
843 }
844
845 /************************************************************************
846  * Identify the adapter, print some information about it.
847  */
848 static int
849 ciss_identify_adapter(struct ciss_softc *sc)
850 {
851     struct ciss_request *cr;
852     int                 error, command_status;
853
854     debug_called(1);
855
856     cr = NULL;
857
858     /*
859      * Get a request, allocate storage for the adapter data.
860      */
861     if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_CTLR,
862                                        (void **)&sc->ciss_id,
863                                        sizeof(*sc->ciss_id))) != 0)
864         goto out;
865
866     /*
867      * Submit the request and wait for it to complete.
868      */
869     if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
870         ciss_printf(sc, "error sending BMIC ID_CTLR command (%d)\n", error);
871         goto out;
872     }
873
874     /*
875      * Check response.
876      */
877     ciss_report_request(cr, &command_status, NULL);
878     switch(command_status) {
879     case CISS_CMD_STATUS_SUCCESS:               /* buffer right size */
880         break;
881     case CISS_CMD_STATUS_DATA_UNDERRUN:
882     case CISS_CMD_STATUS_DATA_OVERRUN:
883         ciss_printf(sc, "data over/underrun reading adapter information\n");
884     default:
885         ciss_printf(sc, "error reading adapter information (%s)\n",
886                     ciss_name_command_status(command_status));
887         error = EIO;
888         goto out;
889     }
890
891     /* sanity-check reply */
892     if (!sc->ciss_id->big_map_supported) {
893         ciss_printf(sc, "adapter does not support BIG_MAP\n");
894         error = ENXIO;
895         goto out;
896     }
897
898 #if 0
899     /* XXX later revisions may not 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     crit_enter();
3544     for (;;) {
3545         if (TAILQ_EMPTY(&sc->ciss_notify) != 0 &&
3546             (sc->ciss_flags & CISS_FLAG_THREAD_SHUT) == 0) {
3547             tsleep(&sc->ciss_notify, 0, "idle", 0);
3548         }
3549
3550         if (sc->ciss_flags & CISS_FLAG_THREAD_SHUT)
3551             break;
3552
3553         cr = ciss_dequeue_notify(sc);
3554         crit_exit();
3555
3556         if (cr == NULL)
3557                 panic("cr null");
3558         cn = (struct ciss_notify *)cr->cr_data;
3559
3560         switch (cn->class) {
3561         case CISS_NOTIFY_HOTPLUG:
3562             ciss_notify_hotplug(sc, cn);
3563             break;
3564         case CISS_NOTIFY_LOGICAL:
3565             ciss_notify_logical(sc, cn);
3566             break;
3567         case CISS_NOTIFY_PHYSICAL:
3568             ciss_notify_physical(sc, cn);
3569             break;
3570         }
3571
3572         ciss_release_request(cr);
3573
3574         crit_enter();
3575     }
3576     sc->ciss_notify_thread = NULL;
3577     wakeup(&sc->ciss_notify_thread);
3578     crit_exit();
3579
3580     kthread_exit();
3581 }
3582
3583 /************************************************************************
3584  * Start the notification kernel thread.
3585  */
3586 static void
3587 ciss_spawn_notify_thread(struct ciss_softc *sc)
3588 {
3589     if (kthread_create((void(*)(void *))ciss_notify_thread, sc,
3590                        &sc->ciss_notify_thread, "ciss_notify%d",
3591                        device_get_unit(sc->ciss_dev)))
3592         panic("Could not create notify thread\n");
3593 }
3594
3595 /************************************************************************
3596  * Kill the notification kernel thread.
3597  */
3598 static void
3599 ciss_kill_notify_thread(struct ciss_softc *sc)
3600 {
3601
3602     if (sc->ciss_notify_thread == NULL)
3603         return;
3604
3605     sc->ciss_flags |= CISS_FLAG_THREAD_SHUT;
3606     wakeup(&sc->ciss_notify);
3607     tsleep(&sc->ciss_notify_thread, 0, "thtrm", 0);
3608 }
3609
3610 /************************************************************************
3611  * Print a request.
3612  */
3613 static void
3614 ciss_print_request(struct ciss_request *cr)
3615 {
3616     struct ciss_softc   *sc;
3617     struct ciss_command *cc;
3618     int                 i;
3619
3620     sc = cr->cr_sc;
3621     cc = CISS_FIND_COMMAND(cr);
3622
3623     ciss_printf(sc, "REQUEST @ %p\n", cr);
3624     ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
3625               cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
3626               "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
3627     ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
3628                 cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
3629     switch(cc->header.address.mode.mode) {
3630     case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
3631     case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
3632         ciss_printf(sc, "  physical bus %d target %d\n",
3633                     cc->header.address.physical.bus, cc->header.address.physical.target);
3634         break;
3635     case CISS_HDR_ADDRESS_MODE_LOGICAL:
3636         ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
3637         break;
3638     }
3639     ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
3640                 (cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
3641                 (cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
3642                 (cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
3643                 cc->cdb.cdb_length,
3644                 (cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
3645                 (cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
3646                 (cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
3647                 (cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
3648                 (cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
3649                 (cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
3650                 (cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
3651     ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
3652
3653     if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
3654         /* XXX print error info */
3655     } else {
3656         /* since we don't use chained s/g, don't support it here */
3657         for (i = 0; i < cc->header.sg_in_list; i++) {
3658             if ((i % 4) == 0)
3659                 ciss_printf(sc, "   ");
3660             kprintf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
3661             if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
3662                 kprintf("\n");
3663         }
3664     }
3665 }
3666
3667 /************************************************************************
3668  * Print information about the status of a logical drive.
3669  */
3670 static void
3671 ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
3672 {
3673     int         bus, target, i;
3674
3675     if (ld->cl_lstatus == NULL) {
3676         kprintf("does not exist\n");
3677         return;
3678     }
3679
3680     /* print drive status */
3681     switch(ld->cl_lstatus->status) {
3682     case CISS_LSTATUS_OK:
3683         kprintf("online\n");
3684         break;
3685     case CISS_LSTATUS_INTERIM_RECOVERY:
3686         kprintf("in interim recovery mode\n");
3687         break;
3688     case CISS_LSTATUS_READY_RECOVERY:
3689         kprintf("ready to begin recovery\n");
3690         break;
3691     case CISS_LSTATUS_RECOVERING:
3692         bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3693         target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3694         kprintf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
3695                bus, target, ld->cl_lstatus->blocks_to_recover);
3696         break;
3697     case CISS_LSTATUS_EXPANDING:
3698         kprintf("being expanded, %u blocks remaining\n",
3699                ld->cl_lstatus->blocks_to_recover);
3700         break;
3701     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3702         kprintf("queued for expansion\n");
3703         break;
3704     case CISS_LSTATUS_FAILED:
3705         kprintf("queued for expansion\n");
3706         break;
3707     case CISS_LSTATUS_WRONG_PDRIVE:
3708         kprintf("wrong physical drive inserted\n");
3709         break;
3710     case CISS_LSTATUS_MISSING_PDRIVE:
3711         kprintf("missing a needed physical drive\n");
3712         break;
3713     case CISS_LSTATUS_BECOMING_READY:
3714         kprintf("becoming ready\n");
3715         break;
3716     }
3717
3718     /* print failed physical drives */
3719     for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
3720         bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
3721         target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
3722         if (bus == -1)
3723             continue;
3724         ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
3725                     ld->cl_lstatus->drive_failure_map[i]);
3726     }
3727 }
3728
3729 #ifdef CISS_DEBUG
3730 /************************************************************************
3731  * Print information about the controller/driver.
3732  */
3733 static void
3734 ciss_print_adapter(struct ciss_softc *sc)
3735 {
3736     int         i, j;
3737
3738     ciss_printf(sc, "ADAPTER:\n");
3739     for (i = 0; i < CISSQ_COUNT; i++) {
3740         ciss_printf(sc, "%s     %d/%d\n",
3741             i == 0 ? "free" :
3742             i == 1 ? "busy" : "complete",
3743             sc->ciss_qstat[i].q_length,
3744             sc->ciss_qstat[i].q_max);
3745     }
3746     ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
3747     ciss_printf(sc, "flags %b\n", sc->ciss_flags,
3748         "\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
3749
3750     for (i = 0; i < sc->ciss_max_logical_bus; i++) {
3751         for (j = 0; j < CISS_MAX_LOGICAL; j++) {
3752             ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
3753             ciss_print_ldrive(sc, &sc->ciss_logical[i][j]);
3754         }
3755     }
3756
3757     /* XXX Should physical drives be printed out here? */
3758
3759     for (i = 1; i < sc->ciss_max_requests; i++)
3760         ciss_print_request(sc->ciss_request + i);
3761 }
3762
3763 /* DDB hook */
3764 static void
3765 ciss_print0(void)
3766 {
3767     struct ciss_softc   *sc;
3768
3769     sc = devclass_get_softc(devclass_find("ciss"), 0);
3770     if (sc == NULL) {
3771         kprintf("no ciss controllers\n");
3772     } else {
3773         ciss_print_adapter(sc);
3774     }
3775 }
3776 #endif
3777
3778 /************************************************************************
3779  * Return a name for a logical drive status value.
3780  */
3781 static const char *
3782 ciss_name_ldrive_status(int status)
3783 {
3784     switch (status) {
3785     case CISS_LSTATUS_OK:
3786         return("OK");
3787     case CISS_LSTATUS_FAILED:
3788         return("failed");
3789     case CISS_LSTATUS_NOT_CONFIGURED:
3790         return("not configured");
3791     case CISS_LSTATUS_INTERIM_RECOVERY:
3792         return("interim recovery");
3793     case CISS_LSTATUS_READY_RECOVERY:
3794         return("ready for recovery");
3795     case CISS_LSTATUS_RECOVERING:
3796         return("recovering");
3797     case CISS_LSTATUS_WRONG_PDRIVE:
3798         return("wrong physical drive inserted");
3799     case CISS_LSTATUS_MISSING_PDRIVE:
3800         return("missing physical drive");
3801     case CISS_LSTATUS_EXPANDING:
3802         return("expanding");
3803     case CISS_LSTATUS_BECOMING_READY:
3804         return("becoming ready");
3805     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3806         return("queued for expansion");
3807     }
3808     return("unknown status");
3809 }
3810
3811 /************************************************************************
3812  * Return an online/offline/nonexistent value for a logical drive
3813  * status value.
3814  */
3815 static int
3816 ciss_decode_ldrive_status(int status)
3817 {
3818     switch(status) {
3819     case CISS_LSTATUS_NOT_CONFIGURED:
3820         return(CISS_LD_NONEXISTENT);
3821
3822     case CISS_LSTATUS_OK:
3823     case CISS_LSTATUS_INTERIM_RECOVERY:
3824     case CISS_LSTATUS_READY_RECOVERY:
3825     case CISS_LSTATUS_RECOVERING:
3826     case CISS_LSTATUS_EXPANDING:
3827     case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3828         return(CISS_LD_ONLINE);
3829
3830     case CISS_LSTATUS_FAILED:
3831     case CISS_LSTATUS_WRONG_PDRIVE:
3832     case CISS_LSTATUS_MISSING_PDRIVE:
3833     case CISS_LSTATUS_BECOMING_READY:
3834     default:
3835         return(CISS_LD_OFFLINE);
3836     }
3837 }
3838
3839
3840 /************************************************************************
3841  * Return a name for a logical drive's organisation.
3842  */
3843 static const char *
3844 ciss_name_ldrive_org(int org)
3845 {
3846     switch(org) {
3847     case CISS_LDRIVE_RAID0:
3848         return("RAID 0");
3849     case CISS_LDRIVE_RAID1:
3850         return("RAID 1");
3851     case CISS_LDRIVE_RAID4:
3852         return("RAID 4");
3853     case CISS_LDRIVE_RAID5:
3854         return("RAID 5");
3855     case CISS_LDRIVE_RAID51:
3856         return("RAID 5+1");
3857     case CISS_LDRIVE_RAIDADG:
3858         return("RAID ADG");
3859     }
3860     return("unknown");
3861 }
3862
3863 /************************************************************************
3864  * Return a name for a command status value.
3865  */
3866 static const char *
3867 ciss_name_command_status(int status)
3868 {
3869     switch(status) {
3870     case CISS_CMD_STATUS_SUCCESS:
3871         return("success");
3872     case CISS_CMD_STATUS_TARGET_STATUS:
3873         return("target status");
3874     case CISS_CMD_STATUS_DATA_UNDERRUN:
3875         return("data underrun");
3876     case CISS_CMD_STATUS_DATA_OVERRUN:
3877         return("data overrun");
3878     case CISS_CMD_STATUS_INVALID_COMMAND:
3879         return("invalid command");
3880     case CISS_CMD_STATUS_PROTOCOL_ERROR:
3881         return("protocol error");
3882     case CISS_CMD_STATUS_HARDWARE_ERROR:
3883         return("hardware error");
3884     case CISS_CMD_STATUS_CONNECTION_LOST:
3885         return("connection lost");
3886     case CISS_CMD_STATUS_ABORTED:
3887         return("aborted");
3888     case CISS_CMD_STATUS_ABORT_FAILED:
3889         return("abort failed");
3890     case CISS_CMD_STATUS_UNSOLICITED_ABORT:
3891         return("unsolicited abort");
3892     case CISS_CMD_STATUS_TIMEOUT:
3893         return("timeout");
3894     case CISS_CMD_STATUS_UNABORTABLE:
3895         return("unabortable");
3896     }
3897     return("unknown status");
3898 }
3899
3900 /************************************************************************
3901  * Handle an open on the control device.
3902  */
3903 static int
3904 ciss_open(struct dev_open_args *ap)
3905 {
3906     cdev_t dev = ap->a_head.a_dev;
3907     struct ciss_softc   *sc;
3908
3909     debug_called(1);
3910
3911     sc = (struct ciss_softc *)dev->si_drv1;
3912
3913     /* we might want to veto if someone already has us open */
3914
3915     sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
3916     return(0);
3917 }
3918
3919 /************************************************************************
3920  * Handle the last close on the control device.
3921  */
3922 static int
3923 ciss_close(struct dev_close_args *ap)
3924 {
3925     cdev_t dev = ap->a_head.a_dev;
3926     struct ciss_softc   *sc;
3927
3928     debug_called(1);
3929
3930     sc = (struct ciss_softc *)dev->si_drv1;
3931
3932     sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
3933     return (0);
3934 }
3935
3936 /********************************************************************************
3937  * Handle adapter-specific control operations.
3938  *
3939  * Note that the API here is compatible with the Linux driver, in order to
3940  * simplify the porting of Compaq's userland tools.
3941  */
3942 static int
3943 ciss_ioctl(struct dev_ioctl_args *ap)
3944 {
3945     cdev_t dev = ap->a_head.a_dev;
3946     struct ciss_softc           *sc;
3947     int                         error;
3948
3949     debug_called(1);
3950
3951     sc = (struct ciss_softc *)dev->si_drv1;
3952     error = 0;
3953
3954     switch(ap->a_cmd) {
3955     case CCISS_GETPCIINFO:
3956     {
3957         cciss_pci_info_struct   *pis = (cciss_pci_info_struct *)ap->a_data;
3958
3959         pis->bus = pci_get_bus(sc->ciss_dev);
3960         pis->dev_fn = pci_get_slot(sc->ciss_dev);
3961         pis->board_id = pci_get_devid(sc->ciss_dev);
3962
3963         break;
3964     }
3965
3966     case CCISS_GETINTINFO:
3967     {
3968         cciss_coalint_struct    *cis = (cciss_coalint_struct *)ap->a_data;
3969
3970         cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
3971         cis->count = sc->ciss_cfg->interrupt_coalesce_count;
3972
3973         break;
3974     }
3975
3976     case CCISS_SETINTINFO:
3977     {
3978         cciss_coalint_struct    *cis = (cciss_coalint_struct *)ap->a_data;
3979
3980         if ((cis->delay == 0) && (cis->count == 0)) {
3981             error = EINVAL;
3982             break;
3983         }
3984
3985         /*
3986          * XXX apparently this is only safe if the controller is idle,
3987          *     we should suspend it before doing this.
3988          */
3989         sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
3990         sc->ciss_cfg->interrupt_coalesce_count = cis->count;
3991
3992         if (ciss_update_config(sc))
3993             error = EIO;
3994
3995         /* XXX resume the controller here */
3996         break;
3997     }
3998
3999     case CCISS_GETNODENAME:
4000         bcopy(sc->ciss_cfg->server_name, (NodeName_type *)ap->a_data,
4001               sizeof(NodeName_type));
4002         break;
4003
4004     case CCISS_SETNODENAME:
4005         bcopy((NodeName_type *)ap->a_data, sc->ciss_cfg->server_name,
4006               sizeof(NodeName_type));
4007         if (ciss_update_config(sc))
4008             error = EIO;
4009         break;
4010
4011     case CCISS_GETHEARTBEAT:
4012         *(Heartbeat_type *)ap->a_data = sc->ciss_cfg->heartbeat;
4013         break;
4014
4015     case CCISS_GETBUSTYPES:
4016         *(BusTypes_type *)ap->a_data = sc->ciss_cfg->bus_types;
4017         break;
4018
4019     case CCISS_GETFIRMVER:
4020         bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)ap->a_data,
4021               sizeof(FirmwareVer_type));
4022         break;
4023
4024     case CCISS_GETDRIVERVER:
4025         *(DriverVer_type *)ap->a_data = CISS_DRIVER_VERSION;
4026         break;
4027
4028     case CCISS_REVALIDVOLS:
4029         /*
4030          * This is a bit ugly; to do it "right" we really need
4031          * to find any disks that have changed, kick CAM off them,
4032          * then rescan only these disks.  It'd be nice if they
4033          * a) told us which disk(s) they were going to play with,
4034          * and b) which ones had arrived. 8(
4035          */
4036         break;
4037
4038     case CCISS_PASSTHRU:
4039         error = ciss_user_command(sc, (IOCTL_Command_struct *)ap->a_data);
4040         break;
4041
4042     default:
4043         debug(0, "unknown ioctl 0x%lx", ap->a_cmd);
4044
4045         debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
4046         debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
4047         debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
4048         debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
4049         debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
4050         debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
4051         debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
4052         debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
4053         debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
4054         debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
4055         debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
4056
4057         error = ENOIOCTL;
4058         break;
4059     }
4060
4061     return(error);
4062 }