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