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