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