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