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