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