Home | History | Annotate | Line # | Download | only in usb
umass.c revision 1.12
      1 /*	$NetBSD: umass.c,v 1.12 1999/09/05 19:32:19 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();
    416 	if (!reqh) {
    417 		DPRINTF(UDMASS_USB, ("Not enough memory\n"));
    418 		return USBD_NOMEM;
    419 	}
    420 
    421 	(void) usbd_setup_request(reqh, pipe, 0, buf, buflen,
    422 				flags, 3000 /*ms*/, NULL);
    423 	err = usbd_sync_transfer(reqh);
    424 	if (err) {
    425 		DPRINTF(UDMASS_USB, ("transfer failed, %s\n",
    426 			usbd_errstr(err)));
    427 		usbd_free_request(reqh);
    428 		return(err);
    429 	}
    430 
    431 	usbd_get_request_status(reqh, &priv, &buffer, &size, &err);
    432 
    433 	if (xfer_size)
    434 		*xfer_size = size;
    435 
    436 	usbd_free_request(reqh);
    437 	return(USBD_NORMAL_COMPLETION);
    438 }
    439 
    440 usbd_status
    441 umass_bulk_get_max_lun(umass_softc_t *sc, u_int8_t *maxlun)
    442 {
    443 	usbd_device_handle dev;
    444 	usb_device_request_t req;
    445 	usbd_status err;
    446 	usb_interface_descriptor_t *id;
    447 
    448 	DPRINTF(UDMASS_BULK, ("%s: Get Max Lun\n", USBDEVNAME(sc->sc_dev)));
    449 
    450 	usbd_interface2device_handle(sc->sc_iface, &dev);
    451 	id = usbd_get_interface_descriptor(sc->sc_iface);
    452 
    453 	/* The Get Max Lun command is a class-specific request. */
    454 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    455 	req.bRequest = UR_GET_MAX_LUN;
    456 	USETW(req.wValue, 0);
    457 	USETW(req.wIndex, id->bInterfaceNumber);
    458 	USETW(req.wLength, 1);
    459 
    460 	err = usbd_do_request(dev, &req, maxlun);
    461 	switch (err) {
    462 	case USBD_NORMAL_COMPLETION:
    463 		DPRINTF(UDMASS_BULK, ("%s: Max Lun %d\n",
    464 		    USBDEVNAME(sc->sc_dev), *maxlun));
    465 		break;
    466 
    467 	case USBD_STALLED:
    468 		/*
    469 		 * Device doesn't support Get Max Lun request.  Default
    470 		 * to `0' (one LUN).
    471 		 */
    472 		*maxlun = 0;
    473 		err = USBD_NORMAL_COMPLETION;
    474 		DPRINTF(UDMASS_BULK, ("%s: Get Max Lun not supported\n",
    475 		    USBDEVNAME(sc->sc_dev)));
    476 		break;
    477 
    478 	default:
    479 		printf("%s: Get Max Lun failed: %s\n",
    480 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    481 		/* XXX Should we port_reset the device? */
    482 	}
    483 
    484 	return (err);
    485 }
    486 
    487 usbd_status
    488 umass_bulk_reset(umass_softc_t *sc)
    489 {
    490 	usbd_device_handle dev;
    491         usb_device_request_t req;
    492 	usbd_status err;
    493 	usb_interface_descriptor_t *id;
    494 
    495 	/*
    496 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
    497 	 *
    498 	 * For Reset Recovery the host shall issue in the following order:
    499 	 * a) a Bulk-Only Mass Storage Reset
    500 	 * b) a Clear Feature HALT to the Bulk-In endpoint
    501 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
    502 	 */
    503 
    504 	DPRINTF(UDMASS_BULK, ("%s: Reset\n",
    505 		USBDEVNAME(sc->sc_dev)));
    506 
    507 	usbd_interface2device_handle(sc->sc_iface, &dev);
    508 	id = usbd_get_interface_descriptor(sc->sc_iface);
    509 
    510 	/* the reset command is a class specific interface request */
    511 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    512 	req.bRequest = UR_RESET;
    513 	USETW(req.wValue, 0);
    514 	USETW(req.wIndex, id->bInterfaceNumber);
    515 	USETW(req.wLength, 0);
    516 
    517 	err = usbd_do_request(dev, &req, 0);
    518 	if (err) {
    519 		printf("%s: Reset failed, %s\n",
    520 			USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    521 		/* XXX we should port_reset the device */
    522 		return(err);
    523 	}
    524 
    525 	usbd_clear_endpoint_stall(sc->sc_bulkout_pipe);
    526 	usbd_clear_endpoint_stall(sc->sc_bulkin_pipe);
    527 
    528 	/*
    529 	 * XXX we should convert this into a more friendly delay.
    530 	 * Perhaps a tsleep (or is this routine run from int context?)
    531 	 */
    532 
    533 	DELAY(2500000 /*us*/);
    534 
    535 	return(USBD_NORMAL_COMPLETION);
    536 }
    537 
    538 /*
    539  * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
    540  * a data phase of datalen bytes from/to data and finally a csw read
    541  * phase.
    542  *
    543  * If the data direction was inbound a maximum of datalen bytes
    544  * is stored in the buffer pointed to by data.
    545  * The status returned is USBD_NORMAL_COMPLETION,
    546  * USBD_IOERROR, USBD_COMMAND_FAILED.
    547  * In the last case *residue is set to the residue from the CSW,
    548  * otherwise to 0.
    549  *
    550  * For the functionality of this subroutine see the Mass Storage
    551  * Spec., the graphs on page 14 and page 19 and beyong (v0.9 of
    552  * the spec).
    553  */
    554 
    555 usbd_status
    556 umass_bulk_transfer(umass_softc_t *sc, int lun, void *cmd, int cmdlen,
    557 		    void *data, int datalen, int dir, int *residue)
    558 {
    559 	static int dCBWtag = 42;	/* tag to be used in transfers,
    560 					 * incremented at each transfer */
    561 	usb_bulk_cbw_t cbw;		/* command block wrapper struct */
    562 	usb_bulk_csw_t csw;		/* command status wrapper struct */
    563 	u_int32_t n = 0;		/* number of bytes transported */
    564 	usbd_status err;
    565 
    566 #ifdef UMASS_DEBUG
    567 	u_int8_t *c = cmd;
    568 
    569 	/* check the given arguments */
    570 	if (!data && datalen > 0) {	/* no buffer for transfer */
    571 		DPRINTF(UDMASS_BULK, ("%s: no buffer, but datalen > 0 !\n",
    572 			USBDEVNAME(sc->sc_dev)));
    573 		return USBD_IOERROR;
    574 	}
    575 
    576 	DPRINTF(UDMASS_BULK, ("%s: cmd: %d bytes (0x%02x%02x%02x%02x%02x%02x%s)"
    577 		", data: %d bytes, dir: %s\n",
    578 		USBDEVNAME(sc->sc_dev),
    579 		cmdlen, c[0], c[1], c[2], c[3], c[4], c[5],
    580 		(cmdlen > 6? "...":""),
    581 		datalen, (dir == DIR_IN? "in":"out")));
    582 #endif
    583 
    584 	if (dir == DIR_NONE || datalen == 0) {		/* make sure they correspond */
    585 		datalen = 0;
    586 		dir = DIR_NONE;
    587 	}
    588 
    589 	*residue = 0;			/* reset residue */
    590 
    591 	/*
    592 	 * Determine the direction of transferring data and data length.
    593 	 *
    594 	 * dCBWDataTransferLength (datalen) :
    595 	 *   This field indicates the number of bytes of data that the host
    596 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
    597 	 *   the Direction bit) during the execution of this command. If this
    598 	 *   field is set to 0, the device will expect that no data will be
    599 	 *   transferred IN or OUT during this command, regardless of the value
    600 	 *   of the Direction bit defined in dCBWFlags.
    601 	 *
    602 	 * dCBWFlags (dir) :
    603 	 *   The bits of the Flags field are defined as follows:
    604 	 *     Bits 0-6  reserved
    605 	 *     Bit  7    Direction - this bit shall be ignored if the
    606 	 *                           dCBWDataTransferLength field is zero.
    607 	 *               0 = data Out from host to device
    608 	 *               1 = data In from device to host
    609 	 */
    610 
    611 
    612 	/*
    613 	 * Command transport phase
    614 	 */
    615 
    616 	/* Fill in the Command Block Wrapper */
    617 	USETDW(cbw.dCBWSignature, CBWSIGNATURE);
    618 	USETDW(cbw.dCBWTag, dCBWtag++);
    619 	USETDW(cbw.dCBWDataTransferLength, datalen);
    620 	/* we do not check for DIR_NONE below (see text on dCBWFlags above) */
    621 	cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
    622 	cbw.bCBWLUN = lun;
    623 	cbw.bCDBLength = cmdlen;
    624 	bcopy(cmd, cbw.CBWCDB, cmdlen);
    625 
    626 	/* Send the CBW from host to device via bulk-out endpoint. */
    627 	err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkout_pipe,
    628 				&cbw, USB_BULK_CBW_SIZE, 0, NULL);
    629 	if (err) {
    630 		DPRINTF(UDMASS_BULK, ("%s: failed to send CBW\n",
    631 		         USBDEVNAME(sc->sc_dev)));
    632 		/* If the device detects that the CBW is invalid, then the
    633 		 * device may STALL both bulk endpoints and require a
    634 		 * Bulk-Only MS Reset
    635 		 */
    636 		umass_bulk_reset(sc);
    637 		return(USBD_IOERROR);
    638 	}
    639 
    640 
    641 	/*
    642 	 * Data transport phase (only if there is data to be sent/received)
    643 	 */
    644 
    645 	if (dir == DIR_IN) {
    646 		/* we allow short transfers for bulk-in pipes */
    647 		err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    648 					data, datalen,
    649 					USBD_SHORT_XFER_OK, &n);
    650 		if (err)
    651 			DPRINTF(UDMASS_BULK, ("%s: failed to receive data, "
    652 				"(%d bytes, n = %d), %s\n",
    653 				USBDEVNAME(sc->sc_dev),
    654 				datalen, n, usbd_errstr(err)));
    655 	} else if (dir == DIR_OUT) {
    656 		err = umass_usb_transfer(sc->sc_iface,
    657 					sc->sc_bulkout_pipe,
    658 					data, datalen, 0, &n);
    659 		if (err)
    660 			DPRINTF(UDMASS_BULK, ("%s: failed to send data, "
    661 				"(%d bytes, n = %d), %s\n",
    662 				USBDEVNAME(sc->sc_dev),
    663 				datalen, n, usbd_errstr(err)));
    664 	}
    665 	if (err && err != USBD_STALLED)
    666 		return(USBD_IOERROR);
    667 
    668 
    669 	/*
    670 	 * Status transport phase
    671 	 */
    672 
    673 	/* Read the Command Status Wrapper via bulk-in endpoint. */
    674 	err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    675 				&csw, USB_BULK_CSW_SIZE, 0, NULL);
    676 	/* Try again if the bulk-in pipe was stalled */
    677 	if (err == USBD_STALLED) {
    678 		err = usbd_clear_endpoint_stall(sc->sc_bulkin_pipe);
    679 		if (!err) {
    680 			err = umass_usb_transfer(sc->sc_iface, sc->sc_bulkin_pipe,
    681 						&csw, USB_BULK_CSW_SIZE, 0, NULL);
    682 		}
    683 	}
    684 	if (err && err != USBD_STALLED)
    685 		return(USBD_IOERROR);
    686 
    687 	/*
    688 	 * Check the CSW for status and validity, and check for fatal errors
    689 	 */
    690 
    691 	/* Invalid CSW: Wrong signature or wrong tag might indicate
    692 	 * that the device is confused -> reset it.
    693 	 * Other fatal errors: STALL on read of CSW and Phase error
    694 	 * or unknown status.
    695 	 */
    696 	if (err == USBD_STALLED
    697 	    || UGETDW(csw.dCSWSignature) != CSWSIGNATURE
    698 	    || UGETDW(csw.dCSWTag) != UGETDW(cbw.dCBWTag)
    699 	    || csw.bCSWStatus == CSWSTATUS_PHASE
    700 	    || csw.bCSWStatus > CSWSTATUS_PHASE) {
    701 		if (err) {
    702 			printf("%s: failed to read CSW, %s\n",
    703 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    704 		} else if (csw.bCSWStatus == CSWSTATUS_PHASE) {
    705 			printf("%s: Phase Error, residue = %d, n = %d\n",
    706 				USBDEVNAME(sc->sc_dev),
    707 				UGETDW(csw.dCSWDataResidue), n);
    708 		} else if (csw.bCSWStatus > CSWSTATUS_PHASE) {
    709 			printf("%s: Unknown status %d in CSW\n",
    710 				USBDEVNAME(sc->sc_dev), csw.bCSWStatus);
    711 		} else {
    712 			printf("%s: invalid CSW, sig = 0x%08x, tag = %d (!= %d)\n",
    713 				USBDEVNAME(sc->sc_dev),
    714 				UGETDW(csw.dCSWSignature),
    715 				UGETDW(csw.dCSWTag), UGETDW(cbw.dCBWTag));
    716 		}
    717 		umass_bulk_reset(sc);
    718 		return(USBD_IOERROR);
    719 	}
    720 
    721 	if (csw.bCSWStatus == CSWSTATUS_FAILED) {
    722 		DPRINTF(UDMASS_BULK, ("%s: Command Failed, "
    723 			"residue = %d, n = %d\n",
    724 			USBDEVNAME(sc->sc_dev),
    725 			UGETDW(csw.dCSWDataResidue), n));
    726 		*residue = UGETDW(csw.dCSWDataResidue);
    727 		return(USBD_COMMAND_FAILED);
    728 	}
    729 
    730 	/*
    731 	 * XXX a residue not equal to 0 might indicate that something
    732 	 * is wrong. Does CAM high level drivers check this for us?
    733 	 */
    734 
    735 	return(USBD_NORMAL_COMPLETION);
    736 }
    737 
    738 
    739 /*
    740  * SCSIPI specific functions
    741  */
    742 
    743 int
    744 umass_scsipi_scsi_cmd(xs)
    745 	struct scsipi_xfer *xs;
    746 {
    747 	struct scsipi_link *sc_link = xs->sc_link;
    748 	struct umass_softc *sc = sc_link->adapter_softc;
    749 	int residue, dir;
    750 	usbd_status err;
    751 
    752 	DPRINTF(UDMASS_SCSI, ("%s: umass_scsi_cmd %d:%d\n",
    753 	    USBDEVNAME(sc->sc_dev),
    754 	    sc_link->scsipi_scsi.target, sc_link->scsipi_scsi.lun));
    755 
    756 #ifdef UMASS_DEBUG
    757 	if (sc_link->scsipi_scsi.target != UMASS_SCSIID_DEVICE) {
    758 		DPRINTF(UDMASS_SCSI, ("%s: Wrong SCSI ID %d\n",
    759 		    USBDEVNAME(sc->sc_dev),
    760 		    sc_link->scsipi_scsi.target));
    761 		xs->error = XS_DRIVER_STUFFUP;
    762 		return (COMPLETE);
    763 	}
    764 #endif
    765 
    766 	dir = DIR_NONE;
    767 	if (xs->datalen) {
    768 		switch (xs->flags & (SCSI_DATA_IN|SCSI_DATA_OUT)) {
    769 		case SCSI_DATA_IN:
    770 			dir = DIR_IN;
    771 			break;
    772 		case SCSI_DATA_OUT:
    773 			dir = DIR_OUT;
    774 			break;
    775 		}
    776 	}
    777 
    778 	err = umass_bulk_transfer(sc, sc_link->scsipi_scsi.lun,
    779 	    xs->cmd, xs->cmdlen, xs->data, xs->datalen, dir, &residue);
    780 
    781 	/*
    782 	 * FAILED commands are supposed to be SCSI failed commands
    783 	 * and are therefore considered to be successfull CDW/CSW
    784 	 * transfers.  PHASE errors are more serious and should return
    785 	 * an error to the SCSIPI system.
    786 	 *
    787 	 * XXX This is however more based on empirical evidence than on
    788 	 * hard proof from the Bulk-Only spec.
    789 	 */
    790 	if (err == USBD_NORMAL_COMPLETION)
    791 		xs->error = XS_NOERROR;
    792 	else
    793 		xs->error = XS_DRIVER_STUFFUP;	/* XXX */
    794 	xs->resid = residue;
    795 
    796 	DPRINTF(UDMASS_SCSI, ("%s: umass_scsi_cmd: error = %d, resid = 0x%x\n",
    797 	    USBDEVNAME(sc->sc_dev), xs->error, xs->resid));
    798 
    799 	xs->flags |= ITSDONE;
    800 	scsipi_done(xs);
    801 
    802 	/*
    803 	 * XXXJRT We must return successfully queued if we're an
    804 	 * XXXJRT `asynchronous' command, otherwise `xs' will be
    805 	 * XXXJRT freed twice: once in scsipi_done(), and once in
    806 	 * XXXJRT scsi_scsipi_cmd().
    807 	 */
    808 	if (SCSIPI_XFER_ASYNC(xs))
    809 		return (SUCCESSFULLY_QUEUED);
    810 
    811 	return (COMPLETE);
    812 }
    813 
    814 void
    815 umass_scsipi_minphys(bp)
    816 	struct buf *bp;
    817 {
    818 
    819 	/* No limit here. */
    820 	minphys(bp);
    821 }
    822