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