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