Home | History | Annotate | Line # | Download | only in usb
umass.c revision 1.32
      1 /*	$NetBSD: umass.c,v 1.32 2000/04/04 20:16:47 augustss Exp $	*/
      2 /*-
      3  * Copyright (c) 1999 MAEKAWA Masahide <bishop (at) rr.iij4u.or.jp>,
      4  *		      Nick Hibma <n_hibma (at) freebsd.org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  *     $FreeBSD: src/sys/dev/usb/umass.c,v 1.13 2000/03/26 01:39:12 n_hibma Exp $
     29  */
     30 
     31 /*
     32  * Universal Serial Bus Mass Storage Class Bulk-Only Transport
     33  * http://www.usb.org/developers/usbmassbulk_09.pdf
     34  * XXX Add URL to CBI spec in www.usb.org
     35  */
     36 
     37 /*
     38  * Ported to NetBSD by Lennart Augustsson <augustss (at) netbsd.org>.
     39  * Parts of the code written my Jason R. Thorpe <thorpej (at) shagadelic.org>.
     40  */
     41 
     42 /*
     43  * The driver handles 3 Wire Protocols
     44  * - Command/Bulk/Interrupt (CBI)
     45  * - Command/Bulk/Interrupt with Command Completion Interrupt (CBI with CCI)
     46  * - Mass Storage Bulk-Only (BBB)
     47  *   (BBB refers Bulk/Bulk/Bulk for Command/Data/Status phases)
     48  *
     49  * Over these wire protocols it handles the following command protocols
     50  * - SCSI
     51  * - UFI (floppy command set)
     52  * - 8070 (ATA/ATAPI)
     53  *
     54  * UFI and 8070i are transformed versions of the SCSI command set. The
     55  * sc->transform method is used to convert the commands into the appropriate
     56  * format (if at all necessary). For example, UFI requires all commands to be
     57  * 12 bytes in length amongst other things.
     58  *
     59  * The source code below is marked and can be split into a number of pieces
     60  * (in this order):
     61  *
     62  * - probe/attach/detach
     63  * - generic transfer routines
     64  * - BBB
     65  * - CBI
     66  * - CBI_I (in addition to functions from CBI)
     67  * - CAM (Common Access Method)
     68  * - SCSI
     69  * - UFI
     70  * - 8070i
     71  *
     72  * The protocols are implemented using a state machine, for the transfers as
     73  * well as for the resets. The state machine is contained in umass_*_state.
     74  * The state machine is started through either umass_*_transfer or
     75  * umass_*_reset.
     76  *
     77  * The reason for doing this is a) CAM performs a lot better this way and b) it
     78  * avoids using tsleep from interrupt context (for example after a failed
     79  * transfer).
     80  */
     81 
     82 /*
     83  * The SCSI related part of this driver has been derived from the
     84  * dev/ppbus/vpo.c driver, by Nicolas Souchu (nsouch (at) freebsd.org).
     85  *
     86  * The CAM layer uses so called actions which are messages sent to the host
     87  * adapter for completion. The actions come in through umass_cam_action. The
     88  * appropriate block of routines is called depending on the transport protocol
     89  * in use. When the transfer has finished, these routines call
     90  * umass_cam_cb again to complete the CAM command.
     91  */
     92 
     93 /* XXX Should we split the driver into a number of files?  umass.c,
     94  *     umass_scsi.c, umass_8070.c, umass_ufi.c, umass_bbb.c, umass_cbi.c or
     95  *     something similar?
     96  */
     97 
     98 #include "atapibus.h"
     99 
    100 #include <sys/param.h>
    101 #include <sys/systm.h>
    102 #include <sys/kernel.h>
    103 #include <sys/conf.h>
    104 #if defined(__NetBSD__) || defined(__OpenBSD__)
    105 #include <sys/buf.h>
    106 #include <sys/device.h>
    107 #include <sys/ioctl.h>
    108 #include <sys/malloc.h>
    109 #undef KASSERT
    110 #define KASSERT(cond, msg)
    111 #elif defined(__FreeBSD__)
    112 #include <sys/module.h>
    113 #include <sys/bus.h>
    114 #include <machine/clock.h>
    115 #endif
    116 
    117 #include <dev/usb/usb.h>
    118 #include <dev/usb/usbdi.h>
    119 #include <dev/usb/usbdi_util.h>
    120 #include <dev/usb/usbdevs.h>
    121 
    122 #if defined(__FreeBSD__)
    123 #include <cam/cam.h>
    124 #include <cam/cam_ccb.h>
    125 #include <cam/cam_sim.h>
    126 #include <cam/cam_xpt_sim.h>
    127 #include <cam/scsi/scsi_all.h>
    128 #include <cam/scsi/scsi_da.h>
    129 
    130 #ifdef UMASS_DO_CAM_RESCAN
    131 #include <sys/devicestat.h>
    132 #include <cam/cam_periph.h>
    133 #endif
    134 
    135 #elif defined(__NetBSD__) || defined(__OpenBSD__)
    136 #include <sys/scsiio.h>
    137 #include <dev/scsipi/scsi_all.h>
    138 #include <dev/scsipi/scsipi_all.h>
    139 #include <dev/scsipi/scsiconf.h>
    140 
    141 #include <dev/scsipi/atapiconf.h>
    142 
    143 #include <dev/scsipi/scsipi_disk.h>
    144 #include <dev/scsipi/scsi_disk.h>
    145 #include <dev/scsipi/scsi_changer.h>
    146 
    147 #include <dev/ata/atavar.h>	/* XXX */
    148 #endif
    149 
    150 #ifdef UMASS_DEBUG
    151 #define DIF(m, x)	if (umassdebug & (m)) do { x ; } while (0)
    152 #define DPRINTF(m, x)	if (umassdebug & (m)) logprintf x
    153 #define UDMASS_UPPER	0x00008000	/* upper layer */
    154 #define UDMASS_GEN	0x00010000	/* general */
    155 #define UDMASS_SCSI	0x00020000	/* scsi */
    156 #define UDMASS_UFI	0x00040000	/* ufi command set */
    157 #define UDMASS_8070	0x00080000	/* 8070i command set */
    158 #define UDMASS_USB	0x00100000	/* USB general */
    159 #define UDMASS_BBB	0x00200000	/* Bulk-Only transfers */
    160 #define UDMASS_CBI	0x00400000	/* CBI transfers */
    161 #define UDMASS_ALL	0xffff0000	/* all of the above */
    162 
    163 #define UDMASS_XFER	0x40000000	/* all transfers */
    164 #define UDMASS_CMD	0x80000000
    165 
    166 int umassdebug = 0; //UDMASS_ALL;
    167 #else
    168 #define DIF(m, x)	/* nop */
    169 #define DPRINTF(m, x)	/* nop */
    170 #endif
    171 
    172 
    173 /* Generic definitions */
    174 
    175 #define UFI_PROTO_LEN 12
    176 
    177 /* Direction for umass_*_transfer */
    178 #define DIR_NONE	0
    179 #define DIR_IN		1
    180 #define DIR_OUT		2
    181 
    182 /* The transfer speed determines the timeout value */
    183 #define UMASS_DEFAULT_TRANSFER_SPEED	150	/* in kb/s, conservative est. */
    184 #define UMASS_FLOPPY_TRANSFER_SPEED	20
    185 #define UMASS_ZIP100_TRANSFER_SPEED	650
    186 
    187 #define UMASS_SPINUP_TIME 10000	/* ms */
    188 
    189 #ifdef __FreeBSD__
    190 /* device name */
    191 #define DEVNAME		"umass"
    192 #define DEVNAME_SIM	"umass-"
    193 
    194 #define UMASS_MAX_TRANSFER_SIZE		65536
    195 
    196 /* CAM specific definitions */
    197 
    198 /* The bus id, whatever that is */
    199 #define UMASS_SCSI_BUS		0
    200 
    201 /* All USB drives are 'connected' to one SIM (SCSI controller). umass3
    202  * ends up being target 3 on that SIM. When a request for target 3
    203  * comes in we fetch the softc with devclass_get_softc(target_id).
    204  *
    205  * The SIM is the highest target number. This makes sure that umass0 corresponds
    206  * to target 0 on the USB SCSI bus.
    207  */
    208 #ifndef UMASS_DEBUG
    209 #define UMASS_SCSIID_MAX	32	/* maximum number of drives expected */
    210 #else
    211 /* while debugging avoid unnecessary clutter in the output at umass_cam_rescan
    212  * (XPT_PATH_INQ)
    213  */
    214 #define UMASS_SCSIID_MAX	3	/* maximum number of drives expected */
    215 #endif
    216 #define UMASS_SCSIID_HOST	UMASS_SCSIID_MAX
    217 #endif
    218 
    219 #define MS_TO_TICKS(ms) ((ms) * hz / 1000)
    220 
    221 
    222 /* Bulk-Only features */
    223 
    224 #define UR_BBB_RESET	0xff		/* Bulk-Only reset */
    225 #define	UR_BBB_GET_MAX_LUN	0xfe
    226 
    227 /* Command Block Wrapper */
    228 typedef struct {
    229 	uDWord		dCBWSignature;
    230 #	define CBWSIGNATURE	0x43425355
    231 	uDWord		dCBWTag;
    232 	uDWord		dCBWDataTransferLength;
    233 	uByte		bCBWFlags;
    234 #	define CBWFLAGS_OUT	0x00
    235 #	define CBWFLAGS_IN	0x80
    236 	uByte		bCBWLUN;
    237 	uByte		bCDBLength;
    238 #	define CBWCDBLENGTH	16
    239 	uByte		CBWCDB[CBWCDBLENGTH];
    240 } umass_bbb_cbw_t;
    241 #define UMASS_BBB_CBW_SIZE	31
    242 
    243 /* Command Status Wrapper */
    244 typedef struct {
    245 	uDWord		dCSWSignature;
    246 #	define CSWSIGNATURE	0x53425355
    247 	uDWord		dCSWTag;
    248 	uDWord		dCSWDataResidue;
    249 	uByte		bCSWStatus;
    250 #	define CSWSTATUS_GOOD	0x0
    251 #	define CSWSTATUS_FAILED 0x1
    252 #	define CSWSTATUS_PHASE	0x2
    253 } umass_bbb_csw_t;
    254 #define UMASS_BBB_CSW_SIZE	13
    255 
    256 /* CBI features */
    257 
    258 #define UR_CBI_ADSC	0x00
    259 
    260 typedef unsigned char umass_cbi_cbl_t[16];	/* Command block */
    261 
    262 typedef union {
    263 	struct {
    264 		unsigned char	type;
    265 		#define IDB_TYPE_CCI		0x00
    266 		unsigned char	value;
    267 		#define IDB_VALUE_PASS		0x00
    268 		#define IDB_VALUE_FAIL		0x01
    269 		#define IDB_VALUE_PHASE		0x02
    270 		#define IDB_VALUE_PERSISTENT	0x03
    271 		#define IDB_VALUE_STATUS_MASK	0x03
    272 	} common;
    273 
    274 	struct {
    275 		unsigned char	asc;
    276 		unsigned char	ascq;
    277 	} ufi;
    278 } umass_cbi_sbl_t;
    279 
    280 
    281 
    282 struct umass_softc;		/* see below */
    283 
    284 typedef void (*transfer_cb_f)	__P((struct umass_softc *sc, void *priv,
    285 				int residue, int status));
    286 #define STATUS_CMD_OK		0	/* everything ok */
    287 #define STATUS_CMD_UNKNOWN	1	/* will have to fetch sense */
    288 #define STATUS_CMD_FAILED	2	/* transfer was ok, command failed */
    289 #define STATUS_WIRE_FAILED	3	/* couldn't even get command across */
    290 
    291 typedef void (*wire_reset_f)	__P((struct umass_softc *sc, int status));
    292 typedef void (*wire_transfer_f) __P((struct umass_softc *sc, int lun,
    293 				void *cmd, int cmdlen, void *data, int datalen,
    294 				int dir, transfer_cb_f cb, void *priv));
    295 typedef void (*wire_state_f)	__P((usbd_xfer_handle xfer,
    296 				usbd_private_handle priv, usbd_status err));
    297 
    298 #if defined(__FreeBSD__)
    299 typedef int (*command_transform_f)	__P((struct umass_softc *sc,
    300 				unsigned char *cmd, int cmdlen,
    301 				unsigned char **rcmd, int *rcmdlen));
    302 #endif
    303 
    304 
    305 /* the per device structure */
    306 struct umass_softc {
    307 	USBBASEDEVICE		sc_dev;		/* base device */
    308 	usbd_device_handle	sc_udev;	/* device */
    309 
    310 	unsigned char		drive;
    311 #	define DRIVE_GENERIC		0	/* use defaults for this one */
    312 #	define ZIP_100			1	/* to be used for quirks */
    313 #	define SHUTTLE_EUSB		2
    314 
    315 	unsigned char		quirks;
    316 	/* The drive does not support Test Unit Ready. Convert to
    317 	 * Start Unit.
    318 	 * Y-E Data
    319 	 * ZIP 100
    320 	 */
    321 #	define NO_TEST_UNIT_READY	0x01
    322 	/* The drive does not reset the Unit Attention state after
    323 	 * REQUEST SENSE has been sent. The INQUIRY command does not reset
    324 	 * the UA either, and so CAM runs in circles trying to retrieve the
    325 	 * initial INQUIRY data.
    326 	 * Y-E Data
    327 	 */
    328 #	define RS_NO_CLEAR_UA		0x02	/* no REQUEST SENSE on INQUIRY*/
    329 	/* The drive does not support START_STOP.
    330 	 * Shuttle E-USB
    331 	 */
    332 #	define NO_START_STOP		0x04
    333 
    334 	unsigned int		proto;
    335 #	define PROTO_UNKNOWN	0x0000		/* unknown protocol */
    336 #	define PROTO_BBB	0x0001		/* USB wire protocol */
    337 #	define PROTO_CBI	0x0002
    338 #	define PROTO_CBI_I	0x0004
    339 #	define PROTO_WIRE	0x00ff		/* USB wire protocol mask */
    340 #	define PROTO_SCSI	0x0100		/* command protocol */
    341 #	define PROTO_8070	0x0200
    342 #	define PROTO_UFI	0x0400
    343 #	define PROTO_COMMAND	0xff00		/* command protocol mask */
    344 
    345 	usbd_interface_handle	iface;		/* Mass Storage interface */
    346 	int			ifaceno;	/* MS iface number */
    347 
    348 	u_int8_t		bulkin;		/* bulk-in Endpoint Address */
    349 	u_int8_t		bulkout;	/* bulk-out Endpoint Address */
    350 	u_int8_t		intrin;		/* intr-in Endp. (CBI) */
    351 	usbd_pipe_handle	bulkin_pipe;
    352 	usbd_pipe_handle	bulkout_pipe;
    353 	usbd_pipe_handle	intrin_pipe;
    354 
    355 	/* Reset the device in a wire protocol specific way */
    356 	wire_reset_f		reset;
    357 
    358 	/* The start of a wire transfer. It prepares the whole transfer (cmd,
    359 	 * data, and status stage) and initiates it. It is up to the state
    360 	 * machine (below) to handle the various stages and errors in these
    361 	 */
    362 	wire_transfer_f		transfer;
    363 
    364 	/* The state machine, handling the various states during a transfer */
    365 	wire_state_f		state;
    366 
    367 #if defined(__FreeBSD__)
    368 	/* The command transform function is used to conver the SCSI commands
    369 	 * into their derivatives, like UFI, ATAPI, and friends.
    370 	 */
    371 	command_transform_f	transform;	/* command transform */
    372 #endif
    373 
    374 	/* Bulk specific variables for transfers in progress */
    375 	umass_bbb_cbw_t		cbw;	/* command block wrapper */
    376 	umass_bbb_csw_t		csw;	/* command status wrapper*/
    377 	/* CBI specific variables for transfers in progress */
    378 	umass_cbi_cbl_t		cbl;	/* command block */
    379 	umass_cbi_sbl_t		sbl;	/* status block */
    380 
    381 	/* generic variables for transfers in progress */
    382 	/* ctrl transfer requests */
    383 	usb_device_request_t	request;
    384 
    385 	/* xfer handles
    386 	 * Most of our operations are initiated from interrupt context, so
    387 	 * we need to avoid using the one that is in use. We want to avoid
    388 	 * allocating them in the interrupt context as well.
    389 	 */
    390 	/* indices into array below */
    391 #	define XFER_BBB_CBW		0	/* Bulk-Only */
    392 #	define XFER_BBB_DATA		1
    393 #	define XFER_BBB_DCLEAR		2
    394 #	define XFER_BBB_CSW1		3
    395 #	define XFER_BBB_CSW2		4
    396 #	define XFER_BBB_SCLEAR		5
    397 #	define XFER_BBB_RESET1		6
    398 #	define XFER_BBB_RESET2		7
    399 #	define XFER_BBB_RESET3		8
    400 
    401 #	define XFER_CBI_CB		0	/* CBI */
    402 #	define XFER_CBI_DATA		1
    403 #	define XFER_CBI_STATUS		2
    404 #	define XFER_CBI_DCLEAR		3
    405 #	define XFER_CBI_SCLEAR		4
    406 #	define XFER_CBI_RESET1		5
    407 #	define XFER_CBI_RESET2		6
    408 #	define XFER_CBI_RESET3		7
    409 
    410 #	define XFER_NR			9	/* maximum number */
    411 
    412 	usbd_xfer_handle	transfer_xfer[XFER_NR]; /* for ctrl xfers */
    413 
    414 	void			*data_buffer;
    415 
    416 	int			transfer_dir;		/* data direction */
    417 	void			*transfer_data;		/* data buffer */
    418 	int			transfer_datalen;	/* (maximum) length */
    419 	int			transfer_actlen;	/* actual length */
    420 	transfer_cb_f		transfer_cb;		/* callback */
    421 	void			*transfer_priv;		/* for callback */
    422 	int			transfer_status;
    423 
    424 	int			transfer_state;
    425 #	define TSTATE_IDLE			0
    426 #	define TSTATE_BBB_COMMAND		1	/* CBW transfer */
    427 #	define TSTATE_BBB_DATA			2	/* Data transfer */
    428 #	define TSTATE_BBB_DCLEAR		3	/* clear endpt stall */
    429 #	define TSTATE_BBB_STATUS1		4	/* clear endpt stall */
    430 #	define TSTATE_BBB_SCLEAR		5	/* clear endpt stall */
    431 #	define TSTATE_BBB_STATUS2		6	/* CSW transfer */
    432 #	define TSTATE_BBB_RESET1		7	/* reset command */
    433 #	define TSTATE_BBB_RESET2		8	/* in clear stall */
    434 #	define TSTATE_BBB_RESET3		9	/* out clear stall */
    435 #	define TSTATE_CBI_COMMAND		10	/* command transfer */
    436 #	define TSTATE_CBI_DATA			11	/* data transfer */
    437 #	define TSTATE_CBI_STATUS		12	/* status transfer */
    438 #	define TSTATE_CBI_DCLEAR		13	/* clear ep stall */
    439 #	define TSTATE_CBI_SCLEAR		14	/* clear ep stall */
    440 #	define TSTATE_CBI_RESET1		15	/* reset command */
    441 #	define TSTATE_CBI_RESET2		16	/* in clear stall */
    442 #	define TSTATE_CBI_RESET3		17	/* out clear stall */
    443 #	define TSTATE_STATES			18	/* # of states above */
    444 
    445 
    446 	int			transfer_speed;		/* in kb/s */
    447 	int			timeout;		/* in msecs */
    448 
    449 	u_int8_t		maxlun;			/* max lun supported */
    450 
    451 #if defined(__FreeBSD__)
    452 	/* SCSI/CAM specific variables */
    453 	struct scsi_sense	cam_scsi_sense;
    454 
    455 #elif defined(__NetBSD__) || defined(__OpenBSD__)
    456 	union {
    457 		struct scsipi_link	sc_link;
    458 		struct {
    459 			struct ata_atapi_attach	sc_aa;
    460 			struct ata_drive_datas	sc_aa_drive;
    461 		} aa;
    462 	} u;
    463 	struct atapi_adapter	sc_atapi_adapter;
    464 #define sc_adapter sc_atapi_adapter._generic
    465 	int			sc_xfer_flags;
    466 	usbd_status		sc_sync_status;
    467 	struct scsipi_sense	sc_sense_cmd;
    468 
    469 	device_ptr_t		sc_child;	/* child device, for detach */
    470 	char			sc_dying;
    471 
    472 #endif
    473 };
    474 
    475 #ifdef UMASS_DEBUG
    476 char *states[TSTATE_STATES+1] = {
    477 	/* should be kept in sync with the list at transfer_state */
    478 	"Idle",
    479 	"BBB CBW",
    480 	"BBB Data",
    481 	"BBB Data bulk-in/-out clear stall",
    482 	"BBB CSW, 1st attempt",
    483 	"BBB CSW bulk-in clear stall",
    484 	"BBB CSW, 2nd attempt",
    485 	"BBB Reset",
    486 	"BBB bulk-in clear stall",
    487 	"BBB bulk-out clear stall",
    488 	"CBI Command",
    489 	"CBI Data",
    490 	"CBI Status",
    491 	"CBI Data bulk-in/-out clear stall",
    492 	"CBI Status intr-in clear stall",
    493 	"CBI Reset",
    494 	"CBI bulk-in clear stall",
    495 	"CBI bulk-out clear stall",
    496 	NULL
    497 };
    498 #endif
    499 
    500 struct cam_sim *umass_sim;	/* SCSI Interface Module */
    501 struct cam_path *umass_path;	/*   and its path */
    502 
    503 
    504 /* USB device probe/attach/detach functions */
    505 USB_DECLARE_DRIVER(umass);
    506 Static void umass_disco		__P((struct umass_softc *sc));
    507 Static int umass_match_proto	__P((struct umass_softc *sc,
    508 				usbd_interface_handle iface,
    509 				usbd_device_handle dev));
    510 Static void umass_init_shuttle	__P((struct umass_softc *sc));
    511 
    512 /* generic transfer functions */
    513 Static usbd_status umass_setup_transfer __P((struct umass_softc *sc,
    514 				usbd_pipe_handle pipe,
    515 				void *buffer, int buflen, int flags,
    516 				usbd_xfer_handle xfer));
    517 Static usbd_status umass_setup_ctrl_transfer	__P((struct umass_softc *sc,
    518 				usbd_device_handle dev,
    519 				usb_device_request_t *req,
    520 				void *buffer, int buflen, int flags,
    521 				usbd_xfer_handle xfer));
    522 Static void umass_clear_endpoint_stall	__P((struct umass_softc *sc,
    523 				u_int8_t endpt, usbd_pipe_handle pipe,
    524 				int state, usbd_xfer_handle xfer));
    525 #if 0
    526 Static void umass_reset		__P((struct umass_softc *sc,
    527 				transfer_cb_f cb, void *priv));
    528 #endif
    529 
    530 /* Bulk-Only related functions */
    531 Static void umass_bbb_reset	__P((struct umass_softc *sc, int status));
    532 Static void umass_bbb_transfer	__P((struct umass_softc *sc, int lun,
    533 				void *cmd, int cmdlen,
    534 				void *data, int datalen, int dir,
    535 				transfer_cb_f cb, void *priv));
    536 Static void umass_bbb_state	__P((usbd_xfer_handle xfer,
    537 				usbd_private_handle priv,
    538 				usbd_status err));
    539 usbd_status umass_bbb_get_max_lun __P((struct umass_softc *sc,
    540 				       u_int8_t *maxlun));
    541 
    542 
    543 /* CBI related functions */
    544 Static int umass_cbi_adsc	__P((struct umass_softc *sc, char *buffer,int buflen,
    545 				usbd_xfer_handle xfer));
    546 Static void umass_cbi_reset	__P((struct umass_softc *sc, int status));
    547 Static void umass_cbi_transfer	__P((struct umass_softc *sc, int lun,
    548 				void *cmd, int cmdlen,
    549 				void *data, int datalen, int dir,
    550 				transfer_cb_f cb, void *priv));
    551 Static void umass_cbi_state	__P((usbd_xfer_handle xfer,
    552 				usbd_private_handle priv, usbd_status err));
    553 
    554 #if defined(__FreeBSD__)
    555 /* CAM related functions */
    556 Static void umass_cam_action	__P((struct cam_sim *sim, union ccb *ccb));
    557 Static void umass_cam_poll	__P((struct cam_sim *sim));
    558 
    559 Static void umass_cam_cb	__P((struct umass_softc *sc, void *priv,
    560 				int residue, int status));
    561 Static void umass_cam_sense_cb	__P((struct umass_softc *sc, void *priv,
    562 				int residue, int status));
    563 
    564 #ifdef UMASS_DO_CAM_RESCAN
    565 Static void umass_cam_rescan	__P((struct umass_softc *sc));
    566 #endif
    567 
    568 Static int umass_cam_attach_sim __P((void));
    569 Static int umass_cam_attach	__P((struct umass_softc *sc));
    570 Static int umass_cam_detach_sim __P((void));
    571 Static int umass_cam_detach	__P((struct umass_softc *sc));
    572 
    573 #elif defined(__NetBSD__) || defined(__OpenBSD__)
    574 
    575 #define UMASS_SCSIID_HOST	0x00
    576 #define UMASS_SCSIID_DEVICE	0x01
    577 
    578 #define UMASS_MAX_TRANSFER_SIZE	MAXBSIZE
    579 
    580 struct scsipi_device umass_dev =
    581 {
    582 	NULL,			/* Use default error handler */
    583 	NULL,			/* have a queue, served by this */
    584 	NULL,			/* have no async handler */
    585 	NULL,			/* Use default 'done' routine */
    586 };
    587 
    588 Static int umass_scsipi_cmd __P((struct scsipi_xfer *xs));
    589 Static void umass_scsipi_minphys __P((struct buf *bp));
    590 Static int umass_scsipi_ioctl __P((struct scsipi_link *, u_long,
    591 				   caddr_t, int, struct proc *));
    592 Static void umass_scsipi_cb	__P((struct umass_softc *sc, void *priv,
    593 				     int residue, int status));
    594 Static void umass_scsipi_sense_cb __P((struct umass_softc *sc, void *priv,
    595 				       int residue, int status));
    596 
    597 Static int scsipiprint __P((void *aux, const char *pnp));
    598 #if NATAPIBUS > 0
    599 Static void umass_atapi_probedev __P((struct atapibus_softc *, int));
    600 #endif
    601 #endif
    602 
    603 #if defined(__FreeBSD__)
    604 /* SCSI specific functions */
    605 Static int umass_scsi_transform __P((struct umass_softc *sc,
    606 				unsigned char *cmd, int cmdlen,
    607 				unsigned char **rcmd, int *rcmdlen));
    608 
    609 /* UFI specific functions */
    610 Static int umass_ufi_transform	__P((struct umass_softc *sc,
    611 				unsigned char *cmd, int cmdlen,
    612 				unsigned char **rcmd, int *rcmdlen));
    613 
    614 /* 8070 specific functions */
    615 Static int umass_8070_transform __P((struct umass_softc *sc,
    616 				unsigned char *cmd, int cmdlen,
    617 				unsigned char **rcmd, int *rcmdlen));
    618 #endif
    619 
    620 #ifdef UMASS_DEBUG
    621 /* General debugging functions */
    622 Static void umass_bbb_dump_cbw	__P((struct umass_softc *sc,
    623 				umass_bbb_cbw_t *cbw));
    624 Static void umass_bbb_dump_csw	__P((struct umass_softc *sc,
    625 				umass_bbb_csw_t *csw));
    626 Static void umass_dump_buffer	__P((struct umass_softc *sc, u_int8_t *buffer,
    627 				int buflen, int printlen));
    628 #endif
    629 
    630 
    631 void usbd_clear_endpoint_toggle(usbd_pipe_handle pipe);	/* XXXXX */
    632 
    633 /*
    634  * USB device probe/attach/detach
    635  */
    636 
    637 /*
    638  * Match the device we are seeing with the devices supported. Fill in the
    639  * proto and drive fields in the softc accordingly.
    640  * This function is called from both probe and attach.
    641  */
    642 
    643 Static int
    644 umass_match_proto(sc, iface, dev)
    645 	struct umass_softc *sc;
    646 	usbd_interface_handle iface;
    647 	usbd_device_handle dev;
    648 {
    649 	usb_device_descriptor_t *dd;
    650 	usb_interface_descriptor_t *id;
    651 
    652 	/*
    653 	 * Fill in sc->drive and sc->proto and return a match
    654 	 * value if both are determined and 0 otherwise.
    655 	 */
    656 
    657 	sc->drive = DRIVE_GENERIC;
    658 	sc->proto = PROTO_UNKNOWN;
    659 	sc->transfer_speed = UMASS_DEFAULT_TRANSFER_SPEED;
    660 
    661 	sc->sc_udev = dev;
    662 	dd = usbd_get_device_descriptor(dev);
    663 
    664 	if (UGETW(dd->idVendor) == USB_VENDOR_SHUTTLE
    665 	    && UGETW(dd->idProduct) == USB_PRODUCT_SHUTTLE_EUSB) {
    666 		sc->drive = SHUTTLE_EUSB;
    667 #if CBI_I
    668 		sc->proto = PROTO_8070 | PROTO_CBI_I;
    669 #else
    670 		sc->proto = PROTO_8070 | PROTO_CBI;
    671 #endif
    672 		sc->quirks |= NO_TEST_UNIT_READY | NO_START_STOP;
    673 		return (UMATCH_VENDOR_PRODUCT);
    674 	}
    675 
    676 	if (UGETW(dd->idVendor) == USB_VENDOR_YEDATA
    677 	    && UGETW(dd->idProduct) == USB_PRODUCT_YEDATA_FLASHBUSTERU) {
    678 
    679 		/* Revisions < 1.28 do not handle the interrupt endpoint
    680 		 * very well.
    681 		 */
    682 		if (UGETW(dd->bcdDevice) < 0x128)
    683 			sc->proto = PROTO_UFI | PROTO_CBI;
    684 		else
    685 #if CBI_I
    686 			sc->proto = PROTO_UFI | PROTO_CBI_I;
    687 #else
    688 			sc->proto = PROTO_UFI | PROTO_CBI;
    689 #endif
    690 		/*
    691 		 * Revisions < 1.28 do not have the TEST UNIT READY command
    692 		 * Revisions == 1.28 have a broken TEST UNIT READY
    693 		 */
    694 		if (UGETW(dd->bcdDevice) <= 0x128)
    695 			sc->quirks |= NO_TEST_UNIT_READY;
    696 
    697 		sc->quirks |= RS_NO_CLEAR_UA;
    698 		sc->transfer_speed = UMASS_FLOPPY_TRANSFER_SPEED;
    699 		return (UMATCH_VENDOR_PRODUCT_REV);
    700 	}
    701 
    702 
    703 	id = usbd_get_interface_descriptor(iface);
    704 	if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
    705 		return (UMATCH_NONE);
    706 
    707 	switch (id->bInterfaceSubClass) {
    708 	case UISUBCLASS_SCSI:
    709 		sc->proto |= PROTO_SCSI;
    710 		break;
    711 	case UISUBCLASS_UFI:
    712 		sc->transfer_speed = UMASS_FLOPPY_TRANSFER_SPEED;
    713 		sc->proto |= PROTO_UFI;
    714 		break;
    715 	case UISUBCLASS_SFF8020I:
    716 	case UISUBCLASS_SFF8070I:
    717 	case UISUBCLASS_QIC157:
    718 		sc->proto |= PROTO_8070;
    719 		break;
    720 	default:
    721 		DPRINTF(UDMASS_GEN, ("%s: Unsupported command protocol %d\n",
    722 			USBDEVNAME(sc->sc_dev), id->bInterfaceSubClass));
    723 		return (UMATCH_NONE);
    724 	}
    725 
    726 	switch (id->bInterfaceProtocol) {
    727 	case UIPROTO_MASS_CBI:
    728 		sc->proto |= PROTO_CBI;
    729 		break;
    730 	case UIPROTO_MASS_CBI_I:
    731 #if CBI_I
    732 		sc->proto |= PROTO_CBI_I;
    733 #else
    734 		sc->proto |= PROTO_CBI;
    735 #endif
    736 		break;
    737 	case UIPROTO_MASS_BBB:
    738 		sc->proto |= PROTO_BBB;
    739 		break;
    740 	case UIPROTO_MASS_BBB_P:
    741 		sc->drive = ZIP_100;
    742 		sc->proto |= PROTO_BBB;
    743 		sc->transfer_speed = UMASS_ZIP100_TRANSFER_SPEED;
    744 		sc->quirks |= NO_TEST_UNIT_READY;
    745 		break;
    746 	default:
    747 		DPRINTF(UDMASS_GEN, ("%s: Unsupported wire protocol %d\n",
    748 			USBDEVNAME(sc->sc_dev), id->bInterfaceProtocol));
    749 		return (UMATCH_NONE);
    750 	}
    751 
    752 	return (UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO);
    753 }
    754 
    755 USB_MATCH(umass)
    756 {
    757 	USB_MATCH_START(umass, uaa);
    758 #if defined(__FreeBSD__)
    759 	struct umass_softc *sc = device_get_softc(self);
    760 #else if defined(__NetBSD__) || defined(__OpenBSD__)
    761 	struct umass_softc scs, *sc = &scs;
    762 	memset(sc, 0, sizeof *sc);
    763 #endif
    764 
    765 	if (uaa->iface == NULL)
    766 		return(UMATCH_NONE);
    767 
    768 	return (umass_match_proto(sc, uaa->iface, uaa->device));
    769 }
    770 
    771 USB_ATTACH(umass)
    772 {
    773 	USB_ATTACH_START(umass, sc, uaa);
    774 	usb_interface_descriptor_t *id;
    775 	usb_endpoint_descriptor_t *ed;
    776 	const char *sSubclass, *sProto;
    777 	char devinfo[1024];
    778 	int i, bno;
    779 	int err;
    780 
    781 	/*
    782 	 * the softc struct is bzero-ed in device_set_driver. We can safely
    783 	 * call umass_detach without specifically initialising the struct.
    784 	 */
    785 
    786 	usbd_devinfo(uaa->device, 0, devinfo);
    787 	USB_ATTACH_SETUP;
    788 
    789 	sc->iface = uaa->iface;
    790 	sc->ifaceno = uaa->ifaceno;
    791 
    792 	/* initialise the proto and drive values in the umass_softc (again) */
    793 	(void) umass_match_proto(sc, sc->iface, uaa->device);
    794 
    795 	/*
    796 	 * The timeout is based on the maximum expected transfer size
    797 	 * divided by the expected transfer speed.
    798 	 * We multiply by 4 to make sure a busy system doesn't make things
    799 	 * fail.
    800 	 */
    801 	sc->timeout = 4 * UMASS_MAX_TRANSFER_SIZE / sc->transfer_speed;
    802 	sc->timeout += UMASS_SPINUP_TIME;	/* allow for spinning up */
    803 
    804 	id = usbd_get_interface_descriptor(sc->iface);
    805 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
    806 
    807 	switch (id->bInterfaceSubClass) {
    808 	case UISUBCLASS_SCSI:
    809 		sSubclass = "SCSI";
    810 		break;
    811 	case UISUBCLASS_UFI:
    812 		sSubclass = "UFI";
    813 		break;
    814 	case UISUBCLASS_SFF8020I:
    815 		sSubclass = "SFF8020i";
    816 		break;
    817 	case UISUBCLASS_SFF8070I:
    818 		sSubclass = "SFF8070i";
    819 		break;
    820 	case UISUBCLASS_QIC157:
    821 		sSubclass = "QIC157";
    822 		break;
    823 	default:
    824 		sSubclass = "unknown";
    825 		break;
    826 	}
    827 	switch (id->bInterfaceProtocol) {
    828 	case UIPROTO_MASS_CBI:
    829 		sProto = "CBI";
    830 		break;
    831 	case UIPROTO_MASS_CBI_I:
    832 		sProto = "CBI-I";
    833 		break;
    834 	case UIPROTO_MASS_BBB:
    835 		sProto = "BBB";
    836 		break;
    837 	case UIPROTO_MASS_BBB_P:
    838 		sProto = "BBB-P";
    839 		break;
    840 	default:
    841 		sProto = "unknown";
    842 		break;
    843 	}
    844 	printf("%s: using %s over %s\n", USBDEVNAME(sc->sc_dev), sSubclass,
    845 	       sProto);
    846 
    847 	/*
    848 	 * In addition to the Control endpoint the following endpoints
    849 	 * are required:
    850 	 * a) bulk-in endpoint.
    851 	 * b) bulk-out endpoint.
    852 	 * and for Control/Bulk/Interrupt with CCI (CBI_I)
    853 	 * c) intr-in
    854 	 *
    855 	 * The endpoint addresses are not fixed, so we have to read them
    856 	 * from the device descriptors of the current interface.
    857 	 */
    858 	for (i = 0 ; i < id->bNumEndpoints ; i++) {
    859 		ed = usbd_interface2endpoint_descriptor(sc->iface, i);
    860 		if (!ed) {
    861 			printf("%s: could not read endpoint descriptor\n",
    862 			       USBDEVNAME(sc->sc_dev));
    863 			USB_ATTACH_ERROR_RETURN;
    864 		}
    865 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
    866 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    867 			sc->bulkin = ed->bEndpointAddress;
    868 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT
    869 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    870 			sc->bulkout = ed->bEndpointAddress;
    871 		} else if (sc->proto & PROTO_CBI_I
    872 		    && UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
    873 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_INTERRUPT) {
    874 			sc->intrin = ed->bEndpointAddress;
    875 #ifdef UMASS_DEBUG
    876 			if (UGETW(ed->wMaxPacketSize) > 2) {
    877 				DPRINTF(UDMASS_CBI, ("%s: intr size is %d\n",
    878 					USBDEVNAME(sc->sc_dev),
    879 					UGETW(ed->wMaxPacketSize)));
    880 			}
    881 #endif
    882 		}
    883 	}
    884 
    885 	/* check whether we found all the endpoints we need */
    886 	if (!sc->bulkin || !sc->bulkout
    887 	    || (sc->proto & PROTO_CBI_I && !sc->intrin) ) {
    888 		DPRINTF(UDMASS_USB, ("%s: endpoint not found %d/%d/%d\n",
    889 			USBDEVNAME(sc->sc_dev),
    890 			sc->bulkin, sc->bulkout, sc->intrin));
    891 		umass_disco(sc);
    892 		USB_ATTACH_ERROR_RETURN;
    893 	}
    894 
    895 	/*
    896 	 * Get the maximum LUN supported by the device.
    897 	 */
    898 	if ((sc->proto & PROTO_WIRE) == PROTO_BBB) {
    899 		err = umass_bbb_get_max_lun(sc, &sc->maxlun);
    900 		if (err) {
    901 			printf("%s: unable to get Max Lun: %s\n",
    902 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    903 			USB_ATTACH_ERROR_RETURN;
    904 		}
    905 	} else {
    906 		sc->maxlun = 0;
    907 	}
    908 
    909 	/* Open the bulk-in and -out pipe */
    910 	err = usbd_open_pipe(sc->iface, sc->bulkout,
    911 				USBD_EXCLUSIVE_USE, &sc->bulkout_pipe);
    912 	if (err) {
    913 		DPRINTF(UDMASS_USB, ("%s: cannot open %d-out pipe (bulk)\n",
    914 			USBDEVNAME(sc->sc_dev), sc->bulkout));
    915 		umass_disco(sc);
    916 		USB_ATTACH_ERROR_RETURN;
    917 	}
    918 	err = usbd_open_pipe(sc->iface, sc->bulkin,
    919 				USBD_EXCLUSIVE_USE, &sc->bulkin_pipe);
    920 	if (err) {
    921 		DPRINTF(UDMASS_USB, ("%s: could not open %d-in pipe (bulk)\n",
    922 			USBDEVNAME(sc->sc_dev), sc->bulkin));
    923 		umass_disco(sc);
    924 		USB_ATTACH_ERROR_RETURN;
    925 	}
    926 	/*
    927 	 * Open the intr-in pipe if the protocol is CBI with CCI.
    928 	 * Note: early versions of the Zip drive do have an interrupt pipe, but
    929 	 * this pipe is unused
    930 	 *
    931 	 * We do not open the interrupt pipe as an interrupt pipe, but as a
    932 	 * normal bulk endpoint. We send an IN transfer down the wire at the
    933 	 * appropriate time, because we know exactly when to expect data on
    934 	 * that endpoint. This saves bandwidth, but more important, makes the
    935 	 * code for handling the data on that endpoint simpler. No data
    936 	 * arriving concurrently.
    937 	 */
    938 	if (sc->proto & PROTO_CBI_I) {
    939 		err = usbd_open_pipe(sc->iface, sc->intrin,
    940 				USBD_EXCLUSIVE_USE, &sc->intrin_pipe);
    941 		if (err) {
    942 			DPRINTF(UDMASS_USB, ("%s: couldn't open %d-in (intr)\n",
    943 				USBDEVNAME(sc->sc_dev), sc->intrin));
    944 			umass_disco(sc);
    945 			USB_ATTACH_ERROR_RETURN;
    946 		}
    947 	}
    948 
    949 	/* initialisation of generic part */
    950 	sc->transfer_state = TSTATE_IDLE;
    951 
    952 	/* request a sufficient number of xfer handles */
    953 	for (i = 0; i < XFER_NR; i++) {
    954 		sc->transfer_xfer[i] = usbd_alloc_xfer(uaa->device);
    955 		if (sc->transfer_xfer[i] == 0) {
    956 			DPRINTF(UDMASS_USB, ("%s: Out of memory\n",
    957 				USBDEVNAME(sc->sc_dev)));
    958 			umass_disco(sc);
    959 			USB_ATTACH_ERROR_RETURN;
    960 		}
    961 	}
    962 	/* Allocate buffer for data transfer (it's huge). */
    963 	switch (sc->proto & PROTO_WIRE) {
    964 	case PROTO_BBB:
    965 		bno = XFER_BBB_DATA;
    966 		goto dalloc;
    967 	case PROTO_CBI:
    968 		bno = XFER_CBI_DATA;
    969 		goto dalloc;
    970 	case PROTO_CBI_I:
    971 		bno = XFER_CBI_DATA;
    972 	dalloc:
    973 		sc->data_buffer = usbd_alloc_buffer(sc->transfer_xfer[bno],
    974 						    UMASS_MAX_TRANSFER_SIZE);
    975 		if (sc->data_buffer == NULL) {
    976 			umass_disco(sc);
    977 			USB_ATTACH_ERROR_RETURN;
    978 		}
    979 		break;
    980 	default:
    981 		break;
    982 	}
    983 
    984 	/* Initialise the wire protocol specific methods */
    985 	if (sc->proto & PROTO_BBB) {
    986 		sc->reset = umass_bbb_reset;
    987 		sc->transfer = umass_bbb_transfer;
    988 		sc->state = umass_bbb_state;
    989 	} else if ((sc->proto & PROTO_CBI) || (sc->proto & PROTO_CBI_I)) {
    990 		sc->reset = umass_cbi_reset;
    991 		sc->transfer = umass_cbi_transfer;
    992 		sc->state = umass_cbi_state;
    993 #ifdef UMASS_DEBUG
    994 	} else {
    995 		panic("%s:%d: Unknown proto 0x%02x\n",
    996 		      __FILE__, __LINE__, sc->proto);
    997 #endif
    998 	}
    999 
   1000 	if (sc->drive == SHUTTLE_EUSB)
   1001 		umass_init_shuttle(sc);
   1002 
   1003 #if defined(__FreeBSD__)
   1004 	if (sc->proto & PROTO_SCSI)
   1005 		sc->transform = umass_scsi_transform;
   1006 	else if (sc->proto & PROTO_UFI)
   1007 		sc->transform = umass_ufi_transform;
   1008 	else if (sc->proto & PROTO_8070)
   1009 		sc->transform = umass_8070_transform;
   1010 #ifdef UMASS_DEBUG
   1011 	else
   1012 		panic("No transformation defined for command proto 0x%02x\n",
   1013 		      sc->proto & PROTO_COMMAND);
   1014 #endif
   1015 
   1016 	/* From here onwards the device can be used. */
   1017 
   1018 	if ((sc->proto & PROTO_SCSI) ||
   1019 	    (sc->proto & PROTO_8070) ||
   1020 	    (sc->proto & PROTO_UFI)) {
   1021 		/* Prepare the SCSI command block */
   1022 		sc->cam_scsi_sense.opcode = REQUEST_SENSE;
   1023 
   1024 		/* If this is the first device register the SIM */
   1025 		if (umass_sim == NULL) {
   1026 			err = umass_cam_attach_sim();
   1027 			if (err) {
   1028 				umass_disco(self);
   1029 				USB_ATTACH_ERROR_RETURN;
   1030 			}
   1031 		}
   1032 
   1033 		/* Attach the new device to our SCSI host controller (SIM) */
   1034 		err = umass_cam_attach(sc);
   1035 		if (err) {
   1036 			umass_disco(self);
   1037 			USB_ATTACH_ERROR_RETURN;
   1038 		}
   1039 	} else {
   1040 		panic("%s:%d: Unknown proto 0x%02x\n",
   1041 		      __FILE__, __LINE__, sc->proto);
   1042 	}
   1043 #elif defined(__NetBSD__) || defined(__OpenBSD__)
   1044 	/*
   1045 	 * Fill in the adapter.
   1046 	 */
   1047 	sc->sc_adapter.scsipi_cmd = umass_scsipi_cmd;
   1048 	sc->sc_adapter.scsipi_minphys = umass_scsipi_minphys;
   1049 	sc->sc_adapter.scsipi_ioctl = umass_scsipi_ioctl;
   1050 
   1051 	/*
   1052 	 * fill in the prototype scsipi_link.
   1053 	 */
   1054 	switch (sc->proto & PROTO_COMMAND) {
   1055 	case PROTO_SCSI:
   1056 	case PROTO_UFI:
   1057 		sc->u.sc_link.type = BUS_SCSI;
   1058 		sc->u.sc_link.scsipi_scsi.channel = SCSI_CHANNEL_ONLY_ONE;
   1059 		sc->u.sc_link.adapter_softc = sc;
   1060 		sc->u.sc_link.scsipi_scsi.adapter_target = UMASS_SCSIID_HOST;
   1061 		sc->u.sc_link.adapter = &sc->sc_adapter;
   1062 		sc->u.sc_link.device = &umass_dev;
   1063 		sc->u.sc_link.openings = 1;
   1064 		sc->u.sc_link.scsipi_scsi.max_target = UMASS_SCSIID_DEVICE;
   1065 		sc->u.sc_link.scsipi_scsi.max_lun = sc->maxlun;
   1066 
   1067 		if(sc->quirks & NO_TEST_UNIT_READY)
   1068 			sc->u.sc_link.quirks |= ADEV_NOTUR;
   1069 		break;
   1070 
   1071 #if NATAPIBUS > 0
   1072 	case PROTO_8070:
   1073 		sc->u.aa.sc_aa.aa_type = T_ATAPI;
   1074 		sc->u.aa.sc_aa.aa_channel = 0;
   1075 		sc->u.aa.sc_aa.aa_openings = 1;
   1076 		sc->u.aa.sc_aa.aa_drv_data = &sc->u.aa.sc_aa_drive;
   1077 		sc->u.aa.sc_aa.aa_bus_private = &sc->sc_atapi_adapter;
   1078 		sc->sc_atapi_adapter.atapi_probedev = umass_atapi_probedev;
   1079 		sc->sc_atapi_adapter.atapi_kill_pending = scsi_kill_pending;
   1080 		break;
   1081 #endif
   1082 
   1083 	default:
   1084 		printf("%s: proto=0x%x not supported yet\n",
   1085 		       USBDEVNAME(sc->sc_dev), sc->proto);
   1086 		umass_disco(sc);
   1087 		USB_ATTACH_ERROR_RETURN;
   1088 	}
   1089 
   1090 	sc->sc_child = config_found(&sc->sc_dev, &sc->u, scsipiprint);
   1091 	if (sc->sc_child == NULL) {
   1092 		umass_disco(sc);
   1093 		/* Not an error, just not a complete success. */
   1094 		USB_ATTACH_SUCCESS_RETURN;
   1095 	}
   1096 #endif
   1097 
   1098 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
   1099 			   USBDEV(sc->sc_dev));
   1100 
   1101 	DPRINTF(UDMASS_GEN, ("%s: Attach finished\n", USBDEVNAME(sc->sc_dev)));
   1102 
   1103 	USB_ATTACH_SUCCESS_RETURN;
   1104 }
   1105 
   1106 Static int
   1107 scsipiprint(aux, pnp)
   1108 	void *aux;
   1109 	const char *pnp;
   1110 {
   1111 	extern int atapi_print __P((void *aux, const char *pnp));
   1112 	struct scsipi_link *l = aux;
   1113 
   1114 	if (l->type == BUS_SCSI)
   1115 		return (scsiprint(aux, pnp));
   1116 	else
   1117 		return (atapi_print(aux, pnp));
   1118 }
   1119 
   1120 USB_DETACH(umass)
   1121 {
   1122 	USB_DETACH_START(umass, sc);
   1123 	int rv = 0;
   1124 
   1125 	DPRINTF(UDMASS_USB, ("%s: detached\n", USBDEVNAME(sc->sc_dev)));
   1126 
   1127 	/* Abort the pipes to wake up any waiting processes. */
   1128 	if (sc->bulkout_pipe != NULL)
   1129 		usbd_abort_pipe(sc->bulkout_pipe);
   1130 	if (sc->bulkin_pipe != NULL)
   1131 		usbd_abort_pipe(sc->bulkin_pipe);
   1132 	if (sc->intrin_pipe != NULL)
   1133 		usbd_abort_pipe(sc->intrin_pipe);
   1134 
   1135 #if 0
   1136 	/* Do we really need referebce counting?  Perhaps in ioctl() */
   1137 	s = splusb();
   1138 	if (--sc->sc_refcnt >= 0) {
   1139 		/* Wait for processes to go away. */
   1140 		usb_detach_wait(USBDEV(sc->sc_dev));
   1141 	}
   1142 	splx(s);
   1143 #endif
   1144 
   1145 #if defined(__FreeBSD__)
   1146 	if ((sc->proto & PROTO_SCSI) ||
   1147 	    (sc->proto & PROTO_8070) ||
   1148 	    (sc->proto & PROTO_UFI))
   1149 		/* detach the device from the SCSI host controller (SIM) */
   1150 		rv = umass_cam_detach(sc);
   1151 #elif defined(__NetBSD__) || defined(__OpenBSD__)
   1152 	if (sc->sc_child != NULL)
   1153 		rv = config_detach(sc->sc_child, flags);
   1154 #endif
   1155 	if (rv != 0)
   1156 		return (rv);
   1157 
   1158 	umass_disco(sc);
   1159 
   1160 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
   1161 			   USBDEV(sc->sc_dev));
   1162 
   1163 	return (0);
   1164 }
   1165 
   1166 #if defined(__NetBSD__) || defined(__OpenBSD__)
   1167 int
   1168 umass_activate(self, act)
   1169 	struct device *self;
   1170 	enum devact act;
   1171 {
   1172 	struct umass_softc *sc = (struct umass_softc *) self;
   1173 	int rv = 0;
   1174 
   1175 	DPRINTF(UDMASS_USB, ("%s: umass_activate: %d\n",
   1176 	    USBDEVNAME(sc->sc_dev), act));
   1177 
   1178 	switch (act) {
   1179 	case DVACT_ACTIVATE:
   1180 		rv = EOPNOTSUPP;
   1181 		break;
   1182 
   1183 	case DVACT_DEACTIVATE:
   1184 		if (sc->sc_child != NULL)
   1185 			break;
   1186 		rv = config_deactivate(sc->sc_child);
   1187 		DPRINTF(UDMASS_USB, ("%s: umass_activate: child "
   1188 		    "returned %d\n", USBDEVNAME(sc->sc_dev), rv));
   1189 		if (rv == 0)
   1190 			sc->sc_dying = 1;
   1191 		break;
   1192 	}
   1193 	return (rv);
   1194 }
   1195 #endif
   1196 
   1197 Static void
   1198 umass_disco(sc)
   1199 	struct umass_softc *sc;
   1200 {
   1201 	int i;
   1202 
   1203 	DPRINTF(UDMASS_GEN, ("umass_disco\n"));
   1204 
   1205 	/* Free the xfers. */
   1206 	for (i = 0; i < XFER_NR; i++)
   1207 		if (sc->transfer_xfer[i] != NULL) {
   1208 			usbd_free_xfer(sc->transfer_xfer[i]);
   1209 			sc->transfer_xfer[i] = NULL;
   1210 		}
   1211 
   1212 	/* Remove all the pipes. */
   1213 	if (sc->bulkout_pipe != NULL)
   1214 		usbd_close_pipe(sc->bulkout_pipe);
   1215 	if (sc->bulkin_pipe != NULL)
   1216 		usbd_close_pipe(sc->bulkin_pipe);
   1217 	if (sc->intrin_pipe != NULL)
   1218 		usbd_close_pipe(sc->intrin_pipe);
   1219 }
   1220 
   1221 Static void
   1222 umass_init_shuttle(struct umass_softc *sc)
   1223 {
   1224 	usb_device_request_t req;
   1225 	u_char status[2];
   1226 
   1227 	/* The Linux driver does this */
   1228 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
   1229 	req.bRequest = 1;
   1230 	USETW(req.wValue, 0);
   1231 	USETW(req.wIndex, sc->ifaceno);
   1232 	USETW(req.wLength, sizeof status);
   1233 	(void)usbd_do_request(sc->sc_udev, &req, &status);
   1234 }
   1235 
   1236 /*
   1237  * Generic functions to handle transfers
   1238  */
   1239 
   1240 Static usbd_status
   1241 umass_setup_transfer(struct umass_softc *sc, usbd_pipe_handle pipe,
   1242 			void *buffer, int buflen, int flags,
   1243 			usbd_xfer_handle xfer)
   1244 {
   1245 	usbd_status err;
   1246 
   1247 	if (sc->sc_dying)
   1248 		return (USBD_IOERROR);
   1249 
   1250 	/* Initialiase a USB transfer and then schedule it */
   1251 
   1252 	usbd_setup_xfer(xfer, pipe, (void *)sc, buffer, buflen,
   1253 	    flags | sc->sc_xfer_flags, sc->timeout, sc->state);
   1254 
   1255 	err = usbd_transfer(xfer);
   1256 	DPRINTF(UDMASS_XFER,("%s: start xfer buffer=%p buflen=%d flags=0x%x "
   1257 	    "timeout=%d\n", USBDEVNAME(sc->sc_dev),
   1258 	    buffer, buflen, flags | sc->sc_xfer_flags, sc->timeout));
   1259 	if (err && err != USBD_IN_PROGRESS) {
   1260 		DPRINTF(UDMASS_BBB, ("%s: failed to setup transfer, %s\n",
   1261 			USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
   1262 		return (err);
   1263 	}
   1264 
   1265 	return (USBD_NORMAL_COMPLETION);
   1266 }
   1267 
   1268 
   1269 Static usbd_status
   1270 umass_setup_ctrl_transfer(struct umass_softc *sc, usbd_device_handle dev,
   1271 	 usb_device_request_t *req,
   1272 	 void *buffer, int buflen, int flags,
   1273 	 usbd_xfer_handle xfer)
   1274 {
   1275 	usbd_status err;
   1276 
   1277 	if (sc->sc_dying)
   1278 		return (USBD_IOERROR);
   1279 
   1280 	/* Initialiase a USB control transfer and then schedule it */
   1281 
   1282 	usbd_setup_default_xfer(xfer, dev, (void *) sc,
   1283 	    sc->timeout, req, buffer, buflen, flags, sc->state);
   1284 
   1285 	err = usbd_transfer(xfer);
   1286 	if (err && err != USBD_IN_PROGRESS) {
   1287 		DPRINTF(UDMASS_BBB, ("%s: failed to setup ctrl transfer, %s\n",
   1288 			 USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
   1289 
   1290 		/* do not reset, as this would make us loop */
   1291 		return (err);
   1292 	}
   1293 
   1294 	return (USBD_NORMAL_COMPLETION);
   1295 }
   1296 
   1297 Static void
   1298 umass_clear_endpoint_stall(struct umass_softc *sc,
   1299 	u_int8_t endpt, usbd_pipe_handle pipe,
   1300 	int state, usbd_xfer_handle xfer)
   1301 {
   1302 	usbd_device_handle dev;
   1303 
   1304 	if (sc->sc_dying)
   1305 		return;
   1306 
   1307 	DPRINTF(UDMASS_BBB, ("%s: Clear endpoint 0x%02x stall\n",
   1308 		USBDEVNAME(sc->sc_dev), endpt));
   1309 
   1310 	usbd_interface2device_handle(sc->iface, &dev);
   1311 
   1312 	sc->transfer_state = state;
   1313 
   1314 	usbd_clear_endpoint_toggle(pipe);
   1315 
   1316 	sc->request.bmRequestType = UT_WRITE_ENDPOINT;
   1317 	sc->request.bRequest = UR_CLEAR_FEATURE;
   1318 	USETW(sc->request.wValue, UF_ENDPOINT_HALT);
   1319 	USETW(sc->request.wIndex, endpt);
   1320 	USETW(sc->request.wLength, 0);
   1321 	umass_setup_ctrl_transfer(sc, dev, &sc->request, NULL, 0, 0, xfer);
   1322 }
   1323 
   1324 #if 0
   1325 Static void
   1326 umass_reset(struct umass_softc *sc, transfer_cb_f cb, void *priv)
   1327 {
   1328 	sc->transfer_cb = cb;
   1329 	sc->transfer_priv = priv;
   1330 
   1331 	/* The reset is a forced reset, so no error (yet) */
   1332 	sc->reset(sc, STATUS_CMD_OK);
   1333 }
   1334 #endif
   1335 
   1336 /*
   1337  * Bulk protocol specific functions
   1338  */
   1339 
   1340 Static void
   1341 umass_bbb_reset(struct umass_softc *sc, int status)
   1342 {
   1343 	usbd_device_handle dev;
   1344 
   1345 	KASSERT(sc->proto & PROTO_BBB,
   1346 		("sc->proto == 0x%02x wrong for umass_bbb_reset\n", sc->proto));
   1347 
   1348 	if (sc->sc_dying)
   1349 		return;
   1350 
   1351 	/*
   1352 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
   1353 	 *
   1354 	 * For Reset Recovery the host shall issue in the following order:
   1355 	 * a) a Bulk-Only Mass Storage Reset
   1356 	 * b) a Clear Feature HALT to the Bulk-In endpoint
   1357 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
   1358 	 *
   1359 	 * This is done in 3 steps, states:
   1360 	 * TSTATE_BBB_RESET1
   1361 	 * TSTATE_BBB_RESET2
   1362 	 * TSTATE_BBB_RESET3
   1363 	 *
   1364 	 * If the reset doesn't succeed, the device should be port reset.
   1365 	 */
   1366 
   1367 	DPRINTF(UDMASS_BBB, ("%s: Bulk Reset\n",
   1368 		USBDEVNAME(sc->sc_dev)));
   1369 
   1370 	sc->transfer_state = TSTATE_BBB_RESET1;
   1371 	sc->transfer_status = status;
   1372 
   1373 	usbd_interface2device_handle(sc->iface, &dev);
   1374 
   1375 	/* reset is a class specific interface write */
   1376 	sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   1377 	sc->request.bRequest = UR_BBB_RESET;
   1378 	USETW(sc->request.wValue, 0);
   1379 	USETW(sc->request.wIndex, sc->ifaceno);
   1380 	USETW(sc->request.wLength, 0);
   1381 	umass_setup_ctrl_transfer(sc, dev, &sc->request, NULL, 0, 0,
   1382 				  sc->transfer_xfer[XFER_BBB_RESET1]);
   1383 }
   1384 
   1385 Static void
   1386 umass_bbb_transfer(struct umass_softc *sc, int lun, void *cmd, int cmdlen,
   1387 		    void *data, int datalen, int dir,
   1388 		    transfer_cb_f cb, void *priv)
   1389 {
   1390 	static int dCBWtag = 42;	/* unique for CBW of transfer */
   1391 
   1392 	DPRINTF(UDMASS_BBB,("%s: umass_bbb_transfer cmd=0x%02x\n",
   1393 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd));
   1394 
   1395 	KASSERT(sc->proto & PROTO_BBB,
   1396 		("sc->proto == 0x%02x wrong for umass_bbb_transfer\n",
   1397 		sc->proto));
   1398 
   1399 	/*
   1400 	 * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
   1401 	 * a data phase of datalen bytes from/to the device and finally a
   1402 	 * csw read phase.
   1403 	 * If the data direction was inbound a maximum of datalen bytes
   1404 	 * is stored in the buffer pointed to by data.
   1405 	 *
   1406 	 * umass_bbb_transfer initialises the transfer and lets the state
   1407 	 * machine in umass_bbb_state handle the completion. It uses the
   1408 	 * following states:
   1409 	 * TSTATE_BBB_COMMAND
   1410 	 *   -> TSTATE_BBB_DATA
   1411 	 *   -> TSTATE_BBB_STATUS
   1412 	 *   -> TSTATE_BBB_STATUS2
   1413 	 *   -> TSTATE_BBB_IDLE
   1414 	 *
   1415 	 * An error in any of those states will invoke
   1416 	 * umass_bbb_reset.
   1417 	 */
   1418 
   1419 	/* check the given arguments */
   1420 	KASSERT(datalen == 0 || data != NULL,
   1421 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
   1422 	KASSERT(cmdlen <= CBWCDBLENGTH,
   1423 		("%s: cmdlen exceeds CDB length in CBW (%d > %d)",
   1424 			USBDEVNAME(sc->sc_dev), cmdlen, CBWCDBLENGTH));
   1425 	KASSERT(dir == DIR_NONE || datalen > 0,
   1426 		("%s: datalen == 0 while direction is not NONE\n",
   1427 			USBDEVNAME(sc->sc_dev)));
   1428 	KASSERT(datalen == 0 || dir != DIR_NONE,
   1429 		("%s: direction is NONE while datalen is not zero\n",
   1430 			USBDEVNAME(sc->sc_dev)));
   1431 	KASSERT(sizeof(umass_bbb_cbw_t) == UMASS_BBB_CBW_SIZE,
   1432 		("%s: CBW struct does not have the right size (%d vs. %d)\n",
   1433 			USBDEVNAME(sc->sc_dev),
   1434 			sizeof(umass_bbb_cbw_t), UMASS_BBB_CBW_SIZE));
   1435 	KASSERT(sizeof(umass_bbb_csw_t) == UMASS_BBB_CSW_SIZE,
   1436 		("%s: CSW struct does not have the right size (%d vs. %d)\n",
   1437 			USBDEVNAME(sc->sc_dev),
   1438 			sizeof(umass_bbb_csw_t), UMASS_BBB_CSW_SIZE));
   1439 
   1440 	/*
   1441 	 * Determine the direction of the data transfer and the length.
   1442 	 *
   1443 	 * dCBWDataTransferLength (datalen) :
   1444 	 *   This field indicates the number of bytes of data that the host
   1445 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
   1446 	 *   the Direction bit) during the execution of this command. If this
   1447 	 *   field is set to 0, the device will expect that no data will be
   1448 	 *   transferred IN or OUT during this command, regardless of the value
   1449 	 *   of the Direction bit defined in dCBWFlags.
   1450 	 *
   1451 	 * dCBWFlags (dir) :
   1452 	 *   The bits of the Flags field are defined as follows:
   1453 	 *     Bits 0-6	 reserved
   1454 	 *     Bit  7	 Direction - this bit shall be ignored if the
   1455 	 *			     dCBWDataTransferLength field is zero.
   1456 	 *		 0 = data Out from host to device
   1457 	 *		 1 = data In from device to host
   1458 	 */
   1459 
   1460 	/* Fill in the Command Block Wrapper */
   1461 	USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
   1462 	USETDW(sc->cbw.dCBWTag, dCBWtag);
   1463 	dCBWtag++;	/* cannot be done in macro (it will be done 4 times) */
   1464 	USETDW(sc->cbw.dCBWDataTransferLength, datalen);
   1465 	/* DIR_NONE is treated as DIR_OUT (0x00) */
   1466 	sc->cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
   1467 	sc->cbw.bCBWLUN = lun;
   1468 	sc->cbw.bCDBLength = cmdlen;
   1469 	bcopy(cmd, sc->cbw.CBWCDB, cmdlen);
   1470 
   1471 	DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
   1472 
   1473 	/* store the details for the data transfer phase */
   1474 	sc->transfer_dir = dir;
   1475 	sc->transfer_data = data;
   1476 	sc->transfer_datalen = datalen;
   1477 	sc->transfer_actlen = 0;
   1478 	sc->transfer_cb = cb;
   1479 	sc->transfer_priv = priv;
   1480 	sc->transfer_status = STATUS_CMD_OK;
   1481 
   1482 	/* move from idle to the command state */
   1483 	sc->transfer_state = TSTATE_BBB_COMMAND;
   1484 
   1485 	/* Send the CBW from host to device via bulk-out endpoint. */
   1486 	if (umass_setup_transfer(sc, sc->bulkout_pipe,
   1487 			&sc->cbw, UMASS_BBB_CBW_SIZE, 0,
   1488 			sc->transfer_xfer[XFER_BBB_CBW])) {
   1489 		umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1490 	}
   1491 }
   1492 
   1493 
   1494 Static void
   1495 umass_bbb_state(usbd_xfer_handle xfer, usbd_private_handle priv,
   1496 		usbd_status err)
   1497 {
   1498 	struct umass_softc *sc = (struct umass_softc *) priv;
   1499 	usbd_xfer_handle next_xfer;
   1500 
   1501 	KASSERT(sc->proto & PROTO_BBB,
   1502 		("sc->proto == 0x%02x wrong for umass_bbb_state\n",sc->proto));
   1503 
   1504 	if (sc->sc_dying)
   1505 		return;
   1506 
   1507 	/*
   1508 	 * State handling for BBB transfers.
   1509 	 *
   1510 	 * The subroutine is rather long. It steps through the states given in
   1511 	 * Annex A of the Bulk-Only specification.
   1512 	 * Each state first does the error handling of the previous transfer
   1513 	 * and then prepares the next transfer.
   1514 	 * Each transfer is done asynchroneously so after the request/transfer
   1515 	 * has been submitted you will find a 'return;'.
   1516 	 */
   1517 
   1518 	DPRINTF(UDMASS_BBB, ("%s: Handling BBB state %d (%s), xfer=%p, %s\n",
   1519 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
   1520 		states[sc->transfer_state], xfer, usbd_errstr(err)));
   1521 
   1522 	switch (sc->transfer_state) {
   1523 
   1524 	/***** Bulk Transfer *****/
   1525 	case TSTATE_BBB_COMMAND:
   1526 		/* Command transport phase, error handling */
   1527 		if (err) {
   1528 			DPRINTF(UDMASS_BBB, ("%s: failed to send CBW\n",
   1529 				USBDEVNAME(sc->sc_dev)));
   1530 			/* If the device detects that the CBW is invalid, then
   1531 			 * the device may STALL both bulk endpoints and require
   1532 			 * a Bulk-Reset
   1533 			 */
   1534 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1535 			return;
   1536 		}
   1537 
   1538 		/* Data transport phase, setup transfer */
   1539 		sc->transfer_state = TSTATE_BBB_DATA;
   1540 		if (sc->transfer_dir == DIR_IN) {
   1541 			if (umass_setup_transfer(sc, sc->bulkin_pipe,
   1542 					sc->data_buffer, sc->transfer_datalen,
   1543 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
   1544 					sc->transfer_xfer[XFER_BBB_DATA]))
   1545 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1546 
   1547 			return;
   1548 		} else if (sc->transfer_dir == DIR_OUT) {
   1549 			memcpy(sc->data_buffer, sc->transfer_data,
   1550 			       sc->transfer_datalen);
   1551 			if (umass_setup_transfer(sc, sc->bulkout_pipe,
   1552 					sc->data_buffer, sc->transfer_datalen,
   1553 					USBD_NO_COPY,/* fixed length transfer */
   1554 					sc->transfer_xfer[XFER_BBB_DATA]))
   1555 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1556 
   1557 			return;
   1558 		} else {
   1559 			DPRINTF(UDMASS_BBB, ("%s: no data phase\n",
   1560 				USBDEVNAME(sc->sc_dev)));
   1561 		}
   1562 
   1563 		/* FALLTHROUGH if no data phase, err == 0 */
   1564 	case TSTATE_BBB_DATA:
   1565 		/* Command transport phase, error handling (ignored if no data
   1566 		 * phase (fallthrough from previous state)) */
   1567 		if (sc->transfer_dir != DIR_NONE) {
   1568 			/* retrieve the length of the transfer that was done */
   1569 			usbd_get_xfer_status(xfer, NULL, NULL,
   1570 					     &sc->transfer_actlen, NULL);
   1571 
   1572 			if (err) {
   1573 				DPRINTF(UDMASS_BBB, ("%s: Data-%s %db failed, "
   1574 					"%s\n", USBDEVNAME(sc->sc_dev),
   1575 					(sc->transfer_dir == DIR_IN?"in":"out"),
   1576 					sc->transfer_datalen,usbd_errstr(err)));
   1577 
   1578 				if (err == USBD_STALLED) {
   1579 					umass_clear_endpoint_stall(sc,
   1580 					  (sc->transfer_dir == DIR_IN?
   1581 					    sc->bulkin:sc->bulkout),
   1582 					  (sc->transfer_dir == DIR_IN?
   1583 					    sc->bulkin_pipe:sc->bulkout_pipe),
   1584 					  TSTATE_BBB_DCLEAR,
   1585 					  sc->transfer_xfer[XFER_BBB_DCLEAR]);
   1586 					return;
   1587 				} else {
   1588 					/* Unless the error is a pipe stall the
   1589 					 * error is fatal.
   1590 					 */
   1591 					umass_bbb_reset(sc,STATUS_WIRE_FAILED);
   1592 					return;
   1593 				}
   1594 			}
   1595 		}
   1596 
   1597 		if (sc->transfer_dir == DIR_IN)
   1598 			memcpy(sc->transfer_data, sc->data_buffer,
   1599 			       sc->transfer_actlen);
   1600 
   1601 		DIF(UDMASS_BBB, if (sc->transfer_dir == DIR_IN)
   1602 					umass_dump_buffer(sc, sc->transfer_data,
   1603 						sc->transfer_datalen, 48));
   1604 
   1605 		/* FALLTHROUGH, err == 0 (no data phase or successfull) */
   1606 	case TSTATE_BBB_DCLEAR: /* stall clear after data phase */
   1607 	case TSTATE_BBB_SCLEAR: /* stall clear after status phase */
   1608 		/* Reading of CSW after bulk stall condition in data phase
   1609 		 * (TSTATE_BBB_DATA2) or bulk-in stall condition after
   1610 		 * reading CSW (TSTATE_BBB_SCLEAR).
   1611 		 * In the case of no data phase or successfull data phase,
   1612 		 * err == 0 and the following if block is passed.
   1613 		 */
   1614 		if (err) {	/* should not occur */
   1615 			/* try the transfer below, even if clear stall failed */
   1616 			DPRINTF(UDMASS_BBB, ("%s: bulk-%s stall clear failed"
   1617 				", %s\n", USBDEVNAME(sc->sc_dev),
   1618 				(sc->transfer_dir == DIR_IN? "in":"out"),
   1619 				usbd_errstr(err)));
   1620 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1621 			return;
   1622 		}
   1623 
   1624 		/* Status transport phase, setup transfer */
   1625 		if (sc->transfer_state == TSTATE_BBB_COMMAND ||
   1626 		    sc->transfer_state == TSTATE_BBB_DATA ||
   1627 		    sc->transfer_state == TSTATE_BBB_DCLEAR) {
   1628 			/* After no data phase, successfull data phase and
   1629 			 * after clearing bulk-in/-out stall condition
   1630 			 */
   1631 			sc->transfer_state = TSTATE_BBB_STATUS1;
   1632 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW1];
   1633 		} else {
   1634 			/* After first attempt of fetching CSW */
   1635 			sc->transfer_state = TSTATE_BBB_STATUS2;
   1636 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW2];
   1637 		}
   1638 
   1639 		/* Read the Command Status Wrapper via bulk-in endpoint. */
   1640 		if (umass_setup_transfer(sc, sc->bulkin_pipe,
   1641 				&sc->csw, UMASS_BBB_CSW_SIZE, 0,
   1642 				next_xfer)) {
   1643 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1644 			return;
   1645 		}
   1646 
   1647 		return;
   1648 	case TSTATE_BBB_STATUS1:	/* first attempt */
   1649 	case TSTATE_BBB_STATUS2:	/* second attempt */
   1650 		/* Status transfer, error handling */
   1651 		if (err) {
   1652 			DPRINTF(UDMASS_BBB, ("%s: Failed to read CSW, %s%s\n",
   1653 				USBDEVNAME(sc->sc_dev), usbd_errstr(err),
   1654 				(sc->transfer_state == TSTATE_BBB_STATUS1?
   1655 					", retrying":"")));
   1656 
   1657 			/* If this was the first attempt at fetching the CSW
   1658 			 * retry it, otherwise fail.
   1659 			 */
   1660 			if (sc->transfer_state == TSTATE_BBB_STATUS1) {
   1661 				umass_clear_endpoint_stall(sc,
   1662 						sc->bulkin, sc->bulkin_pipe,
   1663 						TSTATE_BBB_SCLEAR,
   1664 						sc->transfer_xfer[XFER_BBB_SCLEAR]);
   1665 				return;
   1666 			} else {
   1667 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1668 				return;
   1669 			}
   1670 		}
   1671 
   1672 		DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
   1673 
   1674 		/* Check CSW and handle any error */
   1675 		if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
   1676 			/* Invalid CSW: Wrong signature or wrong tag might
   1677 			 * indicate that the device is confused -> reset it.
   1678 			 */
   1679 			printf("%s: Invalid CSW: sig 0x%08x should be 0x%08x\n",
   1680 				USBDEVNAME(sc->sc_dev),
   1681 				UGETDW(sc->csw.dCSWSignature),
   1682 				CSWSIGNATURE);
   1683 
   1684 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1685 			return;
   1686 		} else if (UGETDW(sc->csw.dCSWTag)
   1687 				!= UGETDW(sc->cbw.dCBWTag)) {
   1688 			printf("%s: Invalid CSW: tag %d should be %d\n",
   1689 				USBDEVNAME(sc->sc_dev),
   1690 				UGETDW(sc->csw.dCSWTag),
   1691 				UGETDW(sc->cbw.dCBWTag));
   1692 
   1693 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1694 			return;
   1695 
   1696 		/* CSW is valid here */
   1697 		} else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
   1698 			printf("%s: Invalid CSW: status %d > %d\n",
   1699 				USBDEVNAME(sc->sc_dev),
   1700 				sc->csw.bCSWStatus,
   1701 				CSWSTATUS_PHASE);
   1702 
   1703 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1704 			return;
   1705 		} else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
   1706 			printf("%s: Phase Error, residue = %d\n",
   1707 				USBDEVNAME(sc->sc_dev),
   1708 				UGETDW(sc->csw.dCSWDataResidue));
   1709 
   1710 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1711 			return;
   1712 
   1713 		} else if (sc->transfer_actlen > sc->transfer_datalen) {
   1714 			/* Buffer overrun! Don't let this go by unnoticed */
   1715 			panic("%s: transferred %d bytes instead of %d bytes\n",
   1716 				USBDEVNAME(sc->sc_dev),
   1717 				sc->transfer_actlen, sc->transfer_datalen);
   1718 		} else if (sc->transfer_datalen - sc->transfer_actlen
   1719 			   != UGETDW(sc->csw.dCSWDataResidue)) {
   1720 			DPRINTF(UDMASS_BBB, ("%s: actlen=%d != residue=%d\n",
   1721 				USBDEVNAME(sc->sc_dev),
   1722 				sc->transfer_datalen - sc->transfer_actlen,
   1723 				UGETDW(sc->csw.dCSWDataResidue)));
   1724 
   1725 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1726 			return;
   1727 
   1728 		} else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
   1729 			DPRINTF(UDMASS_BBB, ("%s: Command Failed, res = %d\n",
   1730 				USBDEVNAME(sc->sc_dev),
   1731 				UGETDW(sc->csw.dCSWDataResidue)));
   1732 
   1733 			/* SCSI command failed but transfer was succesful */
   1734 			sc->transfer_state = TSTATE_IDLE;
   1735 			sc->transfer_cb(sc, sc->transfer_priv,
   1736 					UGETDW(sc->csw.dCSWDataResidue),
   1737 					STATUS_CMD_FAILED);
   1738 
   1739 			return;
   1740 
   1741 		} else {	/* success */
   1742 			sc->transfer_state = TSTATE_IDLE;
   1743 			sc->transfer_cb(sc, sc->transfer_priv,
   1744 					UGETDW(sc->csw.dCSWDataResidue),
   1745 					STATUS_CMD_OK);
   1746 
   1747 			return;
   1748 		}
   1749 
   1750 	/***** Bulk Reset *****/
   1751 	case TSTATE_BBB_RESET1:
   1752 		if (err)
   1753 			printf("%s: BBB reset failed, %s\n",
   1754 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1755 
   1756 		umass_clear_endpoint_stall(sc,
   1757 			sc->bulkin, sc->bulkin_pipe, TSTATE_BBB_RESET2,
   1758 			sc->transfer_xfer[XFER_BBB_RESET2]);
   1759 
   1760 		return;
   1761 	case TSTATE_BBB_RESET2:
   1762 		if (err)	/* should not occur */
   1763 			printf("%s: BBB bulk-in clear stall failed, %s\n",
   1764 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1765 			/* no error recovery, otherwise we end up in a loop */
   1766 
   1767 		umass_clear_endpoint_stall(sc,
   1768 			sc->bulkout, sc->bulkout_pipe, TSTATE_BBB_RESET3,
   1769 			sc->transfer_xfer[XFER_BBB_RESET3]);
   1770 
   1771 		return;
   1772 	case TSTATE_BBB_RESET3:
   1773 		if (err)	/* should not occur */
   1774 			printf("%s: BBB bulk-out clear stall failed, %s\n",
   1775 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1776 			/* no error recovery, otherwise we end up in a loop */
   1777 
   1778 		sc->transfer_state = TSTATE_IDLE;
   1779 		if (sc->transfer_priv) {
   1780 			sc->transfer_cb(sc, sc->transfer_priv,
   1781 					sc->transfer_datalen,
   1782 					sc->transfer_status);
   1783 		}
   1784 
   1785 		return;
   1786 
   1787 	/***** Default *****/
   1788 	default:
   1789 		panic("%s: Unknown state %d\n",
   1790 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
   1791 	}
   1792 }
   1793 
   1794 /*
   1795  * Command/Bulk/Interrupt (CBI) specific functions
   1796  */
   1797 
   1798 Static int
   1799 umass_cbi_adsc(struct umass_softc *sc, char *buffer, int buflen,
   1800 	       usbd_xfer_handle xfer)
   1801 {
   1802 	usbd_device_handle dev;
   1803 
   1804 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1805 		("sc->proto == 0x%02x wrong for umass_cbi_adsc\n",sc->proto));
   1806 
   1807 	usbd_interface2device_handle(sc->iface, &dev);
   1808 
   1809 	sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   1810 	sc->request.bRequest = UR_CBI_ADSC;
   1811 	USETW(sc->request.wValue, 0);
   1812 	USETW(sc->request.wIndex, sc->ifaceno);
   1813 	USETW(sc->request.wLength, buflen);
   1814 	return umass_setup_ctrl_transfer(sc, dev, &sc->request, buffer,
   1815 					 buflen, 0, xfer);
   1816 }
   1817 
   1818 
   1819 Static void
   1820 umass_cbi_reset(struct umass_softc *sc, int status)
   1821 {
   1822 	int i;
   1823 #	define SEND_DIAGNOSTIC_CMDLEN	12
   1824 
   1825 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1826 		("sc->proto == 0x%02x wrong for umass_cbi_reset\n",sc->proto));
   1827 
   1828 	if (sc->sc_dying)
   1829 		return;
   1830 
   1831 	/*
   1832 	 * Command Block Reset Protocol
   1833 	 *
   1834 	 * First send a reset request to the device. Then clear
   1835 	 * any possibly stalled bulk endpoints.
   1836 
   1837 	 * This is done in 3 steps, states:
   1838 	 * TSTATE_CBI_RESET1
   1839 	 * TSTATE_CBI_RESET2
   1840 	 * TSTATE_CBI_RESET3
   1841 	 *
   1842 	 * If the reset doesn't succeed, the device should be port reset.
   1843 	 */
   1844 
   1845 	DPRINTF(UDMASS_CBI, ("%s: CBI Reset\n",
   1846 		USBDEVNAME(sc->sc_dev)));
   1847 
   1848 	KASSERT(sizeof(sc->cbl) >= SEND_DIAGNOSTIC_CMDLEN,
   1849 		("%s: CBL struct is too small (%d < %d)\n",
   1850 			USBDEVNAME(sc->sc_dev),
   1851 			sizeof(sc->cbl), SEND_DIAGNOSTIC_CMDLEN));
   1852 
   1853 	sc->transfer_state = TSTATE_CBI_RESET1;
   1854 	sc->transfer_status = status;
   1855 
   1856 	/* The 0x1d code is the SEND DIAGNOSTIC command. To distingiush between
   1857 	 * the two the last 10 bytes of the cbl is filled with 0xff (section
   1858 	 * 2.2 of the CBI spec).
   1859 	 */
   1860 	sc->cbl[0] = 0x1d;	/* Command Block Reset */
   1861 	sc->cbl[1] = 0x04;
   1862 	for (i = 2; i < SEND_DIAGNOSTIC_CMDLEN; i++)
   1863 		sc->cbl[i] = 0xff;
   1864 
   1865 	umass_cbi_adsc(sc, sc->cbl, SEND_DIAGNOSTIC_CMDLEN,
   1866 		       sc->transfer_xfer[XFER_CBI_RESET1]);
   1867 	/* XXX if the command fails we should reset the port on the bub */
   1868 }
   1869 
   1870 Static void
   1871 umass_cbi_transfer(struct umass_softc *sc, int lun,
   1872 		void *cmd, int cmdlen, void *data, int datalen, int dir,
   1873 		transfer_cb_f cb, void *priv)
   1874 {
   1875 	DPRINTF(UDMASS_CBI,("%s: umass_cbi_transfer cmd=0x%02x, len=%d\n",
   1876 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd, datalen));
   1877 
   1878 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1879 		("sc->proto == 0x%02x wrong for umass_cbi_transfer\n",
   1880 		sc->proto));
   1881 
   1882 	if (sc->sc_dying)
   1883 		return;
   1884 
   1885 	/*
   1886 	 * Do a CBI transfer with cmdlen bytes from cmd, possibly
   1887 	 * a data phase of datalen bytes from/to the device and finally a
   1888 	 * csw read phase.
   1889 	 * If the data direction was inbound a maximum of datalen bytes
   1890 	 * is stored in the buffer pointed to by data.
   1891 	 *
   1892 	 * umass_cbi_transfer initialises the transfer and lets the state
   1893 	 * machine in umass_cbi_state handle the completion. It uses the
   1894 	 * following states:
   1895 	 * TSTATE_CBI_COMMAND
   1896 	 *   -> XXX fill in
   1897 	 *
   1898 	 * An error in any of those states will invoke
   1899 	 * umass_cbi_reset.
   1900 	 */
   1901 
   1902 	/* check the given arguments */
   1903 	KASSERT(datalen == 0 || data != NULL,
   1904 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
   1905 	KASSERT(datalen == 0 || dir != DIR_NONE,
   1906 		("%s: direction is NONE while datalen is not zero\n",
   1907 			USBDEVNAME(sc->sc_dev)));
   1908 
   1909 	/* store the details for the data transfer phase */
   1910 	sc->transfer_dir = dir;
   1911 	sc->transfer_data = data;
   1912 	sc->transfer_datalen = datalen;
   1913 	sc->transfer_actlen = 0;
   1914 	sc->transfer_cb = cb;
   1915 	sc->transfer_priv = priv;
   1916 	sc->transfer_status = STATUS_CMD_OK;
   1917 
   1918 	/* move from idle to the command state */
   1919 	sc->transfer_state = TSTATE_CBI_COMMAND;
   1920 
   1921 	/* Send the Command Block from host to device via control endpoint. */
   1922 	if (umass_cbi_adsc(sc, cmd, cmdlen, sc->transfer_xfer[XFER_CBI_CB]))
   1923 		umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1924 }
   1925 
   1926 Static void
   1927 umass_cbi_state(usbd_xfer_handle xfer, usbd_private_handle priv,
   1928 		usbd_status err)
   1929 {
   1930 	struct umass_softc *sc = (struct umass_softc *) priv;
   1931 
   1932 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1933 		("sc->proto == 0x%02x wrong for umass_cbi_state\n", sc->proto));
   1934 
   1935 	if (sc->sc_dying)
   1936 		return;
   1937 
   1938 	/*
   1939 	 * State handling for CBI transfers.
   1940 	 */
   1941 
   1942 	DPRINTF(UDMASS_CBI, ("%s: Handling CBI state %d (%s), xfer=%p, %s\n",
   1943 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
   1944 		states[sc->transfer_state], xfer, usbd_errstr(err)));
   1945 
   1946 	switch (sc->transfer_state) {
   1947 
   1948 	/***** CBI Transfer *****/
   1949 	case TSTATE_CBI_COMMAND:
   1950 		if (err == USBD_STALLED) {
   1951 			DPRINTF(UDMASS_CBI, ("%s: Command Transport failed\n",
   1952 				USBDEVNAME(sc->sc_dev)));
   1953 			/* Status transport by control pipe (section 2.3.2.1).
   1954 			 * The command contained in the command block failed.
   1955 			 *
   1956 			 * The control pipe has already been unstalled by the
   1957 			 * USB stack.
   1958 			 * Section 2.4.3.1.1 states that the bulk in endpoints
   1959 			 * should not stalled at this point.
   1960 			 */
   1961 
   1962 			sc->transfer_state = TSTATE_IDLE;
   1963 			sc->transfer_cb(sc, sc->transfer_priv,
   1964 					sc->transfer_datalen,
   1965 					STATUS_CMD_FAILED);
   1966 
   1967 			return;
   1968 		} else if (err) {
   1969 			DPRINTF(UDMASS_CBI, ("%s: failed to send ADSC\n",
   1970 				USBDEVNAME(sc->sc_dev)));
   1971 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1972 
   1973 			return;
   1974 		}
   1975 
   1976 		sc->transfer_state = TSTATE_CBI_DATA;
   1977 		if (sc->transfer_dir == DIR_IN) {
   1978 			if (umass_setup_transfer(sc, sc->bulkin_pipe,
   1979 					sc->transfer_data, sc->transfer_datalen,
   1980 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
   1981 					sc->transfer_xfer[XFER_CBI_DATA]))
   1982 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1983 
   1984 		} else if (sc->transfer_dir == DIR_OUT) {
   1985 			memcpy(sc->data_buffer, sc->transfer_data,
   1986 			       sc->transfer_datalen);
   1987 			if (umass_setup_transfer(sc, sc->bulkout_pipe,
   1988 					sc->transfer_data, sc->transfer_datalen,
   1989 					USBD_NO_COPY,/* fixed length transfer */
   1990 					sc->transfer_xfer[XFER_CBI_DATA]))
   1991 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1992 
   1993 		} else if (sc->proto & PROTO_CBI_I) {
   1994 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
   1995 				USBDEVNAME(sc->sc_dev)));
   1996 			sc->transfer_state = TSTATE_CBI_STATUS;
   1997 			if (umass_setup_transfer(sc, sc->intrin_pipe,
   1998 					&sc->sbl, sizeof(sc->sbl),
   1999 					0,	/* fixed length transfer */
   2000 					sc->transfer_xfer[XFER_CBI_STATUS])){
   2001 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   2002 			}
   2003 		} else {
   2004 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
   2005 				USBDEVNAME(sc->sc_dev)));
   2006 			/* No command completion interrupt. Request
   2007 			 * sense data.
   2008 			 */
   2009 			sc->transfer_state = TSTATE_IDLE;
   2010 			sc->transfer_cb(sc, sc->transfer_priv,
   2011 			       0, STATUS_CMD_UNKNOWN);
   2012 		}
   2013 
   2014 		return;
   2015 
   2016 	case TSTATE_CBI_DATA:
   2017 		/* retrieve the length of the transfer that was done */
   2018 		usbd_get_xfer_status(xfer,NULL,NULL,&sc->transfer_actlen,NULL);
   2019 		DPRINTF(UDMASS_CBI, ("%s: CBI_DATA actlen=%d\n",
   2020 			USBDEVNAME(sc->sc_dev), sc->transfer_actlen));
   2021 
   2022 		if (err) {
   2023 			DPRINTF(UDMASS_CBI, ("%s: Data-%s %db failed, "
   2024 				"%s\n", USBDEVNAME(sc->sc_dev),
   2025 				(sc->transfer_dir == DIR_IN?"in":"out"),
   2026 				sc->transfer_datalen,usbd_errstr(err)));
   2027 
   2028 			if (err == USBD_STALLED) {
   2029 				umass_clear_endpoint_stall(sc,
   2030 					sc->bulkin, sc->bulkin_pipe,
   2031 					TSTATE_CBI_DCLEAR,
   2032 					sc->transfer_xfer[XFER_CBI_DCLEAR]);
   2033 			} else {
   2034 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   2035 			}
   2036 			return;
   2037 		}
   2038 
   2039 		if (sc->transfer_dir == DIR_IN)
   2040 			memcpy(sc->transfer_data, sc->data_buffer,
   2041 			       sc->transfer_actlen);
   2042 
   2043 		DIF(UDMASS_CBI, if (sc->transfer_dir == DIR_IN)
   2044 					umass_dump_buffer(sc, sc->transfer_data,
   2045 						sc->transfer_actlen, 48));
   2046 
   2047 		if (sc->proto & PROTO_CBI_I) {
   2048 			sc->transfer_state = TSTATE_CBI_STATUS;
   2049 			memset(&sc->sbl, 0, sizeof(sc->sbl));
   2050 			if (umass_setup_transfer(sc, sc->intrin_pipe,
   2051 				    &sc->sbl, sizeof(sc->sbl),
   2052 				    0,	/* fixed length transfer */
   2053 				    sc->transfer_xfer[XFER_CBI_STATUS])){
   2054 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   2055 			}
   2056 		} else {
   2057 			/* No command completion interrupt. Request
   2058 			 * sense to get status of command.
   2059 			 */
   2060 			sc->transfer_state = TSTATE_IDLE;
   2061 			sc->transfer_cb(sc, sc->transfer_priv,
   2062 				sc->transfer_datalen - sc->transfer_actlen,
   2063 				STATUS_CMD_UNKNOWN);
   2064 		}
   2065 		return;
   2066 
   2067 	case TSTATE_CBI_STATUS:
   2068 		if (err) {
   2069 			DPRINTF(UDMASS_CBI, ("%s: Status Transport failed\n",
   2070 				USBDEVNAME(sc->sc_dev)));
   2071 			/* Status transport by interrupt pipe (section 2.3.2.2).
   2072 			 */
   2073 
   2074 			if (err == USBD_STALLED) {
   2075 				umass_clear_endpoint_stall(sc,
   2076 					sc->intrin, sc->intrin_pipe,
   2077 					TSTATE_CBI_SCLEAR,
   2078 					sc->transfer_xfer[XFER_CBI_SCLEAR]);
   2079 			} else {
   2080 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   2081 			}
   2082 			return;
   2083 		}
   2084 
   2085 		/* Dissect the information in the buffer */
   2086 
   2087 		if (sc->proto & PROTO_UFI) {
   2088 			int status;
   2089 
   2090 			/* Section 3.4.3.1.3 specifies that the UFI command
   2091 			 * protocol returns an ASC and ASCQ in the interrupt
   2092 			 * data block.
   2093 			 */
   2094 
   2095 			DPRINTF(UDMASS_CBI, ("%s: UFI CCI, ASC = 0x%02x, "
   2096 				"ASCQ = 0x%02x\n",
   2097 				USBDEVNAME(sc->sc_dev),
   2098 				sc->sbl.ufi.asc, sc->sbl.ufi.ascq));
   2099 
   2100 			if (sc->sbl.ufi.asc == 0 && sc->sbl.ufi.ascq == 0)
   2101 				status = STATUS_CMD_OK;
   2102 			else
   2103 				status = STATUS_CMD_FAILED;
   2104 
   2105 			/* No sense, command successfull */
   2106 		} else {
   2107 			/* Command Interrupt Data Block */
   2108 			DPRINTF(UDMASS_CBI, ("%s: type=0x%02x, value=0x%02x\n",
   2109 				USBDEVNAME(sc->sc_dev),
   2110 				sc->sbl.common.type, sc->sbl.common.value));
   2111 
   2112 			if (sc->sbl.common.type == IDB_TYPE_CCI) {
   2113 				int err;
   2114 
   2115 				if ((sc->sbl.common.value&IDB_VALUE_STATUS_MASK)
   2116 							== IDB_VALUE_PASS) {
   2117 					err = STATUS_CMD_OK;
   2118 				} else if ((sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
   2119 							== IDB_VALUE_FAIL ||
   2120 					   (sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
   2121 						== IDB_VALUE_PERSISTENT) {
   2122 					err = STATUS_CMD_FAILED;
   2123 				} else {
   2124 					err = STATUS_WIRE_FAILED;
   2125 				}
   2126 
   2127 				sc->transfer_state = TSTATE_IDLE;
   2128 				sc->transfer_cb(sc, sc->transfer_priv,
   2129 						sc->transfer_datalen,
   2130 						err);
   2131 			}
   2132 		}
   2133 		return;
   2134 
   2135 	case TSTATE_CBI_DCLEAR:
   2136 		if (err) {	/* should not occur */
   2137 			printf("%s: CBI bulk-in/out stall clear failed, %s\n",
   2138 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   2139 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   2140 		}
   2141 
   2142 		sc->transfer_state = TSTATE_IDLE;
   2143 		sc->transfer_cb(sc, sc->transfer_priv,
   2144 				sc->transfer_datalen,
   2145 				STATUS_CMD_FAILED);
   2146 		return;
   2147 
   2148 	case TSTATE_CBI_SCLEAR:
   2149 		if (err)	/* should not occur */
   2150 			printf("%s: CBI intr-in stall clear failed, %s\n",
   2151 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   2152 
   2153 		/* Something really bad is going on. Reset the device */
   2154 		umass_cbi_reset(sc, STATUS_CMD_FAILED);
   2155 		return;
   2156 
   2157 	/***** CBI Reset *****/
   2158 	case TSTATE_CBI_RESET1:
   2159 		if (err)
   2160 			printf("%s: CBI reset failed, %s\n",
   2161 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   2162 
   2163 		umass_clear_endpoint_stall(sc,
   2164 			sc->bulkin, sc->bulkin_pipe, TSTATE_CBI_RESET2,
   2165 			sc->transfer_xfer[XFER_CBI_RESET2]);
   2166 
   2167 		return;
   2168 	case TSTATE_CBI_RESET2:
   2169 		if (err)	/* should not occur */
   2170 			printf("%s: CBI bulk-in stall clear failed, %s\n",
   2171 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   2172 			/* no error recovery, otherwise we end up in a loop */
   2173 
   2174 		umass_clear_endpoint_stall(sc,
   2175 			sc->bulkout, sc->bulkout_pipe, TSTATE_CBI_RESET3,
   2176 			sc->transfer_xfer[XFER_CBI_RESET3]);
   2177 
   2178 		return;
   2179 	case TSTATE_CBI_RESET3:
   2180 		if (err)	/* should not occur */
   2181 			printf("%s: CBI bulk-out stall clear failed, %s\n",
   2182 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   2183 			/* no error recovery, otherwise we end up in a loop */
   2184 
   2185 		sc->transfer_state = TSTATE_IDLE;
   2186 		if (sc->transfer_priv) {
   2187 			sc->transfer_cb(sc, sc->transfer_priv,
   2188 					sc->transfer_datalen,
   2189 					sc->transfer_status);
   2190 		}
   2191 
   2192 		return;
   2193 
   2194 
   2195 	/***** Default *****/
   2196 	default:
   2197 		panic("%s: Unknown state %d\n",
   2198 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
   2199 	}
   2200 }
   2201 
   2202 usbd_status
   2203 umass_bbb_get_max_lun(struct umass_softc *sc, u_int8_t *maxlun)
   2204 {
   2205 	usbd_device_handle dev;
   2206 	usb_device_request_t req;
   2207 	usbd_status err;
   2208 	usb_interface_descriptor_t *id;
   2209 
   2210 	*maxlun = 0;		/* Default to 0. */
   2211 
   2212 	DPRINTF(UDMASS_BBB, ("%s: Get Max Lun\n", USBDEVNAME(sc->sc_dev)));
   2213 
   2214 	usbd_interface2device_handle(sc->iface, &dev);
   2215 	id = usbd_get_interface_descriptor(sc->iface);
   2216 
   2217 	/* The Get Max Lun command is a class-specific request. */
   2218 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
   2219 	req.bRequest = UR_BBB_GET_MAX_LUN;
   2220 	USETW(req.wValue, 0);
   2221 	USETW(req.wIndex, id->bInterfaceNumber);
   2222 	USETW(req.wLength, 1);
   2223 
   2224 	err = usbd_do_request(dev, &req, maxlun);
   2225 	switch (err) {
   2226 	case USBD_NORMAL_COMPLETION:
   2227 		DPRINTF(UDMASS_BBB, ("%s: Max Lun %d\n",
   2228 		    USBDEVNAME(sc->sc_dev), *maxlun));
   2229 		break;
   2230 
   2231 	case USBD_STALLED:
   2232 		/*
   2233 		 * Device doesn't support Get Max Lun request.
   2234 		 */
   2235 		err = USBD_NORMAL_COMPLETION;
   2236 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun not supported\n",
   2237 		    USBDEVNAME(sc->sc_dev)));
   2238 		break;
   2239 
   2240 	case USBD_SHORT_XFER:
   2241 		/*
   2242 		 * XXX This must mean Get Max Lun is not supported, too!
   2243 		 */
   2244 		err = USBD_NORMAL_COMPLETION;
   2245 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun SHORT_XFER\n",
   2246 		    USBDEVNAME(sc->sc_dev)));
   2247 		break;
   2248 
   2249 	default:
   2250 		printf("%s: Get Max Lun failed: %s\n",
   2251 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   2252 		/* XXX Should we port_reset the device? */
   2253 		break;
   2254 	}
   2255 
   2256 	return (err);
   2257 }
   2258 
   2259 
   2260 
   2261 #if defined(__FreeBSD__)
   2262 /*
   2263  * CAM specific functions (used by SCSI, UFI, 8070)
   2264  */
   2265 
   2266 Static int
   2267 umass_cam_attach_sim()
   2268 {
   2269 	struct cam_devq *devq;		/* Per device Queue */
   2270 
   2271 	/* A HBA is attached to the CAM layer.
   2272 	 *
   2273 	 * The CAM layer will then after a while start probing for
   2274 	 * devices on the bus. The number of devices is limitted to one.
   2275 	 */
   2276 
   2277 	/* SCSI transparent command set */
   2278 
   2279 	devq = cam_simq_alloc(1 /*maximum openings*/);
   2280 	if (devq == NULL)
   2281 		return(ENOMEM);
   2282 
   2283 	umass_sim = cam_sim_alloc(umass_cam_action, umass_cam_poll, DEVNAME,
   2284 				NULL /*priv*/, 0 /*unit number*/,
   2285 				1 /*maximum device openings*/,
   2286 				0 /*maximum tagged device openings*/,
   2287 				devq);
   2288 	if (umass_sim == NULL) {
   2289 		cam_simq_free(devq);
   2290 		return(ENOMEM);
   2291 	}
   2292 
   2293 	if(xpt_bus_register(umass_sim, 0) != CAM_SUCCESS)
   2294 		return(ENOMEM);
   2295 
   2296 	if (xpt_create_path(&umass_path, NULL, cam_sim_path(umass_sim),
   2297 			    UMASS_SCSIID_HOST, 0)
   2298 	    != CAM_REQ_CMP)
   2299 		return(ENOMEM);
   2300 
   2301 	return(0);
   2302 }
   2303 
   2304 #ifdef UMASS_DO_CAM_RESCAN
   2305 /* this function is only used from umass_cam_rescan, so mention
   2306  * prototype down here.
   2307  */
   2308 Static void umass_cam_rescan_callback(struct cam_periph *periph,union ccb *ccb);
   2309 
   2310 Static void
   2311 umass_cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
   2312 {
   2313 #ifdef UMASS_DEBUG
   2314 	struct umass_softc *sc = devclass_get_softc(umass_devclass,
   2315 					       ccb->ccb_h.target_id);
   2316 
   2317 	if (ccb->ccb_h.status != CAM_REQ_CMP) {
   2318 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d: Rescan failed, 0x%04x\n",
   2319 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2320 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2321 			ccb->ccb_h.status));
   2322 	} else {
   2323 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d: Rescan succeeded, freeing resources.\n",
   2324 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2325 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
   2326 	}
   2327 #endif
   2328 
   2329 	xpt_free_path(ccb->ccb_h.path);
   2330 	free(ccb, M_USBDEV);
   2331 }
   2332 
   2333 Static void
   2334 umass_cam_rescan(struct umass_softc *sc)
   2335 {
   2336 	struct cam_path *path;
   2337 	union ccb *ccb = malloc(sizeof(union ccb), M_USBDEV, M_WAITOK);
   2338 
   2339 	memset(ccb, 0, sizeof(union ccb));
   2340 
   2341 	DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d: scanning bus for new device %d\n",
   2342 		USBDEVNAME(sc->sc_dev),	 cam_sim_path(umass_sim),
   2343 		device_get_unit(sc->sc_dev), 0,
   2344 		device_get_unit(sc->sc_dev)));
   2345 
   2346 	if (xpt_create_path(&path, xpt_periph, cam_sim_path(umass_sim),
   2347 		    device_get_unit(sc->sc_dev), 0)
   2348 	    != CAM_REQ_CMP)
   2349 		return;
   2350 
   2351 	xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
   2352 	ccb->ccb_h.func_code = XPT_SCAN_BUS;
   2353 	ccb->ccb_h.cbfcnp = umass_cam_rescan_callback;
   2354 	ccb->crcn.flags = CAM_FLAG_NONE;
   2355 	xpt_action(ccb);
   2356 
   2357 	/* The scan is in progress now. */
   2358 }
   2359 #endif
   2360 
   2361 Static int
   2362 umass_cam_attach(struct umass_softc *sc)
   2363 {
   2364 	/* SIM already attached at module load. The device is a target on the
   2365 	 * one SIM we registered: target device_get_unit(self).
   2366 	 */
   2367 
   2368 	/* The artificial limit UMASS_SCSIID_MAX is there because CAM expects
   2369 	 * a limit to the number of targets that are present on a SIM.
   2370 	 */
   2371 	if (device_get_unit(sc->sc_dev) > UMASS_SCSIID_MAX) {
   2372 		printf("%s: Increase UMASS_SCSIID_MAX (currently %d) in %s "
   2373 			"and try again.\n", USBDEVNAME(sc->sc_dev),
   2374 			UMASS_SCSIID_MAX, __FILE__);
   2375 		return(1);
   2376 	}
   2377 
   2378 #ifdef UMASS_DO_CAM_RESCAN
   2379 	if (!cold) {
   2380 		/* Notify CAM of the new device. Any failure is benign, as the
   2381 		 * user can still do it by hand (camcontrol rescan <busno>).
   2382 		 * Only do this if we are not booting, because CAM does a scan
   2383 		 * after booting has completed, when interrupts have been
   2384 		 * enabled.
   2385 		 */
   2386 		umass_cam_rescan(sc);
   2387 	}
   2388 #endif
   2389 
   2390 	return(0);	/* always succesful */
   2391 }
   2392 
   2393 /* umass_cam_detach
   2394  *	detach from the CAM layer
   2395  */
   2396 
   2397 Static int
   2398 umass_cam_detach_sim()
   2399 {
   2400 	if (umass_sim)
   2401 		return(EBUSY);	/* XXX CAM can't handle disappearing SIMs yet */
   2402 
   2403 	if (umass_path) {
   2404 		/* XXX do we need to send an asynchroneous event for the SIM?
   2405 		xpt_async(AC_LOST_DEVICE, umass_path, NULL);
   2406 		 */
   2407 		xpt_free_path(umass_path);
   2408 		umass_path = NULL;
   2409 	}
   2410 
   2411 	if (umass_sim) {
   2412 		if (xpt_bus_deregister(cam_sim_path(umass_sim)))
   2413 			cam_sim_free(umass_sim, /*free_devq*/TRUE);
   2414 		else
   2415 			return(EBUSY);
   2416 
   2417 		umass_sim = NULL;
   2418 	}
   2419 
   2420 	return(0);
   2421 }
   2422 
   2423 Static int
   2424 umass_cam_detach(struct umass_softc *sc)
   2425 {
   2426 	struct cam_path *path;
   2427 
   2428 	/* detach of sim not done until module unload */
   2429 	DPRINTF(UDMASS_SCSI, ("%s: losing CAM device entry\n",
   2430 		USBDEVNAME(sc->sc_dev)));
   2431 
   2432 	if (xpt_create_path(&path, NULL, cam_sim_path(umass_sim),
   2433 		    device_get_unit(sc->sc_dev), CAM_LUN_WILDCARD)
   2434 	    != CAM_REQ_CMP)
   2435 		return(ENOMEM);
   2436 	xpt_async(AC_LOST_DEVICE, path, NULL);
   2437 	xpt_free_path(path);
   2438 
   2439 	return(0);
   2440 }
   2441 
   2442 
   2443 
   2444 /* umass_cam_action
   2445  *	CAM requests for action come through here
   2446  */
   2447 
   2448 Static void
   2449 umass_cam_action(struct cam_sim *sim, union ccb *ccb)
   2450 {
   2451 	struct umass_softc *sc = devclass_get_softc(umass_devclass,
   2452 					       ccb->ccb_h.target_id);
   2453 
   2454 	/* The softc is still there, but marked as going away. umass_cam_detach
   2455 	 * has not yet notified CAM of the lost device however.
   2456 	 */
   2457 	if (sc && sc->sc_dying) {
   2458 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
   2459 			"Invalid target (gone)\n",
   2460 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2461 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2462 			ccb->ccb_h.func_code));
   2463 		ccb->ccb_h.status = CAM_TID_INVALID;
   2464 		xpt_done(ccb);
   2465 		return;
   2466 	}
   2467 
   2468 	/* Verify, depending on the operation to perform, that we either got a
   2469 	 * valid sc, because an existing target was referenced, or otherwise
   2470 	 * the SIM is addressed.
   2471 	 *
   2472 	 * This avoids bombing out at a printf and does give the CAM layer some
   2473 	 * sensible feedback on errors.
   2474 	 */
   2475 	switch (ccb->ccb_h.func_code) {
   2476 	case XPT_SCSI_IO:
   2477 	case XPT_RESET_DEV:
   2478 	case XPT_GET_TRAN_SETTINGS:
   2479 	case XPT_SET_TRAN_SETTINGS:
   2480 	case XPT_CALC_GEOMETRY:
   2481 		/* the opcodes requiring a target. These should never occur. */
   2482 		if (sc == NULL) {
   2483 			printf("%s:%d:%d:%d:func_code 0x%04x: "
   2484 				"Invalid target\n",
   2485 				DEVNAME_SIM, UMASS_SCSI_BUS,
   2486 				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2487 				ccb->ccb_h.func_code);
   2488 
   2489 			ccb->ccb_h.status = CAM_TID_INVALID;
   2490 			xpt_done(ccb);
   2491 			return;
   2492 		}
   2493 		break;
   2494 	case XPT_PATH_INQ:
   2495 	case XPT_NOOP:
   2496 		/* The opcodes sometimes aimed at a target (sc is valid),
   2497 		 * sometimes aimed at the SIM (sc is invalid and target is
   2498 		 * CAM_TARGET_WILDCARD)
   2499 		 */
   2500 		if (sc == NULL && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
   2501 			DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
   2502 				"Invalid target\n",
   2503 				DEVNAME_SIM, UMASS_SCSI_BUS,
   2504 				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2505 				ccb->ccb_h.func_code));
   2506 
   2507 			ccb->ccb_h.status = CAM_TID_INVALID;
   2508 			xpt_done(ccb);
   2509 			return;
   2510 		}
   2511 		break;
   2512 	default:
   2513 		/* XXX Hm, we should check the input parameters */
   2514 	}
   2515 
   2516 	/* Perform the requested action */
   2517 	switch (ccb->ccb_h.func_code) {
   2518 	case XPT_SCSI_IO:
   2519 	{
   2520 		struct ccb_scsiio *csio = &ccb->csio;	/* deref union */
   2521 		int dir;
   2522 		unsigned char *cmd;
   2523 		int cmdlen;
   2524 
   2525 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SCSI_IO: "
   2526 			"cmd: 0x%02x, flags: 0x%02x, "
   2527 			"%db cmd/%db data/%db sense\n",
   2528 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2529 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2530 			csio->cdb_io.cdb_bytes[0],
   2531 			ccb->ccb_h.flags & CAM_DIR_MASK,
   2532 			csio->cdb_len, csio->dxfer_len,
   2533 			csio->sense_len));
   2534 
   2535 		/* clear the end of the buffer to make sure we don't send out
   2536 		 * garbage.
   2537 		 */
   2538 		DIF(UDMASS_SCSI, if ((ccb->ccb_h.flags & CAM_DIR_MASK)
   2539 				     == CAM_DIR_OUT)
   2540 					umass_dump_buffer(sc, csio->data_ptr,
   2541 						csio->dxfer_len, 48));
   2542 
   2543 		if (sc->transfer_state != TSTATE_IDLE) {
   2544 			DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SCSI_IO: "
   2545 				"I/O requested while busy (state %d, %s)\n",
   2546 				USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2547 				ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2548 				sc->transfer_state,states[sc->transfer_state]));
   2549 			ccb->ccb_h.status = CAM_SCSI_BUSY;
   2550 			xpt_done(ccb);
   2551 			return;
   2552 		}
   2553 
   2554 		switch(ccb->ccb_h.flags&CAM_DIR_MASK) {
   2555 		case CAM_DIR_IN:
   2556 			dir = DIR_IN;
   2557 			break;
   2558 		case CAM_DIR_OUT:
   2559 			dir = DIR_OUT;
   2560 			break;
   2561 		default:
   2562 			dir = DIR_NONE;
   2563 		}
   2564 
   2565 		ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
   2566 		if (sc->transform(sc, csio->cdb_io.cdb_bytes, csio->cdb_len,
   2567 				  &cmd, &cmdlen)) {
   2568 			sc->transfer(sc, ccb->ccb_h.target_lun, cmd, cmdlen,
   2569 				     csio->data_ptr,
   2570 				     csio->dxfer_len, dir,
   2571 				     umass_cam_cb, (void *) ccb);
   2572 		} else {
   2573 			ccb->ccb_h.status = CAM_REQ_INVALID;
   2574 			xpt_done(ccb);
   2575 		}
   2576 
   2577 		break;
   2578 	}
   2579 	case XPT_PATH_INQ:
   2580 	{
   2581 		struct ccb_pathinq *cpi = &ccb->cpi;
   2582 
   2583 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_PATH_INQ:.\n",
   2584 			(sc == NULL? DEVNAME_SIM:USBDEVNAME(sc->sc_dev)),
   2585 			UMASS_SCSI_BUS,
   2586 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
   2587 
   2588 		/* host specific information */
   2589 		cpi->version_num = 1;
   2590 		cpi->hba_inquiry = 0;
   2591 		cpi->target_sprt = 0;
   2592 		cpi->hba_misc = 0;
   2593 		cpi->hba_eng_cnt = 0;
   2594 		cpi->max_target = UMASS_SCSIID_MAX;	/* one target */
   2595 		cpi->max_lun = 0;	/* no LUN's supported */
   2596 		cpi->initiator_id = UMASS_SCSIID_HOST;
   2597 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
   2598 		strncpy(cpi->hba_vid, "USB SCSI", HBA_IDLEN);
   2599 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
   2600 		cpi->unit_number = cam_sim_unit(sim);
   2601 		cpi->bus_id = UMASS_SCSI_BUS;
   2602 		if (sc) {
   2603 			cpi->base_transfer_speed = sc->transfer_speed;
   2604 			cpi->max_lun = sc->maxlun;
   2605 		}
   2606 
   2607 		cpi->ccb_h.status = CAM_REQ_CMP;
   2608 		xpt_done(ccb);
   2609 		break;
   2610 	}
   2611 	case XPT_RESET_DEV:
   2612 	{
   2613 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_RESET_DEV:.\n",
   2614 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2615 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
   2616 
   2617 		ccb->ccb_h.status = CAM_REQ_INPROG;
   2618 		umass_reset(sc, umass_cam_cb, (void *) ccb);
   2619 		break;
   2620 	}
   2621 	case XPT_GET_TRAN_SETTINGS:
   2622 	{
   2623 		struct ccb_trans_settings *cts = &ccb->cts;
   2624 
   2625 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_GET_TRAN_SETTINGS:.\n",
   2626 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2627 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
   2628 
   2629 		cts->valid = 0;
   2630 		cts->flags = 0;		/* no disconnection, tagging */
   2631 
   2632 		ccb->ccb_h.status = CAM_REQ_CMP;
   2633 		xpt_done(ccb);
   2634 		break;
   2635 	}
   2636 	case XPT_SET_TRAN_SETTINGS:
   2637 	{
   2638 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_SET_TRAN_SETTINGS:.\n",
   2639 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2640 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
   2641 
   2642 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
   2643 		xpt_done(ccb);
   2644 		break;
   2645 	}
   2646 	case XPT_CALC_GEOMETRY:
   2647 	{
   2648 		struct ccb_calc_geometry *ccg = &ccb->ccg;
   2649 
   2650 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_CALC_GEOMETRY: "
   2651 			"Volume size = %d\n",
   2652 			USBDEVNAME(sc->sc_dev), UMASS_SCSI_BUS,
   2653 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2654 			ccg->volume_size));
   2655 
   2656 		/* XXX We should probably ask the drive for the details
   2657 		 *     instead of cluching them up ourselves
   2658 		 */
   2659 		if (sc->drive == ZIP_100) {
   2660 			ccg->heads = 64;
   2661 			ccg->secs_per_track = 32;
   2662 			ccg->cylinders = ccg->volume_size / ccg->heads
   2663 					  / ccg->secs_per_track;
   2664 			ccb->ccb_h.status = CAM_REQ_CMP;
   2665 			break;
   2666 		} else if (sc->proto & PROTO_UFI) {
   2667 			ccg->heads = 2;
   2668 			if (ccg->volume_size == 2880)
   2669 				ccg->secs_per_track = 18;
   2670 			else
   2671 				ccg->secs_per_track = 9;
   2672 			ccg->cylinders = 80;
   2673 			break;
   2674 		} else {
   2675 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
   2676 		}
   2677 
   2678 		xpt_done(ccb);
   2679 		break;
   2680 	}
   2681 	case XPT_NOOP:
   2682 	{
   2683 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:XPT_NOOP:.\n",
   2684 			(sc == NULL? DEVNAME_SIM:USBDEVNAME(sc->sc_dev)),
   2685 			UMASS_SCSI_BUS,
   2686 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun));
   2687 
   2688 		ccb->ccb_h.status = CAM_REQ_CMP;
   2689 		xpt_done(ccb);
   2690 		break;
   2691 	}
   2692 	default:
   2693 		DPRINTF(UDMASS_SCSI, ("%s:%d:%d:%d:func_code 0x%04x: "
   2694 			"Not implemented\n",
   2695 			(sc == NULL? DEVNAME_SIM:USBDEVNAME(sc->sc_dev)),
   2696 			UMASS_SCSI_BUS,
   2697 			ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
   2698 			ccb->ccb_h.func_code));
   2699 
   2700 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
   2701 		xpt_done(ccb);
   2702 		break;
   2703 	}
   2704 }
   2705 
   2706 /* umass_cam_poll
   2707  *	all requests are handled through umass_cam_action, requests
   2708  *	are never pending. So, nothing to do here.
   2709  */
   2710 Static void
   2711 umass_cam_poll(struct cam_sim *sim)
   2712 {
   2713 #ifdef UMASS_DEBUG
   2714 	struct umass_softc *sc = (struct umass_softc *) sim->softc;
   2715 
   2716 	DPRINTF(UDMASS_SCSI, ("%s: CAM poll\n",
   2717 		USBDEVNAME(sc->sc_dev)));
   2718 #endif
   2719 
   2720 	/* nop */
   2721 }
   2722 
   2723 
   2724 /* umass_cam_cb
   2725  *	finalise a completed CAM command
   2726  */
   2727 
   2728 Static void
   2729 umass_cam_cb(struct umass_softc *sc, void *priv, int residue, int status)
   2730 {
   2731 	union ccb *ccb = (union ccb *) priv;
   2732 	struct ccb_scsiio *csio = &ccb->csio;		/* deref union */
   2733 
   2734 	csio->resid = residue;
   2735 
   2736 	switch (status) {
   2737 	case STATUS_CMD_OK:
   2738 		ccb->ccb_h.status = CAM_REQ_CMP;
   2739 		xpt_done(ccb);
   2740 		break;
   2741 
   2742 	case STATUS_CMD_UNKNOWN:
   2743 	case STATUS_CMD_FAILED:
   2744 		switch (ccb->ccb_h.func_code) {
   2745 		case XPT_SCSI_IO:
   2746 		{
   2747 			unsigned char *cmd;
   2748 			int cmdlen;
   2749 
   2750 			/* fetch sense data */
   2751 			DPRINTF(UDMASS_SCSI,("%s: Fetching %db sense data\n",
   2752 			        USBDEVNAME(sc->sc_dev),
   2753 			        sc->cam_scsi_sense.length));
   2754 
   2755 			sc->cam_scsi_sense.length = csio->sense_len;
   2756 
   2757 			if (sc->transform(sc, (char *) &sc->cam_scsi_sense,
   2758 				      sizeof(sc->cam_scsi_sense),
   2759 				      &cmd, &cmdlen)) {
   2760 				sc->transfer(sc, ccb->ccb_h.target_lun,
   2761 					     cmd, cmdlen,
   2762 					     &csio->sense_data,
   2763 					     csio->sense_len, DIR_IN,
   2764 					     umass_cam_sense_cb, (void *) ccb);
   2765 			} else {
   2766 #ifdef UMASS_DEBUG
   2767 				panic("transform(REQUEST_SENSE) failed\n");
   2768 #else
   2769 				csio->resid = sc->transfer_datalen;
   2770 				ccb->ccb_h.status = CAM_REQ_CMP_ERR;
   2771 				xpt_done(ccb);
   2772 #endif
   2773 			}
   2774 			break;
   2775 		}
   2776 		case XPT_RESET_DEV: /* Reset failed */
   2777 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
   2778 			xpt_done(ccb);
   2779 			break;
   2780 		default:
   2781 			panic("umass_cam_cb called for func_code %d\n",
   2782 			      ccb->ccb_h.func_code);
   2783 		}
   2784 		break;
   2785 
   2786 	case STATUS_WIRE_FAILED:
   2787 		/* the wire protocol failed and will have recovered
   2788 		 * (hopefully).	 We return an error to CAM and let CAM retry
   2789 		 * the command if necessary.
   2790 		 */
   2791 		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
   2792 		xpt_done(ccb);
   2793 		break;
   2794 
   2795 	default:
   2796 		panic("%s: Unknown status %d in umass_cam_cb\n",
   2797 			USBDEVNAME(sc->sc_dev), status);
   2798 	}
   2799 }
   2800 
   2801 /* Finalise a completed autosense operation
   2802  */
   2803 Static void
   2804 umass_cam_sense_cb(struct umass_softc *sc, void *priv, int residue, int status)
   2805 {
   2806 	union ccb *ccb = (union ccb *) priv;
   2807 	struct ccb_scsiio *csio = &ccb->csio;		/* deref union */
   2808 
   2809 	switch (status) {
   2810 	case STATUS_CMD_OK:
   2811 	case STATUS_CMD_UNKNOWN:
   2812 		/* Getting sense data succeeded. The length of the sense data
   2813 		 * is not returned in any way. The sense data itself contains
   2814 		 * the length of the sense data that is valid.
   2815 		 */
   2816 		if (sc->quirks & RS_NO_CLEAR_UA
   2817 		    && csio->cdb_io.cdb_bytes[0] == INQUIRY
   2818 		    && (csio->sense_data.flags & SSD_KEY)
   2819 						== SSD_KEY_UNIT_ATTENTION) {
   2820 			/* Ignore unit attention errors in the case where
   2821 			 * the Unit Attention state is not cleared on
   2822 			 * REQUEST SENSE. They will appear again at the next
   2823 			 * command.
   2824 			 */
   2825 			ccb->ccb_h.status = CAM_REQ_CMP;
   2826 		} else if ((csio->sense_data.flags & SSD_KEY)
   2827 						== SSD_KEY_NO_SENSE) {
   2828 			/* No problem after all (in the case of CBI without
   2829 			 * CCI)
   2830 			 */
   2831 			ccb->ccb_h.status = CAM_REQ_CMP;
   2832 		} else {
   2833 			ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR
   2834 					    | CAM_AUTOSNS_VALID;
   2835 			csio->scsi_status = SCSI_STATUS_CHECK_COND;
   2836 		}
   2837 		xpt_done(ccb);
   2838 		break;
   2839 
   2840 	default:
   2841 		DPRINTF(UDMASS_SCSI, ("%s: Autosense failed, status %d\n",
   2842 			USBDEVNAME(sc->sc_dev), status));
   2843 		ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
   2844 		xpt_done(ccb);
   2845 	}
   2846 }
   2847 
   2848 
   2849 Static int
   2850 umass_driver_load(module_t mod, int what, void *arg)
   2851 {
   2852 	int err;
   2853 
   2854 	switch (what) {
   2855 	case MOD_UNLOAD:
   2856 		err = umass_cam_detach_sim();
   2857 		if (err)
   2858 			return(err);
   2859 		return(usbd_driver_load(mod, what, arg));
   2860 	case MOD_LOAD:
   2861 		/* We don't attach to CAM at this point, because it will try
   2862 		 * and malloc memory for it. This is not possible when the
   2863 		 * boot loader loads umass as a module before the kernel
   2864 		 * has been bootstrapped.
   2865 		 */
   2866 	default:
   2867 		return(usbd_driver_load(mod, what, arg));
   2868 	}
   2869 }
   2870 
   2871 
   2872 
   2873 /* (even the comment is missing) */
   2874 
   2875 DRIVER_MODULE(umass, uhub, umass_driver, umass_devclass, umass_driver_load, 0);
   2876 
   2877 
   2878 /*
   2879  * SCSI specific functions
   2880  */
   2881 
   2882 Static int
   2883 umass_scsi_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
   2884 		     unsigned char **rcmd, int *rcmdlen)
   2885 {
   2886 	*rcmd = cmd;		/* trivial copy */
   2887 	*rcmdlen = cmdlen;
   2888 
   2889 	switch (cmd[0]) {
   2890 	case TEST_UNIT_READY:
   2891 		if (sc->quirks & NO_TEST_UNIT_READY) {
   2892 			DPRINTF(UDMASS_SCSI, ("%s: Converted TEST_UNIT_READY "
   2893 				"to START_UNIT\n", USBDEVNAME(sc->sc_dev)));
   2894 			cmd[0] = START_STOP_UNIT;
   2895 			cmd[4] = SSS_START;
   2896 		}
   2897 		break;
   2898 	}
   2899 
   2900 	return 1;		/* success */
   2901 }
   2902 
   2903 /*
   2904  * UFI specific functions
   2905  */
   2906 
   2907 Static int
   2908 umass_ufi_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
   2909 		    unsigned char **rcmd, int *rcmdlen)
   2910 {
   2911 	*rcmd = cmd;
   2912 	/* A UFI command is always 12 bytes in length */
   2913 	/* XXX cmd[(cmdlen+1)..12] contains garbage */
   2914 	*rcmdlen = 12;
   2915 
   2916 	switch (cmd[0]) {
   2917 	case TEST_UNIT_READY:
   2918 		if (sc->quirks &  NO_TEST_UNIT_READY) {
   2919 			DPRINTF(UDMASS_UFI, ("%s: Converted TEST_UNIT_READY "
   2920 				"to START_UNIT\n", USBDEVNAME(sc->sc_dev)));
   2921 			cmd[0] = START_STOP_UNIT;
   2922 			cmd[4] = SSS_START;
   2923 		}
   2924 		return 1;
   2925 	case INQUIRY:
   2926 	case START_STOP_UNIT:
   2927 	case MODE_SENSE:
   2928 	case PREVENT_ALLOW:
   2929 	case READ_10:
   2930 	case READ_12:
   2931 	case READ_CAPACITY:
   2932 	case REQUEST_SENSE:
   2933 	case REZERO_UNIT:
   2934 	case POSITION_TO_ELEMENT:	/* SEEK_10 */
   2935 	case SEND_DIAGNOSTIC:
   2936 	case WRITE_10:
   2937 	case WRITE_12:
   2938 	/* FORMAT_UNIT */
   2939 	/* MODE_SELECT */
   2940 	/* READ_FORMAT_CAPACITY */
   2941 	/* VERIFY */
   2942 	/* WRITE_AND_VERIFY */
   2943 		return 1;	/* success */
   2944 	default:
   2945 		return 0;	/* success */
   2946 	}
   2947 }
   2948 
   2949 /*
   2950  * 8070 specific functions
   2951  */
   2952 Static int
   2953 umass_8070_transform(struct umass_softc *sc, unsigned char *cmd, int cmdlen,
   2954 		     unsigned char **rcmd, int *rcmdlen)
   2955 {
   2956 	return 0;	/* failure */
   2957 }
   2958 
   2959 #endif /* __FreeBSD__ */
   2960 
   2961 
   2962 #ifdef UMASS_DEBUG
   2963 Static void
   2964 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
   2965 {
   2966 	int clen = cbw->bCDBLength;
   2967 	int dlen = UGETDW(cbw->dCBWDataTransferLength);
   2968 	u_int8_t *c = cbw->CBWCDB;
   2969 	int tag = UGETDW(cbw->dCBWTag);
   2970 	int flags = cbw->bCBWFlags;
   2971 
   2972 	DPRINTF(UDMASS_BBB, ("%s: CBW %d: cmd = %db "
   2973 		"(0x%02x%02x%02x%02x%02x%02x%s), "
   2974 		"data = %d bytes, dir = %s\n",
   2975 		USBDEVNAME(sc->sc_dev), tag, clen,
   2976 		c[0], c[1], c[2], c[3], c[4], c[5], (clen > 6? "...":""),
   2977 		dlen, (flags == CBWFLAGS_IN? "in":
   2978 		       (flags == CBWFLAGS_OUT? "out":"<invalid>"))));
   2979 }
   2980 
   2981 Static void
   2982 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
   2983 {
   2984 	int sig = UGETDW(csw->dCSWSignature);
   2985 	int tag = UGETW(csw->dCSWTag);
   2986 	int res = UGETDW(csw->dCSWDataResidue);
   2987 	int status = csw->bCSWStatus;
   2988 
   2989 	DPRINTF(UDMASS_BBB, ("%s: CSW %d: sig = 0x%08x (%s), tag = %d, "
   2990 		"res = %d, status = 0x%02x (%s)\n", USBDEVNAME(sc->sc_dev),
   2991 		tag, sig, (sig == CSWSIGNATURE?	 "valid":"invalid"),
   2992 		tag, res,
   2993 		status, (status == CSWSTATUS_GOOD? "good":
   2994 			 (status == CSWSTATUS_FAILED? "failed":
   2995 			  (status == CSWSTATUS_PHASE? "phase":"<invalid>")))));
   2996 }
   2997 
   2998 Static void
   2999 umass_dump_buffer(struct umass_softc *sc, u_int8_t *buffer, int buflen,
   3000 		  int printlen)
   3001 {
   3002 	int i, j;
   3003 	char s1[40];
   3004 	char s2[40];
   3005 	char s3[5];
   3006 
   3007 	s1[0] = '\0';
   3008 	s3[0] = '\0';
   3009 
   3010 	sprintf(s2, " buffer=%p, buflen=%d", buffer, buflen);
   3011 	for (i = 0; i < buflen && i < printlen; i++) {
   3012 		j = i % 16;
   3013 		if (j == 0 && i != 0) {
   3014 			DPRINTF(UDMASS_GEN, ("%s: 0x %s%s\n",
   3015 				USBDEVNAME(sc->sc_dev), s1, s2));
   3016 			s2[0] = '\0';
   3017 		}
   3018 		sprintf(&s1[j*2], "%02x", buffer[i] & 0xff);
   3019 	}
   3020 	if (buflen > printlen)
   3021 		sprintf(s3, " ...");
   3022 	DPRINTF(UDMASS_GEN, ("%s: 0x %s%s%s\n",
   3023 		USBDEVNAME(sc->sc_dev), s1, s2, s3));
   3024 }
   3025 #endif
   3026 
   3027 
   3028 
   3029 
   3030 
   3031 
   3032 
   3033 
   3034 #if defined(__NetBSD__) || defined(__OpenBSD__)
   3035 Static int
   3036 umass_scsipi_cmd(xs)
   3037 	struct scsipi_xfer *xs;
   3038 {
   3039 	struct scsipi_link *sc_link = xs->sc_link;
   3040 	struct umass_softc *sc = sc_link->adapter_softc;
   3041 	int cmdlen;
   3042 	int dir;
   3043 
   3044 	DIF(UDMASS_UPPER, sc_link->flags |= DEBUGLEVEL);
   3045 
   3046 	DPRINTF(UDMASS_CMD, ("%s: umass_scsi_cmd:  %d:%d xs=%p cmd=0x%02x "
   3047 	    "(quirks=0x%x, poll=%d)\n", USBDEVNAME(sc->sc_dev),
   3048 	    sc_link->scsipi_scsi.target, sc_link->scsipi_scsi.lun,
   3049 	    xs, xs->cmd->opcode, sc_link->quirks,
   3050 	    xs->xs_control & XS_CTL_POLL));
   3051 #if defined(USB_DEBUG) && defined(SCSIDEBUG)
   3052 	if (umassdebug & UDMASS_SCSI)
   3053 		show_scsipi_xs(xs);
   3054 	else if (umassdebug & ~UDMASS_CMD)
   3055 		show_scsipi_cmd(xs);
   3056 #endif
   3057 
   3058 	if (sc->sc_dying) {
   3059 		xs->error = XS_DRIVER_STUFFUP;
   3060 		goto done;
   3061 	}
   3062 
   3063 #ifdef UMASS_DEBUG
   3064 	if ((sc_link->type == BUS_ATAPI ?
   3065 	     sc_link->scsipi_atapi.drive : sc_link->scsipi_scsi.target)
   3066 	    != UMASS_SCSIID_DEVICE) {
   3067 		DPRINTF(UDMASS_SCSI, ("%s: wrong SCSI ID %d\n",
   3068 		    USBDEVNAME(sc->sc_dev),
   3069 		    sc_link->scsipi_scsi.target));
   3070 		xs->error = XS_DRIVER_STUFFUP;
   3071 		goto done;
   3072 	}
   3073 #endif
   3074 
   3075 	if (xs->cmd->opcode == SCSI_MODE_SENSE &&
   3076 	    (sc_link->quirks & SDEV_NOMODESENSE)) {
   3077 		/*printf("%s: SCSI_MODE_SENSE\n", USBDEVNAME(sc->sc_dev));*/
   3078 		xs->error = XS_TIMEOUT;
   3079 		goto done;
   3080 	}
   3081 
   3082 	if (xs->cmd->opcode == START_STOP &&
   3083 	    (sc->quirks & NO_START_STOP)) {
   3084 		/*printf("%s: START_STOP\n", USBDEVNAME(sc->sc_dev));*/
   3085 		xs->error = XS_NOERROR;
   3086 		goto done;
   3087 	}
   3088 
   3089 	dir = DIR_NONE;
   3090 	if (xs->datalen) {
   3091 		switch (xs->xs_control & (XS_CTL_DATA_IN | XS_CTL_DATA_OUT)) {
   3092 		case XS_CTL_DATA_IN:
   3093 			dir = DIR_IN;
   3094 			break;
   3095 		case XS_CTL_DATA_OUT:
   3096 			dir = DIR_OUT;
   3097 			break;
   3098 		}
   3099 	}
   3100 
   3101 	if (xs->datalen > UMASS_MAX_TRANSFER_SIZE) {
   3102 		printf("umass_cmd: large datalen, %d\n", xs->datalen);
   3103 		xs->error = XS_DRIVER_STUFFUP;
   3104 		goto done;
   3105 	}
   3106 
   3107 	cmdlen = xs->cmdlen;
   3108 	/* All UFI commands are 12 bytes.  We'll get a few garbage bytes by extending... */
   3109 	if (sc->proto & PROTO_UFI)
   3110 		cmdlen = UFI_PROTO_LEN;
   3111 
   3112 	if (xs->xs_control & XS_CTL_POLL) {
   3113 		/* Use sync transfer. XXX Broken! */
   3114 		DPRINTF(UDMASS_SCSI, ("umass_scsi_cmd: sync dir=%d\n", dir));
   3115 		sc->sc_xfer_flags = USBD_SYNCHRONOUS;
   3116 		sc->sc_sync_status = USBD_INVAL;
   3117 		sc->transfer(sc, sc_link->scsipi_scsi.lun, xs->cmd, cmdlen,
   3118 			     xs->data, xs->datalen, dir, 0, xs);
   3119 		sc->sc_xfer_flags = 0;
   3120 		DPRINTF(UDMASS_SCSI, ("umass_scsi_cmd: done err=%d\n",
   3121 				      sc->sc_sync_status));
   3122 		switch (sc->sc_sync_status) {
   3123 		case USBD_NORMAL_COMPLETION:
   3124 			xs->error = XS_NOERROR;
   3125 			break;
   3126 		case USBD_TIMEOUT:
   3127 			xs->error = XS_TIMEOUT;
   3128 			break;
   3129 		default:
   3130 			xs->error = XS_DRIVER_STUFFUP;
   3131 			break;
   3132 		}
   3133 		goto done;
   3134 	} else {
   3135 		DPRINTF(UDMASS_SCSI, ("umass_scsi_cmd: async dir=%d, cmdlen=%d"
   3136 				      " datalen=%d\n",
   3137 				      dir, cmdlen, xs->datalen));
   3138 		sc->transfer(sc, sc_link->scsipi_scsi.lun, xs->cmd, cmdlen,
   3139 		    xs->data, xs->datalen, dir, umass_scsipi_cb, xs);
   3140 		return (SUCCESSFULLY_QUEUED);
   3141 	}
   3142 
   3143 	/* Return if command finishes early. */
   3144  done:
   3145 	xs->xs_status |= XS_STS_DONE;
   3146 	scsipi_done(xs);
   3147 	if (xs->xs_control & XS_CTL_POLL)
   3148 		return (COMPLETE);
   3149 	else
   3150 		return (SUCCESSFULLY_QUEUED);
   3151 }
   3152 
   3153 Static void
   3154 umass_scsipi_minphys(bp)
   3155 	struct buf *bp;
   3156 {
   3157 	if (bp->b_bcount > UMASS_MAX_TRANSFER_SIZE)
   3158 		bp->b_bcount = UMASS_MAX_TRANSFER_SIZE;
   3159 	minphys(bp);
   3160 }
   3161 
   3162 int
   3163 umass_scsipi_ioctl(link, cmd, arg, flag, p)
   3164 	struct scsipi_link *link;
   3165 	u_long cmd;
   3166 	caddr_t arg;
   3167 	int flag;
   3168 	struct proc *p;
   3169 {
   3170 	/*struct umass_softc *sc = link->adapter_softc;*/
   3171 
   3172 	switch (cmd) {
   3173 #if 0
   3174 	case SCBUSIORESET:
   3175 		ccb->ccb_h.status = CAM_REQ_INPROG;
   3176 		umass_reset(sc, umass_cam_cb, (void *) ccb);
   3177 		return (0);
   3178 #endif
   3179 	default:
   3180 		return (ENOTTY);
   3181 	}
   3182 }
   3183 
   3184 Static void
   3185 umass_scsipi_cb(struct umass_softc *sc, void *priv, int residue, int status)
   3186 {
   3187 	struct scsipi_xfer *xs = priv;
   3188 	struct scsipi_link *sc_link = xs->sc_link;
   3189 	int cmdlen;
   3190 	int s;
   3191 
   3192 	DPRINTF(UDMASS_CMD,("umass_scsipi_cb: xs=%p residue=%d status=%d\n",
   3193 		xs, residue, status));
   3194 
   3195 	xs->resid = residue;
   3196 
   3197 	switch (status) {
   3198 	case STATUS_CMD_OK:
   3199 		xs->error = XS_NOERROR;
   3200 		break;
   3201 
   3202 	case STATUS_CMD_UNKNOWN:
   3203 	case STATUS_CMD_FAILED:
   3204 		/* fetch sense data */
   3205 		memset(&sc->sc_sense_cmd, 0, sizeof(sc->sc_sense_cmd));
   3206 		sc->sc_sense_cmd.opcode = REQUEST_SENSE;
   3207 		sc->sc_sense_cmd.byte2 = sc_link->scsipi_scsi.lun <<
   3208 		    SCSI_CMD_LUN_SHIFT;
   3209 		sc->sc_sense_cmd.length = sizeof(xs->sense);
   3210 
   3211 		cmdlen = sizeof(sc->sc_sense_cmd);
   3212 		if (sc->proto & PROTO_UFI)
   3213 			cmdlen = UFI_PROTO_LEN;
   3214 		sc->transfer(sc, sc_link->scsipi_scsi.lun,
   3215 			     &sc->sc_sense_cmd, cmdlen,
   3216 			     &xs->sense, sizeof(xs->sense), DIR_IN,
   3217 			     umass_scsipi_sense_cb, xs);
   3218 		return;
   3219 
   3220 	case STATUS_WIRE_FAILED:
   3221 		xs->error = XS_RESET;
   3222 		break;
   3223 
   3224 	default:
   3225 		panic("%s: Unknown status %d in umass_scsipi_cb\n",
   3226 			USBDEVNAME(sc->sc_dev), status);
   3227 	}
   3228 
   3229 	xs->xs_status |= XS_STS_DONE;
   3230 
   3231 	DPRINTF(UDMASS_CMD,("umass_scsipi_cb: return xs->error=%d, "
   3232 		"xs->xs_status=0x%x xs->resid=%d\n", xs->error, xs->xs_status,
   3233 		xs->resid));
   3234 
   3235 	s = splbio();
   3236 	scsipi_done(xs);
   3237 	splx(s);
   3238 }
   3239 
   3240 /*
   3241  * Finalise a completed autosense operation
   3242  */
   3243 Static void
   3244 umass_scsipi_sense_cb(struct umass_softc *sc, void *priv, int residue,
   3245 		      int status)
   3246 {
   3247 	struct scsipi_xfer *xs = priv;
   3248 	int s;
   3249 
   3250 	DPRINTF(UDMASS_CMD,("umass_scsipi_sense_cb: xs=%p residue=%d "
   3251 		"status=%d\n", xs, residue, status));
   3252 
   3253 	switch (status) {
   3254 	case STATUS_CMD_OK:
   3255 	case STATUS_CMD_UNKNOWN:
   3256 		/* getting sense data succeeded */
   3257 		/* XXX look at residue */
   3258 		if (residue == 0 || residue == 14)/* XXX */
   3259 			xs->error = XS_SENSE;
   3260 		else
   3261 			xs->error = XS_SHORTSENSE;
   3262 		break;
   3263 	default:
   3264 		DPRINTF(UDMASS_SCSI, ("%s: Autosense failed, status %d\n",
   3265 			USBDEVNAME(sc->sc_dev), status));
   3266 		xs->error = XS_DRIVER_STUFFUP;
   3267 		break;
   3268 	}
   3269 
   3270 	xs->xs_status |= XS_STS_DONE;
   3271 
   3272 	DPRINTF(UDMASS_CMD,("umass_scsipi_sense_cb: return xs->error=%d, "
   3273 		"xs->xs_status=0x%x xs->resid=%d\n", xs->error, xs->xs_status,
   3274 		xs->resid));
   3275 
   3276 	s = splbio();
   3277 	scsipi_done(xs);
   3278 	splx(s);
   3279 }
   3280 
   3281 #if NATAPIBUS > 0
   3282 Static void
   3283 umass_atapi_probedev(atapi, target)
   3284 	struct atapibus_softc *atapi;
   3285 	int target;
   3286 {
   3287 	struct scsipi_link *sc_link;
   3288 	struct scsipibus_attach_args sa;
   3289 	struct ata_drive_datas *drvp = &atapi->sc_drvs[target];
   3290 	char vendor[33], product[65], revision[17];
   3291 	struct scsipi_inquiry_data inqbuf;
   3292 
   3293 	DPRINTF(UDMASS_SCSI,("umass_atapi_probedev: atapi=%p target=%d\n",
   3294 			     atapi, target));
   3295 
   3296 	if (atapi->sc_link[target])
   3297 		return;
   3298 
   3299 	sc_link = malloc(sizeof(*sc_link), M_DEVBUF, M_NOWAIT);
   3300 	if (sc_link == NULL) {
   3301 		printf("%s: can't allocate link for drive %d\n",
   3302 		       atapi->sc_dev.dv_xname, target);
   3303 		return;
   3304 	}
   3305 	*sc_link = *atapi->adapter_link;
   3306 
   3307 	DIF(UDMASS_UPPER, sc_link->flags |= DEBUGLEVEL);
   3308 
   3309 	/* Fill generic parts of the link. */
   3310 	sc_link->active = 0;
   3311 	sc_link->scsipi_atapi.drive = target;
   3312 	sc_link->device = &umass_dev;
   3313 	TAILQ_INIT(&sc_link->pending_xfers);
   3314 
   3315 	DPRINTF(UDMASS_SCSI, ("umass_atapi_probedev: doing inquiry\n"));
   3316 	/* Now go ask the device all about itself. */
   3317 	memset(&inqbuf, 0, sizeof(inqbuf));
   3318 	if (scsipi_inquire(sc_link, &inqbuf, XS_CTL_DISCOVERY) != 0)
   3319 		goto bad;
   3320 
   3321 	scsipi_strvis(vendor, 33, inqbuf.vendor, 8);
   3322 	scsipi_strvis(product, 65, inqbuf.product, 16);
   3323 	scsipi_strvis(revision, 17, inqbuf.revision, 4);
   3324 
   3325 	sa.sa_sc_link = sc_link;
   3326 	sa.sa_inqbuf.type = inqbuf.device;
   3327 	sa.sa_inqbuf.removable = inqbuf.dev_qual2 & SID_REMOVABLE ?
   3328 	    T_REMOV : T_FIXED;
   3329 	if (sa.sa_inqbuf.removable)
   3330 		sc_link->flags |= SDEV_REMOVABLE;
   3331 	/* XXX how? sc_link->scsipi_atapi.cap |= ACAP_LEN;*/
   3332 	sa.sa_inqbuf.vendor = vendor;
   3333 	sa.sa_inqbuf.product = product;
   3334 	sa.sa_inqbuf.revision = revision;
   3335 	sa.sa_inqptr = NULL;
   3336 
   3337 	drvp->drv_softc = atapi_probedev(atapi, target, sc_link, &sa);
   3338 	/* atapi_probedev() frees the scsipi_link when there is no device. */
   3339 	return;
   3340 
   3341 bad:
   3342 	free(sc_link, M_DEVBUF);
   3343 	return;
   3344 }
   3345 #endif
   3346 #endif
   3347