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