Home | History | Annotate | Line # | Download | only in usb
umass.c revision 1.13
      1 /*	$NetBSD: umass.c,v 1.13 1999/09/09 12:26:46 augustss 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 	USBBASEDEVICE		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 
    144 	device_ptr_t		sc_child;	/* child device, for detach */
    145 
    146 	char			sc_dying;
    147 } umass_softc_t;
    148 
    149 #define USBD_COMMAND_FAILED	USBD_INVAL	/* redefine some errors for */
    150 
    151 #define UMASS_SCSIID_HOST	0x00
    152 #define UMASS_SCSIID_DEVICE	0x01
    153 
    154 #define DIR_OUT		0
    155 #define DIR_IN		1
    156 #define DIR_NONE	2
    157 
    158 /* Bulk-Only specific request */
    159 #define	UR_RESET	0xff
    160 #define	UR_GET_MAX_LUN	0xfe
    161 
    162 /* Bulk-Only Mass Storage features */
    163 /* Command Block Wrapper */
    164 typedef struct {
    165 	uDWord		dCBWSignature;
    166 #define  CBWSIGNATURE		0x43425355
    167 	uDWord		dCBWTag;
    168 	uDWord		dCBWDataTransferLength;
    169 	uByte		bCBWFlags;
    170 #define	 CBWFLAGS_OUT	0x00
    171 #define	 CBWFLAGS_IN	0x80
    172 	uByte		bCBWLUN;
    173 	uByte		bCDBLength;
    174 	uByte		CBWCDB[16];
    175 } usb_bulk_cbw_t;
    176 #define	USB_BULK_CBW_SIZE	31
    177 
    178 /* Command Status Wrapper */
    179 typedef struct {
    180 	uDWord		dCSWSignature;
    181 #define	 CSWSIGNATURE		0x53425355
    182 	uDWord		dCSWTag;
    183 	uDWord		dCSWDataResidue;
    184 	uByte		bCSWStatus;
    185 #define  CSWSTATUS_GOOD		0x0
    186 #define  CSWSTATUS_FAILED	0x1
    187 #define  CSWSTATUS_PHASE	0x2
    188 } usb_bulk_csw_t;
    189 #define	USB_BULK_CSW_SIZE	13
    190 
    191 
    192 USB_DECLARE_DRIVER(umass);
    193 
    194 /* USB related functions */
    195 usbd_status umass_usb_transfer __P((usbd_interface_handle iface,
    196 				usbd_pipe_handle pipe,
    197 		                void *buf, int buflen,
    198 				int flags, int *xfer_size));
    199 
    200 /* Bulk-Only related functions */
    201 usbd_status umass_bulk_reset	__P((umass_softc_t *sc));
    202 usbd_status umass_bulk_get_max_lun __P((umass_softc_t *sc, u_int8_t *maxlun));
    203 usbd_status umass_bulk_transfer	__P((umass_softc_t *sc, int lun,
    204 				void *cmd, int cmdlen,
    205 		    		void *data, int datalen,
    206 				int dir, int *residue));
    207 
    208 /* SCSIPI related functions */
    209 struct scsipi_device umass_dev = {
    210 	NULL,			/* Use default error handler */
    211 	NULL,			/* have a queue, served by this */
    212 	NULL,			/* have no async handler */
    213 	NULL,			/* Use default `done' routine */
    214 };
    215 
    216 void	umass_scsipi_minphys	__P((struct buf *));
    217 int	umass_scsipi_scsi_cmd	__P((struct scsipi_xfer *));
    218 
    219 
    220 
    221 USB_MATCH(umass)
    222 {
    223 	USB_MATCH_START(umass, uaa);
    224 	usb_interface_descriptor_t *id;
    225 
    226 	if (!uaa->iface)
    227 		return(UMATCH_NONE);
    228 
    229 	id = usbd_get_interface_descriptor(uaa->iface);
    230 	if (id
    231 	    && id->bInterfaceClass == UCLASS_MASS
    232 	    && id->bInterfaceSubClass == USUBCLASS_SCSI
    233 	    && id->bInterfaceProtocol == UPROTO_MASS_BULK)
    234 		return(UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
    235 
    236 	return(UMATCH_NONE);
    237 }
    238 
    239 USB_ATTACH(umass)
    240 {
    241 	USB_ATTACH_START(umass, sc, uaa);
    242 	usb_interface_descriptor_t *id;
    243 	usb_endpoint_descriptor_t *ed;
    244 	char devinfo[1024];
    245 	usbd_status err;
    246 	int i;
    247 	u_int8_t maxlun;
    248 
    249 	sc->sc_iface = uaa->iface;
    250 	sc->sc_bulkout_pipe = NULL;
    251 	sc->sc_bulkin_pipe = NULL;
    252 
    253 	usbd_devinfo(uaa->device, 0, devinfo);
    254 	USB_ATTACH_SETUP;
    255 
    256 	id = usbd_get_interface_descriptor(sc->sc_iface);
    257 	printf("%s: %s, iclass %d/%d/%d\n", USBDEVNAME(sc->sc_dev), devinfo,
    258 	       id->bInterfaceClass, id->bInterfaceSubClass,
    259 	       id->bInterfaceProtocol);
    260 
    261 	/*
    262 	 * A Bulk-Only Mass Storage device supports the following endpoints,
    263 	 * in addition to the Endpoint 0 for Control transfer that is required
    264 	 * of all USB devices:
    265 	 * (a) bulk-in endpoint.
    266 	 * (b) bulk-out endpoint.
    267 	 *
    268 	 * The endpoint addresses are not fixed, so we have to read them
    269 	 * from the device descriptors of the current interface.
    270 	 */
    271 	for (i = 0 ; i < id->bNumEndpoints ; i++) {
    272 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
    273 		if (!ed) {
    274 			printf("%s: could not read endpoint descriptor\n",
    275 			       USBDEVNAME(sc->sc_dev));
    276 			USB_ATTACH_ERROR_RETURN;
    277 		}
    278 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
    279 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    280 			sc->sc_bulkin = ed->bEndpointAddress;
    281 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT
    282 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    283 			sc->sc_bulkout = ed->bEndpointAddress;
    284 		}
    285 	}
    286 
    287 	/*
    288 	 * Get the maximum LUN supported by the device.
    289 	 */
    290 	err = umass_bulk_get_max_lun(sc, &maxlun);
    291 	if (err != USBD_NORMAL_COMPLETION) {
    292 		printf("%s: unable to get Max Lun: %s\n",
    293 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    294 		USB_ATTACH_ERROR_RETURN;
    295 	}
    296 
    297 	/* Open the bulk-in and -out pipe */
    298 	err = usbd_open_pipe(sc->sc_iface, sc->sc_bulkout,
    299 				USBD_EXCLUSIVE_USE, &sc->sc_bulkout_pipe);
    300 	if (err) {
    301 		DPRINTF(UDMASS_USB, ("cannot open bulk out pipe (address %d)\n",
    302 			sc->sc_bulkout));
    303 		USB_ATTACH_ERROR_RETURN;
    304 	}
    305 	err = usbd_open_pipe(sc->sc_iface, sc->sc_bulkin,
    306 				USBD_EXCLUSIVE_USE, &sc->sc_bulkin_pipe);
    307 	if (err) {
    308 		DPRINTF(UDMASS_USB, ("cannot open bulk in pipe (address %d)\n",
    309 			sc->sc_bulkin));
    310 		usbd_close_pipe(sc->sc_bulkout_pipe);
    311 		USB_ATTACH_ERROR_RETURN;
    312 	}
    313 
    314 	/* attach the device to the SCSIPI layer */
    315 	sc->sc_adapter.scsipi_cmd = umass_scsipi_scsi_cmd;
    316 	sc->sc_adapter.scsipi_minphys = umass_scsipi_minphys;
    317 
    318 	sc->sc_link.scsipi_scsi.channel = SCSI_CHANNEL_ONLY_ONE;
    319 	sc->sc_link.adapter_softc = sc;
    320 	sc->sc_link.scsipi_scsi.adapter_target = UMASS_SCSIID_HOST;
    321 	sc->sc_link.adapter = &sc->sc_adapter;
    322 	sc->sc_link.device = &umass_dev;
    323 	sc->sc_link.openings = 1;
    324 	sc->sc_link.scsipi_scsi.max_target = UMASS_SCSIID_DEVICE; /* XXX */
    325 	sc->sc_link.scsipi_scsi.max_lun = maxlun;
    326 	sc->sc_link.type = BUS_SCSI;
    327 
    328 	sc->sc_child = config_found(&sc->sc_dev, &sc->sc_link, scsiprint);
    329 	if (sc->sc_child == NULL) {
    330 		usbd_close_pipe(sc->sc_bulkout_pipe);
    331 		usbd_close_pipe(sc->sc_bulkin_pipe);
    332 		/* XXX Not really an error. */
    333 		USB_ATTACH_ERROR_RETURN;
    334 	}
    335 
    336 	USB_ATTACH_SUCCESS_RETURN;
    337 }
    338 
    339 int
    340 umass_activate(self, act)
    341 	struct device *self;
    342 	enum devact act;
    343 {
    344 	struct umass_softc *sc = (struct umass_softc *) self;
    345 	int rv = 0;
    346 
    347 	DPRINTF(UDMASS_USB, ("%s: umass_activate: %d\n",
    348 	    USBDEVNAME(sc->sc_dev), act));
    349 
    350 	switch (act) {
    351 	case DVACT_ACTIVATE:
    352 		rv = EOPNOTSUPP;
    353 		break;
    354 
    355 	case DVACT_DEACTIVATE:
    356 		if (sc->sc_child != NULL)
    357 			break;
    358 		rv = config_deactivate(sc->sc_child);
    359 		DPRINTF(UDMASS_USB, ("%s: umass_activate: child "
    360 		    "returned %d\n", USBDEVNAME(sc->sc_dev), rv));
    361 		if (rv == 0)
    362 			sc->sc_dying = 1;
    363 		break;
    364 	}
    365 	return (rv);
    366 }
    367 
    368 int
    369 umass_detach(self, flags)
    370 	struct device *self;
    371 	int flags;
    372 {
    373 	struct umass_softc *sc = (struct umass_softc *) self;
    374 	int rv = 0;
    375 
    376 	DPRINTF(UDMASS_USB, ("%s: umass_detach: flags 0x%x\n",
    377 	    USBDEVNAME(sc->sc_dev), flags));
    378 
    379 	if (sc->sc_child != NULL)
    380 		rv = config_detach(sc->sc_child, flags);
    381 
    382 	if (rv == 0) {
    383 		usbd_abort_pipe(sc->sc_bulkin_pipe);
    384 		usbd_close_pipe(sc->sc_bulkin_pipe);
    385 		usbd_abort_pipe(sc->sc_bulkout_pipe);
    386 		usbd_close_pipe(sc->sc_bulkout_pipe);
    387 	}
    388 
    389 	return (rv);
    390 }
    391 
    392 /* Performs a request over a pipe.
    393  *
    394  * flags: Can be set to USBD_SHORT_XFER_OK
    395  * xfer_size: if not null returns the nr. of bytes transferred
    396  *
    397  * If the returned error is USBD_STALLED the pipe stall has
    398  * been cleared again.
    399  */
    400 
    401 usbd_status
    402 umass_usb_transfer(usbd_interface_handle iface, usbd_pipe_handle pipe,
    403 		   void *buf, int buflen, int flags, int *xfer_size)
    404 {
    405 	usbd_request_handle reqh;
    406 	usbd_private_handle priv;
    407 	void *buffer;
    408 	int size;
    409 	usbd_status err;
    410 
    411 	/* A transfer is done synchronously. We create and schedule the
    412 	 * transfer and then wait for it to complete
    413 	 */
    414 
    415 	reqh = usbd_alloc_request(usbd_pipe2device_handle(pipe));
    416 	if (!reqh) {
    417 		DPRINTF(UDMASS_USB, ("Not enough memory\n"));
    418 		return USBD_NOMEM;
    419 	}
    420 
    421 	usbd_setup_request(reqh, pipe, 0, buf, buflen,flags, 3000 /*ms*/, NULL);
    422 	err = usbd_sync_transfer(reqh);
    423 	if (err) {
    424 		DPRINTF(UDMASS_USB, ("transfer failed, %s\n",
    425 			usbd_errstr(err)));
    426 		usbd_free_request(reqh);
    427 		return(err);
    428 	}
    429 
    430 	usbd_get_request_status(reqh, &priv, &buffer, &size, &err);
    431 
    432 	if (xfer_size)
    433 		*xfer_size = size;
    434 
    435 	usbd_free_request(reqh);
    436 	return(USBD_NORMAL_COMPLETION);
    437 }
    438 
    439 usbd_status
    440 umass_bulk_get_max_lun(umass_softc_t *sc, u_int8_t *maxlun)
    441 {
    442 	usbd_device_handle dev;
    443 	usb_device_request_t req;
    444 	usbd_status err;
    445 	usb_interface_descriptor_t *id;
    446 
    447 	DPRINTF(UDMASS_BULK, ("%s: Get Max Lun\n", USBDEVNAME(sc->sc_dev)));
    448 
    449 	usbd_interface2device_handle(sc->sc_iface, &dev);
    450 	id = usbd_get_interface_descriptor(sc->sc_iface);
    451 
    452 	/* The Get Max Lun command is a class-specific request. */
    453 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    454 	req.bRequest = UR_GET_MAX_LUN;
    455 	USETW(req.wValue, 0);
    456 	USETW(req.wIndex, id->bInterfaceNumber);
    457 	USETW(req.wLength, 1);
    458 
    459 	err = usbd_do_request(dev, &req, maxlun);
    460 	switch (err) {
    461 	case USBD_NORMAL_COMPLETION:
    462 		DPRINTF(UDMASS_BULK, ("%s: Max Lun %d\n",
    463 		    USBDEVNAME(sc->sc_dev), *maxlun));
    464 		break;
    465 
    466 	case USBD_STALLED:
    467 		/*
    468 		 * Device doesn't support Get Max Lun request.  Default
    469 		 * to `0' (one LUN).
    470 		 */
    471 		*maxlun = 0;
    472 		err = USBD_NORMAL_COMPLETION;
    473 		DPRINTF(UDMASS_BULK, ("%s: Get Max Lun not supported\n",
    474 		    USBDEVNAME(sc->sc_dev)));
    475 		break;
    476 
    477 	default:
    478 		printf("%s: Get Max Lun failed: %s\n",
    479 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    480 		/* XXX Should we port_reset the device? */
    481 	}
    482 
    483 	return (err);
    484 }
    485 
    486 usbd_status
    487 umass_bulk_reset(umass_softc_t *sc)
    488 {
    489 	usbd_device_handle dev;
    490         usb_device_request_t req;
    491 	usbd_status err;
    492 	usb_interface_descriptor_t *id;
    493 
    494 	/*
    495 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
    496 	 *
    497 	 * For Reset Recovery the host shall issue in the following order:
    498 	 * a) a Bulk-Only Mass Storage Reset
    499 	 * b) a Clear Feature HALT to the Bulk-In endpoint
    500 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
    501 	 */
    502 
    503 	DPRINTF(UDMASS_BULK, ("%s: Reset\n",
    504 		USBDEVNAME(sc->sc_dev)));
    505 
    506 	usbd_interface2device_handle(sc->sc_iface, &dev);
    507 	id = usbd_get_interface_descriptor(sc->sc_iface);
    508 
    509 	/* the reset command is a class specific interface request */
    510 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    511 	req.bRequest = UR_RESET;
    512 	USETW(req.wValue, 0);
    513 	USETW(req.wIndex, id->bInterfaceNumber);
    514 	USETW(req.wLength, 0);
    515 
    516 	err = usbd_do_request(dev, &req, 0);
    517 	if (err) {
    518 		printf("%s: Reset failed, %s\n",
    519 			USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    520 		/* XXX we should port_reset the device */
    521 		return(err);
    522 	}
    523 
    524 	usbd_clear_endpoint_stall(sc->sc_bulkout_pipe);
    525 	usbd_clear_endpoint_stall(sc->sc_bulkin_pipe);
    526 
    527 	/*
    528 	 * XXX we should convert this into a more friendly delay.
    529 	 * Perhaps a tsleep (or is this routine run from int context?)
    530 	 */
    531 
    532 	DELAY(2500000 /*us*/);
    533 
    534 	return(USBD_NORMAL_COMPLETION);
    535 }
    536 
    537 /*
    538  * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
    539  * a data phase of datalen bytes from/to data and finally a csw read
    540  * phase.
    541  *
    542  * If the data direction was inbound a maximum of datalen bytes
    543  * is stored in the buffer pointed to by data.
    544  * The status returned is USBD_NORMAL_COMPLETION,
    545  * USBD_IOERROR, USBD_COMMAND_FAILED.
    546  * In the last case *residue is set to the residue from the CSW,
    547  * otherwise to 0.
    548  *
    549  * For the functionality of this subroutine see the Mass Storage
    550  * Spec., the graphs on page 14 and page 19 and beyong (v0.9 of
    551  * the spec).
    552  */
    553 
    554 usbd_status
    555 umass_bulk_transfer(umass_softc_t *sc, int lun, void *cmd, int cmdlen,
    556 		    void *data, int datalen, int dir, int *residue)
    557 {
    558 	static int dCBWtag = 42;	/* tag to be used in transfers,
    559 					 * incremented at each transfer */
    560 	usb_bulk_cbw_t cbw;		/* command block wrapper struct */
    561 	usb_bulk_csw_t csw;		/* command status wrapper struct */
    562 	u_int32_t n = 0;		/* number of bytes transported */
    563 	usbd_status err;
    564 
    565 #ifdef UMASS_DEBUG
    566 	u_int8_t *c = cmd;
    567 
    568 	/* check the given arguments */
    569 	if (!data && datalen > 0) {	/* no buffer for transfer */
    570 		DPRINTF(UDMASS_BULK, ("%s: no buffer, but datalen > 0 !\n",
    571 			USBDEVNAME(sc->sc_dev)));
    572 		return USBD_IOERROR;
    573 	}
    574 
    575 	DPRINTF(UDMASS_BULK, ("%s: cmd: %d bytes (0x%02x%02x%02x%02x%02x%02x%s)"
    576 		", data: %d bytes, dir: %s\n",
    577 		USBDEVNAME(sc->sc_dev),
    578 		cmdlen, c[0], c[1], c[2], c[3], c[4], c[5],
    579 		(cmdlen > 6? "...":""),
    580 		datalen, (dir == DIR_IN? "in":"out")));
    581 #endif
    582 
    583 	if (dir == DIR_NONE || datalen == 0) {		/* make sure they correspond */
    584 		datalen = 0;
    585 		dir = DIR_NONE;
    586 	}
    587 
    588 	*residue = 0;			/* reset residue */
    589 
    590 	/*
    591 	 * Determine the direction of transferring data and data length.
    592 	 *
    593 	 * dCBWDataTransferLength (datalen) :
    594 	 *   This field indicates the number of bytes of data that the host
    595 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
    596 	 *   the Direction bit) during the execution of this command. If this
    597 	 *   field is set to 0, the device will expect that no data will be
    598 	 *   transferred IN or OUT during this command, regardless of the value
    599 	 *   of the Direction bit defined in dCBWFlags.
    600 	 *
    601 	 * dCBWFlags (dir) :
    602 	 *   The bits of the Flags field are defined as follows:
    603 	 *     Bits 0-6  reserved
    604 	 *     Bit  7    Direction - this bit shall be ignored if the
    605 	 *                           dCBWDataTransferLength field is zero.
    606 	 *               0 = data Out from host to device
    607 	 *               1 = data In from device to host
    608 	 */
    609 
    610 
    611 	/*
    612 	 * Command transport phase
    613 	 */
    614 
    615 	/* Fill in the Command Block Wrapper */
    616 	USETDW(cbw.dCBWSignature, CBWSIGNATURE);
    617 	USETDW(cbw.dCBWTag, dCBWtag++);
    618 	USETDW(cbw.dCBWDataTransferLength, datalen);
    619 	/* we do not check for DIR_NONE below (see text on dCBWFlags above) */
    620 	cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
    621 	cbw.bCBWLUN = lun;
    622 	cbw.bCDBLength = cmdlen;
    623 	bcopy(cmd, cbw.CBWCDB, cmdlen);
    624 
    625 	/* Send the CBW from host to device via bulk-out endpoint. */
    626 	err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkout_pipe,
    627 				&cbw, USB_BULK_CBW_SIZE, 0, NULL);
    628 	if (err) {
    629 		DPRINTF(UDMASS_BULK, ("%s: failed to send CBW\n",
    630 		         USBDEVNAME(sc->sc_dev)));
    631 		/* If the device detects that the CBW is invalid, then the
    632 		 * device may STALL both bulk endpoints and require a
    633 		 * Bulk-Only MS Reset
    634 		 */
    635 		umass_bulk_reset(sc);
    636 		return(USBD_IOERROR);
    637 	}
    638 
    639 
    640 	/*
    641 	 * Data transport phase (only if there is data to be sent/received)
    642 	 */
    643 
    644 	if (dir == DIR_IN) {
    645 		/* we allow short transfers for bulk-in pipes */
    646 		err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    647 					data, datalen,
    648 					USBD_SHORT_XFER_OK, &n);
    649 		if (err)
    650 			DPRINTF(UDMASS_BULK, ("%s: failed to receive data, "
    651 				"(%d bytes, n = %d), %s\n",
    652 				USBDEVNAME(sc->sc_dev),
    653 				datalen, n, usbd_errstr(err)));
    654 	} else if (dir == DIR_OUT) {
    655 		err = umass_usb_transfer(sc->sc_iface,
    656 					sc->sc_bulkout_pipe,
    657 					data, datalen, 0, &n);
    658 		if (err)
    659 			DPRINTF(UDMASS_BULK, ("%s: failed to send data, "
    660 				"(%d bytes, n = %d), %s\n",
    661 				USBDEVNAME(sc->sc_dev),
    662 				datalen, n, usbd_errstr(err)));
    663 	}
    664 	if (err && err != USBD_STALLED)
    665 		return(USBD_IOERROR);
    666 
    667 
    668 	/*
    669 	 * Status transport phase
    670 	 */
    671 
    672 	/* Read the Command Status Wrapper via bulk-in endpoint. */
    673 	err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    674 				&csw, USB_BULK_CSW_SIZE, 0, NULL);
    675 	/* Try again if the bulk-in pipe was stalled */
    676 	if (err == USBD_STALLED) {
    677 		err = usbd_clear_endpoint_stall(sc->sc_bulkin_pipe);
    678 		if (!err) {
    679 			err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    680 						&csw, USB_BULK_CSW_SIZE, 0, NULL);
    681 		}
    682 	}
    683 	if (err && err != USBD_STALLED)
    684 		return(USBD_IOERROR);
    685 
    686 	/*
    687 	 * Check the CSW for status and validity, and check for fatal errors
    688 	 */
    689 
    690 	/* Invalid CSW: Wrong signature or wrong tag might indicate
    691 	 * that the device is confused -> reset it.
    692 	 * Other fatal errors: STALL on read of CSW and Phase error
    693 	 * or unknown status.
    694 	 */
    695 	if (err == USBD_STALLED
    696 	    || UGETDW(csw.dCSWSignature) != CSWSIGNATURE
    697 	    || UGETDW(csw.dCSWTag) != UGETDW(cbw.dCBWTag)
    698 	    || csw.bCSWStatus == CSWSTATUS_PHASE
    699 	    || csw.bCSWStatus > CSWSTATUS_PHASE) {
    700 		if (err) {
    701 			printf("%s: failed to read CSW, %s\n",
    702 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    703 		} else if (csw.bCSWStatus == CSWSTATUS_PHASE) {
    704 			printf("%s: Phase Error, residue = %d, n = %d\n",
    705 				USBDEVNAME(sc->sc_dev),
    706 				UGETDW(csw.dCSWDataResidue), n);
    707 		} else if (csw.bCSWStatus > CSWSTATUS_PHASE) {
    708 			printf("%s: Unknown status %d in CSW\n",
    709 				USBDEVNAME(sc->sc_dev), csw.bCSWStatus);
    710 		} else {
    711 			printf("%s: invalid CSW, sig = 0x%08x, tag = %d (!= %d)\n",
    712 				USBDEVNAME(sc->sc_dev),
    713 				UGETDW(csw.dCSWSignature),
    714 				UGETDW(csw.dCSWTag), UGETDW(cbw.dCBWTag));
    715 		}
    716 		umass_bulk_reset(sc);
    717 		return(USBD_IOERROR);
    718 	}
    719 
    720 	if (csw.bCSWStatus == CSWSTATUS_FAILED) {
    721 		DPRINTF(UDMASS_BULK, ("%s: Command Failed, "
    722 			"residue = %d, n = %d\n",
    723 			USBDEVNAME(sc->sc_dev),
    724 			UGETDW(csw.dCSWDataResidue), n));
    725 		*residue = UGETDW(csw.dCSWDataResidue);
    726 		return(USBD_COMMAND_FAILED);
    727 	}
    728 
    729 	/*
    730 	 * XXX a residue not equal to 0 might indicate that something
    731 	 * is wrong. Does CAM high level drivers check this for us?
    732 	 */
    733 
    734 	return(USBD_NORMAL_COMPLETION);
    735 }
    736 
    737 
    738 /*
    739  * SCSIPI specific functions
    740  */
    741 
    742 int
    743 umass_scsipi_scsi_cmd(xs)
    744 	struct scsipi_xfer *xs;
    745 {
    746 	struct scsipi_link *sc_link = xs->sc_link;
    747 	struct umass_softc *sc = sc_link->adapter_softc;
    748 	int residue, dir;
    749 	usbd_status err;
    750 
    751 	DPRINTF(UDMASS_SCSI, ("%s: umass_scsi_cmd %d:%d\n",
    752 	    USBDEVNAME(sc->sc_dev),
    753 	    sc_link->scsipi_scsi.target, sc_link->scsipi_scsi.lun));
    754 
    755 #ifdef UMASS_DEBUG
    756 	if (sc_link->scsipi_scsi.target != UMASS_SCSIID_DEVICE) {
    757 		DPRINTF(UDMASS_SCSI, ("%s: Wrong SCSI ID %d\n",
    758 		    USBDEVNAME(sc->sc_dev),
    759 		    sc_link->scsipi_scsi.target));
    760 		xs->error = XS_DRIVER_STUFFUP;
    761 		return (COMPLETE);
    762 	}
    763 #endif
    764 
    765 	dir = DIR_NONE;
    766 	if (xs->datalen) {
    767 		switch (xs->flags & (SCSI_DATA_IN|SCSI_DATA_OUT)) {
    768 		case SCSI_DATA_IN:
    769 			dir = DIR_IN;
    770 			break;
    771 		case SCSI_DATA_OUT:
    772 			dir = DIR_OUT;
    773 			break;
    774 		}
    775 	}
    776 
    777 	err = umass_bulk_transfer(sc, sc_link->scsipi_scsi.lun,
    778 	    xs->cmd, xs->cmdlen, xs->data, xs->datalen, dir, &residue);
    779 
    780 	/*
    781 	 * FAILED commands are supposed to be SCSI failed commands
    782 	 * and are therefore considered to be successfull CDW/CSW
    783 	 * transfers.  PHASE errors are more serious and should return
    784 	 * an error to the SCSIPI system.
    785 	 *
    786 	 * XXX This is however more based on empirical evidence than on
    787 	 * hard proof from the Bulk-Only spec.
    788 	 */
    789 	if (err == USBD_NORMAL_COMPLETION)
    790 		xs->error = XS_NOERROR;
    791 	else
    792 		xs->error = XS_DRIVER_STUFFUP;	/* XXX */
    793 	xs->resid = residue;
    794 
    795 	DPRINTF(UDMASS_SCSI, ("%s: umass_scsi_cmd: error = %d, resid = 0x%x\n",
    796 	    USBDEVNAME(sc->sc_dev), xs->error, xs->resid));
    797 
    798 	xs->flags |= ITSDONE;
    799 	scsipi_done(xs);
    800 
    801 	/*
    802 	 * XXXJRT We must return successfully queued if we're an
    803 	 * XXXJRT `asynchronous' command, otherwise `xs' will be
    804 	 * XXXJRT freed twice: once in scsipi_done(), and once in
    805 	 * XXXJRT scsi_scsipi_cmd().
    806 	 */
    807 	if (SCSIPI_XFER_ASYNC(xs))
    808 		return (SUCCESSFULLY_QUEUED);
    809 
    810 	return (COMPLETE);
    811 }
    812 
    813 void
    814 umass_scsipi_minphys(bp)
    815 	struct buf *bp;
    816 {
    817 
    818 	/* No limit here. */
    819 	minphys(bp);
    820 }
    821