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