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