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