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