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