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