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