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