Home | History | Annotate | Line # | Download | only in usb
umass.c revision 1.76
      1 /*	$NetBSD: umass.c,v 1.76 2001/12/14 08:58:49 gehenna Exp $	*/
      2 /*-
      3  * Copyright (c) 1999 MAEKAWA Masahide <bishop (at) rr.iij4u.or.jp>,
      4  *		      Nick Hibma <n_hibma (at) freebsd.org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  *     $FreeBSD: src/sys/dev/usb/umass.c,v 1.13 2000/03/26 01:39:12 n_hibma Exp $
     29  */
     30 
     31 /*
     32  * Universal Serial Bus Mass Storage Class specs:
     33  * http://www.usb.org/developers/data/devclass/usbmassover_11.pdf
     34  * http://www.usb.org/developers/data/devclass/usbmassbulk_10.pdf
     35  * http://www.usb.org/developers/data/devclass/usbmass-cbi10.pdf
     36  * http://www.usb.org/developers/data/devclass/usbmass-ufi10.pdf
     37  */
     38 
     39 /*
     40  * Ported to NetBSD by Lennart Augustsson <augustss (at) netbsd.org>.
     41  * Parts of the code written my Jason R. Thorpe <thorpej (at) shagadelic.org>.
     42  */
     43 
     44 /*
     45  * The driver handles 3 Wire Protocols
     46  * - Command/Bulk/Interrupt (CBI)
     47  * - Command/Bulk/Interrupt with Command Completion Interrupt (CBI with CCI)
     48  * - Mass Storage Bulk-Only (BBB)
     49  *   (BBB refers Bulk/Bulk/Bulk for Command/Data/Status phases)
     50  *
     51  * Over these wire protocols it handles the following command protocols
     52  * - SCSI
     53  * - 8070 (ATA/ATAPI for rewritable removable media)
     54  * - UFI (USB Floppy Interface)
     55  *
     56  * 8070i is a transformed version of the SCSI command set. UFI is a transformed
     57  * version of the 8070i command set.  The sc->transform method is used to
     58  * convert the commands into the appropriate format (if at all necessary).
     59  * For example, ATAPI requires all commands to be 12 bytes in length amongst
     60  * other things.
     61  *
     62  * The source code below is marked and can be split into a number of pieces
     63  * (in this order):
     64  *
     65  * - probe/attach/detach
     66  * - generic transfer routines
     67  * - BBB
     68  * - CBI
     69  * - CBI_I (in addition to functions from CBI)
     70  * - CAM (Common Access Method)
     71  * - SCSI
     72  * - UFI
     73  * - 8070i
     74  *
     75  * The protocols are implemented using a state machine, for the transfers as
     76  * well as for the resets. The state machine is contained in umass_*_state.
     77  * The state machine is started through either umass_*_transfer or
     78  * umass_*_reset.
     79  *
     80  * The reason for doing this is a) CAM performs a lot better this way and b) it
     81  * avoids using tsleep from interrupt context (for example after a failed
     82  * transfer).
     83  */
     84 
     85 /*
     86  * The SCSI related part of this driver has been derived from the
     87  * dev/ppbus/vpo.c driver, by Nicolas Souchu (nsouch (at) freebsd.org).
     88  *
     89  * The CAM layer uses so called actions which are messages sent to the host
     90  * adapter for completion. The actions come in through umass_cam_action. The
     91  * appropriate block of routines is called depending on the transport protocol
     92  * in use. When the transfer has finished, these routines call
     93  * umass_cam_cb again to complete the CAM command.
     94  */
     95 
     96 #include <sys/cdefs.h>
     97 __KERNEL_RCSID(0, "$NetBSD: umass.c,v 1.76 2001/12/14 08:58:49 gehenna Exp $");
     98 
     99 #include "atapibus.h"
    100 
    101 #include <sys/param.h>
    102 #include <sys/systm.h>
    103 #include <sys/kernel.h>
    104 #include <sys/conf.h>
    105 #if defined(__NetBSD__) || defined(__OpenBSD__)
    106 #include <sys/buf.h>
    107 #include <sys/device.h>
    108 #include <sys/ioctl.h>
    109 #include <sys/malloc.h>
    110 #undef KASSERT
    111 #define KASSERT(cond, msg)
    112 #elif defined(__FreeBSD__)
    113 #include <sys/module.h>
    114 #include <sys/bus.h>
    115 #include <machine/clock.h>
    116 #endif
    117 
    118 #include <dev/usb/usb.h>
    119 #include <dev/usb/usbdi.h>
    120 #include <dev/usb/usbdi_util.h>
    121 #include <dev/usb/usbdevs.h>
    122 
    123 #include <dev/usb/umassbus.h>
    124 #include <dev/usb/umassvar.h>
    125 
    126 
    127 
    128 
    129 #ifdef UMASS_DEBUG
    130 int umassdebug = 0;
    131 
    132 char *states[TSTATE_STATES+1] = {
    133 	/* should be kept in sync with the list at transfer_state */
    134 	"Idle",
    135 	"BBB CBW",
    136 	"BBB Data",
    137 	"BBB Data bulk-in/-out clear stall",
    138 	"BBB CSW, 1st attempt",
    139 	"BBB CSW bulk-in clear stall",
    140 	"BBB CSW, 2nd attempt",
    141 	"BBB Reset",
    142 	"BBB bulk-in clear stall",
    143 	"BBB bulk-out clear stall",
    144 	"CBI Command",
    145 	"CBI Data",
    146 	"CBI Status",
    147 	"CBI Data bulk-in/-out clear stall",
    148 	"CBI Status intr-in clear stall",
    149 	"CBI Reset",
    150 	"CBI bulk-in clear stall",
    151 	"CBI bulk-out clear stall",
    152 	NULL
    153 };
    154 #endif
    155 
    156 /* USB device probe/attach/detach functions */
    157 USB_DECLARE_DRIVER(umass);
    158 Static void umass_disco(struct umass_softc *sc);
    159 Static int umass_match_proto(struct umass_softc *sc,
    160 			     usbd_interface_handle iface,
    161 			     usbd_device_handle dev);
    162 Static void umass_init_shuttle(struct umass_softc *sc);
    163 
    164 /* generic transfer functions */
    165 Static usbd_status umass_setup_transfer(struct umass_softc *sc,
    166 				usbd_pipe_handle pipe,
    167 				void *buffer, int buflen, int flags,
    168 				usbd_xfer_handle xfer);
    169 Static usbd_status umass_setup_ctrl_transfer(struct umass_softc *sc,
    170 				usb_device_request_t *req,
    171 				void *buffer, int buflen, int flags,
    172 				usbd_xfer_handle xfer);
    173 Static void umass_clear_endpoint_stall(struct umass_softc *sc, int endpt,
    174 				usbd_xfer_handle xfer);
    175 #if 0
    176 Static void umass_reset(struct umass_softc *sc,	transfer_cb_f cb, void *priv);
    177 #endif
    178 
    179 /* Bulk-Only related functions */
    180 Static void umass_bbb_transfer(struct umass_softc *, int, void *, int, void *,
    181 			       int, int, u_int, umass_callback, void *);
    182 Static void umass_bbb_reset(struct umass_softc *, int);
    183 Static void umass_bbb_state(usbd_xfer_handle, usbd_private_handle, usbd_status);
    184 
    185 usbd_status umass_bbb_get_max_lun(struct umass_softc *, u_int8_t *);
    186 
    187 /* CBI related functions */
    188 Static void umass_cbi_transfer(struct umass_softc *, int, void *, int, void *,
    189 			       int, int, u_int, umass_callback, void *);
    190 Static void umass_cbi_reset(struct umass_softc *, int);
    191 Static void umass_cbi_state(usbd_xfer_handle, usbd_private_handle, usbd_status);
    192 
    193 Static int umass_cbi_adsc(struct umass_softc *, char *, int, usbd_xfer_handle);
    194 
    195 const struct umass_wire_methods umass_bbb_methods = {
    196 	umass_bbb_transfer,
    197 	umass_bbb_reset,
    198 	umass_bbb_state
    199 };
    200 
    201 const struct umass_wire_methods umass_cbi_methods = {
    202 	umass_cbi_transfer,
    203 	umass_cbi_reset,
    204 	umass_cbi_state
    205 };
    206 
    207 #ifdef UMASS_DEBUG
    208 /* General debugging functions */
    209 Static void umass_bbb_dump_cbw(struct umass_softc *sc,
    210 				umass_bbb_cbw_t *cbw);
    211 Static void umass_bbb_dump_csw(struct umass_softc *sc,
    212 				umass_bbb_csw_t *csw);
    213 Static void umass_dump_buffer(struct umass_softc *sc, u_int8_t *buffer,
    214 				int buflen, int printlen);
    215 #endif
    216 
    217 
    218 /*
    219  * USB device probe/attach/detach
    220  */
    221 
    222 /*
    223  * Match the device we are seeing with the devices supported. Fill in the
    224  * proto and drive fields in the softc accordingly.
    225  * This function is called from both probe and attach.
    226  */
    227 
    228 Static int
    229 umass_match_proto(struct umass_softc *sc, usbd_interface_handle iface,
    230 		  usbd_device_handle dev)
    231 {
    232 	usb_device_descriptor_t *dd;
    233 	usb_interface_descriptor_t *id;
    234 	u_int vendor, product;
    235 
    236 	/*
    237 	 * Fill in sc->drive and sc->proto and return a match
    238 	 * value if both are determined and 0 otherwise.
    239 	 */
    240 
    241 	sc->drive = DRIVE_GENERIC;
    242 	sc->transfer_speed = UMASS_DEFAULT_TRANSFER_SPEED;
    243 
    244 	sc->sc_udev = dev;
    245 	dd = usbd_get_device_descriptor(dev);
    246 	vendor = UGETW(dd->idVendor);
    247 	product = UGETW(dd->idProduct);
    248 
    249 	if (vendor == USB_VENDOR_SHUTTLE &&
    250 	    (product == USB_PRODUCT_SHUTTLE_EUSB ||
    251 	     product == USB_PRODUCT_SHUTTLE_ZIOMMC)
    252 	    ) {
    253 		if (product == USB_PRODUCT_SHUTTLE_EUSB)
    254 			sc->drive = SHUTTLE_EUSB;
    255 #if CBI_I
    256 		sc->wire_proto = WPROTO_CBI_I;
    257 		sc->cmd_proto = CPROTO_ATAPI;
    258 #else
    259 		sc->wire_proto = WPROTO_CBI;
    260 		sc->cmd_proto = CPROTO_ATAPI;
    261 #endif
    262 		sc->subclass = UISUBCLASS_SFF8020I;
    263 		sc->protocol = UIPROTO_MASS_CBI;
    264 		sc->quirks |= NO_TEST_UNIT_READY | NO_START_STOP;
    265 		return (UMATCH_VENDOR_PRODUCT);
    266 	}
    267 
    268 	if (vendor == USB_VENDOR_MICROTECH &&
    269 	    product == USB_PRODUCT_MICROTECH_DPCM) {
    270 		sc->wire_proto = WPROTO_CBI;
    271 		sc->cmd_proto = CPROTO_ATAPI;
    272 		sc->subclass = UISUBCLASS_SFF8070I;
    273 		sc->protocol = UIPROTO_MASS_CBI;
    274 		sc->transfer_speed = UMASS_ZIP100_TRANSFER_SPEED * 2;
    275 
    276 		return (UMATCH_VENDOR_PRODUCT);
    277 	}
    278 
    279 	if (vendor == USB_VENDOR_YANO &&
    280 	    product == USB_PRODUCT_YANO_U640MO) {
    281 #if CBI_I
    282 		sc->wire_proto = WPROTO_CBI_I;
    283 		sc->cmd_proto = CPROTO_ATAPI;
    284 #else
    285 		sc->wire_proto = WPROTO_CBI;
    286 		sc->cmd_proto = CPROTO_ATAPI;
    287 #endif
    288 		sc->quirks |= FORCE_SHORT_INQUIRY;
    289 		return (UMATCH_VENDOR_PRODUCT);
    290 	}
    291 
    292 	if (vendor == USB_VENDOR_SONY &&
    293 	    product == USB_PRODUCT_SONY_MSC) {
    294 		sc->quirks |= FORCE_SHORT_INQUIRY;
    295 	}
    296 
    297 	if (vendor == USB_VENDOR_YEDATA &&
    298 	    product == USB_PRODUCT_YEDATA_FLASHBUSTERU) {
    299 
    300 		/* Revisions < 1.28 do not handle the interrupt endpoint
    301 		 * very well.
    302 		 */
    303 		if (UGETW(dd->bcdDevice) < 0x128) {
    304 			sc->wire_proto = WPROTO_CBI;
    305 			sc->cmd_proto = CPROTO_UFI;
    306 		} else
    307 #if CBI_I
    308 			sc->wire_proto = WPROTO_CBI_I;
    309 			sc->cmd_proto = CPROTO_UFI;
    310 #else
    311 			sc->wire_proto = WPROTO_CBI;
    312 			sc->cmd_proto = CPROTO_UFI;
    313 #endif
    314 		/*
    315 		 * Revisions < 1.28 do not have the TEST UNIT READY command
    316 		 * Revisions == 1.28 have a broken TEST UNIT READY
    317 		 */
    318 		if (UGETW(dd->bcdDevice) <= 0x128)
    319 			sc->quirks |= NO_TEST_UNIT_READY;
    320 
    321 		sc->subclass = UISUBCLASS_UFI;
    322 		sc->protocol = UIPROTO_MASS_CBI;
    323 
    324 		sc->quirks |= RS_NO_CLEAR_UA;
    325 		sc->transfer_speed = UMASS_FLOPPY_TRANSFER_SPEED;
    326 		return (UMATCH_VENDOR_PRODUCT_REV);
    327 	}
    328 
    329 	if (vendor == USB_VENDOR_INSYSTEM &&
    330 	    product == USB_PRODUCT_INSYSTEM_USBCABLE) {
    331 		sc->drive = INSYSTEM_USBCABLE;
    332 		sc->wire_proto = WPROTO_CBI;
    333 		sc->cmd_proto = CPROTO_ATAPI;
    334 		sc->quirks |= NO_TEST_UNIT_READY | NO_START_STOP;
    335 		return (UMATCH_VENDOR_PRODUCT);
    336 	}
    337 
    338 	if (vendor == USB_VENDOR_IOMEGA &&
    339 	    (product == USB_PRODUCT_IOMEGA_ZIP100 ||
    340 	     product == USB_PRODUCT_IOMEGA_ZIP250)) {
    341 		sc->drive = ZIP_100;
    342 		sc->transfer_speed = UMASS_ZIP100_TRANSFER_SPEED;
    343 		sc->quirks |= NO_TEST_UNIT_READY;
    344 	}
    345 
    346 	if (vendor == USB_VENDOR_OLYMPUS &&
    347 	    product == USB_PRODUCT_OLYMPUS_C1) {
    348 		/*
    349 		 * The Olympus C-1 camera uses a different command-status
    350 		 * signature.
    351 		 */
    352 		sc->quirks |= WRONG_CSWSIG;
    353 	}
    354 
    355 	id = usbd_get_interface_descriptor(iface);
    356 	if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
    357 		return (UMATCH_NONE);
    358 
    359 	if (vendor == USB_VENDOR_SONY && id->bInterfaceSubClass == 0xff) {
    360 		/*
    361 		 * Sony DSC devices set the sub class to 0xff
    362 		 * instead of 1 (RBC). Fix that here.
    363 		 */
    364 		id->bInterfaceSubClass = UISUBCLASS_RBC;
    365 		/* They also should be able to do higher speed. */
    366 		sc->transfer_speed = 500;
    367 	}
    368 
    369 	if (vendor == USB_VENDOR_FUJIPHOTO &&
    370 	    product == USB_PRODUCT_FUJIPHOTO_MASS0100)
    371 		sc->quirks |= NO_TEST_UNIT_READY | NO_START_STOP;
    372 
    373 	sc->subclass = id->bInterfaceSubClass;
    374 	sc->protocol = id->bInterfaceProtocol;
    375 
    376 	switch (sc->subclass) {
    377 	case UISUBCLASS_SCSI:
    378 		sc->cmd_proto = CPROTO_SCSI;
    379 		break;
    380 	case UISUBCLASS_UFI:
    381 		sc->transfer_speed = UMASS_FLOPPY_TRANSFER_SPEED;
    382 		sc->cmd_proto = CPROTO_UFI;
    383 		break;
    384 	case UISUBCLASS_SFF8020I:
    385 	case UISUBCLASS_SFF8070I:
    386 	case UISUBCLASS_QIC157:
    387 		sc->cmd_proto = CPROTO_ATAPI;
    388 		break;
    389 	case UISUBCLASS_RBC:
    390 		sc->cmd_proto = CPROTO_RBC;
    391 		break;
    392 	default:
    393 		DPRINTF(UDMASS_GEN, ("%s: Unsupported command protocol %d\n",
    394 			USBDEVNAME(sc->sc_dev), id->bInterfaceSubClass));
    395 		return (UMATCH_NONE);
    396 	}
    397 
    398 	switch (sc->protocol) {
    399 	case UIPROTO_MASS_CBI:
    400 		sc->wire_proto = WPROTO_CBI;
    401 		break;
    402 	case UIPROTO_MASS_CBI_I:
    403 #if CBI_I
    404 		sc->wire_proto = WPROTO_CBI_I;
    405 #else
    406 		sc->wire_proto = WPROTO_CBI;
    407 #endif
    408 		break;
    409 	case UIPROTO_MASS_BBB:
    410 	case UIPROTO_MASS_BBB_OLD:
    411 		sc->wire_proto = WPROTO_BBB;
    412 		break;
    413 	default:
    414 		DPRINTF(UDMASS_GEN, ("%s: Unsupported wire protocol %d\n",
    415 			USBDEVNAME(sc->sc_dev), id->bInterfaceProtocol));
    416 		return (UMATCH_NONE);
    417 	}
    418 
    419 	return (UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO);
    420 }
    421 
    422 USB_MATCH(umass)
    423 {
    424 	USB_MATCH_START(umass, uaa);
    425 #if defined(__FreeBSD__)
    426 	struct umass_softc *sc = device_get_softc(self);
    427 #elif defined(__NetBSD__) || defined(__OpenBSD__)
    428 	struct umass_softc scs, *sc = &scs;
    429 	memset(sc, 0, sizeof *sc);
    430 	strcpy(sc->sc_dev.dv_xname, "umass");
    431 #endif
    432 
    433 	if (uaa->iface == NULL)
    434 		return(UMATCH_NONE);
    435 
    436 	return (umass_match_proto(sc, uaa->iface, uaa->device));
    437 }
    438 
    439 USB_ATTACH(umass)
    440 {
    441 	USB_ATTACH_START(umass, sc, uaa);
    442 	usb_interface_descriptor_t *id;
    443 	usb_endpoint_descriptor_t *ed;
    444 	const char *sSubclass, *sProto;
    445 	char devinfo[1024];
    446 	int i, bno;
    447 	int err;
    448 
    449 	/*
    450 	 * the softc struct is bzero-ed in device_set_driver. We can safely
    451 	 * call umass_detach without specifically initialising the struct.
    452 	 */
    453 
    454 	usbd_devinfo(uaa->device, 0, devinfo);
    455 	USB_ATTACH_SETUP;
    456 
    457 	sc->sc_iface = uaa->iface;
    458 	sc->sc_ifaceno = uaa->ifaceno;
    459 
    460 	/* initialise the proto and drive values in the umass_softc (again) */
    461 	if (umass_match_proto(sc, sc->sc_iface, uaa->device) == 0) {
    462 		printf("%s: match failed\n", USBDEVNAME(sc->sc_dev));
    463 		USB_ATTACH_ERROR_RETURN;
    464 	}
    465 
    466 	if (sc->drive == INSYSTEM_USBCABLE) {
    467 		err = usbd_set_interface(sc->sc_iface, 1);
    468 		if (err) {
    469 			DPRINTF(UDMASS_USB, ("%s: could not switch to "
    470 					     "Alt Interface %d\n",
    471 					     USBDEVNAME(sc->sc_dev), 1));
    472 			umass_disco(sc);
    473 			USB_ATTACH_ERROR_RETURN;
    474                 }
    475         }
    476 
    477 	/*
    478 	 * The timeout is based on the maximum expected transfer size
    479 	 * divided by the expected transfer speed.
    480 	 * We multiply by 4 to make sure a busy system doesn't make things
    481 	 * fail.
    482 	 */
    483 	sc->timeout = 4 * UMASS_MAX_TRANSFER_SIZE / sc->transfer_speed;
    484 	sc->timeout += UMASS_SPINUP_TIME;	/* allow for spinning up */
    485 #ifdef UMASS_DEBUG
    486 	printf("%s: timeout=%d ms\n", USBDEVNAME(sc->sc_dev), sc->timeout);
    487 #endif
    488 
    489 	id = usbd_get_interface_descriptor(sc->sc_iface);
    490 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
    491 
    492 	switch (sc->subclass) {
    493 	case UISUBCLASS_RBC:
    494 		sSubclass = "RBC";
    495 		break;
    496 	case UISUBCLASS_SCSI:
    497 		sSubclass = "SCSI";
    498 		break;
    499 	case UISUBCLASS_UFI:
    500 		sSubclass = "UFI";
    501 		break;
    502 	case UISUBCLASS_SFF8020I:
    503 		sSubclass = "SFF8020i";
    504 		break;
    505 	case UISUBCLASS_SFF8070I:
    506 		sSubclass = "SFF8070i";
    507 		break;
    508 	case UISUBCLASS_QIC157:
    509 		sSubclass = "QIC157";
    510 		break;
    511 	default:
    512 		sSubclass = "unknown";
    513 		break;
    514 	}
    515 	switch (sc->protocol) {
    516 	case UIPROTO_MASS_CBI:
    517 		sProto = "CBI";
    518 		break;
    519 	case UIPROTO_MASS_CBI_I:
    520 		sProto = "CBI-I";
    521 		break;
    522 	case UIPROTO_MASS_BBB:
    523 	case UIPROTO_MASS_BBB_OLD:
    524 		sProto = "BBB";
    525 		break;
    526 	default:
    527 		sProto = "unknown";
    528 		break;
    529 	}
    530 	printf("%s: using %s over %s\n", USBDEVNAME(sc->sc_dev), sSubclass,
    531 	       sProto);
    532 
    533 	/*
    534 	 * In addition to the Control endpoint the following endpoints
    535 	 * are required:
    536 	 * a) bulk-in endpoint.
    537 	 * b) bulk-out endpoint.
    538 	 * and for Control/Bulk/Interrupt with CCI (CBI_I)
    539 	 * c) intr-in
    540 	 *
    541 	 * The endpoint addresses are not fixed, so we have to read them
    542 	 * from the device descriptors of the current interface.
    543 	 */
    544 	for (i = 0 ; i < id->bNumEndpoints ; i++) {
    545 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
    546 		if (!ed) {
    547 			printf("%s: could not read endpoint descriptor\n",
    548 			       USBDEVNAME(sc->sc_dev));
    549 			USB_ATTACH_ERROR_RETURN;
    550 		}
    551 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
    552 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    553 			sc->sc_epaddr[UMASS_BULKIN] = ed->bEndpointAddress;
    554 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT
    555 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_BULK) {
    556 			sc->sc_epaddr[UMASS_BULKOUT] = ed->bEndpointAddress;
    557 		} else if (sc->wire_proto == WPROTO_CBI_I
    558 		    && UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN
    559 		    && (ed->bmAttributes & UE_XFERTYPE) == UE_INTERRUPT) {
    560 			sc->sc_epaddr[UMASS_INTRIN] = ed->bEndpointAddress;
    561 #ifdef UMASS_DEBUG
    562 			if (UGETW(ed->wMaxPacketSize) > 2) {
    563 				DPRINTF(UDMASS_CBI, ("%s: intr size is %d\n",
    564 					USBDEVNAME(sc->sc_dev),
    565 					UGETW(ed->wMaxPacketSize)));
    566 			}
    567 #endif
    568 		}
    569 	}
    570 
    571 	/* check whether we found all the endpoints we need */
    572 	if (!sc->sc_epaddr[UMASS_BULKIN] || !sc->sc_epaddr[UMASS_BULKOUT] ||
    573 	    (sc->wire_proto == WPROTO_CBI_I && !sc->sc_epaddr[UMASS_INTRIN]) ) {
    574 		DPRINTF(UDMASS_USB, ("%s: endpoint not found %u/%u/%u\n",
    575 			USBDEVNAME(sc->sc_dev), sc->sc_epaddr[UMASS_BULKIN],
    576 			sc->sc_epaddr[UMASS_BULKOUT],
    577 			sc->sc_epaddr[UMASS_INTRIN]));
    578 		umass_disco(sc);
    579 		USB_ATTACH_ERROR_RETURN;
    580 	}
    581 
    582 	/*
    583 	 * Get the maximum LUN supported by the device.
    584 	 */
    585 	if (sc->wire_proto == WPROTO_BBB) {
    586 		err = umass_bbb_get_max_lun(sc, &sc->maxlun);
    587 		if (err) {
    588 			printf("%s: unable to get Max Lun: %s\n",
    589 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
    590 			USB_ATTACH_ERROR_RETURN;
    591 		}
    592 	} else {
    593 		sc->maxlun = 0;
    594 	}
    595 
    596 	/* Open the bulk-in and -out pipe */
    597 	err = usbd_open_pipe(sc->sc_iface, sc->sc_epaddr[UMASS_BULKOUT],
    598 				USBD_EXCLUSIVE_USE,
    599 				&sc->sc_pipe[UMASS_BULKOUT]);
    600 	if (err) {
    601 		DPRINTF(UDMASS_USB, ("%s: cannot open %u-out pipe (bulk)\n",
    602 			USBDEVNAME(sc->sc_dev), sc->sc_epaddr[UMASS_BULKOUT]));
    603 		umass_disco(sc);
    604 		USB_ATTACH_ERROR_RETURN;
    605 	}
    606 	err = usbd_open_pipe(sc->sc_iface, sc->sc_epaddr[UMASS_BULKIN],
    607 				USBD_EXCLUSIVE_USE, &sc->sc_pipe[UMASS_BULKIN]);
    608 	if (err) {
    609 		DPRINTF(UDMASS_USB, ("%s: could not open %u-in pipe (bulk)\n",
    610 			USBDEVNAME(sc->sc_dev), sc->sc_epaddr[UMASS_BULKIN]));
    611 		umass_disco(sc);
    612 		USB_ATTACH_ERROR_RETURN;
    613 	}
    614 	/*
    615 	 * Open the intr-in pipe if the protocol is CBI with CCI.
    616 	 * Note: early versions of the Zip drive do have an interrupt pipe, but
    617 	 * this pipe is unused
    618 	 *
    619 	 * We do not open the interrupt pipe as an interrupt pipe, but as a
    620 	 * normal bulk endpoint. We send an IN transfer down the wire at the
    621 	 * appropriate time, because we know exactly when to expect data on
    622 	 * that endpoint. This saves bandwidth, but more important, makes the
    623 	 * code for handling the data on that endpoint simpler. No data
    624 	 * arriving concurrently.
    625 	 */
    626 	if (sc->wire_proto == WPROTO_CBI_I) {
    627 		err = usbd_open_pipe(sc->sc_iface, sc->sc_epaddr[UMASS_INTRIN],
    628 				USBD_EXCLUSIVE_USE, &sc->sc_pipe[UMASS_INTRIN]);
    629 		if (err) {
    630 			DPRINTF(UDMASS_USB, ("%s: couldn't open %u-in (intr)\n",
    631 				USBDEVNAME(sc->sc_dev),
    632 				sc->sc_epaddr[UMASS_INTRIN]));
    633 			umass_disco(sc);
    634 			USB_ATTACH_ERROR_RETURN;
    635 		}
    636 	}
    637 
    638 	/* initialisation of generic part */
    639 	sc->transfer_state = TSTATE_IDLE;
    640 
    641 	/* request a sufficient number of xfer handles */
    642 	for (i = 0; i < XFER_NR; i++) {
    643 		sc->transfer_xfer[i] = usbd_alloc_xfer(uaa->device);
    644 		if (sc->transfer_xfer[i] == 0) {
    645 			DPRINTF(UDMASS_USB, ("%s: Out of memory\n",
    646 				USBDEVNAME(sc->sc_dev)));
    647 			umass_disco(sc);
    648 			USB_ATTACH_ERROR_RETURN;
    649 		}
    650 	}
    651 	/* Allocate buffer for data transfer (it's huge). */
    652 	switch (sc->wire_proto) {
    653 	case WPROTO_BBB:
    654 		bno = XFER_BBB_DATA;
    655 		goto dalloc;
    656 	case WPROTO_CBI:
    657 		bno = XFER_CBI_DATA;
    658 		goto dalloc;
    659 	case WPROTO_CBI_I:
    660 		bno = XFER_CBI_DATA;
    661 	dalloc:
    662 		sc->data_buffer = usbd_alloc_buffer(sc->transfer_xfer[bno],
    663 						    UMASS_MAX_TRANSFER_SIZE);
    664 		if (sc->data_buffer == NULL) {
    665 			umass_disco(sc);
    666 			USB_ATTACH_ERROR_RETURN;
    667 		}
    668 		break;
    669 	default:
    670 		break;
    671 	}
    672 
    673 	/* Initialise the wire protocol specific methods */
    674 	if (sc->wire_proto == WPROTO_BBB) {
    675 		sc->sc_methods = &umass_bbb_methods;
    676 	} else if (sc->wire_proto == WPROTO_CBI ||
    677 		   sc->wire_proto == WPROTO_CBI_I) {
    678 		sc->sc_methods = &umass_cbi_methods;
    679 #ifdef UMASS_DEBUG
    680 	} else {
    681 		panic("%s:%d: Unknown wire proto 0x%02x\n",
    682 		      __FILE__, __LINE__, sc->wire_proto);
    683 #endif
    684 	}
    685 
    686 	if (sc->drive == SHUTTLE_EUSB)
    687 		umass_init_shuttle(sc);
    688 
    689 	if (umass_attach_bus(sc)) {
    690 		DPRINTF(UDMASS_GEN, ("%s: bus attach failed\n",
    691 				     USBDEVNAME(sc->sc_dev)));
    692 		umass_disco(sc);
    693 		USB_ATTACH_ERROR_RETURN;
    694 	}
    695 
    696 	DPRINTF(UDMASS_GEN, ("%s: Attach finished\n", USBDEVNAME(sc->sc_dev)));
    697 
    698 	USB_ATTACH_SUCCESS_RETURN;
    699 }
    700 
    701 USB_DETACH(umass)
    702 {
    703 	USB_DETACH_START(umass, sc);
    704 	int rv = 0, i;
    705 
    706 	DPRINTF(UDMASS_USB, ("%s: detached\n", USBDEVNAME(sc->sc_dev)));
    707 
    708 	/* Abort the pipes to wake up any waiting processes. */
    709 	for (i = 0 ; i < UMASS_NEP ; i++) {
    710 		if (sc->sc_pipe[i] != NULL)
    711 			usbd_abort_pipe(sc->sc_pipe[i]);
    712 	}
    713 
    714 #if 0
    715 	/* Do we really need reference counting?  Perhaps in ioctl() */
    716 	s = splusb();
    717 	if (--sc->sc_refcnt >= 0) {
    718 		/* Wait for processes to go away. */
    719 		usb_detach_wait(USBDEV(sc->sc_dev));
    720 	}
    721 	splx(s);
    722 #endif
    723 
    724 	rv = umass_detach_bus(sc, flags);
    725 
    726 	if (rv != 0)
    727 		return (rv);
    728 
    729 	umass_disco(sc);
    730 
    731 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    732 			   USBDEV(sc->sc_dev));
    733 
    734 	return (0);
    735 }
    736 
    737 Static void
    738 umass_disco(struct umass_softc *sc)
    739 {
    740 	int i;
    741 
    742 	DPRINTF(UDMASS_GEN, ("umass_disco\n"));
    743 
    744 	/* Free the xfers. */
    745 	for (i = 0; i < XFER_NR; i++)
    746 		if (sc->transfer_xfer[i] != NULL) {
    747 			usbd_free_xfer(sc->transfer_xfer[i]);
    748 			sc->transfer_xfer[i] = NULL;
    749 		}
    750 
    751 	/* Remove all the pipes. */
    752 	for (i = 0 ; i < UMASS_NEP ; i++) {
    753 		if (sc->sc_pipe[i] != NULL)
    754 			usbd_close_pipe(sc->sc_pipe[i]);
    755 	}
    756 }
    757 
    758 Static void
    759 umass_init_shuttle(struct umass_softc *sc)
    760 {
    761 	usb_device_request_t req;
    762 	u_char status[2];
    763 
    764 	/* The Linux driver does this */
    765 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
    766 	req.bRequest = 1;
    767 	USETW(req.wValue, 0);
    768 	USETW(req.wIndex, sc->sc_ifaceno);
    769 	USETW(req.wLength, sizeof status);
    770 	(void)usbd_do_request(sc->sc_udev, &req, &status);
    771 }
    772 
    773 /*
    774  * Generic functions to handle transfers
    775  */
    776 
    777 Static usbd_status
    778 umass_setup_transfer(struct umass_softc *sc, usbd_pipe_handle pipe,
    779 			void *buffer, int buflen, int flags,
    780 			usbd_xfer_handle xfer)
    781 {
    782 	usbd_status err;
    783 
    784 	if (sc->sc_dying)
    785 		return (USBD_IOERROR);
    786 
    787 	/* Initialiase a USB transfer and then schedule it */
    788 
    789 	usbd_setup_xfer(xfer, pipe, (void *)sc, buffer, buflen,
    790 	    flags | sc->sc_xfer_flags, sc->timeout, sc->sc_methods->wire_state);
    791 
    792 	err = usbd_transfer(xfer);
    793 	DPRINTF(UDMASS_XFER,("%s: start xfer buffer=%p buflen=%d flags=0x%x "
    794 	    "timeout=%d\n", USBDEVNAME(sc->sc_dev),
    795 	    buffer, buflen, flags | sc->sc_xfer_flags, sc->timeout));
    796 	if (err && err != USBD_IN_PROGRESS) {
    797 		DPRINTF(UDMASS_BBB, ("%s: failed to setup transfer, %s\n",
    798 			USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
    799 		return (err);
    800 	}
    801 
    802 	return (USBD_NORMAL_COMPLETION);
    803 }
    804 
    805 
    806 Static usbd_status
    807 umass_setup_ctrl_transfer(struct umass_softc *sc, usb_device_request_t *req,
    808 	 void *buffer, int buflen, int flags, usbd_xfer_handle xfer)
    809 {
    810 	usbd_status err;
    811 
    812 	if (sc->sc_dying)
    813 		return (USBD_IOERROR);
    814 
    815 	/* Initialiase a USB control transfer and then schedule it */
    816 
    817 	usbd_setup_default_xfer(xfer, sc->sc_udev, (void *) sc, sc->timeout,
    818 		req, buffer, buflen, flags, sc->sc_methods->wire_state);
    819 
    820 	err = usbd_transfer(xfer);
    821 	if (err && err != USBD_IN_PROGRESS) {
    822 		DPRINTF(UDMASS_BBB, ("%s: failed to setup ctrl transfer, %s\n",
    823 			 USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
    824 
    825 		/* do not reset, as this would make us loop */
    826 		return (err);
    827 	}
    828 
    829 	return (USBD_NORMAL_COMPLETION);
    830 }
    831 
    832 Static void
    833 umass_clear_endpoint_stall(struct umass_softc *sc, int endpt,
    834 	usbd_xfer_handle xfer)
    835 {
    836 	if (sc->sc_dying)
    837 		return;
    838 
    839 	DPRINTF(UDMASS_BBB, ("%s: Clear endpoint 0x%02x stall\n",
    840 		USBDEVNAME(sc->sc_dev), endpt));
    841 
    842 	usbd_clear_endpoint_toggle(sc->sc_pipe[endpt]);
    843 
    844 	sc->request.bmRequestType = UT_WRITE_ENDPOINT;
    845 	sc->request.bRequest = UR_CLEAR_FEATURE;
    846 	USETW(sc->request.wValue, UF_ENDPOINT_HALT);
    847 	USETW(sc->request.wIndex, sc->sc_epaddr[endpt]);
    848 	USETW(sc->request.wLength, 0);
    849 	umass_setup_ctrl_transfer(sc, &sc->request, NULL, 0, 0, xfer);
    850 }
    851 
    852 #if 0
    853 Static void
    854 umass_reset(struct umass_softc *sc, transfer_cb_f cb, void *priv)
    855 {
    856 	sc->transfer_cb = cb;
    857 	sc->transfer_priv = priv;
    858 
    859 	/* The reset is a forced reset, so no error (yet) */
    860 	sc->reset(sc, STATUS_CMD_OK);
    861 }
    862 #endif
    863 
    864 /*
    865  * Bulk protocol specific functions
    866  */
    867 
    868 Static void
    869 umass_bbb_reset(struct umass_softc *sc, int status)
    870 {
    871 	KASSERT(sc->proto & PROTO_BBB,
    872 		("sc->proto == 0x%02x wrong for umass_bbb_reset\n", sc->proto));
    873 
    874 	if (sc->sc_dying)
    875 		return;
    876 
    877 	/*
    878 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
    879 	 *
    880 	 * For Reset Recovery the host shall issue in the following order:
    881 	 * a) a Bulk-Only Mass Storage Reset
    882 	 * b) a Clear Feature HALT to the Bulk-In endpoint
    883 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
    884 	 *
    885 	 * This is done in 3 steps, states:
    886 	 * TSTATE_BBB_RESET1
    887 	 * TSTATE_BBB_RESET2
    888 	 * TSTATE_BBB_RESET3
    889 	 *
    890 	 * If the reset doesn't succeed, the device should be port reset.
    891 	 */
    892 
    893 	DPRINTF(UDMASS_BBB, ("%s: Bulk Reset\n",
    894 		USBDEVNAME(sc->sc_dev)));
    895 
    896 	sc->transfer_state = TSTATE_BBB_RESET1;
    897 	sc->transfer_status = status;
    898 
    899 	/* reset is a class specific interface write */
    900 	sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    901 	sc->request.bRequest = UR_BBB_RESET;
    902 	USETW(sc->request.wValue, 0);
    903 	USETW(sc->request.wIndex, sc->sc_ifaceno);
    904 	USETW(sc->request.wLength, 0);
    905 	umass_setup_ctrl_transfer(sc, &sc->request, NULL, 0, 0,
    906 				  sc->transfer_xfer[XFER_BBB_RESET1]);
    907 }
    908 
    909 Static void
    910 umass_bbb_transfer(struct umass_softc *sc, int lun, void *cmd, int cmdlen,
    911 		   void *data, int datalen, int dir, u_int timeout,
    912 		   umass_callback cb, void *priv)
    913 {
    914 	static int dCBWtag = 42;	/* unique for CBW of transfer */
    915 
    916 	DPRINTF(UDMASS_BBB,("%s: umass_bbb_transfer cmd=0x%02x\n",
    917 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd));
    918 
    919 	KASSERT(sc->proto & PROTO_BBB,
    920 		("sc->proto == 0x%02x wrong for umass_bbb_transfer\n",
    921 		sc->proto));
    922 
    923 	/* Be a little generous. */
    924 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
    925 
    926 	/*
    927 	 * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
    928 	 * a data phase of datalen bytes from/to the device and finally a
    929 	 * csw read phase.
    930 	 * If the data direction was inbound a maximum of datalen bytes
    931 	 * is stored in the buffer pointed to by data.
    932 	 *
    933 	 * umass_bbb_transfer initialises the transfer and lets the state
    934 	 * machine in umass_bbb_state handle the completion. It uses the
    935 	 * following states:
    936 	 * TSTATE_BBB_COMMAND
    937 	 *   -> TSTATE_BBB_DATA
    938 	 *   -> TSTATE_BBB_STATUS
    939 	 *   -> TSTATE_BBB_STATUS2
    940 	 *   -> TSTATE_BBB_IDLE
    941 	 *
    942 	 * An error in any of those states will invoke
    943 	 * umass_bbb_reset.
    944 	 */
    945 
    946 	/* check the given arguments */
    947 	KASSERT(datalen == 0 || data != NULL,
    948 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
    949 	KASSERT(cmdlen <= CBWCDBLENGTH,
    950 		("%s: cmdlen exceeds CDB length in CBW (%d > %d)",
    951 			USBDEVNAME(sc->sc_dev), cmdlen, CBWCDBLENGTH));
    952 	KASSERT(dir == DIR_NONE || datalen > 0,
    953 		("%s: datalen == 0 while direction is not NONE\n",
    954 			USBDEVNAME(sc->sc_dev)));
    955 	KASSERT(datalen == 0 || dir != DIR_NONE,
    956 		("%s: direction is NONE while datalen is not zero\n",
    957 			USBDEVNAME(sc->sc_dev)));
    958 	KASSERT(sizeof(umass_bbb_cbw_t) == UMASS_BBB_CBW_SIZE,
    959 		("%s: CBW struct does not have the right size (%d vs. %d)\n",
    960 			USBDEVNAME(sc->sc_dev),
    961 			sizeof(umass_bbb_cbw_t), UMASS_BBB_CBW_SIZE));
    962 	KASSERT(sizeof(umass_bbb_csw_t) == UMASS_BBB_CSW_SIZE,
    963 		("%s: CSW struct does not have the right size (%d vs. %d)\n",
    964 			USBDEVNAME(sc->sc_dev),
    965 			sizeof(umass_bbb_csw_t), UMASS_BBB_CSW_SIZE));
    966 
    967 	/*
    968 	 * Determine the direction of the data transfer and the length.
    969 	 *
    970 	 * dCBWDataTransferLength (datalen) :
    971 	 *   This field indicates the number of bytes of data that the host
    972 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
    973 	 *   the Direction bit) during the execution of this command. If this
    974 	 *   field is set to 0, the device will expect that no data will be
    975 	 *   transferred IN or OUT during this command, regardless of the value
    976 	 *   of the Direction bit defined in dCBWFlags.
    977 	 *
    978 	 * dCBWFlags (dir) :
    979 	 *   The bits of the Flags field are defined as follows:
    980 	 *     Bits 0-6	 reserved
    981 	 *     Bit  7	 Direction - this bit shall be ignored if the
    982 	 *			     dCBWDataTransferLength field is zero.
    983 	 *		 0 = data Out from host to device
    984 	 *		 1 = data In from device to host
    985 	 */
    986 
    987 	/* Fill in the Command Block Wrapper */
    988 	USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
    989 	USETDW(sc->cbw.dCBWTag, dCBWtag);
    990 	dCBWtag++;	/* cannot be done in macro (it will be done 4 times) */
    991 	USETDW(sc->cbw.dCBWDataTransferLength, datalen);
    992 	/* DIR_NONE is treated as DIR_OUT (0x00) */
    993 	sc->cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
    994 	sc->cbw.bCBWLUN = lun;
    995 	sc->cbw.bCDBLength = cmdlen;
    996 	memcpy(sc->cbw.CBWCDB, cmd, cmdlen);
    997 
    998 	DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
    999 
   1000 	/* store the details for the data transfer phase */
   1001 	sc->transfer_dir = dir;
   1002 	sc->transfer_data = data;
   1003 	sc->transfer_datalen = datalen;
   1004 	sc->transfer_actlen = 0;
   1005 	sc->transfer_cb = cb;
   1006 	sc->transfer_priv = priv;
   1007 	sc->transfer_status = STATUS_CMD_OK;
   1008 
   1009 	/* move from idle to the command state */
   1010 	sc->transfer_state = TSTATE_BBB_COMMAND;
   1011 
   1012 	/* Send the CBW from host to device via bulk-out endpoint. */
   1013 	if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
   1014 			&sc->cbw, UMASS_BBB_CBW_SIZE, 0,
   1015 			sc->transfer_xfer[XFER_BBB_CBW])) {
   1016 		umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1017 	}
   1018 }
   1019 
   1020 
   1021 Static void
   1022 umass_bbb_state(usbd_xfer_handle xfer, usbd_private_handle priv,
   1023 		usbd_status err)
   1024 {
   1025 	struct umass_softc *sc = (struct umass_softc *) priv;
   1026 	usbd_xfer_handle next_xfer;
   1027 
   1028 	KASSERT(sc->proto & PROTO_BBB,
   1029 		("sc->proto == 0x%02x wrong for umass_bbb_state\n",sc->proto));
   1030 
   1031 	if (sc->sc_dying)
   1032 		return;
   1033 
   1034 	/*
   1035 	 * State handling for BBB transfers.
   1036 	 *
   1037 	 * The subroutine is rather long. It steps through the states given in
   1038 	 * Annex A of the Bulk-Only specification.
   1039 	 * Each state first does the error handling of the previous transfer
   1040 	 * and then prepares the next transfer.
   1041 	 * Each transfer is done asynchroneously so after the request/transfer
   1042 	 * has been submitted you will find a 'return;'.
   1043 	 */
   1044 
   1045 	DPRINTF(UDMASS_BBB, ("%s: Handling BBB state %d (%s), xfer=%p, %s\n",
   1046 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
   1047 		states[sc->transfer_state], xfer, usbd_errstr(err)));
   1048 
   1049 	switch (sc->transfer_state) {
   1050 
   1051 	/***** Bulk Transfer *****/
   1052 	case TSTATE_BBB_COMMAND:
   1053 		/* Command transport phase, error handling */
   1054 		if (err) {
   1055 			DPRINTF(UDMASS_BBB, ("%s: failed to send CBW\n",
   1056 				USBDEVNAME(sc->sc_dev)));
   1057 			/* If the device detects that the CBW is invalid, then
   1058 			 * the device may STALL both bulk endpoints and require
   1059 			 * a Bulk-Reset
   1060 			 */
   1061 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1062 			return;
   1063 		}
   1064 
   1065 		/* Data transport phase, setup transfer */
   1066 		sc->transfer_state = TSTATE_BBB_DATA;
   1067 		if (sc->transfer_dir == DIR_IN) {
   1068 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1069 					sc->data_buffer, sc->transfer_datalen,
   1070 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
   1071 					sc->transfer_xfer[XFER_BBB_DATA]))
   1072 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1073 
   1074 			return;
   1075 		} else if (sc->transfer_dir == DIR_OUT) {
   1076 			memcpy(sc->data_buffer, sc->transfer_data,
   1077 			       sc->transfer_datalen);
   1078 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
   1079 					sc->data_buffer, sc->transfer_datalen,
   1080 					USBD_NO_COPY,/* fixed length transfer */
   1081 					sc->transfer_xfer[XFER_BBB_DATA]))
   1082 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1083 
   1084 			return;
   1085 		} else {
   1086 			DPRINTF(UDMASS_BBB, ("%s: no data phase\n",
   1087 				USBDEVNAME(sc->sc_dev)));
   1088 		}
   1089 
   1090 		/* FALLTHROUGH if no data phase, err == 0 */
   1091 	case TSTATE_BBB_DATA:
   1092 		/* Command transport phase, error handling (ignored if no data
   1093 		 * phase (fallthrough from previous state)) */
   1094 		if (sc->transfer_dir != DIR_NONE) {
   1095 			/* retrieve the length of the transfer that was done */
   1096 			usbd_get_xfer_status(xfer, NULL, NULL,
   1097 					     &sc->transfer_actlen, NULL);
   1098 
   1099 			if (err) {
   1100 				DPRINTF(UDMASS_BBB, ("%s: Data-%s %d failed, "
   1101 					"%s\n", USBDEVNAME(sc->sc_dev),
   1102 					(sc->transfer_dir == DIR_IN?"in":"out"),
   1103 					sc->transfer_datalen,usbd_errstr(err)));
   1104 
   1105 				if (err == USBD_STALLED) {
   1106 					sc->transfer_state = TSTATE_BBB_DCLEAR;
   1107 					umass_clear_endpoint_stall(sc,
   1108 					  (sc->transfer_dir == DIR_IN?
   1109 					    UMASS_BULKIN:UMASS_BULKOUT),
   1110 					  sc->transfer_xfer[XFER_BBB_DCLEAR]);
   1111 					return;
   1112 				} else {
   1113 					/* Unless the error is a pipe stall the
   1114 					 * error is fatal.
   1115 					 */
   1116 					umass_bbb_reset(sc,STATUS_WIRE_FAILED);
   1117 					return;
   1118 				}
   1119 			}
   1120 		}
   1121 
   1122 		if (sc->transfer_dir == DIR_IN)
   1123 			memcpy(sc->transfer_data, sc->data_buffer,
   1124 			       sc->transfer_actlen);
   1125 
   1126 		DIF(UDMASS_BBB, if (sc->transfer_dir == DIR_IN)
   1127 					umass_dump_buffer(sc, sc->transfer_data,
   1128 						sc->transfer_datalen, 48));
   1129 
   1130 		/* FALLTHROUGH, err == 0 (no data phase or successfull) */
   1131 	case TSTATE_BBB_DCLEAR: /* stall clear after data phase */
   1132 	case TSTATE_BBB_SCLEAR: /* stall clear after status phase */
   1133 		/* Reading of CSW after bulk stall condition in data phase
   1134 		 * (TSTATE_BBB_DATA2) or bulk-in stall condition after
   1135 		 * reading CSW (TSTATE_BBB_SCLEAR).
   1136 		 * In the case of no data phase or successfull data phase,
   1137 		 * err == 0 and the following if block is passed.
   1138 		 */
   1139 		if (err) {	/* should not occur */
   1140 			/* try the transfer below, even if clear stall failed */
   1141 			DPRINTF(UDMASS_BBB, ("%s: bulk-%s stall clear failed"
   1142 				", %s\n", USBDEVNAME(sc->sc_dev),
   1143 				(sc->transfer_dir == DIR_IN? "in":"out"),
   1144 				usbd_errstr(err)));
   1145 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1146 			return;
   1147 		}
   1148 
   1149 		/* Status transport phase, setup transfer */
   1150 		if (sc->transfer_state == TSTATE_BBB_COMMAND ||
   1151 		    sc->transfer_state == TSTATE_BBB_DATA ||
   1152 		    sc->transfer_state == TSTATE_BBB_DCLEAR) {
   1153 			/* After no data phase, successfull data phase and
   1154 			 * after clearing bulk-in/-out stall condition
   1155 			 */
   1156 			sc->transfer_state = TSTATE_BBB_STATUS1;
   1157 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW1];
   1158 		} else {
   1159 			/* After first attempt of fetching CSW */
   1160 			sc->transfer_state = TSTATE_BBB_STATUS2;
   1161 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW2];
   1162 		}
   1163 
   1164 		/* Read the Command Status Wrapper via bulk-in endpoint. */
   1165 		if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1166 			&sc->csw, UMASS_BBB_CSW_SIZE, 0, next_xfer)) {
   1167 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1168 			return;
   1169 		}
   1170 
   1171 		return;
   1172 	case TSTATE_BBB_STATUS1:	/* first attempt */
   1173 	case TSTATE_BBB_STATUS2:	/* second attempt */
   1174 		/* Status transfer, error handling */
   1175 		if (err) {
   1176 			DPRINTF(UDMASS_BBB, ("%s: Failed to read CSW, %s%s\n",
   1177 				USBDEVNAME(sc->sc_dev), usbd_errstr(err),
   1178 				(sc->transfer_state == TSTATE_BBB_STATUS1?
   1179 					", retrying":"")));
   1180 
   1181 			/* If this was the first attempt at fetching the CSW
   1182 			 * retry it, otherwise fail.
   1183 			 */
   1184 			if (sc->transfer_state == TSTATE_BBB_STATUS1) {
   1185 				sc->transfer_state = TSTATE_BBB_SCLEAR;
   1186 				umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1187 				    sc->transfer_xfer[XFER_BBB_SCLEAR]);
   1188 				return;
   1189 			} else {
   1190 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1191 				return;
   1192 			}
   1193 		}
   1194 
   1195 		DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
   1196 
   1197 		/* Translate weird command-status signatures. */
   1198 		if ((sc->quirks & WRONG_CSWSIG) &&
   1199 		    UGETDW(sc->csw.dCSWSignature) == CSWSIGNATURE_OLYMPUS_C1)
   1200 			USETDW(sc->csw.dCSWSignature, CSWSIGNATURE);
   1201 
   1202 		/* Check CSW and handle any error */
   1203 		if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
   1204 			/* Invalid CSW: Wrong signature or wrong tag might
   1205 			 * indicate that the device is confused -> reset it.
   1206 			 */
   1207 			printf("%s: Invalid CSW: sig 0x%08x should be 0x%08x\n",
   1208 				USBDEVNAME(sc->sc_dev),
   1209 				UGETDW(sc->csw.dCSWSignature),
   1210 				CSWSIGNATURE);
   1211 
   1212 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1213 			return;
   1214 		} else if (UGETDW(sc->csw.dCSWTag)
   1215 				!= UGETDW(sc->cbw.dCBWTag)) {
   1216 			printf("%s: Invalid CSW: tag %d should be %d\n",
   1217 				USBDEVNAME(sc->sc_dev),
   1218 				UGETDW(sc->csw.dCSWTag),
   1219 				UGETDW(sc->cbw.dCBWTag));
   1220 
   1221 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1222 			return;
   1223 
   1224 		/* CSW is valid here */
   1225 		} else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
   1226 			printf("%s: Invalid CSW: status %d > %d\n",
   1227 				USBDEVNAME(sc->sc_dev),
   1228 				sc->csw.bCSWStatus,
   1229 				CSWSTATUS_PHASE);
   1230 
   1231 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1232 			return;
   1233 		} else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
   1234 			printf("%s: Phase Error, residue = %d\n",
   1235 				USBDEVNAME(sc->sc_dev),
   1236 				UGETDW(sc->csw.dCSWDataResidue));
   1237 
   1238 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1239 			return;
   1240 
   1241 		} else if (sc->transfer_actlen > sc->transfer_datalen) {
   1242 			/* Buffer overrun! Don't let this go by unnoticed */
   1243 			panic("%s: transferred %d bytes instead of %d bytes\n",
   1244 				USBDEVNAME(sc->sc_dev),
   1245 				sc->transfer_actlen, sc->transfer_datalen);
   1246 #if 0
   1247 		} else if (sc->transfer_datalen - sc->transfer_actlen
   1248 			   != UGETDW(sc->csw.dCSWDataResidue)) {
   1249 			DPRINTF(UDMASS_BBB, ("%s: actlen=%d != residue=%d\n",
   1250 				USBDEVNAME(sc->sc_dev),
   1251 				sc->transfer_datalen - sc->transfer_actlen,
   1252 				UGETDW(sc->csw.dCSWDataResidue)));
   1253 
   1254 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1255 			return;
   1256 #endif
   1257 		} else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
   1258 			DPRINTF(UDMASS_BBB, ("%s: Command Failed, res = %d\n",
   1259 				USBDEVNAME(sc->sc_dev),
   1260 				UGETDW(sc->csw.dCSWDataResidue)));
   1261 
   1262 			/* SCSI command failed but transfer was succesful */
   1263 			sc->transfer_state = TSTATE_IDLE;
   1264 			sc->transfer_cb(sc, sc->transfer_priv,
   1265 					UGETDW(sc->csw.dCSWDataResidue),
   1266 					STATUS_CMD_FAILED);
   1267 
   1268 			return;
   1269 
   1270 		} else {	/* success */
   1271 			sc->transfer_state = TSTATE_IDLE;
   1272 			sc->transfer_cb(sc, sc->transfer_priv,
   1273 					UGETDW(sc->csw.dCSWDataResidue),
   1274 					STATUS_CMD_OK);
   1275 
   1276 			return;
   1277 		}
   1278 
   1279 	/***** Bulk Reset *****/
   1280 	case TSTATE_BBB_RESET1:
   1281 		if (err)
   1282 			printf("%s: BBB reset failed, %s\n",
   1283 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1284 
   1285 		sc->transfer_state = TSTATE_BBB_RESET2;
   1286 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1287 			sc->transfer_xfer[XFER_BBB_RESET2]);
   1288 
   1289 		return;
   1290 	case TSTATE_BBB_RESET2:
   1291 		if (err)	/* should not occur */
   1292 			printf("%s: BBB bulk-in clear stall failed, %s\n",
   1293 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1294 			/* no error recovery, otherwise we end up in a loop */
   1295 
   1296 		sc->transfer_state = TSTATE_BBB_RESET3;
   1297 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
   1298 			sc->transfer_xfer[XFER_BBB_RESET3]);
   1299 
   1300 		return;
   1301 	case TSTATE_BBB_RESET3:
   1302 		if (err)	/* should not occur */
   1303 			printf("%s: BBB bulk-out clear stall failed, %s\n",
   1304 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1305 			/* no error recovery, otherwise we end up in a loop */
   1306 
   1307 		sc->transfer_state = TSTATE_IDLE;
   1308 		if (sc->transfer_priv) {
   1309 			sc->transfer_cb(sc, sc->transfer_priv,
   1310 					sc->transfer_datalen,
   1311 					sc->transfer_status);
   1312 		}
   1313 
   1314 		return;
   1315 
   1316 	/***** Default *****/
   1317 	default:
   1318 		panic("%s: Unknown state %d\n",
   1319 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
   1320 	}
   1321 }
   1322 
   1323 /*
   1324  * Command/Bulk/Interrupt (CBI) specific functions
   1325  */
   1326 
   1327 Static int
   1328 umass_cbi_adsc(struct umass_softc *sc, char *buffer, int buflen,
   1329 	       usbd_xfer_handle xfer)
   1330 {
   1331 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1332 		("sc->proto == 0x%02x wrong for umass_cbi_adsc\n",sc->proto));
   1333 
   1334 	sc->request.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   1335 	sc->request.bRequest = UR_CBI_ADSC;
   1336 	USETW(sc->request.wValue, 0);
   1337 	USETW(sc->request.wIndex, sc->sc_ifaceno);
   1338 	USETW(sc->request.wLength, buflen);
   1339 	return umass_setup_ctrl_transfer(sc, &sc->request, buffer,
   1340 					 buflen, 0, xfer);
   1341 }
   1342 
   1343 
   1344 Static void
   1345 umass_cbi_reset(struct umass_softc *sc, int status)
   1346 {
   1347 	int i;
   1348 #	define SEND_DIAGNOSTIC_CMDLEN	12
   1349 
   1350 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1351 		("sc->proto == 0x%02x wrong for umass_cbi_reset\n",sc->proto));
   1352 
   1353 	if (sc->sc_dying)
   1354 		return;
   1355 
   1356 	/*
   1357 	 * Command Block Reset Protocol
   1358 	 *
   1359 	 * First send a reset request to the device. Then clear
   1360 	 * any possibly stalled bulk endpoints.
   1361 
   1362 	 * This is done in 3 steps, states:
   1363 	 * TSTATE_CBI_RESET1
   1364 	 * TSTATE_CBI_RESET2
   1365 	 * TSTATE_CBI_RESET3
   1366 	 *
   1367 	 * If the reset doesn't succeed, the device should be port reset.
   1368 	 */
   1369 
   1370 	DPRINTF(UDMASS_CBI, ("%s: CBI Reset\n",
   1371 		USBDEVNAME(sc->sc_dev)));
   1372 
   1373 	KASSERT(sizeof(sc->cbl) >= SEND_DIAGNOSTIC_CMDLEN,
   1374 		("%s: CBL struct is too small (%d < %d)\n",
   1375 			USBDEVNAME(sc->sc_dev),
   1376 			sizeof(sc->cbl), SEND_DIAGNOSTIC_CMDLEN));
   1377 
   1378 	sc->transfer_state = TSTATE_CBI_RESET1;
   1379 	sc->transfer_status = status;
   1380 
   1381 	/* The 0x1d code is the SEND DIAGNOSTIC command. To distingiush between
   1382 	 * the two the last 10 bytes of the cbl is filled with 0xff (section
   1383 	 * 2.2 of the CBI spec).
   1384 	 */
   1385 	sc->cbl[0] = 0x1d;	/* Command Block Reset */
   1386 	sc->cbl[1] = 0x04;
   1387 	for (i = 2; i < SEND_DIAGNOSTIC_CMDLEN; i++)
   1388 		sc->cbl[i] = 0xff;
   1389 
   1390 	umass_cbi_adsc(sc, sc->cbl, SEND_DIAGNOSTIC_CMDLEN,
   1391 		       sc->transfer_xfer[XFER_CBI_RESET1]);
   1392 	/* XXX if the command fails we should reset the port on the bub */
   1393 }
   1394 
   1395 Static void
   1396 umass_cbi_transfer(struct umass_softc *sc, int lun,
   1397 		   void *cmd, int cmdlen, void *data, int datalen, int dir,
   1398 		   u_int timeout, umass_callback cb, void *priv)
   1399 {
   1400 	DPRINTF(UDMASS_CBI,("%s: umass_cbi_transfer cmd=0x%02x, len=%d\n",
   1401 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd, datalen));
   1402 
   1403 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1404 		("sc->proto == 0x%02x wrong for umass_cbi_transfer\n",
   1405 		sc->proto));
   1406 
   1407 	if (sc->sc_dying)
   1408 		return;
   1409 
   1410 	/* Be a little generous. */
   1411 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
   1412 
   1413 	/*
   1414 	 * Do a CBI transfer with cmdlen bytes from cmd, possibly
   1415 	 * a data phase of datalen bytes from/to the device and finally a
   1416 	 * csw read phase.
   1417 	 * If the data direction was inbound a maximum of datalen bytes
   1418 	 * is stored in the buffer pointed to by data.
   1419 	 *
   1420 	 * umass_cbi_transfer initialises the transfer and lets the state
   1421 	 * machine in umass_cbi_state handle the completion. It uses the
   1422 	 * following states:
   1423 	 * TSTATE_CBI_COMMAND
   1424 	 *   -> XXX fill in
   1425 	 *
   1426 	 * An error in any of those states will invoke
   1427 	 * umass_cbi_reset.
   1428 	 */
   1429 
   1430 	/* check the given arguments */
   1431 	KASSERT(datalen == 0 || data != NULL,
   1432 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
   1433 	KASSERT(datalen == 0 || dir != DIR_NONE,
   1434 		("%s: direction is NONE while datalen is not zero\n",
   1435 			USBDEVNAME(sc->sc_dev)));
   1436 
   1437 	/* store the details for the data transfer phase */
   1438 	sc->transfer_dir = dir;
   1439 	sc->transfer_data = data;
   1440 	sc->transfer_datalen = datalen;
   1441 	sc->transfer_actlen = 0;
   1442 	sc->transfer_cb = cb;
   1443 	sc->transfer_priv = priv;
   1444 	sc->transfer_status = STATUS_CMD_OK;
   1445 
   1446 	/* move from idle to the command state */
   1447 	sc->transfer_state = TSTATE_CBI_COMMAND;
   1448 
   1449 	/* Send the Command Block from host to device via control endpoint. */
   1450 	if (umass_cbi_adsc(sc, cmd, cmdlen, sc->transfer_xfer[XFER_CBI_CB]))
   1451 		umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1452 }
   1453 
   1454 Static void
   1455 umass_cbi_state(usbd_xfer_handle xfer, usbd_private_handle priv,
   1456 		usbd_status err)
   1457 {
   1458 	struct umass_softc *sc = (struct umass_softc *) priv;
   1459 
   1460 	KASSERT(sc->proto & (PROTO_CBI|PROTO_CBI_I),
   1461 		("sc->proto == 0x%02x wrong for umass_cbi_state\n", sc->proto));
   1462 
   1463 	if (sc->sc_dying)
   1464 		return;
   1465 
   1466 	/*
   1467 	 * State handling for CBI transfers.
   1468 	 */
   1469 
   1470 	DPRINTF(UDMASS_CBI, ("%s: Handling CBI state %d (%s), xfer=%p, %s\n",
   1471 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
   1472 		states[sc->transfer_state], xfer, usbd_errstr(err)));
   1473 
   1474 	switch (sc->transfer_state) {
   1475 
   1476 	/***** CBI Transfer *****/
   1477 	case TSTATE_CBI_COMMAND:
   1478 		if (err == USBD_STALLED) {
   1479 			DPRINTF(UDMASS_CBI, ("%s: Command Transport failed\n",
   1480 				USBDEVNAME(sc->sc_dev)));
   1481 			/* Status transport by control pipe (section 2.3.2.1).
   1482 			 * The command contained in the command block failed.
   1483 			 *
   1484 			 * The control pipe has already been unstalled by the
   1485 			 * USB stack.
   1486 			 * Section 2.4.3.1.1 states that the bulk in endpoints
   1487 			 * should not stalled at this point.
   1488 			 */
   1489 
   1490 			sc->transfer_state = TSTATE_IDLE;
   1491 			sc->transfer_cb(sc, sc->transfer_priv,
   1492 					sc->transfer_datalen,
   1493 					STATUS_CMD_FAILED);
   1494 
   1495 			return;
   1496 		} else if (err) {
   1497 			DPRINTF(UDMASS_CBI, ("%s: failed to send ADSC\n",
   1498 				USBDEVNAME(sc->sc_dev)));
   1499 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1500 
   1501 			return;
   1502 		}
   1503 
   1504 		sc->transfer_state = TSTATE_CBI_DATA;
   1505 		if (sc->transfer_dir == DIR_IN) {
   1506 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1507 					sc->transfer_data, sc->transfer_datalen,
   1508 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
   1509 					sc->transfer_xfer[XFER_CBI_DATA]))
   1510 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1511 
   1512 		} else if (sc->transfer_dir == DIR_OUT) {
   1513 			memcpy(sc->data_buffer, sc->transfer_data,
   1514 			       sc->transfer_datalen);
   1515 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
   1516 					sc->transfer_data, sc->transfer_datalen,
   1517 					USBD_NO_COPY,/* fixed length transfer */
   1518 					sc->transfer_xfer[XFER_CBI_DATA]))
   1519 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1520 
   1521 		} else if (sc->wire_proto == WPROTO_CBI_I) {
   1522 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
   1523 				USBDEVNAME(sc->sc_dev)));
   1524 			sc->transfer_state = TSTATE_CBI_STATUS;
   1525 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_INTRIN],
   1526 					&sc->sbl, sizeof(sc->sbl),
   1527 					0,	/* fixed length transfer */
   1528 					sc->transfer_xfer[XFER_CBI_STATUS])){
   1529 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1530 			}
   1531 		} else {
   1532 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
   1533 				USBDEVNAME(sc->sc_dev)));
   1534 			/* No command completion interrupt. Request
   1535 			 * sense data.
   1536 			 */
   1537 			sc->transfer_state = TSTATE_IDLE;
   1538 			sc->transfer_cb(sc, sc->transfer_priv,
   1539 			       0, STATUS_CMD_UNKNOWN);
   1540 		}
   1541 
   1542 		return;
   1543 
   1544 	case TSTATE_CBI_DATA:
   1545 		/* retrieve the length of the transfer that was done */
   1546 		usbd_get_xfer_status(xfer,NULL,NULL,&sc->transfer_actlen,NULL);
   1547 		DPRINTF(UDMASS_CBI, ("%s: CBI_DATA actlen=%d\n",
   1548 			USBDEVNAME(sc->sc_dev), sc->transfer_actlen));
   1549 
   1550 		if (err) {
   1551 			DPRINTF(UDMASS_CBI, ("%s: Data-%s %d failed, "
   1552 				"%s\n", USBDEVNAME(sc->sc_dev),
   1553 				(sc->transfer_dir == DIR_IN?"in":"out"),
   1554 				sc->transfer_datalen,usbd_errstr(err)));
   1555 
   1556 			if (err == USBD_STALLED) {
   1557 				sc->transfer_state = TSTATE_CBI_DCLEAR;
   1558 				umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1559 					sc->transfer_xfer[XFER_CBI_DCLEAR]);
   1560 			} else {
   1561 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1562 			}
   1563 			return;
   1564 		}
   1565 
   1566 		if (sc->transfer_dir == DIR_IN)
   1567 			memcpy(sc->transfer_data, sc->data_buffer,
   1568 			       sc->transfer_actlen);
   1569 
   1570 		DIF(UDMASS_CBI, if (sc->transfer_dir == DIR_IN)
   1571 					umass_dump_buffer(sc, sc->transfer_data,
   1572 						sc->transfer_actlen, 48));
   1573 
   1574 		if (sc->wire_proto == WPROTO_CBI_I) {
   1575 			sc->transfer_state = TSTATE_CBI_STATUS;
   1576 			memset(&sc->sbl, 0, sizeof(sc->sbl));
   1577 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_INTRIN],
   1578 				    &sc->sbl, sizeof(sc->sbl),
   1579 				    0,	/* fixed length transfer */
   1580 				    sc->transfer_xfer[XFER_CBI_STATUS])){
   1581 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1582 			}
   1583 		} else {
   1584 			/* No command completion interrupt. Request
   1585 			 * sense to get status of command.
   1586 			 */
   1587 			sc->transfer_state = TSTATE_IDLE;
   1588 			sc->transfer_cb(sc, sc->transfer_priv,
   1589 				sc->transfer_datalen - sc->transfer_actlen,
   1590 				STATUS_CMD_UNKNOWN);
   1591 		}
   1592 		return;
   1593 
   1594 	case TSTATE_CBI_STATUS:
   1595 		if (err) {
   1596 			DPRINTF(UDMASS_CBI, ("%s: Status Transport failed\n",
   1597 				USBDEVNAME(sc->sc_dev)));
   1598 			/* Status transport by interrupt pipe (section 2.3.2.2).
   1599 			 */
   1600 
   1601 			if (err == USBD_STALLED) {
   1602 				sc->transfer_state = TSTATE_CBI_SCLEAR;
   1603 				umass_clear_endpoint_stall(sc, UMASS_INTRIN,
   1604 					sc->transfer_xfer[XFER_CBI_SCLEAR]);
   1605 			} else {
   1606 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1607 			}
   1608 			return;
   1609 		}
   1610 
   1611 		/* Dissect the information in the buffer */
   1612 
   1613 		if (sc->cmd_proto == CPROTO_UFI) {
   1614 			int status;
   1615 
   1616 			/* Section 3.4.3.1.3 specifies that the UFI command
   1617 			 * protocol returns an ASC and ASCQ in the interrupt
   1618 			 * data block.
   1619 			 */
   1620 
   1621 			DPRINTF(UDMASS_CBI, ("%s: UFI CCI, ASC = 0x%02x, "
   1622 				"ASCQ = 0x%02x\n",
   1623 				USBDEVNAME(sc->sc_dev),
   1624 				sc->sbl.ufi.asc, sc->sbl.ufi.ascq));
   1625 
   1626 			if (sc->sbl.ufi.asc == 0 && sc->sbl.ufi.ascq == 0)
   1627 				status = STATUS_CMD_OK;
   1628 			else
   1629 				status = STATUS_CMD_FAILED;
   1630 
   1631 			/* No sense, command successfull */
   1632 		} else {
   1633 			/* Command Interrupt Data Block */
   1634 			DPRINTF(UDMASS_CBI, ("%s: type=0x%02x, value=0x%02x\n",
   1635 				USBDEVNAME(sc->sc_dev),
   1636 				sc->sbl.common.type, sc->sbl.common.value));
   1637 
   1638 			if (sc->sbl.common.type == IDB_TYPE_CCI) {
   1639 				int err;
   1640 
   1641 				if ((sc->sbl.common.value&IDB_VALUE_STATUS_MASK)
   1642 							== IDB_VALUE_PASS) {
   1643 					err = STATUS_CMD_OK;
   1644 				} else if ((sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
   1645 							== IDB_VALUE_FAIL ||
   1646 					   (sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
   1647 						== IDB_VALUE_PERSISTENT) {
   1648 					err = STATUS_CMD_FAILED;
   1649 				} else {
   1650 					err = STATUS_WIRE_FAILED;
   1651 				}
   1652 
   1653 				sc->transfer_state = TSTATE_IDLE;
   1654 				sc->transfer_cb(sc, sc->transfer_priv,
   1655 						sc->transfer_datalen,
   1656 						err);
   1657 			}
   1658 		}
   1659 		return;
   1660 
   1661 	case TSTATE_CBI_DCLEAR:
   1662 		if (err) {	/* should not occur */
   1663 			printf("%s: CBI bulk-in/out stall clear failed, %s\n",
   1664 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1665 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1666 		}
   1667 
   1668 		sc->transfer_state = TSTATE_IDLE;
   1669 		sc->transfer_cb(sc, sc->transfer_priv,
   1670 				sc->transfer_datalen,
   1671 				STATUS_CMD_FAILED);
   1672 		return;
   1673 
   1674 	case TSTATE_CBI_SCLEAR:
   1675 		if (err)	/* should not occur */
   1676 			printf("%s: CBI intr-in stall clear failed, %s\n",
   1677 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1678 
   1679 		/* Something really bad is going on. Reset the device */
   1680 		umass_cbi_reset(sc, STATUS_CMD_FAILED);
   1681 		return;
   1682 
   1683 	/***** CBI Reset *****/
   1684 	case TSTATE_CBI_RESET1:
   1685 		if (err)
   1686 			printf("%s: CBI reset failed, %s\n",
   1687 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1688 
   1689 		sc->transfer_state = TSTATE_CBI_RESET2;
   1690 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1691 			sc->transfer_xfer[XFER_CBI_RESET2]);
   1692 
   1693 		return;
   1694 	case TSTATE_CBI_RESET2:
   1695 		if (err)	/* should not occur */
   1696 			printf("%s: CBI bulk-in stall clear failed, %s\n",
   1697 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1698 			/* no error recovery, otherwise we end up in a loop */
   1699 
   1700 		sc->transfer_state = TSTATE_CBI_RESET3;
   1701 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
   1702 			sc->transfer_xfer[XFER_CBI_RESET3]);
   1703 
   1704 		return;
   1705 	case TSTATE_CBI_RESET3:
   1706 		if (err)	/* should not occur */
   1707 			printf("%s: CBI bulk-out stall clear failed, %s\n",
   1708 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1709 			/* no error recovery, otherwise we end up in a loop */
   1710 
   1711 		sc->transfer_state = TSTATE_IDLE;
   1712 		if (sc->transfer_priv) {
   1713 			sc->transfer_cb(sc, sc->transfer_priv,
   1714 					sc->transfer_datalen,
   1715 					sc->transfer_status);
   1716 		}
   1717 
   1718 		return;
   1719 
   1720 
   1721 	/***** Default *****/
   1722 	default:
   1723 		panic("%s: Unknown state %d\n",
   1724 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
   1725 	}
   1726 }
   1727 
   1728 usbd_status
   1729 umass_bbb_get_max_lun(struct umass_softc *sc, u_int8_t *maxlun)
   1730 {
   1731 	usb_device_request_t req;
   1732 	usbd_status err;
   1733 
   1734 	*maxlun = 0;		/* Default to 0. */
   1735 
   1736 	DPRINTF(UDMASS_BBB, ("%s: Get Max Lun\n", USBDEVNAME(sc->sc_dev)));
   1737 
   1738 	/* The Get Max Lun command is a class-specific request. */
   1739 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
   1740 	req.bRequest = UR_BBB_GET_MAX_LUN;
   1741 	USETW(req.wValue, 0);
   1742 	USETW(req.wIndex, sc->sc_ifaceno);
   1743 	USETW(req.wLength, 1);
   1744 
   1745 	err = usbd_do_request(sc->sc_udev, &req, maxlun);
   1746 	switch (err) {
   1747 	case USBD_NORMAL_COMPLETION:
   1748 		DPRINTF(UDMASS_BBB, ("%s: Max Lun %d\n",
   1749 		    USBDEVNAME(sc->sc_dev), *maxlun));
   1750 		break;
   1751 
   1752 	case USBD_STALLED:
   1753 		/*
   1754 		 * Device doesn't support Get Max Lun request.
   1755 		 */
   1756 		err = USBD_NORMAL_COMPLETION;
   1757 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun not supported\n",
   1758 		    USBDEVNAME(sc->sc_dev)));
   1759 		break;
   1760 
   1761 	case USBD_SHORT_XFER:
   1762 		/*
   1763 		 * XXX This must mean Get Max Lun is not supported, too!
   1764 		 */
   1765 		err = USBD_NORMAL_COMPLETION;
   1766 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun SHORT_XFER\n",
   1767 		    USBDEVNAME(sc->sc_dev)));
   1768 		break;
   1769 
   1770 	default:
   1771 		printf("%s: Get Max Lun failed: %s\n",
   1772 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1773 		/* XXX Should we port_reset the device? */
   1774 		break;
   1775 	}
   1776 
   1777 	return (err);
   1778 }
   1779 
   1780 
   1781 
   1782 
   1783 #ifdef UMASS_DEBUG
   1784 Static void
   1785 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
   1786 {
   1787 	int clen = cbw->bCDBLength;
   1788 	int dlen = UGETDW(cbw->dCBWDataTransferLength);
   1789 	u_int8_t *c = cbw->CBWCDB;
   1790 	int tag = UGETDW(cbw->dCBWTag);
   1791 	int flags = cbw->bCBWFlags;
   1792 
   1793 	DPRINTF(UDMASS_BBB, ("%s: CBW %d: cmdlen = %d "
   1794 		"(0x%02x%02x%02x%02x%02x%02x%s), "
   1795 		"data = %d bytes, dir = %s\n",
   1796 		USBDEVNAME(sc->sc_dev), tag, clen,
   1797 		c[0], c[1], c[2], c[3], c[4], c[5], (clen > 6? "...":""),
   1798 		dlen, (flags == CBWFLAGS_IN? "in":
   1799 		       (flags == CBWFLAGS_OUT? "out":"<invalid>"))));
   1800 }
   1801 
   1802 Static void
   1803 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
   1804 {
   1805 	int sig = UGETDW(csw->dCSWSignature);
   1806 	int tag = UGETW(csw->dCSWTag);
   1807 	int res = UGETDW(csw->dCSWDataResidue);
   1808 	int status = csw->bCSWStatus;
   1809 
   1810 	DPRINTF(UDMASS_BBB, ("%s: CSW %d: sig = 0x%08x (%s), tag = %d, "
   1811 		"res = %d, status = 0x%02x (%s)\n", USBDEVNAME(sc->sc_dev),
   1812 		tag, sig, (sig == CSWSIGNATURE?	 "valid":"invalid"),
   1813 		tag, res,
   1814 		status, (status == CSWSTATUS_GOOD? "good":
   1815 			 (status == CSWSTATUS_FAILED? "failed":
   1816 			  (status == CSWSTATUS_PHASE? "phase":"<invalid>")))));
   1817 }
   1818 
   1819 Static void
   1820 umass_dump_buffer(struct umass_softc *sc, u_int8_t *buffer, int buflen,
   1821 		  int printlen)
   1822 {
   1823 	int i, j;
   1824 	char s1[40];
   1825 	char s2[40];
   1826 	char s3[5];
   1827 
   1828 	s1[0] = '\0';
   1829 	s3[0] = '\0';
   1830 
   1831 	sprintf(s2, " buffer=%p, buflen=%d", buffer, buflen);
   1832 	for (i = 0; i < buflen && i < printlen; i++) {
   1833 		j = i % 16;
   1834 		if (j == 0 && i != 0) {
   1835 			DPRINTF(UDMASS_GEN, ("%s: 0x %s%s\n",
   1836 				USBDEVNAME(sc->sc_dev), s1, s2));
   1837 			s2[0] = '\0';
   1838 		}
   1839 		sprintf(&s1[j*2], "%02x", buffer[i] & 0xff);
   1840 	}
   1841 	if (buflen > printlen)
   1842 		sprintf(s3, " ...");
   1843 	DPRINTF(UDMASS_GEN, ("%s: 0x %s%s%s\n",
   1844 		USBDEVNAME(sc->sc_dev), s1, s2, s3));
   1845 }
   1846 #endif
   1847