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