ciss.c revision 118833
1132718Skan/*-
2132718Skan * Copyright (c) 2001 Michael Smith
3132718Skan * All rights reserved.
452284Sobrien *
552284Sobrien * Redistribution and use in source and binary forms, with or without
652284Sobrien * modification, are permitted provided that the following conditions
752284Sobrien * are met:
852284Sobrien * 1. Redistributions of source code must retain the above copyright
952284Sobrien *    notice, this list of conditions and the following disclaimer.
1052284Sobrien * 2. Redistributions in binary form must reproduce the above copyright
11132718Skan *    notice, this list of conditions and the following disclaimer in the
1252284Sobrien *    documentation and/or other materials provided with the distribution.
13132718Skan *
1452284Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1552284Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1652284Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1752284Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18132718Skan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1952284Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2052284Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2152284Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2252284Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2352284Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24132718Skan * SUCH DAMAGE.
25169689Skan *
26169689Skan *	$FreeBSD: head/sys/dev/ciss/ciss.c 118833 2003-08-12 17:55:53Z ps $
2752284Sobrien */
2890075Sobrien
2952284Sobrien/*
30117395Skan * Common Interface for SCSI-3 Support driver.
31117395Skan *
3252284Sobrien * CISS claims to provide a common interface between a generic SCSI
3352284Sobrien * transport and an intelligent host adapter.
34117395Skan *
3552284Sobrien * This driver supports CISS as defined in the document "CISS Command
3652284Sobrien * Interface for SCSI-3 Support Open Specification", Version 1.04,
3752284Sobrien * Valence Number 1, dated 20001127, produced by Compaq Computer
3852284Sobrien * Corporation.  This document appears to be a hastily and somewhat
39132718Skan * arbitrarlily cut-down version of a larger (and probably even more
40132718Skan * chaotic and inconsistent) Compaq internal document.  Various
4190075Sobrien * details were also gleaned from Compaq's "cciss" driver for Linux.
4290075Sobrien *
4352284Sobrien * We provide a shim layer between the CISS interface and CAM,
44132718Skan * offloading most of the queueing and being-a-disk chores onto CAM.
4552284Sobrien * Entry to the driver is via the PCI bus attachment (ciss_probe,
4652284Sobrien * ciss_attach, etc) and via the CAM interface (ciss_cam_action,
4752284Sobrien * ciss_cam_poll).  The Compaq CISS adapters are, however, poor SCSI
4852284Sobrien * citizens and we have to fake up some responses to get reasonable
4952284Sobrien * behaviour out of them.  In addition, the CISS command set is by no
5052284Sobrien * means adequate to support the functionality of a RAID controller,
5152284Sobrien * and thus the supported Compaq adapters utilise portions of the
5252284Sobrien * control protocol from earlier Compaq adapter families.
5352284Sobrien *
5452284Sobrien * Note that we only support the "simple" transport layer over PCI.
5552284Sobrien * This interface (ab)uses the I2O register set (specifically the post
5652284Sobrien * queues) to exchange commands with the adapter.  Other interfaces
57169689Skan * are available, but we aren't supposed to know about them, and it is
58169689Skan * dubious whether they would provide major performance improvements
5952284Sobrien * except under extreme load.
60117395Skan *
61117395Skan * Currently the only supported CISS adapters are the Compaq Smart
62117395Skan * Array 5* series (5300, 5i, 532).  Even with only three adapters,
63117395Skan * Compaq still manage to have interface variations.
64117395Skan *
65117395Skan *
66117395Skan * Thanks must go to Fred Harris and Darryl DeVinney at Compaq, as
67117395Skan * well as Paul Saab at Yahoo! for their assistance in making this
68117395Skan * driver happen.
69117395Skan */
70117395Skan
71117395Skan#include <sys/param.h>
72117395Skan#include <sys/systm.h>
73117395Skan#include <sys/malloc.h>
74117395Skan#include <sys/kernel.h>
75117395Skan#include <sys/bus.h>
76132718Skan#include <sys/conf.h>
77117395Skan#include <sys/stat.h>
78132718Skan
79117395Skan#include <cam/cam.h>
80117395Skan#include <cam/cam_ccb.h>
81117395Skan#include <cam/cam_periph.h>
82117395Skan#include <cam/cam_sim.h>
8352284Sobrien#include <cam/cam_xpt_sim.h>
8452284Sobrien#include <cam/scsi/scsi_all.h>
8552284Sobrien#include <cam/scsi/scsi_message.h>
8652284Sobrien
87169689Skan#include <machine/clock.h>
8852284Sobrien#include <machine/bus_memio.h>
89117395Skan#include <machine/bus.h>
9090075Sobrien#include <machine/endian.h>
9152284Sobrien#include <machine/resource.h>
9252284Sobrien#include <sys/rman.h>
9352284Sobrien
9452284Sobrien#include <pci/pcireg.h>
9552284Sobrien#include <pci/pcivar.h>
9690075Sobrien
97132718Skan#include <dev/ciss/cissreg.h>
98132718Skan#include <dev/ciss/cissvar.h>
9952284Sobrien#include <dev/ciss/cissio.h>
10052284Sobrien
10152284SobrienMALLOC_DEFINE(CISS_MALLOC_CLASS, "ciss_data", "ciss internal data buffers");
10252284Sobrien
10352284Sobrien/* pci interface */
10452284Sobrienstatic int	ciss_lookup(device_t dev);
10552284Sobrienstatic int	ciss_probe(device_t dev);
10652284Sobrienstatic int	ciss_attach(device_t dev);
10752284Sobrienstatic int	ciss_detach(device_t dev);
10852284Sobrienstatic int	ciss_shutdown(device_t dev);
10952284Sobrien
11052284Sobrien/* (de)initialisation functions, control wrappers */
11152284Sobrienstatic int	ciss_init_pci(struct ciss_softc *sc);
11252284Sobrienstatic int	ciss_wait_adapter(struct ciss_softc *sc);
11352284Sobrienstatic int	ciss_flush_adapter(struct ciss_softc *sc);
11452284Sobrienstatic int	ciss_init_requests(struct ciss_softc *sc);
11552284Sobrienstatic void	ciss_command_map_helper(void *arg, bus_dma_segment_t *segs,
11652284Sobrien					int nseg, int error);
11752284Sobrienstatic int	ciss_identify_adapter(struct ciss_softc *sc);
11852284Sobrienstatic int	ciss_init_logical(struct ciss_softc *sc);
11952284Sobrienstatic int	ciss_identify_logical(struct ciss_softc *sc, struct ciss_ldrive *ld);
12052284Sobrienstatic int	ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld);
12152284Sobrienstatic int	ciss_update_config(struct ciss_softc *sc);
12252284Sobrienstatic int	ciss_accept_media(struct ciss_softc *sc, int ldrive, int async);
12352284Sobrienstatic void	ciss_accept_media_complete(struct ciss_request *cr);
12452284Sobrienstatic void	ciss_free(struct ciss_softc *sc);
12552284Sobrien
12652284Sobrien/* request submission/completion */
12752284Sobrienstatic int	ciss_start(struct ciss_request *cr);
12852284Sobrienstatic void	ciss_done(struct ciss_softc *sc);
12952284Sobrienstatic void	ciss_intr(void *arg);
13052284Sobrienstatic void	ciss_complete(struct ciss_softc *sc);
13152284Sobrienstatic int	ciss_report_request(struct ciss_request *cr, int *command_status,
13252284Sobrien				    int *scsi_status);
13352284Sobrienstatic int	ciss_synch_request(struct ciss_request *cr, int timeout);
13452284Sobrienstatic int	ciss_poll_request(struct ciss_request *cr, int timeout);
13552284Sobrienstatic int	ciss_wait_request(struct ciss_request *cr, int timeout);
13652284Sobrien#if 0
13752284Sobrienstatic int	ciss_abort_request(struct ciss_request *cr);
13890075Sobrien#endif
13952284Sobrien
14052284Sobrien/* request queueing */
14152284Sobrienstatic int	ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp);
14252284Sobrienstatic void	ciss_preen_command(struct ciss_request *cr);
14352284Sobrienstatic void 	ciss_release_request(struct ciss_request *cr);
14452284Sobrien
145132718Skan/* request helpers */
14652284Sobrienstatic int	ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
14752284Sobrien				      int opcode, void **bufp, size_t bufsize);
14852284Sobrienstatic int	ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc);
14952284Sobrien
150132718Skan/* DMA map/unmap */
15190075Sobrienstatic int	ciss_map_request(struct ciss_request *cr);
152132718Skanstatic void	ciss_request_map_helper(void *arg, bus_dma_segment_t *segs,
15390075Sobrien					int nseg, int error);
15452284Sobrienstatic void	ciss_unmap_request(struct ciss_request *cr);
15552284Sobrien
156132718Skan/* CAM interface */
15752284Sobrienstatic int	ciss_cam_init(struct ciss_softc *sc);
15852284Sobrienstatic void	ciss_cam_rescan_target(struct ciss_softc *sc, int target);
15952284Sobrienstatic void	ciss_cam_rescan_all(struct ciss_softc *sc);
16052284Sobrienstatic void	ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb);
16152284Sobrienstatic void	ciss_cam_action(struct cam_sim *sim, union ccb *ccb);
16252284Sobrienstatic int	ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio);
16352284Sobrienstatic int	ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio);
16452284Sobrienstatic void	ciss_cam_poll(struct cam_sim *sim);
16552284Sobrienstatic void	ciss_cam_complete(struct ciss_request *cr);
16652284Sobrienstatic void	ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio);
16752284Sobrienstatic struct cam_periph *ciss_find_periph(struct ciss_softc *sc, int target);
16852284Sobrienstatic int	ciss_name_device(struct ciss_softc *sc, int target);
16952284Sobrien
17052284Sobrien/* periodic status monitoring */
17152284Sobrienstatic void	ciss_periodic(void *arg);
17252284Sobrienstatic void	ciss_notify_event(struct ciss_softc *sc);
17352284Sobrienstatic void	ciss_notify_complete(struct ciss_request *cr);
17452284Sobrienstatic int	ciss_notify_abort(struct ciss_softc *sc);
17552284Sobrienstatic int	ciss_notify_abort_bmic(struct ciss_softc *sc);
17652284Sobrienstatic void	ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn);
17752284Sobrienstatic void	ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn);
17852284Sobrien
17952284Sobrien/* debugging output */
18052284Sobrienstatic void	ciss_print_request(struct ciss_request *cr);
18152284Sobrienstatic void	ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld);
18252284Sobrienstatic const char *ciss_name_ldrive_status(int status);
18352284Sobrienstatic int	ciss_decode_ldrive_status(int status);
18452284Sobrienstatic const char *ciss_name_ldrive_org(int org);
18552284Sobrienstatic const char *ciss_name_command_status(int status);
186132718Skan
18790075Sobrien/*
188132718Skan * PCI bus interface.
189132718Skan */
19052284Sobrienstatic device_method_t ciss_methods[] = {
19152284Sobrien    /* Device interface */
192132718Skan    DEVMETHOD(device_probe,	ciss_probe),
19352284Sobrien    DEVMETHOD(device_attach,	ciss_attach),
19452284Sobrien    DEVMETHOD(device_detach,	ciss_detach),
19552284Sobrien    DEVMETHOD(device_shutdown,	ciss_shutdown),
19652284Sobrien    { 0, 0 }
19752284Sobrien};
19852284Sobrien
19952284Sobrienstatic driver_t ciss_pci_driver = {
20090075Sobrien    "ciss",
20152284Sobrien    ciss_methods,
20252284Sobrien    sizeof(struct ciss_softc)
20352284Sobrien};
20452284Sobrien
20552284Sobrienstatic devclass_t	ciss_devclass;
20652284SobrienDRIVER_MODULE(ciss, pci, ciss_pci_driver, ciss_devclass, 0, 0);
20752284Sobrien
20852284Sobrien/*
20952284Sobrien * Control device interface.
21052284Sobrien */
21152284Sobrienstatic d_open_t		ciss_open;
21252284Sobrienstatic d_close_t	ciss_close;
21352284Sobrienstatic d_ioctl_t	ciss_ioctl;
21452284Sobrien
21552284Sobrien#define CISS_CDEV_MAJOR  166
21652284Sobrien
21752284Sobrienstatic struct cdevsw ciss_cdevsw = {
21852284Sobrien	.d_open =	ciss_open,
21952284Sobrien	.d_close =	ciss_close,
22052284Sobrien	.d_ioctl =	ciss_ioctl,
22152284Sobrien	.d_name =	"ciss",
22252284Sobrien	.d_maj =	CISS_CDEV_MAJOR,
22352284Sobrien};
22452284Sobrien
22552284Sobrien/************************************************************************
22690075Sobrien * CISS adapters amazingly don't have a defined programming interface
22752284Sobrien * value.  (One could say some very despairing things about PCI and
22852284Sobrien * people just not getting the general idea.)  So we are forced to
22952284Sobrien * stick with matching against subvendor/subdevice, and thus have to
23052284Sobrien * be updated for every new CISS adapter that appears.
23152284Sobrien */
23252284Sobrien#define CISS_BOARD_SA5	(1<<0)
23352284Sobrien#define CISS_BOARD_SA5B	(1<<1)
23452284Sobrien
235117395Skanstatic struct
236117395Skan{
237117395Skan    u_int16_t	subvendor;
238117395Skan    u_int16_t	subdevice;
239117395Skan    int		flags;
240117395Skan    char	*desc;
241132718Skan} ciss_vendor_data[] = {
242132718Skan    { 0x0e11, 0x4070, CISS_BOARD_SA5,	"Compaq Smart Array 5300" },
243132718Skan    { 0x0e11, 0x4080, CISS_BOARD_SA5B,	"Compaq Smart Array 5i" },
244132718Skan    { 0x0e11, 0x4082, CISS_BOARD_SA5B,	"Compaq Smart Array 532" },
245132718Skan    { 0x0e11, 0x4083, CISS_BOARD_SA5B,	"HP Smart Array 5312" },
246132718Skan    { 0x0e11, 0x409A, CISS_BOARD_SA5,	"HP Smart Array 641" },
247132718Skan    { 0x0e11, 0x409B, CISS_BOARD_SA5,	"HP Smart Array 642" },
248132718Skan    { 0x0e11, 0x409C, CISS_BOARD_SA5,	"HP Smart Array 6400" },
249132718Skan    { 0x0e11, 0x409D, CISS_BOARD_SA5,	"HP Smart Array 6400 EM" },
250132718Skan    { 0, 0, 0, NULL }
251132718Skan};
252132718Skan
253132718Skan/************************************************************************
254132718Skan * Find a match for the device in our list of known adapters.
255132718Skan */
256132718Skanstatic int
257132718Skanciss_lookup(device_t dev)
258132718Skan{
259132718Skan    int 	i;
260132718Skan
261132718Skan    for (i = 0; ciss_vendor_data[i].desc != NULL; i++)
262132718Skan	if ((pci_get_subvendor(dev) == ciss_vendor_data[i].subvendor) &&
26396263Sobrien	    (pci_get_subdevice(dev) == ciss_vendor_data[i].subdevice)) {
26452284Sobrien	    return(i);
265117395Skan	}
26652284Sobrien    return(-1);
26752284Sobrien}
26852284Sobrien
26952284Sobrien/************************************************************************
27052284Sobrien * Match a known CISS adapter.
27152284Sobrien */
27252284Sobrienstatic int
27390075Sobrienciss_probe(device_t dev)
27452284Sobrien{
27552284Sobrien    int		i;
27690075Sobrien
27752284Sobrien    i = ciss_lookup(dev);
27852284Sobrien    if (i != -1) {
27952284Sobrien	device_set_desc(dev, ciss_vendor_data[i].desc);
28052284Sobrien	return(-10);
28190075Sobrien    }
28252284Sobrien    return(ENOENT);
28352284Sobrien}
28452284Sobrien
28552284Sobrien/************************************************************************
28652284Sobrien * Attach the driver to this adapter.
28752284Sobrien */
28852284Sobrienstatic int
28952284Sobrienciss_attach(device_t dev)
29052284Sobrien{
29152284Sobrien    struct ciss_softc	*sc;
29252284Sobrien    int			i, error;
29352284Sobrien
29452284Sobrien    debug_called(1);
29590075Sobrien
29652284Sobrien#ifdef CISS_DEBUG
29752284Sobrien    /* print structure/union sizes */
29852284Sobrien    debug_struct(ciss_command);
29952284Sobrien    debug_struct(ciss_header);
30052284Sobrien    debug_union(ciss_device_address);
30152284Sobrien    debug_struct(ciss_cdb);
30252284Sobrien    debug_struct(ciss_report_cdb);
30352284Sobrien    debug_struct(ciss_notify_cdb);
30452284Sobrien    debug_struct(ciss_notify);
30552284Sobrien    debug_struct(ciss_message_cdb);
30652284Sobrien    debug_struct(ciss_error_info_pointer);
30752284Sobrien    debug_struct(ciss_error_info);
30852284Sobrien    debug_struct(ciss_sg_entry);
30952284Sobrien    debug_struct(ciss_config_table);
31052284Sobrien    debug_struct(ciss_bmic_cdb);
31152284Sobrien    debug_struct(ciss_bmic_id_ldrive);
31252284Sobrien    debug_struct(ciss_bmic_id_lstatus);
31390075Sobrien    debug_struct(ciss_bmic_id_table);
31490075Sobrien    debug_struct(ciss_bmic_id_pdrive);
31552284Sobrien    debug_struct(ciss_bmic_blink_pdrive);
31652284Sobrien    debug_struct(ciss_bmic_flush_cache);
31752284Sobrien    debug_const(CISS_MAX_REQUESTS);
31852284Sobrien    debug_const(CISS_MAX_LOGICAL);
31952284Sobrien    debug_const(CISS_INTERRUPT_COALESCE_DELAY);
32052284Sobrien    debug_const(CISS_INTERRUPT_COALESCE_COUNT);
32152284Sobrien    debug_const(CISS_COMMAND_ALLOC_SIZE);
32252284Sobrien    debug_const(CISS_COMMAND_SG_LENGTH);
32352284Sobrien
32452284Sobrien    debug_type(cciss_pci_info_struct);
32552284Sobrien    debug_type(cciss_coalint_struct);
32652284Sobrien    debug_type(cciss_coalint_struct);
327117395Skan    debug_type(NodeName_type);
32852284Sobrien    debug_type(NodeName_type);
329117395Skan    debug_type(Heartbeat_type);
330117395Skan    debug_type(BusTypes_type);
331117395Skan    debug_type(FirmwareVer_type);
332117395Skan    debug_type(DriverVer_type);
33352284Sobrien    debug_type(IOCTL_Command_struct);
33452284Sobrien#endif
33552284Sobrien
33652284Sobrien    sc = device_get_softc(dev);
33790075Sobrien    sc->ciss_dev = dev;
33852284Sobrien
339169689Skan    /*
340169689Skan     * Work out adapter type.
34152284Sobrien     */
342132718Skan    i = ciss_lookup(dev);
343117395Skan    if (ciss_vendor_data[i].flags & CISS_BOARD_SA5) {
344169689Skan	sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5;
34552284Sobrien    } else if (ciss_vendor_data[i].flags & CISS_BOARD_SA5B) {
34652284Sobrien	sc->ciss_interrupt_mask = CISS_TL_SIMPLE_INTR_OPQ_SA5B;
34796263Sobrien    } else {
34852284Sobrien	/* really an error on our part */
34990075Sobrien	ciss_printf(sc, "unable to determine hardware type\n");
35090075Sobrien	error = ENXIO;
35152284Sobrien	goto out;
35290075Sobrien    }
35352284Sobrien
35452284Sobrien    /*
35590075Sobrien     * Do PCI-specific init.
35652284Sobrien     */
35752284Sobrien    if ((error = ciss_init_pci(sc)) != 0)
358132718Skan	goto out;
35996263Sobrien
36096263Sobrien    /*
36196263Sobrien     * Initialise driver queues.
36296263Sobrien     */
36396263Sobrien    ciss_initq_free(sc);
36496263Sobrien    ciss_initq_busy(sc);
36596263Sobrien    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(sc->ciss_dev, SYS_RES_MEMORY, &sc->ciss_regs_rid,
479			    0, ~0, 1, 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(sc->ciss_dev, SYS_RES_MEMORY, &sc->ciss_cfg_rid,
494				0, ~0, 1, 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(sc->ciss_dev, SYS_RES_IRQ, &sc->ciss_irq_rid, 0, ~0, 1,
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		    cbc->log_drive, ciss_name_ldrive_org(ld->cl_ldrive->fault_tolerance),
1156		    ((ld->cl_ldrive->blocks_available / (1024 * 1024)) *
1157		     ld->cl_ldrive->block_size));
1158
1159	ciss_print_ldrive(sc, ld);
1160    }
1161out:
1162    if (error != 0) {
1163	/* make the drive not-exist */
1164	ld->cl_status = CISS_LD_NONEXISTENT;
1165	if (ld->cl_ldrive != NULL) {
1166	    free(ld->cl_ldrive, CISS_MALLOC_CLASS);
1167	    ld->cl_ldrive = NULL;
1168	}
1169	if (ld->cl_lstatus != NULL) {
1170	    free(ld->cl_lstatus, CISS_MALLOC_CLASS);
1171	    ld->cl_lstatus = NULL;
1172	}
1173    }
1174    if (cr != NULL)
1175	ciss_release_request(cr);
1176
1177    return(error);
1178}
1179
1180/************************************************************************
1181 * Get status for a logical drive.
1182 *
1183 * XXX should we also do this in response to Test Unit Ready?
1184 */
1185static int
1186ciss_get_ldrive_status(struct ciss_softc *sc,  struct ciss_ldrive *ld)
1187{
1188    struct ciss_request		*cr;
1189    struct ciss_command		*cc;
1190    struct ciss_bmic_cdb	*cbc;
1191    int				error, command_status;
1192
1193    /*
1194     * Build a CISS BMIC command to get the logical drive status.
1195     */
1196    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ID_LSTATUS,
1197				       (void **)&ld->cl_lstatus,
1198				       sizeof(*ld->cl_lstatus))) != 0)
1199	goto out;
1200    cc = CISS_FIND_COMMAND(cr);
1201    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1202    cbc->log_drive = ld->cl_address.logical.lun;
1203
1204    /*
1205     * Submit the request and wait for it to complete.
1206     */
1207    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1208	ciss_printf(sc, "error sending BMIC LSTATUS command (%d)\n", error);
1209	goto out;
1210    }
1211
1212    /*
1213     * Check response.
1214     */
1215    ciss_report_request(cr, &command_status, NULL);
1216    switch(command_status) {
1217    case CISS_CMD_STATUS_SUCCESS:		/* buffer right size */
1218	break;
1219    case CISS_CMD_STATUS_DATA_UNDERRUN:
1220    case CISS_CMD_STATUS_DATA_OVERRUN:
1221	ciss_printf(sc, "data over/underrun reading logical drive status\n");
1222    default:
1223	ciss_printf(sc, "error reading logical drive status (%s)\n",
1224		    ciss_name_command_status(command_status));
1225	error = EIO;
1226	goto out;
1227    }
1228
1229    /*
1230     * Set the drive's summary status based on the returned status.
1231     *
1232     * XXX testing shows that a failed JBOD drive comes back at next
1233     * boot in "queued for expansion" mode.  WTF?
1234     */
1235    ld->cl_status = ciss_decode_ldrive_status(ld->cl_lstatus->status);
1236
1237out:
1238    if (cr != NULL)
1239	ciss_release_request(cr);
1240    return(error);
1241}
1242
1243/************************************************************************
1244 * Notify the adapter of a config update.
1245 */
1246static int
1247ciss_update_config(struct ciss_softc *sc)
1248{
1249    int		i;
1250
1251    debug_called(1);
1252
1253    CISS_TL_SIMPLE_WRITE(sc, CISS_TL_SIMPLE_IDBR, CISS_TL_SIMPLE_IDBR_CFG_TABLE);
1254    for (i = 0; i < 1000; i++) {
1255	if (!(CISS_TL_SIMPLE_READ(sc, CISS_TL_SIMPLE_IDBR) &
1256	      CISS_TL_SIMPLE_IDBR_CFG_TABLE)) {
1257	    return(0);
1258	}
1259	DELAY(1000);
1260    }
1261    return(1);
1262}
1263
1264/************************************************************************
1265 * Accept new media into a logical drive.
1266 *
1267 * XXX The drive has previously been offline; it would be good if we
1268 *     could make sure it's not open right now.
1269 */
1270static int
1271ciss_accept_media(struct ciss_softc *sc, int ldrive, int async)
1272{
1273    struct ciss_request		*cr;
1274    struct ciss_command		*cc;
1275    struct ciss_bmic_cdb	*cbc;
1276    int				error;
1277
1278    debug(0, "bringing logical drive %d back online %ssynchronously",
1279	  ldrive, async ? "a" : "");
1280
1281    /*
1282     * Build a CISS BMIC command to bring the drive back online.
1283     */
1284    if ((error = ciss_get_bmic_request(sc, &cr, CISS_BMIC_ACCEPT_MEDIA,
1285				       NULL, 0)) != 0)
1286	goto out;
1287    cc = CISS_FIND_COMMAND(cr);
1288    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1289    cbc->log_drive = ldrive;
1290
1291    /*
1292     * Dispatch the request asynchronously if we can't sleep waiting
1293     * for it to complete.
1294     */
1295    if (async) {
1296	cr->cr_complete = ciss_accept_media_complete;
1297	if ((error = ciss_start(cr)) != 0)
1298	    goto out;
1299	return(0);
1300    } else {
1301	/*
1302	 * Submit the request and wait for it to complete.
1303	 */
1304	if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
1305	    ciss_printf(sc, "error sending BMIC LSTATUS command (%d)\n", error);
1306	    goto out;
1307	}
1308    }
1309
1310    /*
1311     * Call the completion callback manually.
1312     */
1313    ciss_accept_media_complete(cr);
1314    return(0);
1315
1316out:
1317    if (cr != NULL)
1318	ciss_release_request(cr);
1319    return(error);
1320}
1321
1322static void
1323ciss_accept_media_complete(struct ciss_request *cr)
1324{
1325    int				command_status;
1326
1327    /*
1328     * Check response.
1329     */
1330    ciss_report_request(cr, &command_status, NULL);
1331    switch(command_status) {
1332    case CISS_CMD_STATUS_SUCCESS:		/* all OK */
1333	/* we should get a logical drive status changed event here */
1334	break;
1335    default:
1336	ciss_printf(cr->cr_sc, "error accepting media into failed logical drive (%s)\n",
1337		    ciss_name_command_status(command_status));
1338	break;
1339    }
1340    ciss_release_request(cr);
1341}
1342
1343/************************************************************************
1344 * Release adapter resources.
1345 */
1346static void
1347ciss_free(struct ciss_softc *sc)
1348{
1349    struct ciss_request *cr;
1350
1351    debug_called(1);
1352
1353    /* we're going away */
1354    sc->ciss_flags |= CISS_FLAG_ABORTING;
1355
1356    /* terminate the periodic heartbeat routine */
1357    untimeout(ciss_periodic, sc, sc->ciss_periodic);
1358
1359    /* cancel the Event Notify chain */
1360    ciss_notify_abort(sc);
1361
1362    /* free the controller data */
1363    if (sc->ciss_id != NULL)
1364	free(sc->ciss_id, CISS_MALLOC_CLASS);
1365
1366    /* release I/O resources */
1367    if (sc->ciss_regs_resource != NULL)
1368	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1369			     sc->ciss_regs_rid, sc->ciss_regs_resource);
1370    if (sc->ciss_cfg_resource != NULL)
1371	bus_release_resource(sc->ciss_dev, SYS_RES_MEMORY,
1372			     sc->ciss_cfg_rid, sc->ciss_cfg_resource);
1373    if (sc->ciss_intr != NULL)
1374	bus_teardown_intr(sc->ciss_dev, sc->ciss_irq_resource, sc->ciss_intr);
1375    if (sc->ciss_irq_resource != NULL)
1376	bus_release_resource(sc->ciss_dev, SYS_RES_IRQ,
1377			     sc->ciss_irq_rid, sc->ciss_irq_resource);
1378
1379    /* destroy DMA tags */
1380    if (sc->ciss_parent_dmat)
1381	bus_dma_tag_destroy(sc->ciss_parent_dmat);
1382
1383    while ((cr = ciss_dequeue_free(sc)) != NULL)
1384	bus_dmamap_destroy(sc->ciss_buffer_dmat, cr->cr_datamap);
1385    if (sc->ciss_buffer_dmat)
1386	bus_dma_tag_destroy(sc->ciss_buffer_dmat);
1387
1388    /* destroy command memory and DMA tag */
1389    if (sc->ciss_command != NULL) {
1390	bus_dmamap_unload(sc->ciss_command_dmat, sc->ciss_command_map);
1391	bus_dmamem_free(sc->ciss_command_dmat, sc->ciss_command, sc->ciss_command_map);
1392    }
1393    if (sc->ciss_command_dmat)
1394	bus_dma_tag_destroy(sc->ciss_command_dmat);
1395
1396    /* disconnect from CAM */
1397    if (sc->ciss_cam_sim) {
1398	xpt_bus_deregister(cam_sim_path(sc->ciss_cam_sim));
1399	cam_sim_free(sc->ciss_cam_sim, 0);
1400    }
1401    if (sc->ciss_cam_devq)
1402	cam_simq_free(sc->ciss_cam_devq);
1403    /* XXX what about ciss_cam_path? */
1404}
1405
1406/************************************************************************
1407 * Give a command to the adapter.
1408 *
1409 * Note that this uses the simple transport layer directly.  If we
1410 * want to add support for other layers, we'll need a switch of some
1411 * sort.
1412 *
1413 * Note that the simple transport layer has no way of refusing a
1414 * command; we only have as many request structures as the adapter
1415 * supports commands, so we don't have to check (this presumes that
1416 * the adapter can handle commands as fast as we throw them at it).
1417 */
1418static int
1419ciss_start(struct ciss_request *cr)
1420{
1421    struct ciss_command	*cc;	/* XXX debugging only */
1422    int			error;
1423
1424    cc = CISS_FIND_COMMAND(cr);
1425    debug(2, "post command %d tag %d ", cr->cr_tag, cc->header.host_tag);
1426
1427    /*
1428     * Map the request's data.
1429     */
1430    if ((error = ciss_map_request(cr)))
1431	return(error);
1432
1433#if 0
1434    ciss_print_request(cr);
1435#endif
1436
1437    return(0);
1438}
1439
1440/************************************************************************
1441 * Fetch completed request(s) from the adapter, queue them for
1442 * completion handling.
1443 *
1444 * Note that this uses the simple transport layer directly.  If we
1445 * want to add support for other layers, we'll need a switch of some
1446 * sort.
1447 *
1448 * Note that the simple transport mechanism does not require any
1449 * reentrancy protection; the OPQ read is atomic.  If there is a
1450 * chance of a race with something else that might move the request
1451 * off the busy list, then we will have to lock against that
1452 * (eg. timeouts, etc.)
1453 */
1454static void
1455ciss_done(struct ciss_softc *sc)
1456{
1457    struct ciss_request	*cr;
1458    struct ciss_command	*cc;
1459    u_int32_t		tag, index;
1460    int			complete;
1461
1462    debug_called(3);
1463
1464    /*
1465     * Loop quickly taking requests from the adapter and moving them
1466     * from the busy queue to the completed queue.
1467     */
1468    complete = 0;
1469    for (;;) {
1470
1471	/* see if the OPQ contains anything */
1472	if (!CISS_TL_SIMPLE_OPQ_INTERRUPT(sc))
1473	    break;
1474
1475	tag = CISS_TL_SIMPLE_FETCH_CMD(sc);
1476	if (tag == CISS_TL_SIMPLE_OPQ_EMPTY)
1477	    break;
1478	index = tag >> 2;
1479	debug(2, "completed command %d%s", index,
1480	      (tag & CISS_HDR_HOST_TAG_ERROR) ? " with error" : "");
1481	if (index >= sc->ciss_max_requests) {
1482	    ciss_printf(sc, "completed invalid request %d (0x%x)\n", index, tag);
1483	    continue;
1484	}
1485	cr = &(sc->ciss_request[index]);
1486	cc = CISS_FIND_COMMAND(cr);
1487	cc->header.host_tag = tag;	/* not updated by adapter */
1488	if (ciss_remove_busy(cr)) {
1489	    /* assume this is garbage out of the adapter */
1490	    ciss_printf(sc, "completed nonbusy request %d\n", index);
1491	} else {
1492	    ciss_enqueue_complete(cr);
1493	}
1494	complete = 1;
1495    }
1496
1497    /*
1498     * Invoke completion processing.  If we can defer this out of
1499     * interrupt context, that'd be good.
1500     */
1501    if (complete)
1502	ciss_complete(sc);
1503}
1504
1505/************************************************************************
1506 * Take an interrupt from the adapter.
1507 */
1508static void
1509ciss_intr(void *arg)
1510{
1511    struct ciss_softc	*sc = (struct ciss_softc *)arg;
1512
1513    /*
1514     * The only interrupt we recognise indicates that there are
1515     * entries in the outbound post queue.
1516     */
1517    ciss_done(sc);
1518}
1519
1520/************************************************************************
1521 * Process completed requests.
1522 *
1523 * Requests can be completed in three fashions:
1524 *
1525 * - by invoking a callback function (cr_complete is non-null)
1526 * - by waking up a sleeper (cr_flags has CISS_REQ_SLEEP set)
1527 * - by clearing the CISS_REQ_POLL flag in interrupt/timeout context
1528 */
1529static void
1530ciss_complete(struct ciss_softc *sc)
1531{
1532    struct ciss_request	*cr;
1533
1534    debug_called(2);
1535
1536    /*
1537     * Loop taking requests off the completed queue and performing
1538     * completion processing on them.
1539     */
1540    for (;;) {
1541	if ((cr = ciss_dequeue_complete(sc)) == NULL)
1542	    break;
1543	ciss_unmap_request(cr);
1544
1545	/*
1546	 * If the request has a callback, invoke it.
1547	 */
1548	if (cr->cr_complete != NULL) {
1549	    cr->cr_complete(cr);
1550	    continue;
1551	}
1552
1553	/*
1554	 * If someone is sleeping on this request, wake them up.
1555	 */
1556	if (cr->cr_flags & CISS_REQ_SLEEP) {
1557	    cr->cr_flags &= ~CISS_REQ_SLEEP;
1558	    wakeup(cr);
1559	    continue;
1560	}
1561
1562	/*
1563	 * If someone is polling this request for completion, signal.
1564	 */
1565	if (cr->cr_flags & CISS_REQ_POLL) {
1566	    cr->cr_flags &= ~CISS_REQ_POLL;
1567	    continue;
1568	}
1569
1570	/*
1571	 * Give up and throw the request back on the free queue.  This
1572	 * should never happen; resources will probably be lost.
1573	 */
1574	ciss_printf(sc, "WARNING: completed command with no submitter\n");
1575	ciss_enqueue_free(cr);
1576    }
1577}
1578
1579/************************************************************************
1580 * Report on the completion status of a request, and pass back SCSI
1581 * and command status values.
1582 */
1583static int
1584ciss_report_request(struct ciss_request *cr, int *command_status, int *scsi_status)
1585{
1586    struct ciss_command		*cc;
1587    struct ciss_error_info	*ce;
1588
1589    debug_called(2);
1590
1591    cc = CISS_FIND_COMMAND(cr);
1592    ce = (struct ciss_error_info *)&(cc->sg[0]);
1593
1594    /*
1595     * We don't consider data under/overrun an error for the Report
1596     * Logical/Physical LUNs commands.
1597     */
1598    if ((cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) &&
1599	((cc->cdb.cdb[0] == CISS_OPCODE_REPORT_LOGICAL_LUNS) ||
1600	 (cc->cdb.cdb[0] == CISS_OPCODE_REPORT_PHYSICAL_LUNS))) {
1601	cc->header.host_tag &= ~CISS_HDR_HOST_TAG_ERROR;
1602	debug(2, "ignoring irrelevant under/overrun error");
1603    }
1604
1605    /*
1606     * Check the command's error bit, if clear, there's no status and
1607     * everything is OK.
1608     */
1609    if (!(cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR)) {
1610	if (scsi_status != NULL)
1611	    *scsi_status = SCSI_STATUS_OK;
1612	if (command_status != NULL)
1613	    *command_status = CISS_CMD_STATUS_SUCCESS;
1614	return(0);
1615    } else {
1616	if (command_status != NULL)
1617	    *command_status = ce->command_status;
1618	if (scsi_status != NULL) {
1619	    if (ce->command_status == CISS_CMD_STATUS_TARGET_STATUS) {
1620		*scsi_status = ce->scsi_status;
1621	    } else {
1622		*scsi_status = -1;
1623	    }
1624	}
1625	if (bootverbose)
1626	    ciss_printf(cr->cr_sc, "command status 0x%x (%s) scsi status 0x%x\n",
1627			ce->command_status, ciss_name_command_status(ce->command_status),
1628			ce->scsi_status);
1629	if (ce->command_status == CISS_CMD_STATUS_INVALID_COMMAND) {
1630	    ciss_printf(cr->cr_sc, "invalid command, offense size %d at %d, value 0x%x\n",
1631			ce->additional_error_info.invalid_command.offense_size,
1632			ce->additional_error_info.invalid_command.offense_offset,
1633			ce->additional_error_info.invalid_command.offense_value);
1634	}
1635    }
1636    return(1);
1637}
1638
1639/************************************************************************
1640 * Issue a request and don't return until it's completed.
1641 *
1642 * Depending on adapter status, we may poll or sleep waiting for
1643 * completion.
1644 */
1645static int
1646ciss_synch_request(struct ciss_request *cr, int timeout)
1647{
1648    if (cr->cr_sc->ciss_flags & CISS_FLAG_RUNNING) {
1649	return(ciss_wait_request(cr, timeout));
1650    } else {
1651	return(ciss_poll_request(cr, timeout));
1652    }
1653}
1654
1655/************************************************************************
1656 * Issue a request and poll for completion.
1657 *
1658 * Timeout in milliseconds.
1659 */
1660static int
1661ciss_poll_request(struct ciss_request *cr, int timeout)
1662{
1663    int		error;
1664
1665    debug_called(2);
1666
1667    cr->cr_flags |= CISS_REQ_POLL;
1668    if ((error = ciss_start(cr)) != 0)
1669	return(error);
1670
1671    do {
1672	ciss_done(cr->cr_sc);
1673	if (!(cr->cr_flags & CISS_REQ_POLL))
1674	    return(0);
1675	DELAY(1000);
1676    } while (timeout-- >= 0);
1677    return(EWOULDBLOCK);
1678}
1679
1680/************************************************************************
1681 * Issue a request and sleep waiting for completion.
1682 *
1683 * Timeout in milliseconds.  Note that a spurious wakeup will reset
1684 * the timeout.
1685 */
1686static int
1687ciss_wait_request(struct ciss_request *cr, int timeout)
1688{
1689    int		s, error;
1690
1691    debug_called(2);
1692
1693    cr->cr_flags |= CISS_REQ_SLEEP;
1694    if ((error = ciss_start(cr)) != 0)
1695	return(error);
1696
1697    s = splcam();
1698    while (cr->cr_flags & CISS_REQ_SLEEP) {
1699	error = tsleep(cr, PCATCH, "cissREQ", (timeout * hz) / 1000);
1700	/*
1701	 * On wakeup or interruption due to restartable activity, go
1702	 * back and check to see if we're done.
1703	 */
1704	if ((error == 0) || (error == ERESTART)) {
1705	    error = 0;
1706	    continue;
1707	}
1708	/*
1709	 * Timeout, interrupted system call, etc.
1710	 */
1711	break;
1712    }
1713    splx(s);
1714    return(error);
1715}
1716
1717#if 0
1718/************************************************************************
1719 * Abort a request.  Note that a potential exists here to race the
1720 * request being completed; the caller must deal with this.
1721 */
1722static int
1723ciss_abort_request(struct ciss_request *ar)
1724{
1725    struct ciss_request		*cr;
1726    struct ciss_command		*cc;
1727    struct ciss_message_cdb	*cmc;
1728    int				error;
1729
1730    debug_called(1);
1731
1732    /* get a request */
1733    if ((error = ciss_get_request(ar->cr_sc, &cr)) != 0)
1734	return(error);
1735
1736    /* build the abort command */
1737    cc = CISS_FIND_COMMAND(cr);
1738    cc->header.address.mode.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;	/* addressing? */
1739    cc->header.address.physical.target = 0;
1740    cc->header.address.physical.bus = 0;
1741    cc->cdb.cdb_length = sizeof(*cmc);
1742    cc->cdb.type = CISS_CDB_TYPE_MESSAGE;
1743    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1744    cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
1745    cc->cdb.timeout = 30;
1746
1747    cmc = (struct ciss_message_cdb *)&(cc->cdb.cdb[0]);
1748    cmc->opcode = CISS_OPCODE_MESSAGE_ABORT;
1749    cmc->type = CISS_MESSAGE_ABORT_TASK;
1750    cmc->abort_tag = ar->cr_tag;	/* endianness?? */
1751
1752    /*
1753     * Send the request and wait for a response.  If we believe we
1754     * aborted the request OK, clear the flag that indicates it's
1755     * running.
1756     */
1757    error = ciss_synch_request(cr, 35 * 1000);
1758    if (!error)
1759	error = ciss_report_request(cr, NULL, NULL);
1760    ciss_release_request(cr);
1761
1762    return(error);
1763}
1764#endif
1765
1766
1767/************************************************************************
1768 * Fetch and initialise a request
1769 */
1770static int
1771ciss_get_request(struct ciss_softc *sc, struct ciss_request **crp)
1772{
1773    struct ciss_request *cr;
1774
1775    debug_called(2);
1776
1777    /*
1778     * Get a request and clean it up.
1779     */
1780    if ((cr = ciss_dequeue_free(sc)) == NULL)
1781	return(ENOMEM);
1782
1783    cr->cr_data = NULL;
1784    cr->cr_flags = 0;
1785    cr->cr_complete = NULL;
1786    cr->cr_private = NULL;
1787
1788    ciss_preen_command(cr);
1789    *crp = cr;
1790    return(0);
1791}
1792
1793static void
1794ciss_preen_command(struct ciss_request *cr)
1795{
1796    struct ciss_command	*cc;
1797    u_int32_t		cmdphys;
1798
1799    /*
1800     * Clean up the command structure.
1801     *
1802     * Note that we set up the error_info structure here, since the
1803     * length can be overwritten by any command.
1804     */
1805    cc = CISS_FIND_COMMAND(cr);
1806    cc->header.sg_in_list = 0;		/* kinda inefficient this way */
1807    cc->header.sg_total = 0;
1808    cc->header.host_tag = cr->cr_tag << 2;
1809    cc->header.host_tag_zeroes = 0;
1810    cmdphys = CISS_FIND_COMMANDPHYS(cr);
1811    cc->error_info.error_info_address = cmdphys + sizeof(struct ciss_command);
1812    cc->error_info.error_info_length = CISS_COMMAND_ALLOC_SIZE - sizeof(struct ciss_command);
1813
1814}
1815
1816/************************************************************************
1817 * Release a request to the free list.
1818 */
1819static void
1820ciss_release_request(struct ciss_request *cr)
1821{
1822    struct ciss_softc	*sc;
1823
1824    debug_called(2);
1825
1826    sc = cr->cr_sc;
1827
1828    /* release the request to the free queue */
1829    ciss_requeue_free(cr);
1830}
1831
1832/************************************************************************
1833 * Allocate a request that will be used to send a BMIC command.  Do some
1834 * of the common setup here to avoid duplicating it everywhere else.
1835 */
1836static int
1837ciss_get_bmic_request(struct ciss_softc *sc, struct ciss_request **crp,
1838		      int opcode, void **bufp, size_t bufsize)
1839{
1840    struct ciss_request		*cr;
1841    struct ciss_command		*cc;
1842    struct ciss_bmic_cdb	*cbc;
1843    void			*buf;
1844    int				error;
1845    int				dataout;
1846
1847    debug_called(2);
1848
1849    cr = NULL;
1850    buf = NULL;
1851
1852    /*
1853     * Get a request.
1854     */
1855    if ((error = ciss_get_request(sc, &cr)) != 0)
1856	goto out;
1857
1858    /*
1859     * Allocate data storage if requested, determine the data direction.
1860     */
1861    dataout = 0;
1862    if ((bufsize > 0) && (bufp != NULL)) {
1863	if (*bufp == NULL) {
1864	    if ((buf = malloc(bufsize, CISS_MALLOC_CLASS, M_NOWAIT | M_ZERO)) == NULL) {
1865		error = ENOMEM;
1866		goto out;
1867	    }
1868	} else {
1869	    buf = *bufp;
1870	    dataout = 1;	/* we are given a buffer, so we are writing */
1871	}
1872    }
1873
1874    /*
1875     * Build a CISS BMIC command to get the logical drive ID.
1876     */
1877    cr->cr_data = buf;
1878    cr->cr_length = bufsize;
1879    if (!dataout)
1880	cr->cr_flags = CISS_REQ_DATAIN;
1881
1882    cc = CISS_FIND_COMMAND(cr);
1883    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
1884    cc->header.address.physical.bus = 0;
1885    cc->header.address.physical.target = 0;
1886    cc->cdb.cdb_length = sizeof(*cbc);
1887    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
1888    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
1889    cc->cdb.direction = dataout ? CISS_CDB_DIRECTION_WRITE : CISS_CDB_DIRECTION_READ;
1890    cc->cdb.timeout = 0;
1891
1892    cbc = (struct ciss_bmic_cdb *)&(cc->cdb.cdb[0]);
1893    bzero(cbc, sizeof(*cbc));
1894    cbc->opcode = dataout ? CISS_ARRAY_CONTROLLER_WRITE : CISS_ARRAY_CONTROLLER_READ;
1895    cbc->bmic_opcode = opcode;
1896    cbc->size = htons((u_int16_t)bufsize);
1897
1898out:
1899    if (error) {
1900	if (cr != NULL)
1901	    ciss_release_request(cr);
1902	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
1903	    free(buf, CISS_MALLOC_CLASS);
1904    } else {
1905	*crp = cr;
1906	if ((bufp != NULL) && (*bufp == NULL) && (buf != NULL))
1907	    *bufp = buf;
1908    }
1909    return(error);
1910}
1911
1912/************************************************************************
1913 * Handle a command passed in from userspace.
1914 */
1915static int
1916ciss_user_command(struct ciss_softc *sc, IOCTL_Command_struct *ioc)
1917{
1918    struct ciss_request		*cr;
1919    struct ciss_command		*cc;
1920    struct ciss_error_info	*ce;
1921    int				error = 0;
1922
1923    debug_called(1);
1924
1925    cr = NULL;
1926
1927    /*
1928     * Get a request.
1929     */
1930    if ((error = ciss_get_request(sc, &cr)) != 0)
1931	goto out;
1932    cc = CISS_FIND_COMMAND(cr);
1933
1934    /*
1935     * Allocate an in-kernel databuffer if required, copy in user data.
1936     */
1937    cr->cr_length = ioc->buf_size;
1938    if (ioc->buf_size > 0) {
1939	if ((cr->cr_data = malloc(ioc->buf_size, CISS_MALLOC_CLASS, M_WAITOK)) == NULL) {
1940	    error = ENOMEM;
1941	    goto out;
1942	}
1943	if ((error = copyin(ioc->buf, cr->cr_data, ioc->buf_size))) {
1944	    debug(0, "copyin: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
1945	    goto out;
1946	}
1947    }
1948
1949    /*
1950     * Build the request based on the user command.
1951     */
1952    bcopy(&ioc->LUN_info, &cc->header.address, sizeof(cc->header.address));
1953    bcopy(&ioc->Request, &cc->cdb, sizeof(cc->cdb));
1954
1955    /* XXX anything else to populate here? */
1956
1957    /*
1958     * Run the command.
1959     */
1960    if ((error = ciss_synch_request(cr, 60 * 1000))) {
1961	debug(0, "request failed - %d", error);
1962	goto out;
1963    }
1964
1965    /*
1966     * Check to see if the command succeeded.
1967     */
1968    ce = (struct ciss_error_info *)&(cc->sg[0]);
1969    if (ciss_report_request(cr, NULL, NULL) == 0)
1970	bzero(ce, sizeof(*ce));
1971    else
1972	error = EIO;
1973
1974    /*
1975     * Copy the results back to the user.
1976     */
1977    bcopy(ce, &ioc->error_info, sizeof(*ce));
1978    if ((ioc->buf_size > 0) &&
1979	(error = copyout(cr->cr_data, ioc->buf, ioc->buf_size))) {
1980	debug(0, "copyout: bad data buffer %p/%d", ioc->buf, ioc->buf_size);
1981	goto out;
1982    }
1983
1984    /* done OK */
1985    error = 0;
1986
1987out:
1988    if ((cr != NULL) && (cr->cr_data != NULL))
1989	free(cr->cr_data, CISS_MALLOC_CLASS);
1990    if (cr != NULL)
1991	ciss_release_request(cr);
1992    return(error);
1993}
1994
1995/************************************************************************
1996 * Map a request into bus-visible space, initialise the scatter/gather
1997 * list.
1998 */
1999static int
2000ciss_map_request(struct ciss_request *cr)
2001{
2002    struct ciss_softc	*sc;
2003    int			error = 0;
2004
2005    debug_called(2);
2006
2007    sc = cr->cr_sc;
2008
2009    /* check that mapping is necessary */
2010    if (cr->cr_flags & CISS_REQ_MAPPED)
2011	return(0);
2012
2013    cr->cr_flags |= CISS_REQ_MAPPED;
2014
2015    bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2016		    BUS_DMASYNC_PREWRITE);
2017
2018    if (cr->cr_data != NULL) {
2019	error = bus_dmamap_load(sc->ciss_buffer_dmat, cr->cr_datamap,
2020				cr->cr_data, cr->cr_length,
2021				ciss_request_map_helper, cr, 0);
2022	if (error != 0)
2023	    return (error);
2024    } else {
2025	/*
2026	 * Post the command to the adapter.
2027	 */
2028	ciss_enqueue_busy(cr);
2029	CISS_TL_SIMPLE_POST_CMD(cr->cr_sc, CISS_FIND_COMMANDPHYS(cr));
2030    }
2031
2032    return(0);
2033}
2034
2035static void
2036ciss_request_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2037{
2038    struct ciss_command	*cc;
2039    struct ciss_request *cr;
2040    struct ciss_softc	*sc;
2041    int			i;
2042
2043    debug_called(2);
2044
2045    cr = (struct ciss_request *)arg;
2046    sc = cr->cr_sc;
2047    cc = CISS_FIND_COMMAND(cr);
2048
2049    for (i = 0; i < nseg; i++) {
2050	cc->sg[i].address = segs[i].ds_addr;
2051	cc->sg[i].length = segs[i].ds_len;
2052	cc->sg[i].extension = 0;
2053    }
2054    /* we leave the s/g table entirely within the command */
2055    cc->header.sg_in_list = nseg;
2056    cc->header.sg_total = nseg;
2057
2058    if (cr->cr_flags & CISS_REQ_DATAIN)
2059	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREREAD);
2060    if (cr->cr_flags & CISS_REQ_DATAOUT)
2061	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_PREWRITE);
2062
2063    /*
2064     * Post the command to the adapter.
2065     */
2066    ciss_enqueue_busy(cr);
2067    CISS_TL_SIMPLE_POST_CMD(cr->cr_sc, CISS_FIND_COMMANDPHYS(cr));
2068}
2069
2070/************************************************************************
2071 * Unmap a request from bus-visible space.
2072 */
2073static void
2074ciss_unmap_request(struct ciss_request *cr)
2075{
2076    struct ciss_softc	*sc;
2077
2078    debug_called(2);
2079
2080    sc = cr->cr_sc;
2081
2082    /* check that unmapping is necessary */
2083    if ((cr->cr_flags & CISS_REQ_MAPPED) == 0)
2084	return;
2085
2086    bus_dmamap_sync(sc->ciss_command_dmat, sc->ciss_command_map,
2087		    BUS_DMASYNC_POSTWRITE);
2088
2089    if (cr->cr_data == NULL)
2090	goto out;
2091
2092    if (cr->cr_flags & CISS_REQ_DATAIN)
2093	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTREAD);
2094    if (cr->cr_flags & CISS_REQ_DATAOUT)
2095	bus_dmamap_sync(sc->ciss_buffer_dmat, cr->cr_datamap, BUS_DMASYNC_POSTWRITE);
2096
2097    bus_dmamap_unload(sc->ciss_buffer_dmat, cr->cr_datamap);
2098out:
2099    cr->cr_flags &= ~CISS_REQ_MAPPED;
2100}
2101
2102/************************************************************************
2103 * Attach the driver to CAM.
2104 *
2105 * We put all the logical drives on a single SCSI bus.
2106 */
2107static int
2108ciss_cam_init(struct ciss_softc *sc)
2109{
2110
2111    debug_called(1);
2112
2113    /*
2114     * Allocate a devq.  We can reuse this for the masked physical
2115     * devices if we decide to export these as well.
2116     */
2117    if ((sc->ciss_cam_devq = cam_simq_alloc(sc->ciss_max_requests)) == NULL) {
2118	ciss_printf(sc, "can't allocate CAM SIM queue\n");
2119	return(ENOMEM);
2120    }
2121
2122    /*
2123     * Create a SIM.
2124     */
2125    if ((sc->ciss_cam_sim = cam_sim_alloc(ciss_cam_action, ciss_cam_poll, "ciss", sc,
2126					  device_get_unit(sc->ciss_dev),
2127					  sc->ciss_max_requests - 2,
2128					  1,
2129					  sc->ciss_cam_devq)) == NULL) {
2130	ciss_printf(sc, "can't allocate CAM SIM\n");
2131	return(ENOMEM);
2132    }
2133
2134    /*
2135     * Register bus 0 (the 'logical drives' bus) with this SIM.
2136     */
2137    if (xpt_bus_register(sc->ciss_cam_sim, 0) != 0) {
2138	ciss_printf(sc, "can't register SCSI bus 0\n");
2139	return(ENXIO);
2140    }
2141
2142    /*
2143     * Initiate a rescan of the bus.
2144     */
2145    ciss_cam_rescan_all(sc);
2146
2147    return(0);
2148}
2149
2150/************************************************************************
2151 * Initiate a rescan of the 'logical devices' SIM
2152 */
2153static void
2154ciss_cam_rescan_target(struct ciss_softc *sc, int target)
2155{
2156    union ccb	*ccb;
2157
2158    debug_called(1);
2159
2160    if ((ccb = malloc(sizeof(union ccb), M_TEMP, M_WAITOK | M_ZERO)) == NULL) {
2161	ciss_printf(sc, "rescan failed (can't allocate CCB)\n");
2162	return;
2163    }
2164
2165    if (xpt_create_path(&sc->ciss_cam_path, xpt_periph, cam_sim_path(sc->ciss_cam_sim), target, 0)
2166	!= CAM_REQ_CMP) {
2167	ciss_printf(sc, "rescan failed (can't create path)\n");
2168	return;
2169    }
2170
2171    xpt_setup_ccb(&ccb->ccb_h, sc->ciss_cam_path, 5/*priority (low)*/);
2172    ccb->ccb_h.func_code = XPT_SCAN_BUS;
2173    ccb->ccb_h.cbfcnp = ciss_cam_rescan_callback;
2174    ccb->crcn.flags = CAM_FLAG_NONE;
2175    xpt_action(ccb);
2176
2177    /* scan is now in progress */
2178}
2179
2180static void
2181ciss_cam_rescan_all(struct ciss_softc *sc)
2182{
2183    ciss_cam_rescan_target(sc, 0);
2184}
2185
2186static void
2187ciss_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
2188{
2189    xpt_free_path(ccb->ccb_h.path);
2190    free(ccb, M_TEMP);
2191}
2192
2193/************************************************************************
2194 * Handle requests coming from CAM
2195 */
2196static void
2197ciss_cam_action(struct cam_sim *sim, union ccb *ccb)
2198{
2199    struct ciss_softc	*sc;
2200    struct ccb_scsiio	*csio;
2201    int			target;
2202
2203    sc = cam_sim_softc(sim);
2204    csio = (struct ccb_scsiio *)&ccb->csio;
2205    target = csio->ccb_h.target_id;
2206
2207    switch (ccb->ccb_h.func_code) {
2208
2209	/* perform SCSI I/O */
2210    case XPT_SCSI_IO:
2211	if (!ciss_cam_action_io(sim, csio))
2212	    return;
2213	break;
2214
2215	/* perform geometry calculations */
2216    case XPT_CALC_GEOMETRY:
2217    {
2218	struct ccb_calc_geometry	*ccg = &ccb->ccg;
2219	struct ciss_ldrive		*ld = &sc->ciss_logical[target];
2220
2221	debug(1, "XPT_CALC_GEOMETRY %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2222
2223	/*
2224	 * Use the cached geometry settings unless the fault tolerance
2225	 * is invalid.
2226	 */
2227	if (ld->cl_geometry.fault_tolerance == 0xFF) {
2228	    u_int32_t			secs_per_cylinder;
2229
2230	    ccg->heads = 255;
2231	    ccg->secs_per_track = 32;
2232	    secs_per_cylinder = ccg->heads * ccg->secs_per_track;
2233	    ccg->cylinders = ccg->volume_size / secs_per_cylinder;
2234	} else {
2235	    ccg->heads = ld->cl_geometry.heads;
2236	    ccg->secs_per_track = ld->cl_geometry.sectors;
2237	    ccg->cylinders = ntohs(ld->cl_geometry.cylinders);
2238	}
2239	ccb->ccb_h.status = CAM_REQ_CMP;
2240        break;
2241    }
2242
2243	/* handle path attribute inquiry */
2244    case XPT_PATH_INQ:
2245    {
2246	struct ccb_pathinq	*cpi = &ccb->cpi;
2247
2248	debug(1, "XPT_PATH_INQ %d:%d:%d", cam_sim_bus(sim), ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
2249
2250	cpi->version_num = 1;
2251	cpi->hba_inquiry = PI_TAG_ABLE;	/* XXX is this correct? */
2252	cpi->target_sprt = 0;
2253	cpi->hba_misc = 0;
2254	cpi->max_target = CISS_MAX_LOGICAL;
2255	cpi->max_lun = 0;		/* 'logical drive' channel only */
2256	cpi->initiator_id = CISS_MAX_LOGICAL;
2257	strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
2258        strncpy(cpi->hba_vid, "msmith@freebsd.org", HBA_IDLEN);
2259        strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
2260        cpi->unit_number = cam_sim_unit(sim);
2261        cpi->bus_id = cam_sim_bus(sim);
2262	cpi->base_transfer_speed = 132 * 1024;	/* XXX what to set this to? */
2263	ccb->ccb_h.status = CAM_REQ_CMP;
2264	break;
2265    }
2266
2267    case XPT_GET_TRAN_SETTINGS:
2268    {
2269	struct ccb_trans_settings	*cts = &ccb->cts;
2270	int				bus, target;
2271
2272	bus = cam_sim_bus(sim);
2273	target = cts->ccb_h.target_id;
2274
2275	debug(1, "XPT_GET_TRAN_SETTINGS %d:%d", bus, target);
2276	cts->valid = 0;
2277
2278	/* disconnect always OK */
2279	cts->flags |= CCB_TRANS_DISC_ENB;
2280	cts->valid |= CCB_TRANS_DISC_VALID;
2281
2282	cts->ccb_h.status = CAM_REQ_CMP;
2283	break;
2284    }
2285
2286    default:		/* we can't do this */
2287	debug(1, "unspported func_code = 0x%x", ccb->ccb_h.func_code);
2288	ccb->ccb_h.status = CAM_REQ_INVALID;
2289	break;
2290    }
2291
2292    xpt_done(ccb);
2293}
2294
2295/************************************************************************
2296 * Handle a CAM SCSI I/O request.
2297 */
2298static int
2299ciss_cam_action_io(struct cam_sim *sim, struct ccb_scsiio *csio)
2300{
2301    struct ciss_softc	*sc;
2302    int			bus, target;
2303    struct ciss_request	*cr;
2304    struct ciss_command	*cc;
2305    int			error;
2306
2307    sc = cam_sim_softc(sim);
2308    bus = cam_sim_bus(sim);
2309    target = csio->ccb_h.target_id;
2310
2311    debug(2, "XPT_SCSI_IO %d:%d:%d", bus, target, csio->ccb_h.target_lun);
2312
2313    /* check for I/O attempt to nonexistent device */
2314    if ((bus != 0) ||
2315	(target >= CISS_MAX_LOGICAL) ||
2316	(sc->ciss_logical[target].cl_status == CISS_LD_NONEXISTENT)) {
2317	debug(3, "  device does not exist");
2318	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2319    }
2320
2321    /* firmware does not support commands > 10 bytes */
2322    if (csio->cdb_len > 12/*CISS_CDB_BUFFER_SIZE*/) {
2323	debug(3, "  command too large (%d > %d)", csio->cdb_len, CISS_CDB_BUFFER_SIZE);
2324	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2325    }
2326
2327    /* check that the CDB pointer is not to a physical address */
2328    if ((csio->ccb_h.flags & CAM_CDB_POINTER) && (csio->ccb_h.flags & CAM_CDB_PHYS)) {
2329	debug(3, "  CDB pointer is to physical address");
2330	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2331    }
2332
2333    /* if there is data transfer, it must be to/from a virtual address */
2334    if ((csio->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2335	if (csio->ccb_h.flags & CAM_DATA_PHYS) {		/* we can't map it */
2336	    debug(3, "  data pointer is to physical address");
2337	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2338	}
2339	if (csio->ccb_h.flags & CAM_SCATTER_VALID) {	/* we want to do the s/g setup */
2340	    debug(3, "  data has premature s/g setup");
2341	    csio->ccb_h.status = CAM_REQ_CMP_ERR;
2342	}
2343    }
2344
2345    /* abandon aborted ccbs or those that have failed validation */
2346    if ((csio->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2347	debug(3, "abandoning CCB due to abort/validation failure");
2348	return(EINVAL);
2349    }
2350
2351    /* handle emulation of some SCSI commands ourself */
2352    if (ciss_cam_emulate(sc, csio))
2353	return(0);
2354
2355    /*
2356     * Get a request to manage this command.  If we can't, return the
2357     * ccb, freeze the queue and flag so that we unfreeze it when a
2358     * request completes.
2359     */
2360    if ((error = ciss_get_request(sc, &cr)) != 0) {
2361	xpt_freeze_simq(sc->ciss_cam_sim, 1);
2362	csio->ccb_h.status |= CAM_REQUEUE_REQ;
2363	return(error);
2364    }
2365
2366    /*
2367     * Build the command.
2368     */
2369    cc = CISS_FIND_COMMAND(cr);
2370    cr->cr_data = csio->data_ptr;
2371    cr->cr_length = csio->dxfer_len;
2372    cr->cr_complete = ciss_cam_complete;
2373    cr->cr_private = csio;
2374
2375    cc->header.address.logical.mode = CISS_HDR_ADDRESS_MODE_LOGICAL;
2376    cc->header.address.logical.lun = target;
2377    cc->cdb.cdb_length = csio->cdb_len;
2378    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2379    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;	/* XXX ordered tags? */
2380    if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2381	cr->cr_flags = CISS_REQ_DATAOUT;
2382	cc->cdb.direction = CISS_CDB_DIRECTION_WRITE;
2383    } else if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2384	cr->cr_flags = CISS_REQ_DATAIN;
2385	cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2386    } else {
2387	cr->cr_flags = 0;
2388	cc->cdb.direction = CISS_CDB_DIRECTION_NONE;
2389    }
2390    cc->cdb.timeout = (csio->ccb_h.timeout / 1000) + 1;
2391    if (csio->ccb_h.flags & CAM_CDB_POINTER) {
2392	bcopy(csio->cdb_io.cdb_ptr, &cc->cdb.cdb[0], csio->cdb_len);
2393    } else {
2394	bcopy(csio->cdb_io.cdb_bytes, &cc->cdb.cdb[0], csio->cdb_len);
2395    }
2396
2397    /*
2398     * Submit the request to the adapter.
2399     *
2400     * Note that this may fail if we're unable to map the request (and
2401     * if we ever learn a transport layer other than simple, may fail
2402     * if the adapter rejects the command).
2403     */
2404    if ((error = ciss_start(cr)) != 0) {
2405	xpt_freeze_simq(sc->ciss_cam_sim, 1);
2406	if (error == EINPROGRESS) {
2407	    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2408	    error = 0;
2409	} else {
2410	    csio->ccb_h.status |= CAM_REQUEUE_REQ;
2411	    ciss_release_request(cr);
2412	}
2413	return(error);
2414    }
2415
2416    return(0);
2417}
2418
2419/************************************************************************
2420 * Emulate SCSI commands the adapter doesn't handle as we might like.
2421 */
2422static int
2423ciss_cam_emulate(struct ciss_softc *sc, struct ccb_scsiio *csio)
2424{
2425    int		target;
2426    u_int8_t	opcode;
2427
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
2464    /* if we have to fake Synchronise Cache */
2465    if (sc->ciss_flags & CISS_FLAG_FAKE_SYNCH) {
2466
2467	/*
2468	 * If this is a Synchronise Cache command, typically issued when
2469	 * a device is closed, flush the adapter and complete now.
2470	 */
2471	if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2472	     *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE) {
2473	    ciss_flush_adapter(sc);
2474	    csio->ccb_h.status = CAM_REQ_CMP;
2475	    xpt_done((union ccb *)csio);
2476	    return(1);
2477	}
2478    }
2479
2480    return(0);
2481}
2482
2483/************************************************************************
2484 * Check for possibly-completed commands.
2485 */
2486static void
2487ciss_cam_poll(struct cam_sim *sim)
2488{
2489    struct ciss_softc	*sc = cam_sim_softc(sim);
2490
2491    debug_called(2);
2492
2493    ciss_done(sc);
2494}
2495
2496/************************************************************************
2497 * Handle completion of a command - pass results back through the CCB
2498 */
2499static void
2500ciss_cam_complete(struct ciss_request *cr)
2501{
2502    struct ciss_softc		*sc;
2503    struct ciss_command		*cc;
2504    struct ciss_error_info	*ce;
2505    struct ccb_scsiio		*csio;
2506    int				scsi_status;
2507    int				command_status;
2508
2509    debug_called(2);
2510
2511    sc = cr->cr_sc;
2512    cc = CISS_FIND_COMMAND(cr);
2513    ce = (struct ciss_error_info *)&(cc->sg[0]);
2514    csio = (struct ccb_scsiio *)cr->cr_private;
2515
2516    /*
2517     * Extract status values from request.
2518     */
2519    ciss_report_request(cr, &command_status, &scsi_status);
2520    csio->scsi_status = scsi_status;
2521
2522    /*
2523     * Handle specific SCSI status values.
2524     */
2525    switch(scsi_status) {
2526	/* no status due to adapter error */
2527    case -1:
2528	debug(0, "adapter error");
2529	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2530	break;
2531
2532	/* no status due to command completed OK */
2533    case SCSI_STATUS_OK:		/* CISS_SCSI_STATUS_GOOD */
2534	debug(2, "SCSI_STATUS_OK");
2535	csio->ccb_h.status = CAM_REQ_CMP;
2536	break;
2537
2538	/* check condition, sense data included */
2539    case SCSI_STATUS_CHECK_COND:	/* CISS_SCSI_STATUS_CHECK_CONDITION */
2540	debug(0, "SCSI_STATUS_CHECK_COND  sense size %d  resid %d",
2541	      ce->sense_length, ce->residual_count);
2542	bzero(&csio->sense_data, SSD_FULL_SIZE);
2543	bcopy(&ce->sense_info[0], &csio->sense_data, ce->sense_length);
2544	csio->sense_len = ce->sense_length;
2545	csio->resid = ce->residual_count;
2546	csio->ccb_h.status = CAM_SCSI_STATUS_ERROR | CAM_AUTOSNS_VALID;
2547#ifdef CISS_DEBUG
2548	{
2549	    struct scsi_sense_data	*sns = (struct scsi_sense_data *)&ce->sense_info[0];
2550	    debug(0, "sense key %x", sns->flags & SSD_KEY);
2551	}
2552#endif
2553	break;
2554
2555    case SCSI_STATUS_BUSY:		/* CISS_SCSI_STATUS_BUSY */
2556	debug(0, "SCSI_STATUS_BUSY");
2557	csio->ccb_h.status = CAM_SCSI_BUSY;
2558	break;
2559
2560    default:
2561	debug(0, "unknown status 0x%x", csio->scsi_status);
2562	csio->ccb_h.status = CAM_REQ_CMP_ERR;
2563	break;
2564    }
2565
2566    /* handle post-command fixup */
2567    ciss_cam_complete_fixup(sc, csio);
2568
2569    /* tell CAM we're ready for more commands */
2570    csio->ccb_h.status |= CAM_RELEASE_SIMQ;
2571
2572    xpt_done((union ccb *)csio);
2573    ciss_release_request(cr);
2574}
2575
2576/********************************************************************************
2577 * Fix up the result of some commands here.
2578 */
2579static void
2580ciss_cam_complete_fixup(struct ciss_softc *sc, struct ccb_scsiio *csio)
2581{
2582    struct scsi_inquiry_data	*inq;
2583    struct ciss_ldrive		*cl;
2584    int				target;
2585
2586    if (((csio->ccb_h.flags & CAM_CDB_POINTER) ?
2587	 *(u_int8_t *)csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes[0]) == INQUIRY) {
2588
2589	inq = (struct scsi_inquiry_data *)csio->data_ptr;
2590	target = csio->ccb_h.target_id;
2591	cl = &sc->ciss_logical[target];
2592
2593	padstr(inq->vendor, "COMPAQ", 8);
2594	padstr(inq->product, ciss_name_ldrive_org(cl->cl_ldrive->fault_tolerance), 8);
2595	padstr(inq->revision, ciss_name_ldrive_status(cl->cl_lstatus->status), 16);
2596    }
2597}
2598
2599
2600/********************************************************************************
2601 * Find a peripheral attached at (target)
2602 */
2603static struct cam_periph *
2604ciss_find_periph(struct ciss_softc *sc, int target)
2605{
2606    struct cam_periph	*periph;
2607    struct cam_path	*path;
2608    int			status;
2609
2610    status = xpt_create_path(&path, NULL, cam_sim_path(sc->ciss_cam_sim), target, 0);
2611    if (status == CAM_REQ_CMP) {
2612	periph = cam_periph_find(path, NULL);
2613	xpt_free_path(path);
2614    } else {
2615	periph = NULL;
2616    }
2617    return(periph);
2618}
2619
2620/********************************************************************************
2621 * Name the device at (target)
2622 *
2623 * XXX is this strictly correct?
2624 */
2625static int
2626ciss_name_device(struct ciss_softc *sc, int target)
2627{
2628    struct cam_periph	*periph;
2629
2630    if ((periph = ciss_find_periph(sc, target)) != NULL) {
2631	sprintf(sc->ciss_logical[target].cl_name, "%s%d", periph->periph_name, periph->unit_number);
2632	return(0);
2633    }
2634    sc->ciss_logical[target].cl_name[0] = 0;
2635    return(ENOENT);
2636}
2637
2638/************************************************************************
2639 * Periodic status monitoring.
2640 */
2641static void
2642ciss_periodic(void *arg)
2643{
2644    struct ciss_softc	*sc;
2645
2646    debug_called(1);
2647
2648    sc = (struct ciss_softc *)arg;
2649
2650    /*
2651     * Check the adapter heartbeat.
2652     */
2653    if (sc->ciss_cfg->heartbeat == sc->ciss_heartbeat) {
2654	sc->ciss_heart_attack++;
2655	debug(0, "adapter heart attack in progress 0x%x/%d",
2656	      sc->ciss_heartbeat, sc->ciss_heart_attack);
2657	if (sc->ciss_heart_attack == 3) {
2658	    ciss_printf(sc, "ADAPTER HEARTBEAT FAILED\n");
2659	    /* XXX should reset adapter here */
2660	}
2661    } else {
2662	sc->ciss_heartbeat = sc->ciss_cfg->heartbeat;
2663	sc->ciss_heart_attack = 0;
2664	debug(3, "new heartbeat 0x%x", sc->ciss_heartbeat);
2665    }
2666
2667    /*
2668     * If the notify event request has died for some reason, or has
2669     * not started yet, restart it.
2670     */
2671    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK)) {
2672	debug(0, "(re)starting Event Notify chain");
2673	ciss_notify_event(sc);
2674    }
2675
2676    /*
2677     * Reschedule.
2678     */
2679    if (!(sc->ciss_flags & CISS_FLAG_ABORTING))
2680	sc->ciss_periodic = timeout(ciss_periodic, sc, CISS_HEARTBEAT_RATE * hz);
2681}
2682
2683/************************************************************************
2684 * Request a notification response from the adapter.
2685 *
2686 * If (cr) is NULL, this is the first request of the adapter, so
2687 * reset the adapter's message pointer and start with the oldest
2688 * message available.
2689 */
2690static void
2691ciss_notify_event(struct ciss_softc *sc)
2692{
2693    struct ciss_request		*cr;
2694    struct ciss_command		*cc;
2695    struct ciss_notify_cdb	*cnc;
2696    int				error;
2697
2698    debug_called(1);
2699
2700    cr = sc->ciss_periodic_notify;
2701
2702    /* get a request if we don't already have one */
2703    if (cr == NULL) {
2704	if ((error = ciss_get_request(sc, &cr)) != 0) {
2705	    debug(0, "can't get notify event request");
2706	    goto out;
2707	}
2708	sc->ciss_periodic_notify = cr;
2709	cr->cr_complete = ciss_notify_complete;
2710	debug(1, "acquired request %d", cr->cr_tag);
2711    }
2712
2713    /*
2714     * Get a databuffer if we don't already have one, note that the
2715     * adapter command wants a larger buffer than the actual
2716     * structure.
2717     */
2718    if (cr->cr_data == NULL) {
2719	if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2720	    debug(0, "can't get notify event request buffer");
2721	    error = ENOMEM;
2722	    goto out;
2723	}
2724	cr->cr_length = CISS_NOTIFY_DATA_SIZE;
2725    }
2726
2727    /* re-setup the request's command (since we never release it) XXX overkill*/
2728    ciss_preen_command(cr);
2729
2730    /* (re)build the notify event command */
2731    cc = CISS_FIND_COMMAND(cr);
2732    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2733    cc->header.address.physical.bus = 0;
2734    cc->header.address.physical.target = 0;
2735
2736    cc->cdb.cdb_length = sizeof(*cnc);
2737    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2738    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2739    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2740    cc->cdb.timeout = 0;	/* no timeout, we hope */
2741
2742    cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
2743    bzero(cr->cr_data, CISS_NOTIFY_DATA_SIZE);
2744    cnc->opcode = CISS_OPCODE_READ;
2745    cnc->command = CISS_COMMAND_NOTIFY_ON_EVENT;
2746    cnc->timeout = 0;		/* no timeout, we hope */
2747    cnc->synchronous = 0;
2748    cnc->ordered = 0;
2749    cnc->seek_to_oldest = 0;
2750    cnc->new_only = 0;
2751    cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
2752
2753    /* submit the request */
2754    error = ciss_start(cr);
2755
2756 out:
2757    if (error) {
2758	if (cr != NULL) {
2759	    if (cr->cr_data != NULL)
2760		free(cr->cr_data, CISS_MALLOC_CLASS);
2761	    ciss_release_request(cr);
2762	}
2763	sc->ciss_periodic_notify = NULL;
2764	debug(0, "can't submit notify event request");
2765	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2766    } else {
2767	debug(1, "notify event submitted");
2768	sc->ciss_flags |= CISS_FLAG_NOTIFY_OK;
2769    }
2770}
2771
2772static void
2773ciss_notify_complete(struct ciss_request *cr)
2774{
2775    struct ciss_command	*cc;
2776    struct ciss_notify	*cn;
2777    struct ciss_softc	*sc;
2778    int			scsi_status;
2779    int			command_status;
2780
2781    debug_called(1);
2782
2783    cc = CISS_FIND_COMMAND(cr);
2784    cn = (struct ciss_notify *)cr->cr_data;
2785    sc = cr->cr_sc;
2786
2787    /*
2788     * Report request results, decode status.
2789     */
2790    ciss_report_request(cr, &command_status, &scsi_status);
2791
2792    /*
2793     * Abort the chain on a fatal error.
2794     *
2795     * XXX which of these are actually errors?
2796     */
2797    if ((command_status != CISS_CMD_STATUS_SUCCESS) &&
2798	(command_status != CISS_CMD_STATUS_TARGET_STATUS) &&
2799	(command_status != CISS_CMD_STATUS_TIMEOUT)) {	/* XXX timeout? */
2800	ciss_printf(sc, "fatal error in Notify Event request (%s)\n",
2801		    ciss_name_command_status(command_status));
2802	ciss_release_request(cr);
2803	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2804	return;
2805    }
2806
2807    /*
2808     * If the adapter gave us a text message, print it.
2809     */
2810    if (cn->message[0] != 0)
2811	ciss_printf(sc, "*** %.80s\n", cn->message);
2812
2813    debug(0, "notify event class %d subclass %d detail %d",
2814		cn->class, cn->subclass, cn->detail);
2815
2816    /*
2817     * If there's room, save the event for a user-level tool.
2818     */
2819    if (((sc->ciss_notify_head + 1) % CISS_MAX_EVENTS) != sc->ciss_notify_tail) {
2820	sc->ciss_notify[sc->ciss_notify_head] = *cn;
2821	sc->ciss_notify_head = (sc->ciss_notify_head + 1) % CISS_MAX_EVENTS;
2822    }
2823
2824    /*
2825     * Some events are directly of interest to us.
2826     */
2827    switch (cn->class) {
2828    case CISS_NOTIFY_LOGICAL:
2829	ciss_notify_logical(sc, cn);
2830	break;
2831    case CISS_NOTIFY_PHYSICAL:
2832	ciss_notify_physical(sc, cn);
2833	break;
2834    }
2835
2836    /*
2837     * If the response indicates that the notifier has been aborted,
2838     * release the notifier command.
2839     */
2840    if ((cn->class == CISS_NOTIFY_NOTIFIER) &&
2841	(cn->subclass == CISS_NOTIFY_NOTIFIER_STATUS) &&
2842	(cn->detail == 1)) {
2843	debug(0, "notifier exiting");
2844	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2845	ciss_release_request(cr);
2846	sc->ciss_periodic_notify = NULL;
2847	wakeup(&sc->ciss_periodic_notify);
2848    }
2849
2850    /*
2851     * Send a new notify event command, if we're not aborting.
2852     */
2853    if (!(sc->ciss_flags & CISS_FLAG_ABORTING)) {
2854	ciss_notify_event(sc);
2855    }
2856}
2857
2858/************************************************************************
2859 * Abort the Notify Event chain.
2860 *
2861 * Note that we can't just abort the command in progress; we have to
2862 * explicitly issue an Abort Notify Event command in order for the
2863 * adapter to clean up correctly.
2864 *
2865 * If we are called with CISS_FLAG_ABORTING set in the adapter softc,
2866 * the chain will not restart itself.
2867 */
2868static int
2869ciss_notify_abort(struct ciss_softc *sc)
2870{
2871    struct ciss_request		*cr;
2872    struct ciss_command		*cc;
2873    struct ciss_notify_cdb	*cnc;
2874    int				error, s, command_status, scsi_status;
2875
2876    debug_called(1);
2877
2878    cr = NULL;
2879    error = 0;
2880
2881    /* verify that there's an outstanding command */
2882    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
2883	goto out;
2884
2885    /* get a command to issue the abort with */
2886    if ((error = ciss_get_request(sc, &cr)))
2887	goto out;
2888
2889    /* get a buffer for the result */
2890    if ((cr->cr_data = malloc(CISS_NOTIFY_DATA_SIZE, CISS_MALLOC_CLASS, M_NOWAIT)) == NULL) {
2891	debug(0, "can't get notify event request buffer");
2892	error = ENOMEM;
2893	goto out;
2894    }
2895    cr->cr_length = CISS_NOTIFY_DATA_SIZE;
2896
2897    /* build the CDB */
2898    cc = CISS_FIND_COMMAND(cr);
2899    cc->header.address.physical.mode = CISS_HDR_ADDRESS_MODE_PERIPHERAL;
2900    cc->header.address.physical.bus = 0;
2901    cc->header.address.physical.target = 0;
2902    cc->cdb.cdb_length = sizeof(*cnc);
2903    cc->cdb.type = CISS_CDB_TYPE_COMMAND;
2904    cc->cdb.attribute = CISS_CDB_ATTRIBUTE_SIMPLE;
2905    cc->cdb.direction = CISS_CDB_DIRECTION_READ;
2906    cc->cdb.timeout = 0;	/* no timeout, we hope */
2907
2908    cnc = (struct ciss_notify_cdb *)&(cc->cdb.cdb[0]);
2909    bzero(cnc, sizeof(*cnc));
2910    cnc->opcode = CISS_OPCODE_WRITE;
2911    cnc->command = CISS_COMMAND_ABORT_NOTIFY;
2912    cnc->length = htonl(CISS_NOTIFY_DATA_SIZE);
2913
2914    ciss_print_request(cr);
2915
2916    /*
2917     * Submit the request and wait for it to complete.
2918     */
2919    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
2920	ciss_printf(sc, "Abort Notify Event command failed (%d)\n", error);
2921	goto out;
2922    }
2923
2924    /*
2925     * Check response.
2926     */
2927    ciss_report_request(cr, &command_status, &scsi_status);
2928    switch(command_status) {
2929    case CISS_CMD_STATUS_SUCCESS:
2930	break;
2931    case CISS_CMD_STATUS_INVALID_COMMAND:
2932	/*
2933	 * Some older adapters don't support the CISS version of this
2934	 * command.  Fall back to using the BMIC version.
2935	 */
2936	error = ciss_notify_abort_bmic(sc);
2937	if (error != 0)
2938	    goto out;
2939	break;
2940
2941    case CISS_CMD_STATUS_TARGET_STATUS:
2942	/*
2943	 * This can happen if the adapter thinks there wasn't an outstanding
2944	 * Notify Event command but we did.  We clean up here.
2945	 */
2946	if (scsi_status == CISS_SCSI_STATUS_CHECK_CONDITION) {
2947	    if (sc->ciss_periodic_notify != NULL)
2948		ciss_release_request(sc->ciss_periodic_notify);
2949	    error = 0;
2950	    goto out;
2951	}
2952	/* FALLTHROUGH */
2953
2954    default:
2955	ciss_printf(sc, "Abort Notify Event command failed (%s)\n",
2956		    ciss_name_command_status(command_status));
2957	error = EIO;
2958	goto out;
2959    }
2960
2961    /*
2962     * Sleep waiting for the notifier command to complete.  Note
2963     * that if it doesn't, we may end up in a bad situation, since
2964     * the adapter may deliver it later.  Also note that the adapter
2965     * requires the Notify Event command to be cancelled in order to
2966     * maintain internal bookkeeping.
2967     */
2968    s = splcam();
2969    while (sc->ciss_periodic_notify != NULL) {
2970	error = tsleep(&sc->ciss_periodic_notify, 0, "cissNEA", hz * 5);
2971	if (error == EWOULDBLOCK) {
2972	    ciss_printf(sc, "Notify Event command failed to abort, adapter may wedge.\n");
2973	    break;
2974	}
2975    }
2976    splx(s);
2977
2978 out:
2979    /* release the cancel request */
2980    if (cr != NULL) {
2981	if (cr->cr_data != NULL)
2982	    free(cr->cr_data, CISS_MALLOC_CLASS);
2983	ciss_release_request(cr);
2984    }
2985    if (error == 0)
2986	sc->ciss_flags &= ~CISS_FLAG_NOTIFY_OK;
2987    return(error);
2988}
2989
2990/************************************************************************
2991 * Abort the Notify Event chain using a BMIC command.
2992 */
2993static int
2994ciss_notify_abort_bmic(struct ciss_softc *sc)
2995{
2996    struct ciss_request			*cr;
2997    int					error, command_status;
2998
2999    debug_called(1);
3000
3001    cr = NULL;
3002    error = 0;
3003
3004    /* verify that there's an outstanding command */
3005    if (!(sc->ciss_flags & CISS_FLAG_NOTIFY_OK))
3006	goto out;
3007
3008    /*
3009     * Build a BMIC command to cancel the Notify on Event command.
3010     *
3011     * Note that we are sending a CISS opcode here.  Odd.
3012     */
3013    if ((error = ciss_get_bmic_request(sc, &cr, CISS_COMMAND_ABORT_NOTIFY,
3014				       NULL, 0)) != 0)
3015	goto out;
3016
3017    /*
3018     * Submit the request and wait for it to complete.
3019     */
3020    if ((error = ciss_synch_request(cr, 60 * 1000)) != 0) {
3021	ciss_printf(sc, "error sending BMIC Cancel Notify on Event command (%d)\n", error);
3022	goto out;
3023    }
3024
3025    /*
3026     * Check response.
3027     */
3028    ciss_report_request(cr, &command_status, NULL);
3029    switch(command_status) {
3030    case CISS_CMD_STATUS_SUCCESS:
3031	break;
3032    default:
3033	ciss_printf(sc, "error cancelling Notify on Event (%s)\n",
3034		    ciss_name_command_status(command_status));
3035	error = EIO;
3036	goto out;
3037    }
3038
3039out:
3040    if (cr != NULL)
3041	ciss_release_request(cr);
3042    return(error);
3043}
3044
3045/************************************************************************
3046 * Handle a notify event relating to the status of a logical drive.
3047 *
3048 * XXX need to be able to defer some of these to properly handle
3049 *     calling the "ID Physical drive" command, unless the 'extended'
3050 *     drive IDs are always in BIG_MAP format.
3051 */
3052static void
3053ciss_notify_logical(struct ciss_softc *sc, struct ciss_notify *cn)
3054{
3055    struct ciss_ldrive	*ld;
3056    int			ostatus;
3057
3058    debug_called(2);
3059
3060    ld = &sc->ciss_logical[cn->data.logical_status.logical_drive];
3061
3062    switch (cn->subclass) {
3063    case CISS_NOTIFY_LOGICAL_STATUS:
3064	switch (cn->detail) {
3065	case 0:
3066	    ciss_name_device(sc, cn->data.logical_status.logical_drive);
3067	    ciss_printf(sc, "logical drive %d (%s) changed status %s->%s, spare status 0x%b\n",
3068			cn->data.logical_status.logical_drive, ld->cl_name,
3069			ciss_name_ldrive_status(cn->data.logical_status.previous_state),
3070			ciss_name_ldrive_status(cn->data.logical_status.new_state),
3071			cn->data.logical_status.spare_state,
3072			"\20\1configured\2rebuilding\3failed\4in use\5available\n");
3073
3074	    /*
3075	     * Update our idea of the drive's status.
3076	     */
3077	    ostatus = ciss_decode_ldrive_status(cn->data.logical_status.previous_state);
3078	    ld->cl_status = ciss_decode_ldrive_status(cn->data.logical_status.new_state);
3079	    if (ld->cl_lstatus != NULL)
3080		ld->cl_lstatus->status = cn->data.logical_status.new_state;
3081
3082#if 0
3083	    /*
3084	     * Have CAM rescan the drive if its status has changed.
3085	     */
3086	    if (ostatus != ld->cl_status)
3087		ciss_cam_rescan_target(sc, cn->data.logical_status.logical_drive);
3088#endif
3089
3090	    break;
3091
3092	case 1:	/* logical drive has recognised new media, needs Accept Media Exchange */
3093	    ciss_name_device(sc, cn->data.logical_status.logical_drive);
3094	    ciss_printf(sc, "logical drive %d (%s) media exchanged, ready to go online\n",
3095			cn->data.logical_status.logical_drive, ld->cl_name);
3096	    ciss_accept_media(sc, cn->data.logical_status.logical_drive, 1);
3097	    break;
3098
3099	case 2:
3100	case 3:
3101	    ciss_printf(sc, "rebuild of logical drive %d (%s) failed due to %s error\n",
3102			cn->data.rebuild_aborted.logical_drive,
3103			sc->ciss_logical[cn->data.rebuild_aborted.logical_drive].cl_name,
3104			(cn->detail == 2) ? "read" : "write");
3105	    break;
3106	}
3107	break;
3108
3109    case CISS_NOTIFY_LOGICAL_ERROR:
3110	if (cn->detail == 0) {
3111	    ciss_printf(sc, "FATAL I/O ERROR on logical drive %d (%s), SCSI port %d ID %d\n",
3112			cn->data.io_error.logical_drive,
3113			sc->ciss_logical[cn->data.io_error.logical_drive].cl_name,
3114			cn->data.io_error.failure_bus,
3115			cn->data.io_error.failure_drive);
3116	    /* XXX should we take the drive down at this point, or will we be told? */
3117	}
3118	break;
3119
3120    case CISS_NOTIFY_LOGICAL_SURFACE:
3121	if (cn->detail == 0)
3122	    ciss_printf(sc, "logical drive %d (%s) completed consistency initialisation\n",
3123			cn->data.consistency_completed.logical_drive,
3124			sc->ciss_logical[cn->data.consistency_completed.logical_drive].cl_name);
3125	break;
3126    }
3127}
3128
3129/************************************************************************
3130 * Handle a notify event relating to the status of a physical drive.
3131 */
3132static void
3133ciss_notify_physical(struct ciss_softc *sc, struct ciss_notify *cn)
3134{
3135
3136}
3137
3138/************************************************************************
3139 * Print a request.
3140 */
3141static void
3142ciss_print_request(struct ciss_request *cr)
3143{
3144    struct ciss_softc	*sc;
3145    struct ciss_command	*cc;
3146    int			i;
3147
3148    sc = cr->cr_sc;
3149    cc = CISS_FIND_COMMAND(cr);
3150
3151    ciss_printf(sc, "REQUEST @ %p\n", cr);
3152    ciss_printf(sc, "  data %p/%d  tag %d  flags %b\n",
3153	      cr->cr_data, cr->cr_length, cr->cr_tag, cr->cr_flags,
3154	      "\20\1mapped\2sleep\3poll\4dataout\5datain\n");
3155    ciss_printf(sc, "  sg list/total %d/%d  host tag 0x%x\n",
3156		cc->header.sg_in_list, cc->header.sg_total, cc->header.host_tag);
3157    switch(cc->header.address.mode.mode) {
3158    case CISS_HDR_ADDRESS_MODE_PERIPHERAL:
3159    case CISS_HDR_ADDRESS_MODE_MASK_PERIPHERAL:
3160	ciss_printf(sc, "  physical bus %d target %d\n",
3161		    cc->header.address.physical.bus, cc->header.address.physical.target);
3162	break;
3163    case CISS_HDR_ADDRESS_MODE_LOGICAL:
3164	ciss_printf(sc, "  logical unit %d\n", cc->header.address.logical.lun);
3165	break;
3166    }
3167    ciss_printf(sc, "  %s cdb length %d type %s attribute %s\n",
3168		(cc->cdb.direction == CISS_CDB_DIRECTION_NONE) ? "no-I/O" :
3169		(cc->cdb.direction == CISS_CDB_DIRECTION_READ) ? "READ" :
3170		(cc->cdb.direction == CISS_CDB_DIRECTION_WRITE) ? "WRITE" : "??",
3171		cc->cdb.cdb_length,
3172		(cc->cdb.type == CISS_CDB_TYPE_COMMAND) ? "command" :
3173		(cc->cdb.type == CISS_CDB_TYPE_MESSAGE) ? "message" : "??",
3174		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_UNTAGGED) ? "untagged" :
3175		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_SIMPLE) ? "simple" :
3176		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_HEAD_OF_QUEUE) ? "head-of-queue" :
3177		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_ORDERED) ? "ordered" :
3178		(cc->cdb.attribute == CISS_CDB_ATTRIBUTE_AUTO_CONTINGENT) ? "auto-contingent" : "??");
3179    ciss_printf(sc, "  %*D\n", cc->cdb.cdb_length, &cc->cdb.cdb[0], " ");
3180
3181    if (cc->header.host_tag & CISS_HDR_HOST_TAG_ERROR) {
3182	/* XXX print error info */
3183    } else {
3184	/* since we don't use chained s/g, don't support it here */
3185	for (i = 0; i < cc->header.sg_in_list; i++) {
3186	    if ((i % 4) == 0)
3187		ciss_printf(sc, "   ");
3188	    printf("0x%08x/%d ", (u_int32_t)cc->sg[i].address, cc->sg[i].length);
3189	    if ((((i + 1) % 4) == 0) || (i == (cc->header.sg_in_list - 1)))
3190		printf("\n");
3191	}
3192    }
3193}
3194
3195/************************************************************************
3196 * Print information about the status of a logical drive.
3197 */
3198static void
3199ciss_print_ldrive(struct ciss_softc *sc, struct ciss_ldrive *ld)
3200{
3201    int		bus, target, i;
3202
3203    if (ld->cl_lstatus == NULL) {
3204	printf("does not exist\n");
3205	return;
3206    }
3207
3208    /* print drive status */
3209    switch(ld->cl_lstatus->status) {
3210    case CISS_LSTATUS_OK:
3211	printf("online\n");
3212	break;
3213    case CISS_LSTATUS_INTERIM_RECOVERY:
3214	printf("in interim recovery mode\n");
3215	break;
3216    case CISS_LSTATUS_READY_RECOVERY:
3217	printf("ready to begin recovery\n");
3218	break;
3219    case CISS_LSTATUS_RECOVERING:
3220	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3221	target = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_rebuilding);
3222	printf("being recovered, working on physical drive %d.%d, %u blocks remaining\n",
3223	       bus, target, ld->cl_lstatus->blocks_to_recover);
3224	break;
3225    case CISS_LSTATUS_EXPANDING:
3226	printf("being expanded, %u blocks remaining\n",
3227	       ld->cl_lstatus->blocks_to_recover);
3228	break;
3229    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3230	printf("queued for expansion\n");
3231	break;
3232    case CISS_LSTATUS_FAILED:
3233	printf("queued for expansion\n");
3234	break;
3235    case CISS_LSTATUS_WRONG_PDRIVE:
3236	printf("wrong physical drive inserted\n");
3237	break;
3238    case CISS_LSTATUS_MISSING_PDRIVE:
3239	printf("missing a needed physical drive\n");
3240	break;
3241    case CISS_LSTATUS_BECOMING_READY:
3242	printf("becoming ready\n");
3243	break;
3244    }
3245
3246    /* print failed physical drives */
3247    for (i = 0; i < CISS_BIG_MAP_ENTRIES / 8; i++) {
3248	bus = CISS_BIG_MAP_BUS(sc, ld->cl_lstatus->drive_failure_map[i]);
3249	target = CISS_BIG_MAP_TARGET(sc, ld->cl_lstatus->drive_failure_map[i]);
3250	if (bus == -1)
3251	    continue;
3252	ciss_printf(sc, "physical drive %d:%d (%x) failed\n", bus, target,
3253		    ld->cl_lstatus->drive_failure_map[i]);
3254    }
3255}
3256
3257#ifdef CISS_DEBUG
3258/************************************************************************
3259 * Print information about the controller/driver.
3260 */
3261static void
3262ciss_print_adapter(struct ciss_softc *sc)
3263{
3264    int		i;
3265
3266    ciss_printf(sc, "ADAPTER:\n");
3267    for (i = 0; i < CISSQ_COUNT; i++) {
3268	ciss_printf(sc, "%s     %d/%d\n",
3269	    i == 0 ? "free" :
3270	    i == 1 ? "busy" : "complete",
3271	    sc->ciss_qstat[i].q_length,
3272	    sc->ciss_qstat[i].q_max);
3273    }
3274    ciss_printf(sc, "max_requests %d\n", sc->ciss_max_requests);
3275    ciss_printf(sc, "notify_head/tail %d/%d\n",
3276	sc->ciss_notify_head, sc->ciss_notify_tail);
3277    ciss_printf(sc, "flags %b\n", sc->ciss_flags,
3278	"\20\1notify_ok\2control_open\3aborting\4running\21fake_synch\22bmic_abort\n");
3279
3280    for (i = 0; i < CISS_MAX_LOGICAL; i++) {
3281	ciss_printf(sc, "LOGICAL DRIVE %d:  ", i);
3282	ciss_print_ldrive(sc, sc->ciss_logical + i);
3283    }
3284
3285    for (i = 1; i < sc->ciss_max_requests; i++)
3286	ciss_print_request(sc->ciss_request + i);
3287
3288}
3289
3290/* DDB hook */
3291static void
3292ciss_print0(void)
3293{
3294    struct ciss_softc	*sc;
3295
3296    sc = devclass_get_softc(devclass_find("ciss"), 0);
3297    if (sc == NULL) {
3298	printf("no ciss controllers\n");
3299    } else {
3300	ciss_print_adapter(sc);
3301    }
3302}
3303#endif
3304
3305/************************************************************************
3306 * Return a name for a logical drive status value.
3307 */
3308static const char *
3309ciss_name_ldrive_status(int status)
3310{
3311    switch (status) {
3312    case CISS_LSTATUS_OK:
3313	return("OK");
3314    case CISS_LSTATUS_FAILED:
3315	return("failed");
3316    case CISS_LSTATUS_NOT_CONFIGURED:
3317	return("not configured");
3318    case CISS_LSTATUS_INTERIM_RECOVERY:
3319	return("interim recovery");
3320    case CISS_LSTATUS_READY_RECOVERY:
3321	return("ready for recovery");
3322    case CISS_LSTATUS_RECOVERING:
3323	return("recovering");
3324    case CISS_LSTATUS_WRONG_PDRIVE:
3325	return("wrong physical drive inserted");
3326    case CISS_LSTATUS_MISSING_PDRIVE:
3327	return("missing physical drive");
3328    case CISS_LSTATUS_EXPANDING:
3329	return("expanding");
3330    case CISS_LSTATUS_BECOMING_READY:
3331	return("becoming ready");
3332    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3333	return("queued for expansion");
3334    }
3335    return("unknown status");
3336}
3337
3338/************************************************************************
3339 * Return an online/offline/nonexistent value for a logical drive
3340 * status value.
3341 */
3342static int
3343ciss_decode_ldrive_status(int status)
3344{
3345    switch(status) {
3346    case CISS_LSTATUS_NOT_CONFIGURED:
3347	return(CISS_LD_NONEXISTENT);
3348
3349    case CISS_LSTATUS_OK:
3350    case CISS_LSTATUS_INTERIM_RECOVERY:
3351    case CISS_LSTATUS_READY_RECOVERY:
3352    case CISS_LSTATUS_RECOVERING:
3353    case CISS_LSTATUS_EXPANDING:
3354    case CISS_LSTATUS_QUEUED_FOR_EXPANSION:
3355	return(CISS_LD_ONLINE);
3356
3357    case CISS_LSTATUS_FAILED:
3358    case CISS_LSTATUS_WRONG_PDRIVE:
3359    case CISS_LSTATUS_MISSING_PDRIVE:
3360    case CISS_LSTATUS_BECOMING_READY:
3361    default:
3362	return(CISS_LD_OFFLINE);
3363    }
3364}
3365
3366
3367/************************************************************************
3368 * Return a name for a logical drive's organisation.
3369 */
3370static const char *
3371ciss_name_ldrive_org(int org)
3372{
3373    switch(org) {
3374    case CISS_LDRIVE_RAID0:
3375	return("RAID 0");
3376    case CISS_LDRIVE_RAID1:
3377	return("RAID 1");
3378    case CISS_LDRIVE_RAID4:
3379	return("RAID 4");
3380    case CISS_LDRIVE_RAID5:
3381	return("RAID 5");
3382    }
3383    return("unkown");
3384}
3385
3386/************************************************************************
3387 * Return a name for a command status value.
3388 */
3389static const char *
3390ciss_name_command_status(int status)
3391{
3392    switch(status) {
3393    case CISS_CMD_STATUS_SUCCESS:
3394	return("success");
3395    case CISS_CMD_STATUS_TARGET_STATUS:
3396	return("target status");
3397    case CISS_CMD_STATUS_DATA_UNDERRUN:
3398	return("data underrun");
3399    case CISS_CMD_STATUS_DATA_OVERRUN:
3400	return("data overrun");
3401    case CISS_CMD_STATUS_INVALID_COMMAND:
3402	return("invalid command");
3403    case CISS_CMD_STATUS_PROTOCOL_ERROR:
3404	return("protocol error");
3405    case CISS_CMD_STATUS_HARDWARE_ERROR:
3406	return("hardware error");
3407    case CISS_CMD_STATUS_CONNECTION_LOST:
3408	return("connection lost");
3409    case CISS_CMD_STATUS_ABORTED:
3410	return("aborted");
3411    case CISS_CMD_STATUS_ABORT_FAILED:
3412	return("abort failed");
3413    case CISS_CMD_STATUS_UNSOLICITED_ABORT:
3414	return("unsolicited abort");
3415    case CISS_CMD_STATUS_TIMEOUT:
3416	return("timeout");
3417    case CISS_CMD_STATUS_UNABORTABLE:
3418	return("unabortable");
3419    }
3420    return("unknown status");
3421}
3422
3423/************************************************************************
3424 * Handle an open on the control device.
3425 */
3426static int
3427ciss_open(dev_t dev, int flags, int fmt, d_thread_t *p)
3428{
3429    struct ciss_softc	*sc;
3430
3431    debug_called(1);
3432
3433    sc = (struct ciss_softc *)dev->si_drv1;
3434
3435    /* we might want to veto if someone already has us open */
3436
3437    sc->ciss_flags |= CISS_FLAG_CONTROL_OPEN;
3438    return(0);
3439}
3440
3441/************************************************************************
3442 * Handle the last close on the control device.
3443 */
3444static int
3445ciss_close(dev_t dev, int flags, int fmt, d_thread_t *p)
3446{
3447    struct ciss_softc	*sc;
3448
3449    debug_called(1);
3450
3451    sc = (struct ciss_softc *)dev->si_drv1;
3452
3453    sc->ciss_flags &= ~CISS_FLAG_CONTROL_OPEN;
3454    return (0);
3455}
3456
3457/********************************************************************************
3458 * Handle adapter-specific control operations.
3459 *
3460 * Note that the API here is compatible with the Linux driver, in order to
3461 * simplify the porting of Compaq's userland tools.
3462 */
3463static int
3464ciss_ioctl(dev_t dev, u_long cmd, caddr_t addr, int32_t flag, d_thread_t *p)
3465{
3466    struct ciss_softc		*sc;
3467    int				error;
3468
3469    debug_called(1);
3470
3471    sc = (struct ciss_softc *)dev->si_drv1;
3472    error = 0;
3473
3474    switch(cmd) {
3475    case CCISS_GETPCIINFO:
3476    {
3477	cciss_pci_info_struct	*pis = (cciss_pci_info_struct *)addr;
3478
3479	pis->bus = pci_get_bus(sc->ciss_dev);
3480	pis->dev_fn = pci_get_slot(sc->ciss_dev);
3481	pis->board_id = pci_get_devid(sc->ciss_dev);
3482
3483	break;
3484    }
3485
3486    case CCISS_GETINTINFO:
3487    {
3488	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
3489
3490	cis->delay = sc->ciss_cfg->interrupt_coalesce_delay;
3491	cis->count = sc->ciss_cfg->interrupt_coalesce_count;
3492
3493	break;
3494    }
3495
3496    case CCISS_SETINTINFO:
3497    {
3498	cciss_coalint_struct	*cis = (cciss_coalint_struct *)addr;
3499
3500	if ((cis->delay == 0) && (cis->count == 0)) {
3501	    error = EINVAL;
3502	    break;
3503	}
3504
3505	/*
3506	 * XXX apparently this is only safe if the controller is idle,
3507	 *     we should suspend it before doing this.
3508	 */
3509	sc->ciss_cfg->interrupt_coalesce_delay = cis->delay;
3510	sc->ciss_cfg->interrupt_coalesce_count = cis->count;
3511
3512	if (ciss_update_config(sc))
3513	    error = EIO;
3514
3515	/* XXX resume the controller here */
3516	break;
3517    }
3518
3519    case CCISS_GETNODENAME:
3520	bcopy(sc->ciss_cfg->server_name, (NodeName_type *)addr,
3521	      sizeof(NodeName_type));
3522	break;
3523
3524    case CCISS_SETNODENAME:
3525	bcopy((NodeName_type *)addr, sc->ciss_cfg->server_name,
3526	      sizeof(NodeName_type));
3527	if (ciss_update_config(sc))
3528	    error = EIO;
3529	break;
3530
3531    case CCISS_GETHEARTBEAT:
3532	*(Heartbeat_type *)addr = sc->ciss_cfg->heartbeat;
3533	break;
3534
3535    case CCISS_GETBUSTYPES:
3536	*(BusTypes_type *)addr = sc->ciss_cfg->bus_types;
3537	break;
3538
3539    case CCISS_GETFIRMVER:
3540	bcopy(sc->ciss_id->running_firmware_revision, (FirmwareVer_type *)addr,
3541	      sizeof(FirmwareVer_type));
3542	break;
3543
3544    case CCISS_GETDRIVERVER:
3545	*(DriverVer_type *)addr = CISS_DRIVER_VERSION;
3546	break;
3547
3548    case CCISS_REVALIDVOLS:
3549	/*
3550	 * This is a bit ugly; to do it "right" we really need
3551	 * to find any disks that have changed, kick CAM off them,
3552	 * then rescan only these disks.  It'd be nice if they
3553	 * a) told us which disk(s) they were going to play with,
3554	 * and b) which ones had arrived. 8(
3555	 */
3556	break;
3557
3558    case CCISS_PASSTHRU:
3559	error = ciss_user_command(sc, (IOCTL_Command_struct *)addr);
3560	break;
3561
3562    default:
3563	debug(0, "unknown ioctl 0x%lx", cmd);
3564
3565	debug(1, "CCISS_GETPCIINFO:   0x%lx", CCISS_GETPCIINFO);
3566	debug(1, "CCISS_GETINTINFO:   0x%lx", CCISS_GETINTINFO);
3567	debug(1, "CCISS_SETINTINFO:   0x%lx", CCISS_SETINTINFO);
3568	debug(1, "CCISS_GETNODENAME:  0x%lx", CCISS_GETNODENAME);
3569	debug(1, "CCISS_SETNODENAME:  0x%lx", CCISS_SETNODENAME);
3570	debug(1, "CCISS_GETHEARTBEAT: 0x%lx", CCISS_GETHEARTBEAT);
3571	debug(1, "CCISS_GETBUSTYPES:  0x%lx", CCISS_GETBUSTYPES);
3572	debug(1, "CCISS_GETFIRMVER:   0x%lx", CCISS_GETFIRMVER);
3573	debug(1, "CCISS_GETDRIVERVER: 0x%lx", CCISS_GETDRIVERVER);
3574	debug(1, "CCISS_REVALIDVOLS:  0x%lx", CCISS_REVALIDVOLS);
3575	debug(1, "CCISS_PASSTHRU:     0x%lx", CCISS_PASSTHRU);
3576
3577	error = ENOIOCTL;
3578	break;
3579    }
3580
3581    return(error);
3582}
3583