Home | History | Annotate | Line # | Download | only in usb
umass.c revision 1.7
      1 /*	$NetBSD: umass.c,v 1.7 1999/08/29 19:58:55 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*-
     40  * Copyright (c) 1999 MAEKAWA Masahide <bishop (at) rr.iij4u.or.jp>,
     41  *		      Nick Hibma <hibma (at) skylink.it>
     42  * All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  *
     65  *	FreeBSD: src/sys/dev/usb/umass.c,v 1.8 1999/06/20 15:46:13 n_hibma Exp
     66  */
     67 
     68 /*
     69  * Universal Serial Bus Mass Storage Class Control/Interrupt/Bulk (CBI)
     70  * Specification:
     71  *
     72  *	http://www.usb.org/developers/usbmass-cbi10.pdf
     73  *
     74  * Universal Serial Bus Mass Storage Bulk Only 1.0rc4 Specification:
     75  *
     76  *	http://www.usb.org/developers/usbmassbulk_10rc4.pdf
     77  *
     78  * Relevant parts of the old spec (Bulk-only 0.9) have been quoted
     79  * in the source.
     80  */
     81 
     82 /* To do:
     83  *	x The umass_usb_transfer routine uses synchroneous transfers. This
     84  *	  should be changed to async and state handling.
     85  *
     86  *	x Should handle more than just Iomega USB Zip drives.  There are
     87  *	  a fair number of USB->SCSI dongles out there.
     88  *
     89  *	x Need to implement SCSI command timeout/abort handling.
     90  *
     91  *	x Need to handle SCSI Sense handling.
     92  *
     93  *	x Need to handle hot-unplug.
     94  *
     95  *	x Add support for other than Bulk.
     96  *
     97  *	x Add support for other than SCSI.
     98  */
     99 
    100 /* Authors: (with short acronyms for comments)
    101  *   NWH - Nick Hibma <hibma (at) skylink.it>
    102  *   JRT - Jason R. Thorpe <thorpej (at) shagadelic.org>
    103  */
    104 
    105 #include <sys/param.h>
    106 #include <sys/systm.h>
    107 #include <sys/kernel.h>
    108 #include <sys/malloc.h>
    109 #include <sys/device.h>
    110 #include <sys/buf.h>
    111 #include <sys/proc.h>
    112 
    113 #include <dev/usb/usb.h>
    114 #include <dev/usb/usbdi.h>
    115 #include <dev/usb/usbdi_util.h>
    116 
    117 #include <dev/scsipi/scsi_all.h>
    118 #include <dev/scsipi/scsipi_all.h>
    119 #include <dev/scsipi/scsiconf.h>
    120 
    121 #ifdef UMASS_DEBUG
    122 #define	DPRINTF(m, x)	if (umassdebug & (m)) logprintf x
    123 #define UDMASS_SCSI	0x00020000
    124 #define UDMASS_USB	0x00040000
    125 #define UDMASS_BULK	0x00080000
    126 #define UDMASS_ALL	0xffff0000
    127 int umassdebug = /* UDMASS_SCSI|UDMASS_BULK|UDMASS_USB */ 0;
    128 #else
    129 #define	DPRINTF(m, x)
    130 #endif
    131 
    132 typedef struct umass_softc {
    133 	bdevice			sc_dev;		/* base device */
    134 	usbd_interface_handle	sc_iface;	/* the interface we use */
    135 
    136 	u_int8_t		sc_bulkout;	/* bulk-out Endpoint Address */
    137 	usbd_pipe_handle	sc_bulkout_pipe;
    138 	u_int8_t		sc_bulkin;	/* bulk-in Endpoint Address */
    139 	usbd_pipe_handle	sc_bulkin_pipe;
    140 
    141 	struct scsipi_link	sc_link;	/* prototype for devs */
    142 	struct scsipi_adapter	sc_adapter;
    143 } umass_softc_t;
    144 
    145 #define USBD_COMMAND_FAILED	USBD_INVAL	/* redefine some errors for */
    146 
    147 #define UMASS_SCSIID_HOST	0x00
    148 #define UMASS_SCSIID_DEVICE	0x01
    149 
    150 #define DIR_OUT		0
    151 #define DIR_IN		1
    152 #define DIR_NONE	2
    153 
    154 /* Bulk-Only specific request */
    155 #define	UR_RESET	0xff
    156 #define	UR_GET_MAX_LUN	0xfe
    157 
    158 /* Bulk-Only Mass Storage features */
    159 /* Command Block Wrapper */
    160 typedef struct {
    161 	uDWord		dCBWSignature;
    162 #define  CBWSIGNATURE		0x43425355
    163 	uDWord		dCBWTag;
    164 	uDWord		dCBWDataTransferLength;
    165 	uByte		bCBWFlags;
    166 #define	 CBWFLAGS_OUT	0x00
    167 #define	 CBWFLAGS_IN	0x80
    168 	uByte		bCBWLUN;
    169 	uByte		bCDBLength;
    170 	uByte		CBWCDB[16];
    171 } usb_bulk_cbw_t;
    172 #define	USB_BULK_CBW_SIZE	31
    173 
    174 /* Command Status Wrapper */
    175 typedef struct {
    176 	uDWord		dCSWSignature;
    177 #define	 CSWSIGNATURE		0x53425355
    178 	uDWord		dCSWTag;
    179 	uDWord		dCSWDataResidue;
    180 	uByte		bCSWStatus;
    181 #define  CSWSTATUS_GOOD		0x0
    182 #define  CSWSTATUS_FAILED	0x1
    183 #define  CSWSTATUS_PHASE	0x2
    184 } usb_bulk_csw_t;
    185 #define	USB_BULK_CSW_SIZE	13
    186 
    187 
    188 USB_DECLARE_DRIVER(umass);
    189 
    190 /* USB related functions */
    191 usbd_status umass_usb_transfer __P((usbd_interface_handle iface,
    192 				usbd_pipe_handle pipe,
    193 		                void *buf, int buflen,
    194 				int flags, int *xfer_size));
    195 
    196 /* Bulk-Only related functions */
    197 usbd_status umass_bulk_reset	__P((umass_softc_t *sc));
    198 usbd_status umass_bulk_get_max_lun __P((umass_softc_t *sc, u_int8_t *maxlun));
    199 usbd_status umass_bulk_transfer	__P((umass_softc_t *sc, int lun,
    200 				void *cmd, int cmdlen,
    201 		    		void *data, int datalen,
    202 				int dir, int *residue));
    203 
    204 /* SCSIPI related functions */
    205 struct scsipi_device umass_dev = {
    206 	NULL,			/* Use default error handler */
    207 	NULL,			/* have a queue, served by this */
    208 	NULL,			/* have no async handler */
    209 	NULL,			/* Use default `done' routine */
    210 };
    211 
    212 void	umass_minphys		__P((struct buf *));
    213 int	umass_scsi_cmd		__P((struct scsipi_xfer *));
    214 
    215 
    216 
    217 USB_MATCH(umass)
    218 {
    219 	USB_MATCH_START(umass, uaa);
    220 	usb_interface_descriptor_t *id;
    221 
    222 	if (!uaa->iface)
    223 		return(UMATCH_NONE);
    224 
    225 	id = usbd_get_interface_descriptor(uaa->iface);
    226 	if (id
    227 	    && id->bInterfaceClass == UCLASS_MASS
    228 	    && id->bInterfaceSubClass == USUBCLASS_SCSI
    229 	    && id->bInterfaceProtocol == UPROTO_MASS_BULK)
    230 		return(UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
    231 
    232 	return(UMATCH_NONE);
    233 }
    234 
    235 USB_ATTACH(umass)
    236 {
    237 	USB_ATTACH_START(umass, sc, uaa);
    238 	usb_interface_descriptor_t *id;
    239 	usb_endpoint_descriptor_t *ed;
    240 	char devinfo[1024];
    241 	usbd_status err;
    242 	int i;
    243 	u_int8_t maxlun;
    244 
    245 	sc->sc_iface = uaa->iface;
    246 	sc->sc_bulkout_pipe = NULL;
    247 	sc->sc_bulkin_pipe = NULL;
    248 
    249 	usbd_devinfo(uaa->device, 0, devinfo);
    250 	USB_ATTACH_SETUP;
    251 
    252 	id = usbd_get_interface_descriptor(sc->sc_iface);
    253 	printf("%s: %s, iclass %d/%d/%d\n", USBDEVNAME(sc->sc_dev), devinfo,
    254 	       id->bInterfaceClass, id->bInterfaceSubClass,
    255 	       id->bInterfaceProtocol);
    256 
    257 	/*
    258 	 * A Bulk-Only Mass Storage device supports the following endpoints,
    259 	 * in addition to the Endpoint 0 for Control transfer that is required
    260 	 * of all USB devices:
    261 	 * (a) bulk-in endpoint.
    262 	 * (b) bulk-out endpoint.
    263 	 *
    264 	 * The endpoint addresses are not fixed, so we have to read them
    265 	 * from the device descriptors of the current interface.
    266 	 */
    267 	for (i = 0 ; i < id->bNumEndpoints ; i++) {
    268 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
    269 		if (!ed) {
    270 			printf("%s: could not read endpoint descriptor\n",
    271 			       USBDEVNAME(sc->sc_dev));
    272 			USB_ATTACH_ERROR_RETURN;
    273 		}
    274 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_IN
    275 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    276 			sc->sc_bulkin = ed->bEndpointAddress;
    277 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_OUT
    278 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    279 			sc->sc_bulkout = ed->bEndpointAddress;
    280 		}
    281 	}
    282 
    283 	/*
    284 	 * Get the maximum LUN supported by the device.
    285 	 */
    286 	err = umass_bulk_get_max_lun(sc, &maxlun);
    287 	if (err != USBD_NORMAL_COMPLETION) {
    288 		printf("%s: unable to get Max Lun: %s\n",
    289 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    290 		USB_ATTACH_ERROR_RETURN;
    291 	}
    292 
    293 	/* Open the bulk-in and -out pipe */
    294 	err = usbd_open_pipe(sc->sc_iface, sc->sc_bulkout,
    295 				USBD_EXCLUSIVE_USE, &sc->sc_bulkout_pipe);
    296 	if (err) {
    297 		DPRINTF(UDMASS_USB, ("cannot open bulk out pipe (address %d)\n",
    298 			sc->sc_bulkout));
    299 		USB_ATTACH_ERROR_RETURN;
    300 	}
    301 	err = usbd_open_pipe(sc->sc_iface, sc->sc_bulkin,
    302 				USBD_EXCLUSIVE_USE, &sc->sc_bulkin_pipe);
    303 	if (err) {
    304 		DPRINTF(UDMASS_USB, ("cannot open bulk in pipe (address %d)\n",
    305 			sc->sc_bulkin));
    306 		usbd_close_pipe(sc->sc_bulkout_pipe);
    307 		USB_ATTACH_ERROR_RETURN;
    308 	}
    309 
    310 	/* attach the device to the SCSI layer */
    311 	sc->sc_adapter.scsipi_cmd = umass_scsi_cmd;
    312 	sc->sc_adapter.scsipi_minphys = umass_minphys;
    313 
    314 	sc->sc_link.scsipi_scsi.channel = SCSI_CHANNEL_ONLY_ONE;
    315 	sc->sc_link.adapter_softc = sc;
    316 	sc->sc_link.scsipi_scsi.adapter_target = UMASS_SCSIID_HOST;
    317 	sc->sc_link.adapter = &sc->sc_adapter;
    318 	sc->sc_link.device = &umass_dev;
    319 	sc->sc_link.openings = 4;		/* XXX */
    320 	sc->sc_link.scsipi_scsi.max_target = UMASS_SCSIID_DEVICE; /* XXX */
    321 	sc->sc_link.scsipi_scsi.max_lun = maxlun;
    322 	sc->sc_link.type = BUS_SCSI;
    323 
    324 	if (config_found(&sc->sc_dev, &sc->sc_link, scsiprint) == NULL) {
    325 		usbd_close_pipe(sc->sc_bulkout_pipe);
    326 		usbd_close_pipe(sc->sc_bulkin_pipe);
    327 		/* XXX Not really an error. */
    328 		USB_ATTACH_ERROR_RETURN;
    329 	}
    330 
    331 	USB_ATTACH_SUCCESS_RETURN;
    332 }
    333 
    334 int
    335 umass_activate(self, act)
    336 	struct device *self;
    337 	enum devact act;
    338 {
    339 
    340 	switch (act) {
    341 	case DVACT_ACTIVATE:
    342 		return (EOPNOTSUPP);
    343 		break;
    344 
    345 	case DVACT_DEACTIVATE:
    346 		/* XXX Not supported yet. */
    347 		return (EOPNOTSUPP);
    348 		break;
    349 	}
    350 	return (0);
    351 }
    352 
    353 int
    354 umass_detach(self, flags)
    355 	struct device *self;
    356 	int flags;
    357 {
    358 
    359 	/* XXX Not supported yet. */
    360 	return (EOPNOTSUPP);
    361 }
    362 
    363 /* Performs a request over a pipe.
    364  *
    365  * flags: Can be set to USBD_SHORT_XFER_OK
    366  * xfer_size: if not null returns the nr. of bytes transferred
    367  *
    368  * If the returned error is USBD_STALLED the pipe stall has
    369  * been cleared again.
    370  */
    371 
    372 usbd_status
    373 umass_usb_transfer(usbd_interface_handle iface, usbd_pipe_handle pipe,
    374 		   void *buf, int buflen, int flags, int *xfer_size)
    375 {
    376 	usbd_request_handle reqh;
    377 	usbd_private_handle priv;
    378 	void *buffer;
    379 	int size;
    380 	usbd_status err;
    381 
    382 	/* A transfer is done synchronously. We create and schedule the
    383 	 * transfer and then wait for it to complete
    384 	 */
    385 
    386 	reqh = usbd_alloc_request();
    387 	if (!reqh) {
    388 		DPRINTF(UDMASS_USB, ("Not enough memory\n"));
    389 		return USBD_NOMEM;
    390 	}
    391 
    392 	(void) usbd_setup_request(reqh, pipe, 0, buf, buflen,
    393 				flags, 3000 /*ms*/, NULL);
    394 	err = usbd_sync_transfer(reqh);
    395 	if (err) {
    396 		DPRINTF(UDMASS_USB, ("transfer failed, %s\n",
    397 			usbd_errstr(err)));
    398 		usbd_free_request(reqh);
    399 		return(err);
    400 	}
    401 
    402 	usbd_get_request_status(reqh, &priv, &buffer, &size, &err);
    403 
    404 	if (xfer_size)
    405 		*xfer_size = size;
    406 
    407 	usbd_free_request(reqh);
    408 	return(USBD_NORMAL_COMPLETION);
    409 }
    410 
    411 usbd_status
    412 umass_bulk_get_max_lun(umass_softc_t *sc, u_int8_t *maxlun)
    413 {
    414 	usbd_device_handle dev;
    415 	usb_device_request_t req;
    416 	usbd_status err;
    417 	usb_interface_descriptor_t *id;
    418 
    419 	DPRINTF(UDMASS_BULK, ("%s: Get Max Lun\n", USBDEVNAME(sc->sc_dev)));
    420 
    421 	usbd_interface2device_handle(sc->sc_iface, &dev);
    422 	id = usbd_get_interface_descriptor(sc->sc_iface);
    423 
    424 	/* The Get Max Lun command is a class-specific request. */
    425 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    426 	req.bRequest = UR_GET_MAX_LUN;
    427 	USETW(req.wValue, 0);
    428 	USETW(req.wIndex, id->bInterfaceNumber);
    429 	USETW(req.wLength, 1);
    430 
    431 	err = usbd_do_request(dev, &req, maxlun);
    432 	switch (err) {
    433 	case USBD_NORMAL_COMPLETION:
    434 		DPRINTF(UDMASS_BULK, ("%s: Max Lun %d\n",
    435 		    USBDEVNAME(sc->sc_dev), *maxlun));
    436 		break;
    437 
    438 	case USBD_STALLED:
    439 		/*
    440 		 * Device doesn't support Get Max Lun request.  Default
    441 		 * to `0' (one LUN).
    442 		 */
    443 		*maxlun = 0;
    444 		err = USBD_NORMAL_COMPLETION;
    445 		DPRINTF(UDMASS_BULK, ("%s: Get Max Lun not supported\n",
    446 		    USBDEVNAME(sc->sc_dev)));
    447 		break;
    448 
    449 	default:
    450 		printf("%s: Get Max Lun failed: %s\n",
    451 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    452 		/* XXX Should we port_reset the device? */
    453 	}
    454 
    455 	return (err);
    456 }
    457 
    458 usbd_status
    459 umass_bulk_reset(umass_softc_t *sc)
    460 {
    461 	usbd_device_handle dev;
    462         usb_device_request_t req;
    463 	usbd_status err;
    464 	usb_interface_descriptor_t *id;
    465 
    466 	/*
    467 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
    468 	 *
    469 	 * For Reset Recovery the host shall issue in the following order:
    470 	 * a) a Bulk-Only Mass Storage Reset
    471 	 * b) a Clear Feature HALT to the Bulk-In endpoint
    472 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
    473 	 */
    474 
    475 	DPRINTF(UDMASS_BULK, ("%s: Reset\n",
    476 		USBDEVNAME(sc->sc_dev)));
    477 
    478 	usbd_interface2device_handle(sc->sc_iface, &dev);
    479 	id = usbd_get_interface_descriptor(sc->sc_iface);
    480 
    481 	/* the reset command is a class specific interface request */
    482 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    483 	req.bRequest = UR_RESET;
    484 	USETW(req.wValue, 0);
    485 	USETW(req.wIndex, id->bInterfaceNumber);
    486 	USETW(req.wLength, 0);
    487 
    488 	err = usbd_do_request(dev, &req, 0);
    489 	if (err) {
    490 		printf("%s: Reset failed, %s\n",
    491 			USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    492 		/* XXX we should port_reset the device */
    493 		return(err);
    494 	}
    495 
    496 	usbd_clear_endpoint_stall(sc->sc_bulkout_pipe);
    497 	usbd_clear_endpoint_stall(sc->sc_bulkin_pipe);
    498 
    499 	/*
    500 	 * XXX we should convert this into a more friendly delay.
    501 	 * Perhaps a tsleep (or is this routine run from int context?)
    502 	 */
    503 
    504 	DELAY(2500000 /*us*/);
    505 
    506 	return(USBD_NORMAL_COMPLETION);
    507 }
    508 
    509 /*
    510  * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
    511  * a data phase of datalen bytes from/to data and finally a csw read
    512  * phase.
    513  *
    514  * If the data direction was inbound a maximum of datalen bytes
    515  * is stored in the buffer pointed to by data.
    516  * The status returned is USBD_NORMAL_COMPLETION,
    517  * USBD_IOERROR, USBD_COMMAND_FAILED.
    518  * In the last case *residue is set to the residue from the CSW,
    519  * otherwise to 0.
    520  *
    521  * For the functionality of this subroutine see the Mass Storage
    522  * Spec., the graphs on page 14 and page 19 and beyong (v0.9 of
    523  * the spec).
    524  */
    525 
    526 usbd_status
    527 umass_bulk_transfer(umass_softc_t *sc, int lun, void *cmd, int cmdlen,
    528 		    void *data, int datalen, int dir, int *residue)
    529 {
    530 	static int dCBWtag = 42;	/* tag to be used in transfers,
    531 					 * incremented at each transfer */
    532 	usb_bulk_cbw_t cbw;		/* command block wrapper struct */
    533 	usb_bulk_csw_t csw;		/* command status wrapper struct */
    534 	u_int32_t n = 0;		/* number of bytes transported */
    535 	usbd_status err;
    536 
    537 #ifdef UMASS_DEBUG
    538 	u_int8_t *c = cmd;
    539 
    540 	/* check the given arguments */
    541 	if (!data && datalen > 0) {	/* no buffer for transfer */
    542 		DPRINTF(UDMASS_BULK, ("%s: no buffer, but datalen > 0 !\n",
    543 			USBDEVNAME(sc->sc_dev)));
    544 		return USBD_IOERROR;
    545 	}
    546 
    547 	DPRINTF(UDMASS_BULK, ("%s: cmd: %d bytes (0x%02x%02x%02x%02x%02x%02x%s)"
    548 		", data: %d bytes, dir: %s\n",
    549 		USBDEVNAME(sc->sc_dev),
    550 		cmdlen, c[0], c[1], c[2], c[3], c[4], c[5],
    551 		(cmdlen > 6? "...":""),
    552 		datalen, (dir == DIR_IN? "in":"out")));
    553 #endif
    554 
    555 	if (dir == DIR_NONE || datalen == 0) {		/* make sure they correspond */
    556 		datalen = 0;
    557 		dir = DIR_NONE;
    558 	}
    559 
    560 	*residue = 0;			/* reset residue */
    561 
    562 	/*
    563 	 * Determine the direction of transferring data and data length.
    564 	 *
    565 	 * dCBWDataTransferLength (datalen) :
    566 	 *   This field indicates the number of bytes of data that the host
    567 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
    568 	 *   the Direction bit) during the execution of this command. If this
    569 	 *   field is set to 0, the device will expect that no data will be
    570 	 *   transferred IN or OUT during this command, regardless of the value
    571 	 *   of the Direction bit defined in dCBWFlags.
    572 	 *
    573 	 * dCBWFlags (dir) :
    574 	 *   The bits of the Flags field are defined as follows:
    575 	 *     Bits 0-6  reserved
    576 	 *     Bit  7    Direction - this bit shall be ignored if the
    577 	 *                           dCBWDataTransferLength field is zero.
    578 	 *               0 = data Out from host to device
    579 	 *               1 = data In from device to host
    580 	 */
    581 
    582 
    583 	/*
    584 	 * Command transport phase
    585 	 */
    586 
    587 	/* Fill in the Command Block Wrapper */
    588 	USETDW(cbw.dCBWSignature, CBWSIGNATURE);
    589 	USETDW(cbw.dCBWTag, dCBWtag++);
    590 	USETDW(cbw.dCBWDataTransferLength, datalen);
    591 	/* we do not check for DIR_NONE below (see text on dCBWFlags above) */
    592 	cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
    593 	cbw.bCBWLUN = lun;
    594 	cbw.bCDBLength = cmdlen;
    595 	bcopy(cmd, cbw.CBWCDB, cmdlen);
    596 
    597 	/* Send the CBW from host to device via bulk-out endpoint. */
    598 	err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkout_pipe,
    599 				&cbw, USB_BULK_CBW_SIZE, 0, NULL);
    600 	if (err) {
    601 		DPRINTF(UDMASS_BULK, ("%s: failed to send CBW\n",
    602 		         USBDEVNAME(sc->sc_dev)));
    603 		/* If the device detects that the CBW is invalid, then the
    604 		 * device may STALL both bulk endpoints and require a
    605 		 * Bulk-Only MS Reset
    606 		 */
    607 		umass_bulk_reset(sc);
    608 		return(USBD_IOERROR);
    609 	}
    610 
    611 
    612 	/*
    613 	 * Data transport phase (only if there is data to be sent/received)
    614 	 */
    615 
    616 	if (dir == DIR_IN) {
    617 		/* we allow short transfers for bulk-in pipes */
    618 		err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    619 					data, datalen,
    620 					USBD_SHORT_XFER_OK, &n);
    621 		if (err)
    622 			DPRINTF(UDMASS_BULK, ("%s: failed to receive data, "
    623 				"(%d bytes, n = %d), %s\n",
    624 				USBDEVNAME(sc->sc_dev),
    625 				datalen, n, usbd_errstr(err)));
    626 	} else if (dir == DIR_OUT) {
    627 		err = umass_usb_transfer(sc->sc_iface,
    628 					sc->sc_bulkout_pipe,
    629 					data, datalen, 0, &n);
    630 		if (err)
    631 			DPRINTF(UDMASS_BULK, ("%s: failed to send data, "
    632 				"(%d bytes, n = %d), %s\n",
    633 				USBDEVNAME(sc->sc_dev),
    634 				datalen, n, usbd_errstr(err)));
    635 	}
    636 	if (err && err != USBD_STALLED)
    637 		return(USBD_IOERROR);
    638 
    639 
    640 	/*
    641 	 * Status transport phase
    642 	 */
    643 
    644 	/* Read the Command Status Wrapper via bulk-in endpoint. */
    645 	err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    646 				&csw, USB_BULK_CSW_SIZE, 0, NULL);
    647 	/* Try again if the bulk-in pipe was stalled */
    648 	if (err == USBD_STALLED) {
    649 		err = usbd_clear_endpoint_stall(sc->sc_bulkin_pipe);
    650 		if (!err) {
    651 			err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    652 						&csw, USB_BULK_CSW_SIZE, 0, NULL);
    653 		}
    654 	}
    655 	if (err && err != USBD_STALLED)
    656 		return(USBD_IOERROR);
    657 
    658 	/*
    659 	 * Check the CSW for status and validity, and check for fatal errors
    660 	 */
    661 
    662 	/* Invalid CSW: Wrong signature or wrong tag might indicate
    663 	 * that the device is confused -> reset it.
    664 	 * Other fatal errors: STALL on read of CSW and Phase error
    665 	 * or unknown status.
    666 	 */
    667 	if (err == USBD_STALLED
    668 	    || UGETDW(csw.dCSWSignature) != CSWSIGNATURE
    669 	    || UGETDW(csw.dCSWTag) != UGETDW(cbw.dCBWTag)
    670 	    || csw.bCSWStatus == CSWSTATUS_PHASE
    671 	    || csw.bCSWStatus > CSWSTATUS_PHASE) {
    672 		if (err) {
    673 			printf("%s: failed to read CSW, %s\n",
    674 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    675 		} else if (csw.bCSWStatus == CSWSTATUS_PHASE) {
    676 			printf("%s: Phase Error, residue = %d, n = %d\n",
    677 				USBDEVNAME(sc->sc_dev),
    678 				UGETDW(csw.dCSWDataResidue), n);
    679 		} else if (csw.bCSWStatus > CSWSTATUS_PHASE) {
    680 			printf("%s: Unknown status %d in CSW\n",
    681 				USBDEVNAME(sc->sc_dev), csw.bCSWStatus);
    682 		} else {
    683 			printf("%s: invalid CSW, sig = 0x%08x, tag = %d (!= %d)\n",
    684 				USBDEVNAME(sc->sc_dev),
    685 				UGETDW(csw.dCSWSignature),
    686 				UGETDW(csw.dCSWTag), UGETDW(cbw.dCBWTag));
    687 		}
    688 		umass_bulk_reset(sc);
    689 		return(USBD_IOERROR);
    690 	}
    691 
    692 	if (csw.bCSWStatus == CSWSTATUS_FAILED) {
    693 		DPRINTF(UDMASS_BULK, ("%s: Command Failed, "
    694 			"residue = %d, n = %d\n",
    695 			USBDEVNAME(sc->sc_dev),
    696 			UGETDW(csw.dCSWDataResidue), n));
    697 		*residue = UGETDW(csw.dCSWDataResidue);
    698 		return(USBD_COMMAND_FAILED);
    699 	}
    700 
    701 	/*
    702 	 * XXX a residue not equal to 0 might indicate that something
    703 	 * is wrong. Does CAM high level drivers check this for us?
    704 	 */
    705 
    706 	return(USBD_NORMAL_COMPLETION);
    707 }
    708 
    709 
    710 /*
    711  * SCSIPI specific functions
    712  */
    713 
    714 int
    715 umass_scsi_cmd(xs)
    716 	struct scsipi_xfer *xs;
    717 {
    718 	struct scsipi_link *sc_link = xs->sc_link;
    719 	struct umass_softc *sc = sc_link->adapter_softc;
    720 	int residue, dir;
    721 	usbd_status err;
    722 
    723 	DPRINTF(UDMASS_SCSI, ("%s: umass_scsi_cmd %d:%d\n",
    724 	    USBDEVNAME(sc->sc_dev),
    725 	    sc_link->scsipi_scsi.target, sc_link->scsipi_scsi.lun));
    726 
    727 #ifdef UMASS_DEBUG
    728 	if (sc_link->scsipi_scsi.target != UMASS_SCSIID_DEVICE ||
    729 	    sc_link->scsipi_scsi.lun != 0) {
    730 		DPRINTF(UDMASS_SCSI, ("%s: Wrong SCSI ID %d or LUN %d\n",
    731 		    USBDEVNAME(sc->sc_dev),
    732 		    sc_link->scsipi_scsi.target,
    733 		    sc_link->scsipi_scsi.lun));
    734 		xs->error = XS_DRIVER_STUFFUP;
    735 		return (COMPLETE);
    736 	}
    737 #endif
    738 
    739 	dir = DIR_NONE;
    740 	if (xs->datalen) {
    741 		switch (xs->flags & (SCSI_DATA_IN|SCSI_DATA_OUT)) {
    742 		case SCSI_DATA_IN:
    743 			dir = DIR_IN;
    744 			break;
    745 		case SCSI_DATA_OUT:
    746 			dir = DIR_OUT;
    747 			break;
    748 		}
    749 	}
    750 
    751 	err = umass_bulk_transfer(sc, sc_link->scsipi_scsi.lun,
    752 	    xs->cmd, xs->cmdlen, xs->data, xs->datalen, dir, &residue);
    753 
    754 	/*
    755 	 * FAILED commands are supposed to be SCSI failed commands
    756 	 * and are therefore considered to be successfull CDW/CSW
    757 	 * transfers.  PHASE errors are more serious and should return
    758 	 * an error to the SCSIPI system.
    759 	 *
    760 	 * XXX This is however more based on empirical evidence than on
    761 	 * hard proof from the Bulk-Only spec.
    762 	 */
    763 	if (err == USBD_NORMAL_COMPLETION)
    764 		xs->error = XS_NOERROR;
    765 	else
    766 		xs->error = XS_DRIVER_STUFFUP;	/* XXX */
    767 	xs->resid = residue;
    768 
    769 	DPRINTF(UDMASS_SCSI, ("%s: umass_scsi_cmd: error = %d, resid = 0x%x\n",
    770 	    USBDEVNAME(sc->sc_dev), xs->error, xs->resid));
    771 
    772 	xs->flags |= ITSDONE;
    773 	scsipi_done(xs);
    774 
    775 	/*
    776 	 * XXXJRT We must return successfully queued if we're an
    777 	 * XXXJRT `asynchronous' command, otherwise `xs' will be
    778 	 * XXXJRT freed twice: once in scsipi_done(), and once in
    779 	 * XXXJRT scsi_scsipi_cmd().
    780 	 */
    781 	if (SCSIPI_XFER_ASYNC(xs))
    782 		return (SUCCESSFULLY_QUEUED);
    783 
    784 	return (COMPLETE);
    785 }
    786 
    787 void
    788 umass_minphys(bp)
    789 	struct buf *bp;
    790 {
    791 
    792 	/* No limit here. */
    793 	minphys(bp);
    794 }
    795