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