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