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