Home | History | Annotate | Line # | Download | only in usb
umass.c revision 1.79
      1 /*	$NetBSD: umass.c,v 1.79 2001/12/24 13:25:52 augustss Exp $	*/
      2 /*-
      3  * Copyright (c) 1999 MAEKAWA Masahide <bishop (at) rr.iij4u.or.jp>,
      4  *		      Nick Hibma <n_hibma (at) freebsd.org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  *     $FreeBSD: src/sys/dev/usb/umass.c,v 1.13 2000/03/26 01:39:12 n_hibma Exp $
     29  */
     30 
     31 /*
     32  * Universal Serial Bus Mass Storage Class specs:
     33  * http://www.usb.org/developers/data/devclass/usbmassover_11.pdf
     34  * http://www.usb.org/developers/data/devclass/usbmassbulk_10.pdf
     35  * http://www.usb.org/developers/data/devclass/usbmass-cbi10.pdf
     36  * http://www.usb.org/developers/data/devclass/usbmass-ufi10.pdf
     37  */
     38 
     39 /*
     40  * Ported to NetBSD by Lennart Augustsson <augustss (at) netbsd.org>.
     41  * Parts of the code written my Jason R. Thorpe <thorpej (at) shagadelic.org>.
     42  */
     43 
     44 /*
     45  * The driver handles 3 Wire Protocols
     46  * - Command/Bulk/Interrupt (CBI)
     47  * - Command/Bulk/Interrupt with Command Completion Interrupt (CBI with CCI)
     48  * - Mass Storage Bulk-Only (BBB)
     49  *   (BBB refers Bulk/Bulk/Bulk for Command/Data/Status phases)
     50  *
     51  * Over these wire protocols it handles the following command protocols
     52  * - SCSI
     53  * - 8070 (ATA/ATAPI for rewritable removable media)
     54  * - UFI (USB Floppy Interface)
     55  *
     56  * 8070i is a transformed version of the SCSI command set. UFI is a transformed
     57  * version of the 8070i command set.  The sc->transform method is used to
     58  * convert the commands into the appropriate format (if at all necessary).
     59  * For example, ATAPI requires all commands to be 12 bytes in length amongst
     60  * other things.
     61  *
     62  * The source code below is marked and can be split into a number of pieces
     63  * (in this order):
     64  *
     65  * - probe/attach/detach
     66  * - generic transfer routines
     67  * - BBB
     68  * - CBI
     69  * - CBI_I (in addition to functions from CBI)
     70  * - CAM (Common Access Method)
     71  * - SCSI
     72  * - UFI
     73  * - 8070i
     74  *
     75  * The protocols are implemented using a state machine, for the transfers as
     76  * well as for the resets. The state machine is contained in umass_*_state.
     77  * The state machine is started through either umass_*_transfer or
     78  * umass_*_reset.
     79  *
     80  * The reason for doing this is a) CAM performs a lot better this way and b) it
     81  * avoids using tsleep from interrupt context (for example after a failed
     82  * transfer).
     83  */
     84 
     85 /*
     86  * The SCSI related part of this driver has been derived from the
     87  * dev/ppbus/vpo.c driver, by Nicolas Souchu (nsouch (at) freebsd.org).
     88  *
     89  * The CAM layer uses so called actions which are messages sent to the host
     90  * adapter for completion. The actions come in through umass_cam_action. The
     91  * appropriate block of routines is called depending on the transport protocol
     92  * in use. When the transfer has finished, these routines call
     93  * umass_cam_cb again to complete the CAM command.
     94  */
     95 
     96 #include <sys/cdefs.h>
     97 __KERNEL_RCSID(0, "$NetBSD: umass.c,v 1.79 2001/12/24 13:25:52 augustss Exp $");
     98 
     99 #include "atapibus.h"
    100 #include "scsibus.h"
    101 
    102 #include <sys/param.h>
    103 #include <sys/systm.h>
    104 #include <sys/kernel.h>
    105 #include <sys/conf.h>
    106 #if defined(__NetBSD__) || defined(__OpenBSD__)
    107 #include <sys/buf.h>
    108 #include <sys/device.h>
    109 #include <sys/ioctl.h>
    110 #include <sys/malloc.h>
    111 #undef KASSERT
    112 #define KASSERT(cond, msg)
    113 #elif defined(__FreeBSD__)
    114 #include <sys/module.h>
    115 #include <sys/bus.h>
    116 #include <machine/clock.h>
    117 #endif
    118 
    119 #include <dev/usb/usb.h>
    120 #include <dev/usb/usbdi.h>
    121 #include <dev/usb/usbdi_util.h>
    122 #include <dev/usb/usbdevs.h>
    123 
    124 #include <dev/usb/umassvar.h>
    125 #include <dev/usb/umass_quirks.h>
    126 #include <dev/usb/umass_scsipi.h>
    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, error;
    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 	error = 0;
    562 	switch (sc->sc_cmd) {
    563 	case UMASS_CPROTO_RBC:
    564 	case UMASS_CPROTO_SCSI:
    565 #if NSCSIBUS > 0
    566 		error = umass_scsi_attach(sc);
    567 #else
    568 		printf("%s: atapibus not configured\n", USBDEVNAME(sc->sc_dev));
    569 #endif
    570 		break;
    571 
    572 	case UMASS_CPROTO_UFI:
    573 	case UMASS_CPROTO_ATAPI:
    574 #if NATAPIBUS > 0
    575 		error = umass_atapi_attach(sc);
    576 #else
    577 		printf("%s: scsibus not configured\n", USBDEVNAME(sc->sc_dev));
    578 #endif
    579 		break;
    580 
    581 	default:
    582 		printf("%s: command protocol=0x%x not supported\n",
    583 		       USBDEVNAME(sc->sc_dev), sc->sc_cmd);
    584 		umass_disco(sc);
    585 		USB_ATTACH_ERROR_RETURN;
    586 	}
    587 	if (error) {
    588 		printf("%s: bus attach failed\n", USBDEVNAME(sc->sc_dev));
    589 		umass_disco(sc);
    590 		USB_ATTACH_ERROR_RETURN;
    591 	}
    592 
    593 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    594 			   USBDEV(sc->sc_dev));
    595 
    596 	DPRINTF(UDMASS_GEN, ("%s: Attach finished\n", USBDEVNAME(sc->sc_dev)));
    597 
    598 	USB_ATTACH_SUCCESS_RETURN;
    599 }
    600 
    601 USB_DETACH(umass)
    602 {
    603 	USB_DETACH_START(umass, sc);
    604 	struct umassbus_softc *scbus = sc->bus;
    605 	int rv = 0, i;
    606 
    607 	DPRINTF(UDMASS_USB, ("%s: detached\n", USBDEVNAME(sc->sc_dev)));
    608 
    609 	/* Abort the pipes to wake up any waiting processes. */
    610 	for (i = 0 ; i < UMASS_NEP ; i++) {
    611 		if (sc->sc_pipe[i] != NULL)
    612 			usbd_abort_pipe(sc->sc_pipe[i]);
    613 	}
    614 
    615 #if 0
    616 	/* Do we really need reference counting?  Perhaps in ioctl() */
    617 	s = splusb();
    618 	if (--sc->sc_refcnt >= 0) {
    619 		/* Wait for processes to go away. */
    620 		usb_detach_wait(USBDEV(sc->sc_dev));
    621 	}
    622 	splx(s);
    623 #endif
    624 
    625 	if (scbus != NULL) {
    626 		if (scbus->sc_child != NULL)
    627 			rv = config_detach(scbus->sc_child, flags);
    628 		free(scbus, M_DEVBUF);
    629 		sc->bus = NULL;
    630 	}
    631 
    632 	if (rv != 0)
    633 		return (rv);
    634 
    635 	umass_disco(sc);
    636 
    637 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    638 			   USBDEV(sc->sc_dev));
    639 
    640 	return (rv);
    641 }
    642 
    643 int
    644 umass_activate(struct device *dev, enum devact act)
    645 {
    646 	struct umass_softc *sc = (struct umass_softc *)dev;
    647 	struct umassbus_softc *scbus = sc->bus;
    648 	int rv = 0;
    649 
    650 	DPRINTF(UDMASS_USB, ("%s: umass_activate: %d\n",
    651 	    USBDEVNAME(sc->sc_dev), act));
    652 
    653 	switch (act) {
    654 	case DVACT_ACTIVATE:
    655 		rv = EOPNOTSUPP;
    656 		break;
    657 
    658 	case DVACT_DEACTIVATE:
    659 		sc->sc_dying = 1;
    660 		if (scbus->sc_child == NULL)
    661 			break;
    662 		rv = config_deactivate(scbus->sc_child);
    663 		DPRINTF(UDMASS_USB, ("%s: umass_activate: child "
    664 		    "returned %d\n", USBDEVNAME(sc->sc_dev), rv));
    665 		break;
    666 	}
    667 	return (rv);
    668 }
    669 
    670 Static void
    671 umass_disco(struct umass_softc *sc)
    672 {
    673 	int i;
    674 
    675 	DPRINTF(UDMASS_GEN, ("umass_disco\n"));
    676 
    677 	/* Free the xfers. */
    678 	for (i = 0; i < XFER_NR; i++)
    679 		if (sc->transfer_xfer[i] != NULL) {
    680 			usbd_free_xfer(sc->transfer_xfer[i]);
    681 			sc->transfer_xfer[i] = NULL;
    682 		}
    683 
    684 	/* Remove all the pipes. */
    685 	for (i = 0 ; i < UMASS_NEP ; i++) {
    686 		if (sc->sc_pipe[i] != NULL)
    687 			usbd_close_pipe(sc->sc_pipe[i]);
    688 	}
    689 }
    690 
    691 /*
    692  * Generic functions to handle transfers
    693  */
    694 
    695 Static usbd_status
    696 umass_setup_transfer(struct umass_softc *sc, usbd_pipe_handle pipe,
    697 			void *buffer, int buflen, int flags,
    698 			usbd_xfer_handle xfer)
    699 {
    700 	usbd_status err;
    701 
    702 	if (sc->sc_dying)
    703 		return (USBD_IOERROR);
    704 
    705 	/* Initialiase a USB transfer and then schedule it */
    706 
    707 	usbd_setup_xfer(xfer, pipe, (void *)sc, buffer, buflen,
    708 	    flags | sc->sc_xfer_flags, sc->timeout, sc->sc_methods->wire_state);
    709 
    710 	err = usbd_transfer(xfer);
    711 	DPRINTF(UDMASS_XFER,("%s: start xfer buffer=%p buflen=%d flags=0x%x "
    712 	    "timeout=%d\n", USBDEVNAME(sc->sc_dev),
    713 	    buffer, buflen, flags | sc->sc_xfer_flags, sc->timeout));
    714 	if (err && err != USBD_IN_PROGRESS) {
    715 		DPRINTF(UDMASS_BBB, ("%s: failed to setup transfer, %s\n",
    716 			USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
    717 		return (err);
    718 	}
    719 
    720 	return (USBD_NORMAL_COMPLETION);
    721 }
    722 
    723 
    724 Static usbd_status
    725 umass_setup_ctrl_transfer(struct umass_softc *sc, usb_device_request_t *req,
    726 	 void *buffer, int buflen, int flags, usbd_xfer_handle xfer)
    727 {
    728 	usbd_status err;
    729 
    730 	if (sc->sc_dying)
    731 		return (USBD_IOERROR);
    732 
    733 	/* Initialiase a USB control transfer and then schedule it */
    734 
    735 	usbd_setup_default_xfer(xfer, sc->sc_udev, (void *) sc, sc->timeout,
    736 		req, buffer, buflen, flags, sc->sc_methods->wire_state);
    737 
    738 	err = usbd_transfer(xfer);
    739 	if (err && err != USBD_IN_PROGRESS) {
    740 		DPRINTF(UDMASS_BBB, ("%s: failed to setup ctrl transfer, %s\n",
    741 			 USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
    742 
    743 		/* do not reset, as this would make us loop */
    744 		return (err);
    745 	}
    746 
    747 	return (USBD_NORMAL_COMPLETION);
    748 }
    749 
    750 Static void
    751 umass_clear_endpoint_stall(struct umass_softc *sc, int endpt,
    752 	usbd_xfer_handle xfer)
    753 {
    754 	if (sc->sc_dying)
    755 		return;
    756 
    757 	DPRINTF(UDMASS_BBB, ("%s: Clear endpoint 0x%02x stall\n",
    758 		USBDEVNAME(sc->sc_dev), endpt));
    759 
    760 	usbd_clear_endpoint_toggle(sc->sc_pipe[endpt]);
    761 
    762 	sc->sc_req.bmRequestType = UT_WRITE_ENDPOINT;
    763 	sc->sc_req.bRequest = UR_CLEAR_FEATURE;
    764 	USETW(sc->sc_req.wValue, UF_ENDPOINT_HALT);
    765 	USETW(sc->sc_req.wIndex, sc->sc_epaddr[endpt]);
    766 	USETW(sc->sc_req.wLength, 0);
    767 	umass_setup_ctrl_transfer(sc, &sc->sc_req, NULL, 0, 0, xfer);
    768 }
    769 
    770 #if 0
    771 Static void
    772 umass_reset(struct umass_softc *sc, transfer_cb_f cb, void *priv)
    773 {
    774 	sc->transfer_cb = cb;
    775 	sc->transfer_priv = priv;
    776 
    777 	/* The reset is a forced reset, so no error (yet) */
    778 	sc->reset(sc, STATUS_CMD_OK);
    779 }
    780 #endif
    781 
    782 /*
    783  * Bulk protocol specific functions
    784  */
    785 
    786 Static void
    787 umass_bbb_reset(struct umass_softc *sc, int status)
    788 {
    789 	KASSERT(sc->sc_wire & UMASS_WPROTO_BBB,
    790 		("sc->sc_wire == 0x%02x wrong for umass_bbb_reset\n",
    791 		sc->sc_wire));
    792 
    793 	if (sc->sc_dying)
    794 		return;
    795 
    796 	/*
    797 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
    798 	 *
    799 	 * For Reset Recovery the host shall issue in the following order:
    800 	 * a) a Bulk-Only Mass Storage Reset
    801 	 * b) a Clear Feature HALT to the Bulk-In endpoint
    802 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
    803 	 *
    804 	 * This is done in 3 steps, states:
    805 	 * TSTATE_BBB_RESET1
    806 	 * TSTATE_BBB_RESET2
    807 	 * TSTATE_BBB_RESET3
    808 	 *
    809 	 * If the reset doesn't succeed, the device should be port reset.
    810 	 */
    811 
    812 	DPRINTF(UDMASS_BBB, ("%s: Bulk Reset\n",
    813 		USBDEVNAME(sc->sc_dev)));
    814 
    815 	sc->transfer_state = TSTATE_BBB_RESET1;
    816 	sc->transfer_status = status;
    817 
    818 	/* reset is a class specific interface write */
    819 	sc->sc_req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    820 	sc->sc_req.bRequest = UR_BBB_RESET;
    821 	USETW(sc->sc_req.wValue, 0);
    822 	USETW(sc->sc_req.wIndex, sc->sc_ifaceno);
    823 	USETW(sc->sc_req.wLength, 0);
    824 	umass_setup_ctrl_transfer(sc, &sc->sc_req, NULL, 0, 0,
    825 				  sc->transfer_xfer[XFER_BBB_RESET1]);
    826 }
    827 
    828 Static void
    829 umass_bbb_transfer(struct umass_softc *sc, int lun, void *cmd, int cmdlen,
    830 		   void *data, int datalen, int dir, u_int timeout,
    831 		   umass_callback cb, void *priv)
    832 {
    833 	static int dCBWtag = 42;	/* unique for CBW of transfer */
    834 
    835 	DPRINTF(UDMASS_BBB,("%s: umass_bbb_transfer cmd=0x%02x\n",
    836 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd));
    837 
    838 	KASSERT(sc->sc_wire & UMASS_WPROTO_BBB,
    839 		("sc->sc_wire == 0x%02x wrong for umass_bbb_transfer\n",
    840 		sc->sc_wire));
    841 
    842 	/* Be a little generous. */
    843 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
    844 
    845 	/*
    846 	 * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
    847 	 * a data phase of datalen bytes from/to the device and finally a
    848 	 * csw read phase.
    849 	 * If the data direction was inbound a maximum of datalen bytes
    850 	 * is stored in the buffer pointed to by data.
    851 	 *
    852 	 * umass_bbb_transfer initialises the transfer and lets the state
    853 	 * machine in umass_bbb_state handle the completion. It uses the
    854 	 * following states:
    855 	 * TSTATE_BBB_COMMAND
    856 	 *   -> TSTATE_BBB_DATA
    857 	 *   -> TSTATE_BBB_STATUS
    858 	 *   -> TSTATE_BBB_STATUS2
    859 	 *   -> TSTATE_BBB_IDLE
    860 	 *
    861 	 * An error in any of those states will invoke
    862 	 * umass_bbb_reset.
    863 	 */
    864 
    865 	/* check the given arguments */
    866 	KASSERT(datalen == 0 || data != NULL,
    867 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
    868 	KASSERT(cmdlen <= CBWCDBLENGTH,
    869 		("%s: cmdlen exceeds CDB length in CBW (%d > %d)",
    870 			USBDEVNAME(sc->sc_dev), cmdlen, CBWCDBLENGTH));
    871 	KASSERT(dir == DIR_NONE || datalen > 0,
    872 		("%s: datalen == 0 while direction is not NONE\n",
    873 			USBDEVNAME(sc->sc_dev)));
    874 	KASSERT(datalen == 0 || dir != DIR_NONE,
    875 		("%s: direction is NONE while datalen is not zero\n",
    876 			USBDEVNAME(sc->sc_dev)));
    877 	KASSERT(sizeof(umass_bbb_cbw_t) == UMASS_BBB_CBW_SIZE,
    878 		("%s: CBW struct does not have the right size (%d vs. %d)\n",
    879 			USBDEVNAME(sc->sc_dev),
    880 			sizeof(umass_bbb_cbw_t), UMASS_BBB_CBW_SIZE));
    881 	KASSERT(sizeof(umass_bbb_csw_t) == UMASS_BBB_CSW_SIZE,
    882 		("%s: CSW struct does not have the right size (%d vs. %d)\n",
    883 			USBDEVNAME(sc->sc_dev),
    884 			sizeof(umass_bbb_csw_t), UMASS_BBB_CSW_SIZE));
    885 
    886 	/*
    887 	 * Determine the direction of the data transfer and the length.
    888 	 *
    889 	 * dCBWDataTransferLength (datalen) :
    890 	 *   This field indicates the number of bytes of data that the host
    891 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
    892 	 *   the Direction bit) during the execution of this command. If this
    893 	 *   field is set to 0, the device will expect that no data will be
    894 	 *   transferred IN or OUT during this command, regardless of the value
    895 	 *   of the Direction bit defined in dCBWFlags.
    896 	 *
    897 	 * dCBWFlags (dir) :
    898 	 *   The bits of the Flags field are defined as follows:
    899 	 *     Bits 0-6	 reserved
    900 	 *     Bit  7	 Direction - this bit shall be ignored if the
    901 	 *			     dCBWDataTransferLength field is zero.
    902 	 *		 0 = data Out from host to device
    903 	 *		 1 = data In from device to host
    904 	 */
    905 
    906 	/* Fill in the Command Block Wrapper */
    907 	USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
    908 	USETDW(sc->cbw.dCBWTag, dCBWtag);
    909 	dCBWtag++;	/* cannot be done in macro (it will be done 4 times) */
    910 	USETDW(sc->cbw.dCBWDataTransferLength, datalen);
    911 	/* DIR_NONE is treated as DIR_OUT (0x00) */
    912 	sc->cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
    913 	sc->cbw.bCBWLUN = lun;
    914 	sc->cbw.bCDBLength = cmdlen;
    915 	memcpy(sc->cbw.CBWCDB, cmd, cmdlen);
    916 
    917 	DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
    918 
    919 	/* store the details for the data transfer phase */
    920 	sc->transfer_dir = dir;
    921 	sc->transfer_data = data;
    922 	sc->transfer_datalen = datalen;
    923 	sc->transfer_actlen = 0;
    924 	sc->transfer_cb = cb;
    925 	sc->transfer_priv = priv;
    926 	sc->transfer_status = STATUS_CMD_OK;
    927 
    928 	/* move from idle to the command state */
    929 	sc->transfer_state = TSTATE_BBB_COMMAND;
    930 
    931 	/* Send the CBW from host to device via bulk-out endpoint. */
    932 	if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
    933 			&sc->cbw, UMASS_BBB_CBW_SIZE, 0,
    934 			sc->transfer_xfer[XFER_BBB_CBW])) {
    935 		umass_bbb_reset(sc, STATUS_WIRE_FAILED);
    936 	}
    937 }
    938 
    939 
    940 Static void
    941 umass_bbb_state(usbd_xfer_handle xfer, usbd_private_handle priv,
    942 		usbd_status err)
    943 {
    944 	struct umass_softc *sc = (struct umass_softc *) priv;
    945 	usbd_xfer_handle next_xfer;
    946 
    947 	KASSERT(sc->sc_wire & UMASS_WPROTO_BBB,
    948 		("sc->sc_wire == 0x%02x wrong for umass_bbb_state\n",
    949 		sc->sc_wire));
    950 
    951 	if (sc->sc_dying)
    952 		return;
    953 
    954 	/*
    955 	 * State handling for BBB transfers.
    956 	 *
    957 	 * The subroutine is rather long. It steps through the states given in
    958 	 * Annex A of the Bulk-Only specification.
    959 	 * Each state first does the error handling of the previous transfer
    960 	 * and then prepares the next transfer.
    961 	 * Each transfer is done asynchroneously so after the request/transfer
    962 	 * has been submitted you will find a 'return;'.
    963 	 */
    964 
    965 	DPRINTF(UDMASS_BBB, ("%s: Handling BBB state %d (%s), xfer=%p, %s\n",
    966 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
    967 		states[sc->transfer_state], xfer, usbd_errstr(err)));
    968 
    969 	switch (sc->transfer_state) {
    970 
    971 	/***** Bulk Transfer *****/
    972 	case TSTATE_BBB_COMMAND:
    973 		/* Command transport phase, error handling */
    974 		if (err) {
    975 			DPRINTF(UDMASS_BBB, ("%s: failed to send CBW\n",
    976 				USBDEVNAME(sc->sc_dev)));
    977 			/* If the device detects that the CBW is invalid, then
    978 			 * the device may STALL both bulk endpoints and require
    979 			 * a Bulk-Reset
    980 			 */
    981 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
    982 			return;
    983 		}
    984 
    985 		/* Data transport phase, setup transfer */
    986 		sc->transfer_state = TSTATE_BBB_DATA;
    987 		if (sc->transfer_dir == DIR_IN) {
    988 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
    989 					sc->data_buffer, sc->transfer_datalen,
    990 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
    991 					sc->transfer_xfer[XFER_BBB_DATA]))
    992 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
    993 
    994 			return;
    995 		} else if (sc->transfer_dir == DIR_OUT) {
    996 			memcpy(sc->data_buffer, sc->transfer_data,
    997 			       sc->transfer_datalen);
    998 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
    999 					sc->data_buffer, sc->transfer_datalen,
   1000 					USBD_NO_COPY,/* fixed length transfer */
   1001 					sc->transfer_xfer[XFER_BBB_DATA]))
   1002 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1003 
   1004 			return;
   1005 		} else {
   1006 			DPRINTF(UDMASS_BBB, ("%s: no data phase\n",
   1007 				USBDEVNAME(sc->sc_dev)));
   1008 		}
   1009 
   1010 		/* FALLTHROUGH if no data phase, err == 0 */
   1011 	case TSTATE_BBB_DATA:
   1012 		/* Command transport phase, error handling (ignored if no data
   1013 		 * phase (fallthrough from previous state)) */
   1014 		if (sc->transfer_dir != DIR_NONE) {
   1015 			/* retrieve the length of the transfer that was done */
   1016 			usbd_get_xfer_status(xfer, NULL, NULL,
   1017 					     &sc->transfer_actlen, NULL);
   1018 
   1019 			if (err) {
   1020 				DPRINTF(UDMASS_BBB, ("%s: Data-%s %d failed, "
   1021 					"%s\n", USBDEVNAME(sc->sc_dev),
   1022 					(sc->transfer_dir == DIR_IN?"in":"out"),
   1023 					sc->transfer_datalen,usbd_errstr(err)));
   1024 
   1025 				if (err == USBD_STALLED) {
   1026 					sc->transfer_state = TSTATE_BBB_DCLEAR;
   1027 					umass_clear_endpoint_stall(sc,
   1028 					  (sc->transfer_dir == DIR_IN?
   1029 					    UMASS_BULKIN:UMASS_BULKOUT),
   1030 					  sc->transfer_xfer[XFER_BBB_DCLEAR]);
   1031 					return;
   1032 				} else {
   1033 					/* Unless the error is a pipe stall the
   1034 					 * error is fatal.
   1035 					 */
   1036 					umass_bbb_reset(sc,STATUS_WIRE_FAILED);
   1037 					return;
   1038 				}
   1039 			}
   1040 		}
   1041 
   1042 		if (sc->transfer_dir == DIR_IN)
   1043 			memcpy(sc->transfer_data, sc->data_buffer,
   1044 			       sc->transfer_actlen);
   1045 
   1046 		DIF(UDMASS_BBB, if (sc->transfer_dir == DIR_IN)
   1047 					umass_dump_buffer(sc, sc->transfer_data,
   1048 						sc->transfer_datalen, 48));
   1049 
   1050 		/* FALLTHROUGH, err == 0 (no data phase or successfull) */
   1051 	case TSTATE_BBB_DCLEAR: /* stall clear after data phase */
   1052 	case TSTATE_BBB_SCLEAR: /* stall clear after status phase */
   1053 		/* Reading of CSW after bulk stall condition in data phase
   1054 		 * (TSTATE_BBB_DATA2) or bulk-in stall condition after
   1055 		 * reading CSW (TSTATE_BBB_SCLEAR).
   1056 		 * In the case of no data phase or successfull data phase,
   1057 		 * err == 0 and the following if block is passed.
   1058 		 */
   1059 		if (err) {	/* should not occur */
   1060 			/* try the transfer below, even if clear stall failed */
   1061 			DPRINTF(UDMASS_BBB, ("%s: bulk-%s stall clear failed"
   1062 				", %s\n", USBDEVNAME(sc->sc_dev),
   1063 				(sc->transfer_dir == DIR_IN? "in":"out"),
   1064 				usbd_errstr(err)));
   1065 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1066 			return;
   1067 		}
   1068 
   1069 		/* Status transport phase, setup transfer */
   1070 		if (sc->transfer_state == TSTATE_BBB_COMMAND ||
   1071 		    sc->transfer_state == TSTATE_BBB_DATA ||
   1072 		    sc->transfer_state == TSTATE_BBB_DCLEAR) {
   1073 			/* After no data phase, successfull data phase and
   1074 			 * after clearing bulk-in/-out stall condition
   1075 			 */
   1076 			sc->transfer_state = TSTATE_BBB_STATUS1;
   1077 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW1];
   1078 		} else {
   1079 			/* After first attempt of fetching CSW */
   1080 			sc->transfer_state = TSTATE_BBB_STATUS2;
   1081 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW2];
   1082 		}
   1083 
   1084 		/* Read the Command Status Wrapper via bulk-in endpoint. */
   1085 		if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1086 			&sc->csw, UMASS_BBB_CSW_SIZE, 0, next_xfer)) {
   1087 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1088 			return;
   1089 		}
   1090 
   1091 		return;
   1092 	case TSTATE_BBB_STATUS1:	/* first attempt */
   1093 	case TSTATE_BBB_STATUS2:	/* second attempt */
   1094 		/* Status transfer, error handling */
   1095 		if (err) {
   1096 			DPRINTF(UDMASS_BBB, ("%s: Failed to read CSW, %s%s\n",
   1097 				USBDEVNAME(sc->sc_dev), usbd_errstr(err),
   1098 				(sc->transfer_state == TSTATE_BBB_STATUS1?
   1099 					", retrying":"")));
   1100 
   1101 			/* If this was the first attempt at fetching the CSW
   1102 			 * retry it, otherwise fail.
   1103 			 */
   1104 			if (sc->transfer_state == TSTATE_BBB_STATUS1) {
   1105 				sc->transfer_state = TSTATE_BBB_SCLEAR;
   1106 				umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1107 				    sc->transfer_xfer[XFER_BBB_SCLEAR]);
   1108 				return;
   1109 			} else {
   1110 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1111 				return;
   1112 			}
   1113 		}
   1114 
   1115 		DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
   1116 
   1117 		/* Translate weird command-status signatures. */
   1118 		if ((sc->sc_quirks & UMASS_QUIRK_WRONG_CSWSIG) &&
   1119 		    UGETDW(sc->csw.dCSWSignature) == CSWSIGNATURE_OLYMPUS_C1)
   1120 			USETDW(sc->csw.dCSWSignature, CSWSIGNATURE);
   1121 
   1122 		/* Check CSW and handle any error */
   1123 		if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
   1124 			/* Invalid CSW: Wrong signature or wrong tag might
   1125 			 * indicate that the device is confused -> reset it.
   1126 			 */
   1127 			printf("%s: Invalid CSW: sig 0x%08x should be 0x%08x\n",
   1128 				USBDEVNAME(sc->sc_dev),
   1129 				UGETDW(sc->csw.dCSWSignature),
   1130 				CSWSIGNATURE);
   1131 
   1132 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1133 			return;
   1134 		} else if (UGETDW(sc->csw.dCSWTag)
   1135 				!= UGETDW(sc->cbw.dCBWTag)) {
   1136 			printf("%s: Invalid CSW: tag %d should be %d\n",
   1137 				USBDEVNAME(sc->sc_dev),
   1138 				UGETDW(sc->csw.dCSWTag),
   1139 				UGETDW(sc->cbw.dCBWTag));
   1140 
   1141 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1142 			return;
   1143 
   1144 		/* CSW is valid here */
   1145 		} else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
   1146 			printf("%s: Invalid CSW: status %d > %d\n",
   1147 				USBDEVNAME(sc->sc_dev),
   1148 				sc->csw.bCSWStatus,
   1149 				CSWSTATUS_PHASE);
   1150 
   1151 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1152 			return;
   1153 		} else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
   1154 			printf("%s: Phase Error, residue = %d\n",
   1155 				USBDEVNAME(sc->sc_dev),
   1156 				UGETDW(sc->csw.dCSWDataResidue));
   1157 
   1158 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1159 			return;
   1160 
   1161 		} else if (sc->transfer_actlen > sc->transfer_datalen) {
   1162 			/* Buffer overrun! Don't let this go by unnoticed */
   1163 			panic("%s: transferred %d bytes instead of %d bytes\n",
   1164 				USBDEVNAME(sc->sc_dev),
   1165 				sc->transfer_actlen, sc->transfer_datalen);
   1166 #if 0
   1167 		} else if (sc->transfer_datalen - sc->transfer_actlen
   1168 			   != UGETDW(sc->csw.dCSWDataResidue)) {
   1169 			DPRINTF(UDMASS_BBB, ("%s: actlen=%d != residue=%d\n",
   1170 				USBDEVNAME(sc->sc_dev),
   1171 				sc->transfer_datalen - sc->transfer_actlen,
   1172 				UGETDW(sc->csw.dCSWDataResidue)));
   1173 
   1174 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1175 			return;
   1176 #endif
   1177 		} else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
   1178 			DPRINTF(UDMASS_BBB, ("%s: Command Failed, res = %d\n",
   1179 				USBDEVNAME(sc->sc_dev),
   1180 				UGETDW(sc->csw.dCSWDataResidue)));
   1181 
   1182 			/* SCSI command failed but transfer was succesful */
   1183 			sc->transfer_state = TSTATE_IDLE;
   1184 			sc->transfer_cb(sc, sc->transfer_priv,
   1185 					UGETDW(sc->csw.dCSWDataResidue),
   1186 					STATUS_CMD_FAILED);
   1187 
   1188 			return;
   1189 
   1190 		} else {	/* success */
   1191 			sc->transfer_state = TSTATE_IDLE;
   1192 			sc->transfer_cb(sc, sc->transfer_priv,
   1193 					UGETDW(sc->csw.dCSWDataResidue),
   1194 					STATUS_CMD_OK);
   1195 
   1196 			return;
   1197 		}
   1198 
   1199 	/***** Bulk Reset *****/
   1200 	case TSTATE_BBB_RESET1:
   1201 		if (err)
   1202 			printf("%s: BBB reset failed, %s\n",
   1203 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1204 
   1205 		sc->transfer_state = TSTATE_BBB_RESET2;
   1206 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1207 			sc->transfer_xfer[XFER_BBB_RESET2]);
   1208 
   1209 		return;
   1210 	case TSTATE_BBB_RESET2:
   1211 		if (err)	/* should not occur */
   1212 			printf("%s: BBB bulk-in clear stall failed, %s\n",
   1213 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1214 			/* no error recovery, otherwise we end up in a loop */
   1215 
   1216 		sc->transfer_state = TSTATE_BBB_RESET3;
   1217 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
   1218 			sc->transfer_xfer[XFER_BBB_RESET3]);
   1219 
   1220 		return;
   1221 	case TSTATE_BBB_RESET3:
   1222 		if (err)	/* should not occur */
   1223 			printf("%s: BBB bulk-out clear stall failed, %s\n",
   1224 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1225 			/* no error recovery, otherwise we end up in a loop */
   1226 
   1227 		sc->transfer_state = TSTATE_IDLE;
   1228 		if (sc->transfer_priv) {
   1229 			sc->transfer_cb(sc, sc->transfer_priv,
   1230 					sc->transfer_datalen,
   1231 					sc->transfer_status);
   1232 		}
   1233 
   1234 		return;
   1235 
   1236 	/***** Default *****/
   1237 	default:
   1238 		panic("%s: Unknown state %d\n",
   1239 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
   1240 	}
   1241 }
   1242 
   1243 /*
   1244  * Command/Bulk/Interrupt (CBI) specific functions
   1245  */
   1246 
   1247 Static int
   1248 umass_cbi_adsc(struct umass_softc *sc, char *buffer, int buflen,
   1249 	       usbd_xfer_handle xfer)
   1250 {
   1251 	KASSERT(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1252 		("sc->sc_wire == 0x%02x wrong for umass_cbi_adsc\n",
   1253 		sc->sc_wire));
   1254 
   1255 	sc->sc_req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   1256 	sc->sc_req.bRequest = UR_CBI_ADSC;
   1257 	USETW(sc->sc_req.wValue, 0);
   1258 	USETW(sc->sc_req.wIndex, sc->sc_ifaceno);
   1259 	USETW(sc->sc_req.wLength, buflen);
   1260 	return umass_setup_ctrl_transfer(sc, &sc->sc_req, buffer,
   1261 					 buflen, 0, xfer);
   1262 }
   1263 
   1264 
   1265 Static void
   1266 umass_cbi_reset(struct umass_softc *sc, int status)
   1267 {
   1268 	int i;
   1269 #	define SEND_DIAGNOSTIC_CMDLEN	12
   1270 
   1271 	KASSERT(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1272 		("sc->sc_wire == 0x%02x wrong for umass_cbi_reset\n",
   1273 		sc->sc_wire));
   1274 
   1275 	if (sc->sc_dying)
   1276 		return;
   1277 
   1278 	/*
   1279 	 * Command Block Reset Protocol
   1280 	 *
   1281 	 * First send a reset request to the device. Then clear
   1282 	 * any possibly stalled bulk endpoints.
   1283 
   1284 	 * This is done in 3 steps, states:
   1285 	 * TSTATE_CBI_RESET1
   1286 	 * TSTATE_CBI_RESET2
   1287 	 * TSTATE_CBI_RESET3
   1288 	 *
   1289 	 * If the reset doesn't succeed, the device should be port reset.
   1290 	 */
   1291 
   1292 	DPRINTF(UDMASS_CBI, ("%s: CBI Reset\n",
   1293 		USBDEVNAME(sc->sc_dev)));
   1294 
   1295 	KASSERT(sizeof(sc->cbl) >= SEND_DIAGNOSTIC_CMDLEN,
   1296 		("%s: CBL struct is too small (%d < %d)\n",
   1297 			USBDEVNAME(sc->sc_dev),
   1298 			sizeof(sc->cbl), SEND_DIAGNOSTIC_CMDLEN));
   1299 
   1300 	sc->transfer_state = TSTATE_CBI_RESET1;
   1301 	sc->transfer_status = status;
   1302 
   1303 	/* The 0x1d code is the SEND DIAGNOSTIC command. To distingiush between
   1304 	 * the two the last 10 bytes of the cbl is filled with 0xff (section
   1305 	 * 2.2 of the CBI spec).
   1306 	 */
   1307 	sc->cbl[0] = 0x1d;	/* Command Block Reset */
   1308 	sc->cbl[1] = 0x04;
   1309 	for (i = 2; i < SEND_DIAGNOSTIC_CMDLEN; i++)
   1310 		sc->cbl[i] = 0xff;
   1311 
   1312 	umass_cbi_adsc(sc, sc->cbl, SEND_DIAGNOSTIC_CMDLEN,
   1313 		       sc->transfer_xfer[XFER_CBI_RESET1]);
   1314 	/* XXX if the command fails we should reset the port on the bub */
   1315 }
   1316 
   1317 Static void
   1318 umass_cbi_transfer(struct umass_softc *sc, int lun,
   1319 		   void *cmd, int cmdlen, void *data, int datalen, int dir,
   1320 		   u_int timeout, umass_callback cb, void *priv)
   1321 {
   1322 	DPRINTF(UDMASS_CBI,("%s: umass_cbi_transfer cmd=0x%02x, len=%d\n",
   1323 		USBDEVNAME(sc->sc_dev), *(u_char*)cmd, datalen));
   1324 
   1325 	KASSERT(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1326 		("sc->sc_wire == 0x%02x wrong for umass_cbi_transfer\n",
   1327 		sc->sc_wire));
   1328 
   1329 	if (sc->sc_dying)
   1330 		return;
   1331 
   1332 	/* Be a little generous. */
   1333 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
   1334 
   1335 	/*
   1336 	 * Do a CBI transfer with cmdlen bytes from cmd, possibly
   1337 	 * a data phase of datalen bytes from/to the device and finally a
   1338 	 * csw read phase.
   1339 	 * If the data direction was inbound a maximum of datalen bytes
   1340 	 * is stored in the buffer pointed to by data.
   1341 	 *
   1342 	 * umass_cbi_transfer initialises the transfer and lets the state
   1343 	 * machine in umass_cbi_state handle the completion. It uses the
   1344 	 * following states:
   1345 	 * TSTATE_CBI_COMMAND
   1346 	 *   -> XXX fill in
   1347 	 *
   1348 	 * An error in any of those states will invoke
   1349 	 * umass_cbi_reset.
   1350 	 */
   1351 
   1352 	/* check the given arguments */
   1353 	KASSERT(datalen == 0 || data != NULL,
   1354 		("%s: datalen > 0, but no buffer",USBDEVNAME(sc->sc_dev)));
   1355 	KASSERT(datalen == 0 || dir != DIR_NONE,
   1356 		("%s: direction is NONE while datalen is not zero\n",
   1357 			USBDEVNAME(sc->sc_dev)));
   1358 
   1359 	/* store the details for the data transfer phase */
   1360 	sc->transfer_dir = dir;
   1361 	sc->transfer_data = data;
   1362 	sc->transfer_datalen = datalen;
   1363 	sc->transfer_actlen = 0;
   1364 	sc->transfer_cb = cb;
   1365 	sc->transfer_priv = priv;
   1366 	sc->transfer_status = STATUS_CMD_OK;
   1367 
   1368 	/* move from idle to the command state */
   1369 	sc->transfer_state = TSTATE_CBI_COMMAND;
   1370 
   1371 	/* Send the Command Block from host to device via control endpoint. */
   1372 	if (umass_cbi_adsc(sc, cmd, cmdlen, sc->transfer_xfer[XFER_CBI_CB]))
   1373 		umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1374 }
   1375 
   1376 Static void
   1377 umass_cbi_state(usbd_xfer_handle xfer, usbd_private_handle priv,
   1378 		usbd_status err)
   1379 {
   1380 	struct umass_softc *sc = (struct umass_softc *) priv;
   1381 
   1382 	KASSERT(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1383 		("sc->sc_wire == 0x%02x wrong for umass_cbi_state\n",
   1384 		sc->sc_wire));
   1385 
   1386 	if (sc->sc_dying)
   1387 		return;
   1388 
   1389 	/*
   1390 	 * State handling for CBI transfers.
   1391 	 */
   1392 
   1393 	DPRINTF(UDMASS_CBI, ("%s: Handling CBI state %d (%s), xfer=%p, %s\n",
   1394 		USBDEVNAME(sc->sc_dev), sc->transfer_state,
   1395 		states[sc->transfer_state], xfer, usbd_errstr(err)));
   1396 
   1397 	switch (sc->transfer_state) {
   1398 
   1399 	/***** CBI Transfer *****/
   1400 	case TSTATE_CBI_COMMAND:
   1401 		if (err == USBD_STALLED) {
   1402 			DPRINTF(UDMASS_CBI, ("%s: Command Transport failed\n",
   1403 				USBDEVNAME(sc->sc_dev)));
   1404 			/* Status transport by control pipe (section 2.3.2.1).
   1405 			 * The command contained in the command block failed.
   1406 			 *
   1407 			 * The control pipe has already been unstalled by the
   1408 			 * USB stack.
   1409 			 * Section 2.4.3.1.1 states that the bulk in endpoints
   1410 			 * should not stalled at this point.
   1411 			 */
   1412 
   1413 			sc->transfer_state = TSTATE_IDLE;
   1414 			sc->transfer_cb(sc, sc->transfer_priv,
   1415 					sc->transfer_datalen,
   1416 					STATUS_CMD_FAILED);
   1417 
   1418 			return;
   1419 		} else if (err) {
   1420 			DPRINTF(UDMASS_CBI, ("%s: failed to send ADSC\n",
   1421 				USBDEVNAME(sc->sc_dev)));
   1422 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1423 
   1424 			return;
   1425 		}
   1426 
   1427 		sc->transfer_state = TSTATE_CBI_DATA;
   1428 		if (sc->transfer_dir == DIR_IN) {
   1429 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1430 					sc->transfer_data, sc->transfer_datalen,
   1431 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
   1432 					sc->transfer_xfer[XFER_CBI_DATA]))
   1433 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1434 
   1435 		} else if (sc->transfer_dir == DIR_OUT) {
   1436 			memcpy(sc->data_buffer, sc->transfer_data,
   1437 			       sc->transfer_datalen);
   1438 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
   1439 					sc->transfer_data, sc->transfer_datalen,
   1440 					USBD_NO_COPY,/* fixed length transfer */
   1441 					sc->transfer_xfer[XFER_CBI_DATA]))
   1442 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1443 
   1444 		} else if (sc->sc_wire == UMASS_WPROTO_CBI_I) {
   1445 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
   1446 				USBDEVNAME(sc->sc_dev)));
   1447 			sc->transfer_state = TSTATE_CBI_STATUS;
   1448 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_INTRIN],
   1449 					&sc->sbl, sizeof(sc->sbl),
   1450 					0,	/* fixed length transfer */
   1451 					sc->transfer_xfer[XFER_CBI_STATUS])){
   1452 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1453 			}
   1454 		} else {
   1455 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
   1456 				USBDEVNAME(sc->sc_dev)));
   1457 			/* No command completion interrupt. Request
   1458 			 * sense data.
   1459 			 */
   1460 			sc->transfer_state = TSTATE_IDLE;
   1461 			sc->transfer_cb(sc, sc->transfer_priv,
   1462 			       0, STATUS_CMD_UNKNOWN);
   1463 		}
   1464 
   1465 		return;
   1466 
   1467 	case TSTATE_CBI_DATA:
   1468 		/* retrieve the length of the transfer that was done */
   1469 		usbd_get_xfer_status(xfer,NULL,NULL,&sc->transfer_actlen,NULL);
   1470 		DPRINTF(UDMASS_CBI, ("%s: CBI_DATA actlen=%d\n",
   1471 			USBDEVNAME(sc->sc_dev), sc->transfer_actlen));
   1472 
   1473 		if (err) {
   1474 			DPRINTF(UDMASS_CBI, ("%s: Data-%s %d failed, "
   1475 				"%s\n", USBDEVNAME(sc->sc_dev),
   1476 				(sc->transfer_dir == DIR_IN?"in":"out"),
   1477 				sc->transfer_datalen,usbd_errstr(err)));
   1478 
   1479 			if (err == USBD_STALLED) {
   1480 				sc->transfer_state = TSTATE_CBI_DCLEAR;
   1481 				umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1482 					sc->transfer_xfer[XFER_CBI_DCLEAR]);
   1483 			} else {
   1484 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1485 			}
   1486 			return;
   1487 		}
   1488 
   1489 		if (sc->transfer_dir == DIR_IN)
   1490 			memcpy(sc->transfer_data, sc->data_buffer,
   1491 			       sc->transfer_actlen);
   1492 
   1493 		DIF(UDMASS_CBI, if (sc->transfer_dir == DIR_IN)
   1494 					umass_dump_buffer(sc, sc->transfer_data,
   1495 						sc->transfer_actlen, 48));
   1496 
   1497 		if (sc->sc_wire == UMASS_WPROTO_CBI_I) {
   1498 			sc->transfer_state = TSTATE_CBI_STATUS;
   1499 			memset(&sc->sbl, 0, sizeof(sc->sbl));
   1500 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_INTRIN],
   1501 				    &sc->sbl, sizeof(sc->sbl),
   1502 				    0,	/* fixed length transfer */
   1503 				    sc->transfer_xfer[XFER_CBI_STATUS])){
   1504 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1505 			}
   1506 		} else {
   1507 			/* No command completion interrupt. Request
   1508 			 * sense to get status of command.
   1509 			 */
   1510 			sc->transfer_state = TSTATE_IDLE;
   1511 			sc->transfer_cb(sc, sc->transfer_priv,
   1512 				sc->transfer_datalen - sc->transfer_actlen,
   1513 				STATUS_CMD_UNKNOWN);
   1514 		}
   1515 		return;
   1516 
   1517 	case TSTATE_CBI_STATUS:
   1518 		if (err) {
   1519 			DPRINTF(UDMASS_CBI, ("%s: Status Transport failed\n",
   1520 				USBDEVNAME(sc->sc_dev)));
   1521 			/* Status transport by interrupt pipe (section 2.3.2.2).
   1522 			 */
   1523 
   1524 			if (err == USBD_STALLED) {
   1525 				sc->transfer_state = TSTATE_CBI_SCLEAR;
   1526 				umass_clear_endpoint_stall(sc, UMASS_INTRIN,
   1527 					sc->transfer_xfer[XFER_CBI_SCLEAR]);
   1528 			} else {
   1529 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1530 			}
   1531 			return;
   1532 		}
   1533 
   1534 		/* Dissect the information in the buffer */
   1535 
   1536 		if (sc->sc_cmd == UMASS_CPROTO_UFI) {
   1537 			int status;
   1538 
   1539 			/* Section 3.4.3.1.3 specifies that the UFI command
   1540 			 * protocol returns an ASC and ASCQ in the interrupt
   1541 			 * data block.
   1542 			 */
   1543 
   1544 			DPRINTF(UDMASS_CBI, ("%s: UFI CCI, ASC = 0x%02x, "
   1545 				"ASCQ = 0x%02x\n",
   1546 				USBDEVNAME(sc->sc_dev),
   1547 				sc->sbl.ufi.asc, sc->sbl.ufi.ascq));
   1548 
   1549 			if (sc->sbl.ufi.asc == 0 && sc->sbl.ufi.ascq == 0)
   1550 				status = STATUS_CMD_OK;
   1551 			else
   1552 				status = STATUS_CMD_FAILED;
   1553 
   1554 			/* No sense, command successfull */
   1555 		} else {
   1556 			/* Command Interrupt Data Block */
   1557 			DPRINTF(UDMASS_CBI, ("%s: type=0x%02x, value=0x%02x\n",
   1558 				USBDEVNAME(sc->sc_dev),
   1559 				sc->sbl.common.type, sc->sbl.common.value));
   1560 
   1561 			if (sc->sbl.common.type == IDB_TYPE_CCI) {
   1562 				int err;
   1563 
   1564 				if ((sc->sbl.common.value&IDB_VALUE_STATUS_MASK)
   1565 							== IDB_VALUE_PASS) {
   1566 					err = STATUS_CMD_OK;
   1567 				} else if ((sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
   1568 							== IDB_VALUE_FAIL ||
   1569 					   (sc->sbl.common.value & IDB_VALUE_STATUS_MASK)
   1570 						== IDB_VALUE_PERSISTENT) {
   1571 					err = STATUS_CMD_FAILED;
   1572 				} else {
   1573 					err = STATUS_WIRE_FAILED;
   1574 				}
   1575 
   1576 				sc->transfer_state = TSTATE_IDLE;
   1577 				sc->transfer_cb(sc, sc->transfer_priv,
   1578 						sc->transfer_datalen,
   1579 						err);
   1580 			}
   1581 		}
   1582 		return;
   1583 
   1584 	case TSTATE_CBI_DCLEAR:
   1585 		if (err) {	/* should not occur */
   1586 			printf("%s: CBI bulk-in/out stall clear failed, %s\n",
   1587 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1588 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1589 		}
   1590 
   1591 		sc->transfer_state = TSTATE_IDLE;
   1592 		sc->transfer_cb(sc, sc->transfer_priv,
   1593 				sc->transfer_datalen,
   1594 				STATUS_CMD_FAILED);
   1595 		return;
   1596 
   1597 	case TSTATE_CBI_SCLEAR:
   1598 		if (err)	/* should not occur */
   1599 			printf("%s: CBI intr-in stall clear failed, %s\n",
   1600 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1601 
   1602 		/* Something really bad is going on. Reset the device */
   1603 		umass_cbi_reset(sc, STATUS_CMD_FAILED);
   1604 		return;
   1605 
   1606 	/***** CBI Reset *****/
   1607 	case TSTATE_CBI_RESET1:
   1608 		if (err)
   1609 			printf("%s: CBI reset failed, %s\n",
   1610 				USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1611 
   1612 		sc->transfer_state = TSTATE_CBI_RESET2;
   1613 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1614 			sc->transfer_xfer[XFER_CBI_RESET2]);
   1615 
   1616 		return;
   1617 	case TSTATE_CBI_RESET2:
   1618 		if (err)	/* should not occur */
   1619 			printf("%s: CBI bulk-in stall clear failed, %s\n",
   1620 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1621 			/* no error recovery, otherwise we end up in a loop */
   1622 
   1623 		sc->transfer_state = TSTATE_CBI_RESET3;
   1624 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
   1625 			sc->transfer_xfer[XFER_CBI_RESET3]);
   1626 
   1627 		return;
   1628 	case TSTATE_CBI_RESET3:
   1629 		if (err)	/* should not occur */
   1630 			printf("%s: CBI bulk-out stall clear failed, %s\n",
   1631 			       USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1632 			/* no error recovery, otherwise we end up in a loop */
   1633 
   1634 		sc->transfer_state = TSTATE_IDLE;
   1635 		if (sc->transfer_priv) {
   1636 			sc->transfer_cb(sc, sc->transfer_priv,
   1637 					sc->transfer_datalen,
   1638 					sc->transfer_status);
   1639 		}
   1640 
   1641 		return;
   1642 
   1643 
   1644 	/***** Default *****/
   1645 	default:
   1646 		panic("%s: Unknown state %d\n",
   1647 		      USBDEVNAME(sc->sc_dev), sc->transfer_state);
   1648 	}
   1649 }
   1650 
   1651 usbd_status
   1652 umass_bbb_get_max_lun(struct umass_softc *sc, u_int8_t *maxlun)
   1653 {
   1654 	usb_device_request_t req;
   1655 	usbd_status err;
   1656 
   1657 	*maxlun = 0;		/* Default to 0. */
   1658 
   1659 	DPRINTF(UDMASS_BBB, ("%s: Get Max Lun\n", USBDEVNAME(sc->sc_dev)));
   1660 
   1661 	/* The Get Max Lun command is a class-specific request. */
   1662 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
   1663 	req.bRequest = UR_BBB_GET_MAX_LUN;
   1664 	USETW(req.wValue, 0);
   1665 	USETW(req.wIndex, sc->sc_ifaceno);
   1666 	USETW(req.wLength, 1);
   1667 
   1668 	err = usbd_do_request(sc->sc_udev, &req, maxlun);
   1669 	switch (err) {
   1670 	case USBD_NORMAL_COMPLETION:
   1671 		DPRINTF(UDMASS_BBB, ("%s: Max Lun %d\n",
   1672 		    USBDEVNAME(sc->sc_dev), *maxlun));
   1673 		break;
   1674 
   1675 	case USBD_STALLED:
   1676 		/*
   1677 		 * Device doesn't support Get Max Lun request.
   1678 		 */
   1679 		err = USBD_NORMAL_COMPLETION;
   1680 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun not supported\n",
   1681 		    USBDEVNAME(sc->sc_dev)));
   1682 		break;
   1683 
   1684 	case USBD_SHORT_XFER:
   1685 		/*
   1686 		 * XXX This must mean Get Max Lun is not supported, too!
   1687 		 */
   1688 		err = USBD_NORMAL_COMPLETION;
   1689 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun SHORT_XFER\n",
   1690 		    USBDEVNAME(sc->sc_dev)));
   1691 		break;
   1692 
   1693 	default:
   1694 		printf("%s: Get Max Lun failed: %s\n",
   1695 		    USBDEVNAME(sc->sc_dev), usbd_errstr(err));
   1696 		/* XXX Should we port_reset the device? */
   1697 		break;
   1698 	}
   1699 
   1700 	return (err);
   1701 }
   1702 
   1703 
   1704 
   1705 
   1706 #ifdef UMASS_DEBUG
   1707 Static void
   1708 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
   1709 {
   1710 	int clen = cbw->bCDBLength;
   1711 	int dlen = UGETDW(cbw->dCBWDataTransferLength);
   1712 	u_int8_t *c = cbw->CBWCDB;
   1713 	int tag = UGETDW(cbw->dCBWTag);
   1714 	int flags = cbw->bCBWFlags;
   1715 
   1716 	DPRINTF(UDMASS_BBB, ("%s: CBW %d: cmdlen = %d "
   1717 		"(0x%02x%02x%02x%02x%02x%02x%s), "
   1718 		"data = %d bytes, dir = %s\n",
   1719 		USBDEVNAME(sc->sc_dev), tag, clen,
   1720 		c[0], c[1], c[2], c[3], c[4], c[5], (clen > 6? "...":""),
   1721 		dlen, (flags == CBWFLAGS_IN? "in":
   1722 		       (flags == CBWFLAGS_OUT? "out":"<invalid>"))));
   1723 }
   1724 
   1725 Static void
   1726 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
   1727 {
   1728 	int sig = UGETDW(csw->dCSWSignature);
   1729 	int tag = UGETW(csw->dCSWTag);
   1730 	int res = UGETDW(csw->dCSWDataResidue);
   1731 	int status = csw->bCSWStatus;
   1732 
   1733 	DPRINTF(UDMASS_BBB, ("%s: CSW %d: sig = 0x%08x (%s), tag = %d, "
   1734 		"res = %d, status = 0x%02x (%s)\n", USBDEVNAME(sc->sc_dev),
   1735 		tag, sig, (sig == CSWSIGNATURE?	 "valid":"invalid"),
   1736 		tag, res,
   1737 		status, (status == CSWSTATUS_GOOD? "good":
   1738 			 (status == CSWSTATUS_FAILED? "failed":
   1739 			  (status == CSWSTATUS_PHASE? "phase":"<invalid>")))));
   1740 }
   1741 
   1742 Static void
   1743 umass_dump_buffer(struct umass_softc *sc, u_int8_t *buffer, int buflen,
   1744 		  int printlen)
   1745 {
   1746 	int i, j;
   1747 	char s1[40];
   1748 	char s2[40];
   1749 	char s3[5];
   1750 
   1751 	s1[0] = '\0';
   1752 	s3[0] = '\0';
   1753 
   1754 	sprintf(s2, " buffer=%p, buflen=%d", buffer, buflen);
   1755 	for (i = 0; i < buflen && i < printlen; i++) {
   1756 		j = i % 16;
   1757 		if (j == 0 && i != 0) {
   1758 			DPRINTF(UDMASS_GEN, ("%s: 0x %s%s\n",
   1759 				USBDEVNAME(sc->sc_dev), s1, s2));
   1760 			s2[0] = '\0';
   1761 		}
   1762 		sprintf(&s1[j*2], "%02x", buffer[i] & 0xff);
   1763 	}
   1764 	if (buflen > printlen)
   1765 		sprintf(s3, " ...");
   1766 	DPRINTF(UDMASS_GEN, ("%s: 0x %s%s%s\n",
   1767 		USBDEVNAME(sc->sc_dev), s1, s2, s3));
   1768 }
   1769 #endif
   1770