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