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