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