Home | History | Annotate | Line # | Download | only in usb
umass.c revision 1.156
      1 /*	$NetBSD: umass.c,v 1.156 2016/07/07 06:55:42 msaitoh 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.156 2016/07/07 06:55:42 msaitoh 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,
    531 				&sc->sc_pipe[UMASS_BULKOUT]);
    532 	if (err) {
    533 		aprint_error_dev(self, "cannot open %u-out pipe (bulk)\n",
    534 		    sc->sc_epaddr[UMASS_BULKOUT]);
    535 		umass_disco(sc);
    536 		return;
    537 	}
    538 	DPRINTFM(UDMASS_USB, "sc %p: opening iface %p epaddr %d for BULKIN",
    539 	    sc, sc->sc_iface, sc->sc_epaddr[UMASS_BULKIN], 0);
    540 	err = usbd_open_pipe(sc->sc_iface, sc->sc_epaddr[UMASS_BULKIN],
    541 	    USBD_EXCLUSIVE_USE, &sc->sc_pipe[UMASS_BULKIN]);
    542 	if (err) {
    543 		aprint_error_dev(self, "could not open %u-in pipe (bulk)\n",
    544 		    sc->sc_epaddr[UMASS_BULKIN]);
    545 		umass_disco(sc);
    546 		return;
    547 	}
    548 	/*
    549 	 * Open the intr-in pipe if the protocol is CBI with CCI.
    550 	 * Note: early versions of the Zip drive do have an interrupt pipe, but
    551 	 * this pipe is unused
    552 	 *
    553 	 * We do not open the interrupt pipe as an interrupt pipe, but as a
    554 	 * normal bulk endpoint. We send an IN transfer down the wire at the
    555 	 * appropriate time, because we know exactly when to expect data on
    556 	 * that endpoint. This saves bandwidth, but more important, makes the
    557 	 * code for handling the data on that endpoint simpler. No data
    558 	 * arriving concurrently.
    559 	 */
    560 	if (sc->sc_wire == UMASS_WPROTO_CBI_I) {
    561 		DPRINTFM(UDMASS_USB,
    562 		    "sc %p: opening iface %p epaddr %d for INTRIN",
    563 		    sc, sc->sc_iface, sc->sc_epaddr[UMASS_INTRIN], 0);
    564 		err = usbd_open_pipe(sc->sc_iface, sc->sc_epaddr[UMASS_INTRIN],
    565 				USBD_EXCLUSIVE_USE, &sc->sc_pipe[UMASS_INTRIN]);
    566 		if (err) {
    567 			aprint_error_dev(self, "couldn't open %u-in (intr)\n",
    568 			    sc->sc_epaddr[UMASS_INTRIN]);
    569 			umass_disco(sc);
    570 			return;
    571 		}
    572 	}
    573 
    574 	/* initialisation of generic part */
    575 	sc->transfer_state = TSTATE_IDLE;
    576 
    577 	for (i = 0; i < XFER_NR; i++) {
    578 		sc->transfer_xfer[i] = NULL;
    579 	}
    580 
    581 	/*
    582 	 * Create the transfers
    583 	 */
    584 	struct usbd_pipe *pipe0 = usbd_get_pipe0(sc->sc_udev);
    585 	switch (sc->sc_wire) {
    586 	case UMASS_WPROTO_BBB:
    587 		err = usbd_create_xfer(sc->sc_pipe[UMASS_BULKIN],
    588 		    UMASS_MAX_TRANSFER_SIZE, USBD_SHORT_XFER_OK, 0,
    589 		    &sc->transfer_xfer[XFER_BBB_DATAIN]);
    590 		if (err)
    591 			goto fail_create;
    592 		err = usbd_create_xfer(sc->sc_pipe[UMASS_BULKOUT],
    593 		    UMASS_MAX_TRANSFER_SIZE, USBD_SHORT_XFER_OK, 0,
    594 		    &sc->transfer_xfer[XFER_BBB_DATAOUT]);
    595 		if (err)
    596 			goto fail_create;
    597 		err = usbd_create_xfer(sc->sc_pipe[UMASS_BULKOUT],
    598 		    UMASS_BBB_CBW_SIZE, USBD_SHORT_XFER_OK, 0,
    599 		    &sc->transfer_xfer[XFER_BBB_CBW]);
    600 		if (err)
    601 			goto fail_create;
    602 		err = usbd_create_xfer(sc->sc_pipe[UMASS_BULKIN],
    603 		    UMASS_BBB_CSW_SIZE, USBD_SHORT_XFER_OK, 0,
    604 		    &sc->transfer_xfer[XFER_BBB_CSW1]);
    605 		if (err)
    606 			goto fail_create;
    607 		err = usbd_create_xfer(sc->sc_pipe[UMASS_BULKIN],
    608 		    UMASS_BBB_CSW_SIZE, USBD_SHORT_XFER_OK, 0,
    609 		    &sc->transfer_xfer[XFER_BBB_CSW2]);
    610 		if (err)
    611 			goto fail_create;
    612 		err = usbd_create_xfer(pipe0, 0, 0, 0,
    613 		    &sc->transfer_xfer[XFER_BBB_SCLEAR]);
    614 		if (err)
    615 			goto fail_create;
    616 		err = usbd_create_xfer(pipe0, 0, 0, 0,
    617 		    &sc->transfer_xfer[XFER_BBB_DCLEAR]);
    618 		if (err)
    619 			goto fail_create;
    620 		err = usbd_create_xfer(pipe0, 0, 0, 0,
    621 		    &sc->transfer_xfer[XFER_BBB_RESET1]);
    622 		if (err)
    623 			goto fail_create;
    624 		err = usbd_create_xfer(pipe0, 0, 0, 0,
    625 		    &sc->transfer_xfer[XFER_BBB_RESET2]);
    626 		if (err)
    627 			goto fail_create;
    628 		err = usbd_create_xfer(pipe0, 0, 0, 0,
    629 		    &sc->transfer_xfer[XFER_BBB_RESET3]);
    630 		if (err)
    631 			goto fail_create;
    632 		break;
    633 	case UMASS_WPROTO_CBI:
    634 	case UMASS_WPROTO_CBI_I:
    635 		err = usbd_create_xfer(pipe0, sizeof(sc->cbl), 0, 0,
    636 		    &sc->transfer_xfer[XFER_CBI_CB]);
    637 		if (err)
    638 			goto fail_create;
    639 		err = usbd_create_xfer(sc->sc_pipe[UMASS_BULKIN],
    640 		    UMASS_MAX_TRANSFER_SIZE, USBD_SHORT_XFER_OK, 0,
    641 		    &sc->transfer_xfer[XFER_CBI_DATAIN]);
    642 		if (err)
    643 			goto fail_create;
    644 		err = usbd_create_xfer(sc->sc_pipe[UMASS_BULKOUT],
    645 		    UMASS_MAX_TRANSFER_SIZE, 0, 0,
    646 		    &sc->transfer_xfer[XFER_CBI_DATAOUT]);
    647 		if (err)
    648 			goto fail_create;
    649 		err = usbd_create_xfer(sc->sc_pipe[UMASS_INTRIN],
    650 		    sizeof(sc->sbl), 0, 0,
    651 		    &sc->transfer_xfer[XFER_CBI_STATUS]);
    652 		if (err)
    653 			goto fail_create;
    654 		err = usbd_create_xfer(pipe0, 0, 0, 0,
    655 		    &sc->transfer_xfer[XFER_CBI_DCLEAR]);
    656 		if (err)
    657 			goto fail_create;
    658 		err = usbd_create_xfer(pipe0, 0, 0, 0,
    659 		    &sc->transfer_xfer[XFER_CBI_SCLEAR]);
    660 		if (err)
    661 			goto fail_create;
    662 		err = usbd_create_xfer(pipe0, sizeof(sc->cbl), 0, 0,
    663 		    &sc->transfer_xfer[XFER_CBI_RESET1]);
    664 		if (err)
    665 			goto fail_create;
    666 		err = usbd_create_xfer(pipe0, sizeof(sc->cbl), 0, 0,
    667 		    &sc->transfer_xfer[XFER_CBI_RESET2]);
    668 		if (err)
    669 			goto fail_create;
    670 		err = usbd_create_xfer(pipe0, sizeof(sc->cbl), 0, 0,
    671 		    &sc->transfer_xfer[XFER_CBI_RESET3]);
    672 		if (err)
    673 			goto fail_create;
    674 		break;
    675 	default:
    676 	fail_create:
    677 		aprint_error_dev(self, "failed to create xfers\n");
    678 		umass_disco(sc);
    679 		return;
    680 	}
    681 
    682 	/*
    683 	 * Record buffer pinters for data transfer (it's huge), command and
    684 	 * status data here
    685 	 */
    686 	switch (sc->sc_wire) {
    687 	case UMASS_WPROTO_BBB:
    688 		sc->datain_buffer =
    689 		    usbd_get_buffer(sc->transfer_xfer[XFER_BBB_DATAIN]);
    690 		sc->dataout_buffer =
    691 		    usbd_get_buffer(sc->transfer_xfer[XFER_BBB_DATAOUT]);
    692 		sc->cmd_buffer =
    693 		    usbd_get_buffer(sc->transfer_xfer[XFER_BBB_CBW]);
    694 		sc->s1_buffer =
    695 		    usbd_get_buffer(sc->transfer_xfer[XFER_BBB_CSW1]);
    696 		sc->s2_buffer =
    697 		    usbd_get_buffer(sc->transfer_xfer[XFER_BBB_CSW2]);
    698 		break;
    699 	case UMASS_WPROTO_CBI:
    700 	case UMASS_WPROTO_CBI_I:
    701 		sc->datain_buffer =
    702 		    usbd_get_buffer(sc->transfer_xfer[XFER_CBI_DATAIN]);
    703 		sc->dataout_buffer =
    704 		    usbd_get_buffer(sc->transfer_xfer[XFER_CBI_DATAOUT]);
    705 		sc->cmd_buffer =
    706 		    usbd_get_buffer(sc->transfer_xfer[XFER_CBI_CB]);
    707 		sc->s1_buffer =
    708 		    usbd_get_buffer(sc->transfer_xfer[XFER_CBI_STATUS]);
    709 		sc->s2_buffer =
    710 		    usbd_get_buffer(sc->transfer_xfer[XFER_CBI_RESET1]);
    711 		break;
    712 	default:
    713 		break;
    714 	}
    715 
    716 	/* Initialise the wire protocol specific methods */
    717 	switch (sc->sc_wire) {
    718 	case UMASS_WPROTO_BBB:
    719 		sc->sc_methods = &umass_bbb_methods;
    720 		break;
    721 	case UMASS_WPROTO_CBI:
    722 	case UMASS_WPROTO_CBI_I:
    723 		sc->sc_methods = &umass_cbi_methods;
    724 		break;
    725 	default:
    726 		umass_disco(sc);
    727 		return;
    728 	}
    729 
    730 	error = 0;
    731 	switch (sc->sc_cmd) {
    732 	case UMASS_CPROTO_RBC:
    733 	case UMASS_CPROTO_SCSI:
    734 #if NSCSIBUS > 0
    735 		error = umass_scsi_attach(sc);
    736 #else
    737 		aprint_error_dev(self, "scsibus not configured\n");
    738 #endif
    739 		break;
    740 
    741 	case UMASS_CPROTO_UFI:
    742 	case UMASS_CPROTO_ATAPI:
    743 #if NATAPIBUS > 0
    744 		error = umass_atapi_attach(sc);
    745 #else
    746 		aprint_error_dev(self, "atapibus not configured\n");
    747 #endif
    748 		break;
    749 
    750 	case UMASS_CPROTO_ISD_ATA:
    751 #if NWD > 0
    752 		error = umass_isdata_attach(sc);
    753 #else
    754 		aprint_error_dev(self, "isdata not configured\n");
    755 #endif
    756 		break;
    757 
    758 	default:
    759 		aprint_error_dev(self, "command protocol=0x%x not supported\n",
    760 		    sc->sc_cmd);
    761 		umass_disco(sc);
    762 		return;
    763 	}
    764 	if (error) {
    765 		aprint_error_dev(self, "bus attach failed\n");
    766 		umass_disco(sc);
    767 		return;
    768 	}
    769 
    770 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
    771 
    772 	if (!pmf_device_register(self, NULL, NULL))
    773 		aprint_error_dev(self, "couldn't establish power handler\n");
    774 
    775 	DPRINTFM(UDMASS_GEN, "sc %p: Attach finished", sc, 0, 0, 0);
    776 
    777 	return;
    778 }
    779 
    780 static void
    781 umass_childdet(device_t self, device_t child)
    782 {
    783 	struct umass_softc *sc = device_private(self);
    784 
    785 	KASSERTMSG(child == sc->bus->sc_child,
    786 		   "assertion child == sc->bus->sc_child failed\n");
    787 	sc->bus->sc_child = NULL;
    788 }
    789 
    790 int
    791 umass_detach(device_t self, int flags)
    792 {
    793 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
    794 	struct umass_softc *sc = device_private(self);
    795 	struct umassbus_softc *scbus;
    796 	int rv = 0, i;
    797 
    798 	DPRINTFM(UDMASS_USB, "sc %p detached", sc, 0, 0, 0);
    799 
    800 	pmf_device_deregister(self);
    801 
    802 	/* Abort the pipes to wake up any waiting processes. */
    803 	for (i = 0 ; i < UMASS_NEP ; i++) {
    804 		if (sc->sc_pipe[i] != NULL)
    805 			usbd_abort_pipe(sc->sc_pipe[i]);
    806 	}
    807 
    808 	/* Do we really need reference counting?  Perhaps in ioctl() */
    809 	mutex_enter(&sc->sc_lock);
    810 	if (--sc->sc_refcnt >= 0) {
    811 #ifdef DIAGNOSTIC
    812 		aprint_normal_dev(self, "waiting for refcnt\n");
    813 #endif
    814 		/* Wait for processes to go away. */
    815 		usb_detach_wait(sc->sc_dev, &sc->sc_detach_cv, &sc->sc_lock);
    816 	}
    817 	mutex_exit(&sc->sc_lock);
    818 
    819 	scbus = sc->bus;
    820 	if (scbus != NULL) {
    821 		if (scbus->sc_child != NULL)
    822 			rv = config_detach(scbus->sc_child, flags);
    823 		free(scbus, M_DEVBUF);
    824 		sc->bus = NULL;
    825 	}
    826 
    827 	if (rv != 0)
    828 		return rv;
    829 
    830 	umass_disco(sc);
    831 
    832 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
    833 
    834 	mutex_destroy(&sc->sc_lock);
    835 	cv_destroy(&sc->sc_detach_cv);
    836 
    837 	return rv;
    838 }
    839 
    840 int
    841 umass_activate(device_t dev, enum devact act)
    842 {
    843 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
    844 	struct umass_softc *sc = device_private(dev);
    845 
    846 	DPRINTFM(UDMASS_USB, "sc %p act %d", sc, act, 0, 0);
    847 
    848 	switch (act) {
    849 	case DVACT_DEACTIVATE:
    850 		sc->sc_dying = 1;
    851 		return 0;
    852 	default:
    853 		return EOPNOTSUPP;
    854 	}
    855 }
    856 
    857 Static void
    858 umass_disco(struct umass_softc *sc)
    859 {
    860 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
    861 	int i;
    862 
    863 	/* Remove all the pipes. */
    864 	for (i = 0 ; i < UMASS_NEP ; i++) {
    865 		if (sc->sc_pipe[i] != NULL) {
    866 			usbd_abort_pipe(sc->sc_pipe[i]);
    867 		}
    868 	}
    869 
    870 	/* Some xfers may be queued in the default pipe */
    871 	usbd_abort_default_pipe(sc->sc_udev);
    872 
    873 	/* Free the xfers. */
    874 	for (i = 0; i < XFER_NR; i++) {
    875 		if (sc->transfer_xfer[i] != NULL) {
    876 			usbd_destroy_xfer(sc->transfer_xfer[i]);
    877 			sc->transfer_xfer[i] = NULL;
    878 		}
    879 	}
    880 
    881 	for (i = 0 ; i < UMASS_NEP ; i++) {
    882 		if (sc->sc_pipe[i] != NULL) {
    883 			usbd_close_pipe(sc->sc_pipe[i]);
    884 			sc->sc_pipe[i] = NULL;
    885 		}
    886 	}
    887 
    888 }
    889 
    890 /*
    891  * Generic functions to handle transfers
    892  */
    893 
    894 Static usbd_status
    895 umass_setup_transfer(struct umass_softc *sc, struct usbd_pipe *pipe,
    896 			void *buffer, int buflen, int flags,
    897 			struct usbd_xfer *xfer)
    898 {
    899 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
    900 	usbd_status err;
    901 
    902 	if (sc->sc_dying)
    903 		return USBD_IOERROR;
    904 
    905 	/* Initialiase a USB transfer and then schedule it */
    906 
    907 	usbd_setup_xfer(xfer, sc, buffer, buflen, flags, sc->timeout,
    908 	    sc->sc_methods->wire_state);
    909 
    910 	err = usbd_transfer(xfer);
    911 	DPRINTFM(UDMASS_XFER, "start xfer buffer=%p buflen=%d flags=0x%x "
    912 	    "timeout=%d", buffer, buflen, flags, sc->timeout);
    913 	if (err && err != USBD_IN_PROGRESS) {
    914 		DPRINTFM(UDMASS_BBB, "failed to setup transfer... err=%d",
    915 		    err, 0, 0, 0);
    916 		return err;
    917 	}
    918 
    919 	return USBD_NORMAL_COMPLETION;
    920 }
    921 
    922 
    923 Static usbd_status
    924 umass_setup_ctrl_transfer(struct umass_softc *sc, usb_device_request_t *req,
    925 	 void *buffer, int buflen, int flags, struct usbd_xfer *xfer)
    926 {
    927 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
    928 	usbd_status err;
    929 
    930 	if (sc->sc_dying)
    931 		return USBD_IOERROR;
    932 
    933 	/* Initialiase a USB control transfer and then schedule it */
    934 
    935 	usbd_setup_default_xfer(xfer, sc->sc_udev, (void *) sc, sc->timeout,
    936 		req, buffer, buflen, flags, sc->sc_methods->wire_state);
    937 
    938 	err = usbd_transfer(xfer);
    939 	if (err && err != USBD_IN_PROGRESS) {
    940 		DPRINTFM(UDMASS_BBB, "failed to setup ctrl transfer... err=%d",
    941 		    err, 0, 0, 0);
    942 
    943 		/* do not reset, as this would make us loop */
    944 		return err;
    945 	}
    946 
    947 	return USBD_NORMAL_COMPLETION;
    948 }
    949 
    950 Static void
    951 umass_clear_endpoint_stall(struct umass_softc *sc, int endpt,
    952 	struct usbd_xfer *xfer)
    953 {
    954 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
    955 
    956 	if (sc->sc_dying)
    957 		return;
    958 
    959 	DPRINTFM(UDMASS_BBB, "Clear endpoint 0x%02x stall",
    960 	    sc->sc_epaddr[endpt], 0, 0, 0);
    961 
    962 	usbd_clear_endpoint_toggle(sc->sc_pipe[endpt]);
    963 
    964 	sc->sc_req.bmRequestType = UT_WRITE_ENDPOINT;
    965 	sc->sc_req.bRequest = UR_CLEAR_FEATURE;
    966 	USETW(sc->sc_req.wValue, UF_ENDPOINT_HALT);
    967 	USETW(sc->sc_req.wIndex, sc->sc_epaddr[endpt]);
    968 	USETW(sc->sc_req.wLength, 0);
    969 	umass_setup_ctrl_transfer(sc, &sc->sc_req, NULL, 0, 0, xfer);
    970 }
    971 
    972 #if 0
    973 Static void
    974 umass_reset(struct umass_softc *sc, transfer_cb_f cb, void *priv)
    975 {
    976 	sc->transfer_cb = cb;
    977 	sc->transfer_priv = priv;
    978 
    979 	/* The reset is a forced reset, so no error (yet) */
    980 	sc->reset(sc, STATUS_CMD_OK);
    981 }
    982 #endif
    983 
    984 /*
    985  * Bulk protocol specific functions
    986  */
    987 
    988 Static void
    989 umass_bbb_reset(struct umass_softc *sc, int status)
    990 {
    991 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
    992 	KASSERTMSG(sc->sc_wire & UMASS_WPROTO_BBB,
    993 		   "sc->sc_wire == 0x%02x wrong for umass_bbb_reset\n",
    994 		   sc->sc_wire);
    995 
    996 	if (sc->sc_dying)
    997 		return;
    998 
    999 	/*
   1000 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
   1001 	 *
   1002 	 * For Reset Recovery the host shall issue in the following order:
   1003 	 * a) a Bulk-Only Mass Storage Reset
   1004 	 * b) a Clear Feature HALT to the Bulk-In endpoint
   1005 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
   1006 	 *
   1007 	 * This is done in 3 steps, states:
   1008 	 * TSTATE_BBB_RESET1
   1009 	 * TSTATE_BBB_RESET2
   1010 	 * TSTATE_BBB_RESET3
   1011 	 *
   1012 	 * If the reset doesn't succeed, the device should be port reset.
   1013 	 */
   1014 
   1015 	DPRINTFM(UDMASS_BBB, "Bulk Reset", 0, 0, 0, 0);
   1016 
   1017 	sc->transfer_state = TSTATE_BBB_RESET1;
   1018 	sc->transfer_status = status;
   1019 
   1020 	/* reset is a class specific interface write */
   1021 	sc->sc_req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   1022 	sc->sc_req.bRequest = UR_BBB_RESET;
   1023 	USETW(sc->sc_req.wValue, 0);
   1024 	USETW(sc->sc_req.wIndex, sc->sc_ifaceno);
   1025 	USETW(sc->sc_req.wLength, 0);
   1026 	umass_setup_ctrl_transfer(sc, &sc->sc_req, NULL, 0, 0,
   1027 				  sc->transfer_xfer[XFER_BBB_RESET1]);
   1028 }
   1029 
   1030 Static void
   1031 umass_bbb_transfer(struct umass_softc *sc, int lun, void *cmd, int cmdlen,
   1032 		   void *data, int datalen, int dir, u_int timeout,
   1033 		   int flags, umass_callback cb, void *priv)
   1034 {
   1035 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1036 	static int dCBWtag = 42;	/* unique for CBW of transfer */
   1037 
   1038 	DPRINTFM(UDMASS_BBB, "sc %p cmd=0x%02x", sc, *(u_char *)cmd, 0, 0);
   1039 
   1040 	KASSERTMSG(sc->sc_wire & UMASS_WPROTO_BBB,
   1041 		   "sc->sc_wire == 0x%02x wrong for umass_bbb_transfer\n",
   1042 		   sc->sc_wire);
   1043 
   1044 	if (sc->sc_dying)
   1045 		return;
   1046 
   1047 	/* Be a little generous. */
   1048 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
   1049 
   1050 	/*
   1051 	 * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
   1052 	 * a data phase of datalen bytes from/to the device and finally a
   1053 	 * csw read phase.
   1054 	 * If the data direction was inbound a maximum of datalen bytes
   1055 	 * is stored in the buffer pointed to by data.
   1056 	 *
   1057 	 * umass_bbb_transfer initialises the transfer and lets the state
   1058 	 * machine in umass_bbb_state handle the completion. It uses the
   1059 	 * following states:
   1060 	 * TSTATE_BBB_COMMAND
   1061 	 *   -> TSTATE_BBB_DATA
   1062 	 *   -> TSTATE_BBB_STATUS
   1063 	 *   -> TSTATE_BBB_STATUS2
   1064 	 *   -> TSTATE_BBB_IDLE
   1065 	 *
   1066 	 * An error in any of those states will invoke
   1067 	 * umass_bbb_reset.
   1068 	 */
   1069 
   1070 	/* check the given arguments */
   1071 	KASSERTMSG(datalen == 0 || data != NULL,
   1072 		   "%s: datalen > 0, but no buffer",device_xname(sc->sc_dev));
   1073 	KASSERTMSG(cmdlen <= CBWCDBLENGTH,
   1074 		   "%s: cmdlen exceeds CDB length in CBW (%d > %d)",
   1075 			device_xname(sc->sc_dev), cmdlen, CBWCDBLENGTH);
   1076 	KASSERTMSG(dir == DIR_NONE || datalen > 0,
   1077 		   "%s: datalen == 0 while direction is not NONE\n",
   1078 			device_xname(sc->sc_dev));
   1079 	KASSERTMSG(datalen == 0 || dir != DIR_NONE,
   1080 		   "%s: direction is NONE while datalen is not zero\n",
   1081 			device_xname(sc->sc_dev));
   1082 	/* CTASSERT */
   1083 	KASSERTMSG(sizeof(umass_bbb_cbw_t) == UMASS_BBB_CBW_SIZE,
   1084 		   "%s: CBW struct does not have the right size (%zu vs. %u)\n",
   1085 			device_xname(sc->sc_dev),
   1086 			sizeof(umass_bbb_cbw_t), UMASS_BBB_CBW_SIZE);
   1087 	/* CTASSERT */
   1088 	KASSERTMSG(sizeof(umass_bbb_csw_t) == UMASS_BBB_CSW_SIZE,
   1089 		   "%s: CSW struct does not have the right size (%zu vs. %u)\n",
   1090 			device_xname(sc->sc_dev),
   1091 			sizeof(umass_bbb_csw_t), UMASS_BBB_CSW_SIZE);
   1092 
   1093 	/*
   1094 	 * Determine the direction of the data transfer and the length.
   1095 	 *
   1096 	 * dCBWDataTransferLength (datalen) :
   1097 	 *   This field indicates the number of bytes of data that the host
   1098 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
   1099 	 *   the Direction bit) during the execution of this command. If this
   1100 	 *   field is set to 0, the device will expect that no data will be
   1101 	 *   transferred IN or OUT during this command, regardless of the value
   1102 	 *   of the Direction bit defined in dCBWFlags.
   1103 	 *
   1104 	 * dCBWFlags (dir) :
   1105 	 *   The bits of the Flags field are defined as follows:
   1106 	 *     Bits 0-6	 reserved
   1107 	 *     Bit  7	 Direction - this bit shall be ignored if the
   1108 	 *			     dCBWDataTransferLength field is zero.
   1109 	 *		 0 = data Out from host to device
   1110 	 *		 1 = data In from device to host
   1111 	 */
   1112 
   1113 	/* Fill in the Command Block Wrapper */
   1114 	USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
   1115 	USETDW(sc->cbw.dCBWTag, dCBWtag);
   1116 	dCBWtag++;	/* cannot be done in macro (it will be done 4 times) */
   1117 	USETDW(sc->cbw.dCBWDataTransferLength, datalen);
   1118 	/* DIR_NONE is treated as DIR_OUT (0x00) */
   1119 	sc->cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
   1120 	sc->cbw.bCBWLUN = lun;
   1121 	sc->cbw.bCDBLength = cmdlen;
   1122 	memcpy(sc->cbw.CBWCDB, cmd, cmdlen);
   1123 
   1124 	DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
   1125 
   1126 	/* store the details for the data transfer phase */
   1127 	sc->transfer_dir = dir;
   1128 	sc->transfer_data = data;
   1129 	sc->transfer_datalen = datalen;
   1130 	sc->transfer_actlen = 0;
   1131 	sc->transfer_cb = cb;
   1132 	sc->transfer_priv = priv;
   1133 	sc->transfer_status = STATUS_CMD_OK;
   1134 
   1135 	/* move from idle to the command state */
   1136 	sc->transfer_state = TSTATE_BBB_COMMAND;
   1137 
   1138 	/* Send the CBW from host to device via bulk-out endpoint. */
   1139 	if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
   1140 			&sc->cbw, UMASS_BBB_CBW_SIZE, flags,
   1141 			sc->transfer_xfer[XFER_BBB_CBW])) {
   1142 		umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1143 	}
   1144 }
   1145 
   1146 
   1147 Static void
   1148 umass_bbb_state(struct usbd_xfer *xfer, void *priv,
   1149 		usbd_status err)
   1150 {
   1151 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1152 	struct umass_softc *sc = (struct umass_softc *) priv;
   1153 	struct usbd_xfer *next_xfer;
   1154 	int residue;
   1155 
   1156 	KASSERTMSG(sc->sc_wire & UMASS_WPROTO_BBB,
   1157 		   "sc->sc_wire == 0x%02x wrong for umass_bbb_state\n",
   1158 		   sc->sc_wire);
   1159 
   1160 	if (sc->sc_dying)
   1161 		return;
   1162 
   1163 	/*
   1164 	 * State handling for BBB transfers.
   1165 	 *
   1166 	 * The subroutine is rather long. It steps through the states given in
   1167 	 * Annex A of the Bulk-Only specification.
   1168 	 * Each state first does the error handling of the previous transfer
   1169 	 * and then prepares the next transfer.
   1170 	 * Each transfer is done asynchroneously so after the request/transfer
   1171 	 * has been submitted you will find a 'return;'.
   1172 	 */
   1173 
   1174 	DPRINTFM(UDMASS_BBB, "sc %p xfer %p, transfer_state %d dir %d", sc,
   1175 	    xfer, sc->transfer_state, sc->transfer_dir);
   1176 
   1177 	switch (sc->transfer_state) {
   1178 
   1179 	/***** Bulk Transfer *****/
   1180 	case TSTATE_BBB_COMMAND:
   1181 		/* Command transport phase, error handling */
   1182 		if (err) {
   1183 			DPRINTFM(UDMASS_BBB, "sc %p failed to send CBW", sc,
   1184 			    0, 0, 0);
   1185 			/* If the device detects that the CBW is invalid, then
   1186 			 * the device may STALL both bulk endpoints and require
   1187 			 * a Bulk-Reset
   1188 			 */
   1189 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1190 			return;
   1191 		}
   1192 
   1193 		/* Data transport phase, setup transfer */
   1194 		sc->transfer_state = TSTATE_BBB_DATA;
   1195 		if (sc->transfer_dir == DIR_IN) {
   1196 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1197 					sc->datain_buffer, sc->transfer_datalen,
   1198 					USBD_SHORT_XFER_OK,
   1199 					sc->transfer_xfer[XFER_BBB_DATAIN]))
   1200 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1201 
   1202 			return;
   1203 		} else if (sc->transfer_dir == DIR_OUT) {
   1204 			memcpy(sc->dataout_buffer, sc->transfer_data,
   1205 			       sc->transfer_datalen);
   1206 			if (umass_setup_transfer(sc,
   1207 			    sc->sc_pipe[UMASS_BULKOUT], sc->dataout_buffer,
   1208 			    sc->transfer_datalen, 0,/* fixed length transfer */
   1209 			    sc->transfer_xfer[XFER_BBB_DATAOUT]))
   1210 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1211 
   1212 			return;
   1213 		} else {
   1214 			DPRINTFM(UDMASS_BBB, "sc %p: no data phase", sc, 0, 0,
   1215 			    0);
   1216 		}
   1217 
   1218 		/* FALLTHROUGH if no data phase, err == 0 */
   1219 	case TSTATE_BBB_DATA:
   1220 		/* Command transport phase error handling (ignored if no data
   1221 		 * phase (fallthrough from previous state)) */
   1222 		if (sc->transfer_dir != DIR_NONE) {
   1223 			/* retrieve the length of the transfer that was done */
   1224 			usbd_get_xfer_status(xfer, NULL, NULL,
   1225 			     &sc->transfer_actlen, NULL);
   1226 			DPRINTFM(UDMASS_BBB, "sc %p: BBB_DATA actlen=%d",
   1227 			    sc, sc->transfer_actlen, 0, 0);
   1228 
   1229 			if (err) {
   1230 				DPRINTFM(UDMASS_BBB, "sc %p Data dir %d err %d"
   1231 				    " failed, ", sc, sc->transfer_dir,
   1232 				    sc->transfer_datalen, err);
   1233 
   1234 				if (err == USBD_STALLED) {
   1235 					sc->transfer_state = TSTATE_BBB_DCLEAR;
   1236 					umass_clear_endpoint_stall(sc,
   1237 					  (sc->transfer_dir == DIR_IN?
   1238 					    UMASS_BULKIN:UMASS_BULKOUT),
   1239 					  sc->transfer_xfer[XFER_BBB_DCLEAR]);
   1240 				} else {
   1241 					/* Unless the error is a pipe stall the
   1242 					 * error is fatal.
   1243 					 */
   1244 					umass_bbb_reset(sc,STATUS_WIRE_FAILED);
   1245 				}
   1246 				return;
   1247 			}
   1248 		}
   1249 
   1250 		/* FALLTHROUGH, err == 0 (no data phase or successful) */
   1251 	case TSTATE_BBB_DCLEAR: /* stall clear after data phase */
   1252 		if (sc->transfer_dir == DIR_IN)
   1253 			memcpy(sc->transfer_data, sc->datain_buffer,
   1254 			       sc->transfer_actlen);
   1255 
   1256 		DIF(UDMASS_BBB, if (sc->transfer_dir == DIR_IN)
   1257 					umass_dump_buffer(sc, sc->transfer_data,
   1258 						sc->transfer_datalen, 48));
   1259 
   1260 		/* FALLTHROUGH, err == 0 (no data phase or successful) */
   1261 	case TSTATE_BBB_SCLEAR: /* stall clear after status phase */
   1262 		/* Reading of CSW after bulk stall condition in data phase
   1263 		 * (TSTATE_BBB_DATA2) or bulk-in stall condition after
   1264 		 * reading CSW (TSTATE_BBB_SCLEAR).
   1265 		 * In the case of no data phase or successful data phase,
   1266 		 * err == 0 and the following if block is passed.
   1267 		 */
   1268 		if (err) {	/* should not occur */
   1269 			printf("%s: BBB bulk-%s stall clear failed, %s\n",
   1270 			    device_xname(sc->sc_dev),
   1271 			    (sc->transfer_dir == DIR_IN? "in":"out"),
   1272 			    usbd_errstr(err));
   1273 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1274 			return;
   1275 		}
   1276 
   1277 		/* Status transport phase, setup transfer */
   1278 		if (sc->transfer_state == TSTATE_BBB_COMMAND ||
   1279 		    sc->transfer_state == TSTATE_BBB_DATA ||
   1280 		    sc->transfer_state == TSTATE_BBB_DCLEAR) {
   1281 			/* After no data phase, successful data phase and
   1282 			 * after clearing bulk-in/-out stall condition
   1283 			 */
   1284 			sc->transfer_state = TSTATE_BBB_STATUS1;
   1285 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW1];
   1286 		} else {
   1287 			/* After first attempt of fetching CSW */
   1288 			sc->transfer_state = TSTATE_BBB_STATUS2;
   1289 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW2];
   1290 		}
   1291 
   1292 		/* Read the Command Status Wrapper via bulk-in endpoint. */
   1293 		if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1294 			&sc->csw, UMASS_BBB_CSW_SIZE, 0, next_xfer)) {
   1295 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1296 			return;
   1297 		}
   1298 
   1299 		return;
   1300 	case TSTATE_BBB_STATUS1:	/* first attempt */
   1301 	case TSTATE_BBB_STATUS2:	/* second attempt */
   1302 		/* Status transfer, error handling */
   1303 		if (err) {
   1304 			DPRINTFM(UDMASS_BBB, "sc %p Failed to read CSW err %d "
   1305 			    "(state %d)", sc, err, sc->transfer_state, 0);
   1306 
   1307 			/* If this was the first attempt at fetching the CSW
   1308 			 * retry it, otherwise fail.
   1309 			 */
   1310 			if (sc->transfer_state == TSTATE_BBB_STATUS1) {
   1311 				sc->transfer_state = TSTATE_BBB_SCLEAR;
   1312 				umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1313 				    sc->transfer_xfer[XFER_BBB_SCLEAR]);
   1314 				return;
   1315 			} else {
   1316 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1317 				return;
   1318 			}
   1319 		}
   1320 
   1321 		DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
   1322 
   1323 #ifdef UMASS_DEBUG
   1324 		residue = UGETDW(sc->csw.dCSWDataResidue);
   1325 		if (residue != sc->transfer_datalen - sc->transfer_actlen)
   1326 			printf("%s: dCSWDataResidue=%d req=%d act=%d\n",
   1327 			       device_xname(sc->sc_dev), residue,
   1328 			       sc->transfer_datalen, sc->transfer_actlen);
   1329 #endif
   1330 		residue = sc->transfer_datalen - sc->transfer_actlen;
   1331 
   1332 		/* Translate weird command-status signatures. */
   1333 		if ((sc->sc_quirks & UMASS_QUIRK_WRONG_CSWSIG) &&
   1334 		    UGETDW(sc->csw.dCSWSignature) == CSWSIGNATURE_OLYMPUS_C1)
   1335 			USETDW(sc->csw.dCSWSignature, CSWSIGNATURE);
   1336 
   1337 		/* Translate invalid command-status tags */
   1338 		if (sc->sc_quirks & UMASS_QUIRK_WRONG_CSWTAG)
   1339 			USETDW(sc->csw.dCSWTag, UGETDW(sc->cbw.dCBWTag));
   1340 
   1341 		/* Check CSW and handle any error */
   1342 		if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
   1343 			/* Invalid CSW: Wrong signature or wrong tag might
   1344 			 * indicate that the device is confused -> reset it.
   1345 			 */
   1346 			printf("%s: Invalid CSW: sig 0x%08x should be 0x%08x\n",
   1347 				device_xname(sc->sc_dev),
   1348 				UGETDW(sc->csw.dCSWSignature),
   1349 				CSWSIGNATURE);
   1350 
   1351 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1352 			return;
   1353 		} else if (UGETDW(sc->csw.dCSWTag)
   1354 				!= UGETDW(sc->cbw.dCBWTag)) {
   1355 			printf("%s: Invalid CSW: tag %d should be %d\n",
   1356 				device_xname(sc->sc_dev),
   1357 				UGETDW(sc->csw.dCSWTag),
   1358 				UGETDW(sc->cbw.dCBWTag));
   1359 
   1360 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1361 			return;
   1362 
   1363 		/* CSW is valid here */
   1364 		} else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
   1365 			printf("%s: Invalid CSW: status %d > %d\n",
   1366 				device_xname(sc->sc_dev),
   1367 				sc->csw.bCSWStatus,
   1368 				CSWSTATUS_PHASE);
   1369 
   1370 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1371 			return;
   1372 		} else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
   1373 			printf("%s: Phase Error, residue = %d\n",
   1374 				device_xname(sc->sc_dev), residue);
   1375 
   1376 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1377 			return;
   1378 
   1379 		} else if (sc->transfer_actlen > sc->transfer_datalen) {
   1380 			/* Buffer overrun! Don't let this go by unnoticed */
   1381 			panic("%s: transferred %s %d bytes instead of %d bytes",
   1382 			    device_xname(sc->sc_dev),
   1383 			    sc->transfer_dir == DIR_IN ? "IN" : "OUT",
   1384 			    sc->transfer_actlen, sc->transfer_datalen);
   1385 #if 0
   1386 		} else if (sc->transfer_datalen - sc->transfer_actlen
   1387 			   != residue) {
   1388 			DPRINTFM(UDMASS_BBB, "sc %p: actlen=%d != residue=%d\n",
   1389 				sc,
   1390 				sc->transfer_datalen - sc->transfer_actlen,
   1391 				residue));
   1392 
   1393 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
   1394 			return;
   1395 #endif
   1396 		} else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
   1397 			DPRINTFM(UDMASS_BBB, "sc %p: Command Failed, res = %d",
   1398 			    sc, residue, 0, 0);
   1399 
   1400 			/* SCSI command failed but transfer was succesful */
   1401 			sc->transfer_state = TSTATE_IDLE;
   1402 			sc->transfer_cb(sc, sc->transfer_priv, residue,
   1403 					STATUS_CMD_FAILED);
   1404 
   1405 			return;
   1406 
   1407 		} else {	/* success */
   1408 			sc->transfer_state = TSTATE_IDLE;
   1409 			sc->transfer_cb(sc, sc->transfer_priv, residue,
   1410 					STATUS_CMD_OK);
   1411 
   1412 			return;
   1413 		}
   1414 
   1415 	/***** Bulk Reset *****/
   1416 	case TSTATE_BBB_RESET1:
   1417 		if (err)
   1418 			printf("%s: BBB reset failed, %s\n",
   1419 				device_xname(sc->sc_dev), usbd_errstr(err));
   1420 
   1421 		sc->transfer_state = TSTATE_BBB_RESET2;
   1422 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1423 			sc->transfer_xfer[XFER_BBB_RESET2]);
   1424 
   1425 		return;
   1426 	case TSTATE_BBB_RESET2:
   1427 		if (err)	/* should not occur */
   1428 			printf("%s: BBB bulk-in clear stall failed, %s\n",
   1429 			       device_xname(sc->sc_dev), usbd_errstr(err));
   1430 			/* no error recovery, otherwise we end up in a loop */
   1431 
   1432 		sc->transfer_state = TSTATE_BBB_RESET3;
   1433 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
   1434 			sc->transfer_xfer[XFER_BBB_RESET3]);
   1435 
   1436 		return;
   1437 	case TSTATE_BBB_RESET3:
   1438 		if (err)	/* should not occur */
   1439 			printf("%s: BBB bulk-out clear stall failed, %s\n",
   1440 			       device_xname(sc->sc_dev), usbd_errstr(err));
   1441 			/* no error recovery, otherwise we end up in a loop */
   1442 
   1443 		sc->transfer_state = TSTATE_IDLE;
   1444 		if (sc->transfer_priv) {
   1445 			sc->transfer_cb(sc, sc->transfer_priv,
   1446 					sc->transfer_datalen,
   1447 					sc->transfer_status);
   1448 		}
   1449 
   1450 		return;
   1451 
   1452 	/***** Default *****/
   1453 	default:
   1454 		panic("%s: Unknown state %d",
   1455 		      device_xname(sc->sc_dev), sc->transfer_state);
   1456 	}
   1457 }
   1458 
   1459 /*
   1460  * Command/Bulk/Interrupt (CBI) specific functions
   1461  */
   1462 
   1463 Static int
   1464 umass_cbi_adsc(struct umass_softc *sc, char *buffer, int buflen, int flags,
   1465 	       struct usbd_xfer *xfer)
   1466 {
   1467 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1468 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_adsc\n",
   1469 		   sc->sc_wire);
   1470 
   1471 	if ((sc->sc_cmd == UMASS_CPROTO_RBC) &&
   1472 	    (sc->sc_quirks & UMASS_QUIRK_RBC_PAD_TO_12) != 0 && buflen < 12) {
   1473 		(void)memset(buffer + buflen, 0, 12 - buflen);
   1474 		buflen = 12;
   1475 	}
   1476 
   1477 	sc->sc_req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   1478 	sc->sc_req.bRequest = UR_CBI_ADSC;
   1479 	USETW(sc->sc_req.wValue, 0);
   1480 	USETW(sc->sc_req.wIndex, sc->sc_ifaceno);
   1481 	USETW(sc->sc_req.wLength, buflen);
   1482 	return umass_setup_ctrl_transfer(sc, &sc->sc_req, buffer,
   1483 					 buflen, flags, xfer);
   1484 }
   1485 
   1486 
   1487 Static void
   1488 umass_cbi_reset(struct umass_softc *sc, int status)
   1489 {
   1490 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1491 	int i;
   1492 #	define SEND_DIAGNOSTIC_CMDLEN	12
   1493 
   1494 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1495 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_reset\n",
   1496 		   sc->sc_wire);
   1497 
   1498 	if (sc->sc_dying)
   1499 		return;
   1500 
   1501 	/*
   1502 	 * Command Block Reset Protocol
   1503 	 *
   1504 	 * First send a reset request to the device. Then clear
   1505 	 * any possibly stalled bulk endpoints.
   1506 
   1507 	 * This is done in 3 steps, states:
   1508 	 * TSTATE_CBI_RESET1
   1509 	 * TSTATE_CBI_RESET2
   1510 	 * TSTATE_CBI_RESET3
   1511 	 *
   1512 	 * If the reset doesn't succeed, the device should be port reset.
   1513 	 */
   1514 
   1515 	DPRINTFM(UDMASS_CBI, "sc %p: CBI Reset", sc, 0, 0, 0);
   1516 
   1517 	/* CTASSERT */
   1518 	KASSERTMSG(sizeof(sc->cbl) >= SEND_DIAGNOSTIC_CMDLEN,
   1519 		   "%s: CBL struct is too small (%zu < %u)\n",
   1520 			device_xname(sc->sc_dev),
   1521 			sizeof(sc->cbl), SEND_DIAGNOSTIC_CMDLEN);
   1522 
   1523 	sc->transfer_state = TSTATE_CBI_RESET1;
   1524 	sc->transfer_status = status;
   1525 
   1526 	/* The 0x1d code is the SEND DIAGNOSTIC command. To distingiush between
   1527 	 * the two the last 10 bytes of the cbl is filled with 0xff (section
   1528 	 * 2.2 of the CBI spec).
   1529 	 */
   1530 	sc->cbl[0] = 0x1d;	/* Command Block Reset */
   1531 	sc->cbl[1] = 0x04;
   1532 	for (i = 2; i < SEND_DIAGNOSTIC_CMDLEN; i++)
   1533 		sc->cbl[i] = 0xff;
   1534 
   1535 	umass_cbi_adsc(sc, sc->cbl, SEND_DIAGNOSTIC_CMDLEN, 0,
   1536 		       sc->transfer_xfer[XFER_CBI_RESET1]);
   1537 	/* XXX if the command fails we should reset the port on the bub */
   1538 }
   1539 
   1540 Static void
   1541 umass_cbi_transfer(struct umass_softc *sc, int lun,
   1542 		   void *cmd, int cmdlen, void *data, int datalen, int dir,
   1543 		   u_int timeout, int flags, umass_callback cb, void *priv)
   1544 {
   1545 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1546 
   1547 	DPRINTFM(UDMASS_CBI, "sc %p: cmd=0x%02x, len=%d", sc, *(u_char *)cmd,
   1548 	    datalen, 0);
   1549 
   1550 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1551 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_transfer\n",
   1552 		   sc->sc_wire);
   1553 
   1554 	if (sc->sc_dying)
   1555 		return;
   1556 
   1557 	/* Be a little generous. */
   1558 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
   1559 
   1560 	/*
   1561 	 * Do a CBI transfer with cmdlen bytes from cmd, possibly
   1562 	 * a data phase of datalen bytes from/to the device and finally a
   1563 	 * csw read phase.
   1564 	 * If the data direction was inbound a maximum of datalen bytes
   1565 	 * is stored in the buffer pointed to by data.
   1566 	 *
   1567 	 * umass_cbi_transfer initialises the transfer and lets the state
   1568 	 * machine in umass_cbi_state handle the completion. It uses the
   1569 	 * following states:
   1570 	 * TSTATE_CBI_COMMAND
   1571 	 *   -> XXX fill in
   1572 	 *
   1573 	 * An error in any of those states will invoke
   1574 	 * umass_cbi_reset.
   1575 	 */
   1576 
   1577 	/* check the given arguments */
   1578 	KASSERTMSG(datalen == 0 || data != NULL,
   1579 		   "%s: datalen > 0, but no buffer",device_xname(sc->sc_dev));
   1580 	KASSERTMSG(datalen == 0 || dir != DIR_NONE,
   1581 		   "%s: direction is NONE while datalen is not zero\n",
   1582 			device_xname(sc->sc_dev));
   1583 
   1584 	/* store the details for the data transfer phase */
   1585 	sc->transfer_dir = dir;
   1586 	sc->transfer_data = data;
   1587 	sc->transfer_datalen = datalen;
   1588 	sc->transfer_actlen = 0;
   1589 	sc->transfer_cb = cb;
   1590 	sc->transfer_priv = priv;
   1591 	sc->transfer_status = STATUS_CMD_OK;
   1592 
   1593 	/* move from idle to the command state */
   1594 	sc->transfer_state = TSTATE_CBI_COMMAND;
   1595 
   1596 	/* Send the Command Block from host to device via control endpoint. */
   1597 	if (umass_cbi_adsc(sc, cmd, cmdlen, flags,
   1598 	    sc->transfer_xfer[XFER_CBI_CB]))
   1599 		umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1600 }
   1601 
   1602 Static void
   1603 umass_cbi_state(struct usbd_xfer *xfer, void *priv,
   1604 		usbd_status err)
   1605 {
   1606 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1607 	struct umass_softc *sc = (struct umass_softc *) priv;
   1608 
   1609 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
   1610 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_state\n",
   1611 		   sc->sc_wire);
   1612 
   1613 	if (sc->sc_dying)
   1614 		return;
   1615 
   1616 	/*
   1617 	 * State handling for CBI transfers.
   1618 	 */
   1619 
   1620 	DPRINTFM(UDMASS_CBI, "sc %p: Handling CBI state %d, xfer=%p, ...",
   1621 	    sc, sc->transfer_state, xfer, 0);
   1622 	DPRINTFM(UDMASS_CBI, "... err %d", err, 0, 0, 0);
   1623 
   1624 	switch (sc->transfer_state) {
   1625 
   1626 	/***** CBI Transfer *****/
   1627 	case TSTATE_CBI_COMMAND:
   1628 		if (err == USBD_STALLED) {
   1629 			DPRINTFM(UDMASS_CBI, "sc %p: Command Transport failed",
   1630 			    sc, 0, 0, 0);
   1631 			/* Status transport by control pipe (section 2.3.2.1).
   1632 			 * The command contained in the command block failed.
   1633 			 *
   1634 			 * The control pipe has already been unstalled by the
   1635 			 * USB stack.
   1636 			 * Section 2.4.3.1.1 states that the bulk in endpoints
   1637 			 * should not stalled at this point.
   1638 			 */
   1639 
   1640 			sc->transfer_state = TSTATE_IDLE;
   1641 			sc->transfer_cb(sc, sc->transfer_priv,
   1642 					sc->transfer_datalen,
   1643 					STATUS_CMD_FAILED);
   1644 
   1645 			return;
   1646 		} else if (err) {
   1647 			DPRINTFM(UDMASS_CBI, "sc %p: failed to send ADSC",
   1648 			    sc, 0, 0, 0);
   1649 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1650 			return;
   1651 		}
   1652 
   1653 		/* Data transport phase, setup transfer */
   1654 		sc->transfer_state = TSTATE_CBI_DATA;
   1655 		if (sc->transfer_dir == DIR_IN) {
   1656 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
   1657 			    sc->datain_buffer, sc->transfer_datalen,
   1658 			    USBD_SHORT_XFER_OK,
   1659 			    sc->transfer_xfer[XFER_CBI_DATAIN]))
   1660 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1661 
   1662 			return;
   1663 		} else if (sc->transfer_dir == DIR_OUT) {
   1664 			memcpy(sc->dataout_buffer, sc->transfer_data,
   1665 			       sc->transfer_datalen);
   1666 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
   1667 			    sc->dataout_buffer, sc->transfer_datalen,
   1668 			    0, /* fixed length transfer */
   1669 			    sc->transfer_xfer[XFER_CBI_DATAOUT]))
   1670 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1671 
   1672 			return;
   1673 		} else {
   1674 			DPRINTFM(UDMASS_CBI, "sc %p: no data phase", sc, 0, 0,
   1675 			    0);
   1676 		}
   1677 
   1678 		/* FALLTHROUGH if no data phase, err == 0 */
   1679 	case TSTATE_CBI_DATA:
   1680 		/* Command transport phase error handling (ignored if no data
   1681 		 * phase (fallthrough from previous state)) */
   1682 		if (sc->transfer_dir != DIR_NONE) {
   1683 			/* retrieve the length of the transfer that was done */
   1684 			usbd_get_xfer_status(xfer, NULL, NULL,
   1685 			    &sc->transfer_actlen, NULL);
   1686 			DPRINTFM(UDMASS_CBI, "sc %p: CBI_DATA actlen=%d",
   1687 				sc, sc->transfer_actlen, 0, 0);
   1688 
   1689 			if (err) {
   1690 				DPRINTFM(UDMASS_CBI, "sc %p: Data dir %d "
   1691 				    "err %d failed", sc, sc->transfer_dir,
   1692 				    sc->transfer_datalen, err);
   1693 
   1694 				if (err == USBD_STALLED) {
   1695 					sc->transfer_state = TSTATE_CBI_DCLEAR;
   1696 					umass_clear_endpoint_stall(sc,
   1697 					  (sc->transfer_dir == DIR_IN?
   1698 					    UMASS_BULKIN:UMASS_BULKOUT),
   1699 					sc->transfer_xfer[XFER_CBI_DCLEAR]);
   1700 				} else {
   1701 					/* Unless the error is a pipe stall the
   1702 					 * error is fatal.
   1703 					 */
   1704 					umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1705 				}
   1706 				return;
   1707 			}
   1708 		}
   1709 
   1710 		if (sc->transfer_dir == DIR_IN)
   1711 			memcpy(sc->transfer_data, sc->datain_buffer,
   1712 			       sc->transfer_actlen);
   1713 
   1714 		DIF(UDMASS_CBI, if (sc->transfer_dir == DIR_IN)
   1715 					umass_dump_buffer(sc, sc->transfer_data,
   1716 						sc->transfer_actlen, 48));
   1717 
   1718 		/* Status phase */
   1719 		if (sc->sc_wire == UMASS_WPROTO_CBI_I) {
   1720 			sc->transfer_state = TSTATE_CBI_STATUS;
   1721 			memset(&sc->sbl, 0, sizeof(sc->sbl));
   1722 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_INTRIN],
   1723 				    &sc->sbl, sizeof(sc->sbl),
   1724 				    0,	/* fixed length transfer */
   1725 				    sc->transfer_xfer[XFER_CBI_STATUS]))
   1726 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1727 		} else {
   1728 			/* No command completion interrupt. Request
   1729 			 * sense to get status of command.
   1730 			 */
   1731 			sc->transfer_state = TSTATE_IDLE;
   1732 			sc->transfer_cb(sc, sc->transfer_priv,
   1733 				sc->transfer_datalen - sc->transfer_actlen,
   1734 				STATUS_CMD_UNKNOWN);
   1735 		}
   1736 		return;
   1737 
   1738 	case TSTATE_CBI_STATUS:
   1739 		if (err) {
   1740 			DPRINTFM(UDMASS_CBI, "sc %p: Status Transport failed",
   1741 			    sc, 0, 0, 0);
   1742 			/* Status transport by interrupt pipe (section 2.3.2.2).
   1743 			 */
   1744 
   1745 			if (err == USBD_STALLED) {
   1746 				sc->transfer_state = TSTATE_CBI_SCLEAR;
   1747 				umass_clear_endpoint_stall(sc, UMASS_INTRIN,
   1748 					sc->transfer_xfer[XFER_CBI_SCLEAR]);
   1749 			} else {
   1750 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1751 			}
   1752 			return;
   1753 		}
   1754 
   1755 		/* Dissect the information in the buffer */
   1756 
   1757 		{
   1758 			uint32_t actlen;
   1759 			usbd_get_xfer_status(xfer,NULL,NULL,&actlen,NULL);
   1760 			DPRINTFM(UDMASS_CBI, "sc %p: CBI_STATUS actlen=%d",
   1761 			    sc, actlen, 0, 0);
   1762 			if (actlen != 2)
   1763 				break;
   1764 		}
   1765 
   1766 		if (sc->sc_cmd == UMASS_CPROTO_UFI) {
   1767 			int status;
   1768 
   1769 			/* Section 3.4.3.1.3 specifies that the UFI command
   1770 			 * protocol returns an ASC and ASCQ in the interrupt
   1771 			 * data block.
   1772 			 */
   1773 
   1774 			DPRINTFM(UDMASS_CBI, "sc %p: UFI CCI, ASC = 0x%02x, "
   1775 			    "ASCQ = 0x%02x", sc, sc->sbl.ufi.asc,
   1776 			    sc->sbl.ufi.ascq, 0);
   1777 
   1778 			if ((sc->sbl.ufi.asc == 0 && sc->sbl.ufi.ascq == 0) ||
   1779 			    sc->sc_sense)
   1780 				status = STATUS_CMD_OK;
   1781 			else
   1782 				status = STATUS_CMD_FAILED;
   1783 
   1784 			/* No autosense, command successful */
   1785 			sc->transfer_state = TSTATE_IDLE;
   1786 			sc->transfer_cb(sc, sc->transfer_priv,
   1787 			    sc->transfer_datalen - sc->transfer_actlen, status);
   1788 		} else {
   1789 			int status;
   1790 
   1791 			/* Command Interrupt Data Block */
   1792 
   1793 			DPRINTFM(UDMASS_CBI, "sc %p: type=0x%02x, value=0x%02x",
   1794 			    sc, sc->sbl.common.type, sc->sbl.common.value, 0);
   1795 
   1796 			if (sc->sbl.common.type == IDB_TYPE_CCI) {
   1797 				switch (sc->sbl.common.value & IDB_VALUE_STATUS_MASK) {
   1798 				case IDB_VALUE_PASS:
   1799 					status = STATUS_CMD_OK;
   1800 					break;
   1801 				case IDB_VALUE_FAIL:
   1802 				case IDB_VALUE_PERSISTENT:
   1803 					status = STATUS_CMD_FAILED;
   1804 					break;
   1805 				case IDB_VALUE_PHASE:
   1806 				default: /* XXX: gcc */
   1807 					status = STATUS_WIRE_FAILED;
   1808 					break;
   1809 				}
   1810 
   1811 				sc->transfer_state = TSTATE_IDLE;
   1812 				sc->transfer_cb(sc, sc->transfer_priv,
   1813 				    sc->transfer_datalen - sc->transfer_actlen,
   1814 				    status);
   1815 			}
   1816 		}
   1817 		return;
   1818 
   1819 	case TSTATE_CBI_DCLEAR:
   1820 		if (err) {	/* should not occur */
   1821 			printf("%s: CBI bulk-%s stall clear failed, %s\n",
   1822 			    device_xname(sc->sc_dev),
   1823 			    (sc->transfer_dir == DIR_IN? "in":"out"),
   1824 			    usbd_errstr(err));
   1825 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1826 		} else {
   1827 			sc->transfer_state = TSTATE_IDLE;
   1828 			sc->transfer_cb(sc, sc->transfer_priv,
   1829 			    sc->transfer_datalen, STATUS_CMD_FAILED);
   1830 		}
   1831 		return;
   1832 
   1833 	case TSTATE_CBI_SCLEAR:
   1834 		if (err) {	/* should not occur */
   1835 			printf("%s: CBI intr-in stall clear failed, %s\n",
   1836 			       device_xname(sc->sc_dev), usbd_errstr(err));
   1837 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
   1838 		} else {
   1839 			sc->transfer_state = TSTATE_IDLE;
   1840 			sc->transfer_cb(sc, sc->transfer_priv,
   1841 			    sc->transfer_datalen, STATUS_CMD_FAILED);
   1842 		}
   1843 		return;
   1844 
   1845 	/***** CBI Reset *****/
   1846 	case TSTATE_CBI_RESET1:
   1847 		if (err)
   1848 			printf("%s: CBI reset failed, %s\n",
   1849 				device_xname(sc->sc_dev), usbd_errstr(err));
   1850 
   1851 		sc->transfer_state = TSTATE_CBI_RESET2;
   1852 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
   1853 			sc->transfer_xfer[XFER_CBI_RESET2]);
   1854 
   1855 		return;
   1856 	case TSTATE_CBI_RESET2:
   1857 		if (err)	/* should not occur */
   1858 			printf("%s: CBI bulk-in stall clear failed, %s\n",
   1859 			       device_xname(sc->sc_dev), usbd_errstr(err));
   1860 			/* no error recovery, otherwise we end up in a loop */
   1861 
   1862 		sc->transfer_state = TSTATE_CBI_RESET3;
   1863 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
   1864 			sc->transfer_xfer[XFER_CBI_RESET3]);
   1865 
   1866 		return;
   1867 	case TSTATE_CBI_RESET3:
   1868 		if (err)	/* should not occur */
   1869 			printf("%s: CBI bulk-out stall clear failed, %s\n",
   1870 			       device_xname(sc->sc_dev), usbd_errstr(err));
   1871 			/* no error recovery, otherwise we end up in a loop */
   1872 
   1873 		sc->transfer_state = TSTATE_IDLE;
   1874 		if (sc->transfer_priv) {
   1875 			sc->transfer_cb(sc, sc->transfer_priv,
   1876 					sc->transfer_datalen,
   1877 					sc->transfer_status);
   1878 		}
   1879 
   1880 		return;
   1881 
   1882 
   1883 	/***** Default *****/
   1884 	default:
   1885 		panic("%s: Unknown state %d",
   1886 		      device_xname(sc->sc_dev), sc->transfer_state);
   1887 	}
   1888 }
   1889 
   1890 usbd_status
   1891 umass_bbb_get_max_lun(struct umass_softc *sc, uint8_t *maxlun)
   1892 {
   1893 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1894 	usb_device_request_t req;
   1895 	usbd_status err;
   1896 
   1897 	*maxlun = 0;		/* Default to 0. */
   1898 
   1899 	DPRINTFM(UDMASS_BBB, "sc %p: Get Max Lun", sc, 0, 0, 0);
   1900 
   1901 	/* The Get Max Lun command is a class-specific request. */
   1902 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
   1903 	req.bRequest = UR_BBB_GET_MAX_LUN;
   1904 	USETW(req.wValue, 0);
   1905 	USETW(req.wIndex, sc->sc_ifaceno);
   1906 	USETW(req.wLength, 1);
   1907 
   1908 	err = usbd_do_request_flags(sc->sc_udev, &req, maxlun,
   1909 	    USBD_SHORT_XFER_OK, 0, USBD_DEFAULT_TIMEOUT);
   1910 	switch (err) {
   1911 	case USBD_NORMAL_COMPLETION:
   1912 		DPRINTFM(UDMASS_BBB, "sc %p: Max Lun %d", sc, *maxlun , 0, 0);
   1913 		break;
   1914 
   1915 	case USBD_STALLED:
   1916 		/*
   1917 		 * Device doesn't support Get Max Lun request.
   1918 		 */
   1919 		err = USBD_NORMAL_COMPLETION;
   1920 		DPRINTFM(UDMASS_BBB, "sc %p: Get Max Lun not supported", sc,
   1921 		    0, 0, 0);
   1922 		break;
   1923 
   1924 	case USBD_SHORT_XFER:
   1925 		/*
   1926 		 * XXX This must mean Get Max Lun is not supported, too!
   1927 		 */
   1928 		err = USBD_NORMAL_COMPLETION;
   1929 		DPRINTFM(UDMASS_BBB, "sc %p: Get Max Lun SHORT_XFER", sc, 0, 0,
   1930 		    0);
   1931 		break;
   1932 
   1933 	default:
   1934 		printf("%s: Get Max Lun failed: %s\n",
   1935 		    device_xname(sc->sc_dev), usbd_errstr(err));
   1936 		/* XXX Should we port_reset the device? */
   1937 		break;
   1938 	}
   1939 
   1940 	return err;
   1941 }
   1942 
   1943 
   1944 
   1945 
   1946 #ifdef UMASS_DEBUG
   1947 Static void
   1948 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
   1949 {
   1950 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1951 	int clen = cbw->bCDBLength;
   1952 	int dlen = UGETDW(cbw->dCBWDataTransferLength);
   1953 	uint8_t *c = cbw->CBWCDB;
   1954 	int tag = UGETDW(cbw->dCBWTag);
   1955 	int flags = cbw->bCBWFlags;
   1956 
   1957 	DPRINTFM(UDMASS_BBB, "sc %p: CBW %d: cmdlen=%d", sc, tag, clen, 0);
   1958 	DPRINTFM(UDMASS_BBB, "  0x%02x%02x%02x%02x...", c[0], c[1], c[2], c[3]);
   1959 	DPRINTFM(UDMASS_BBB, "  0x%02x%02x%02x%02x...", c[4], c[5], c[6], c[7]);
   1960 	DPRINTFM(UDMASS_BBB, "  0x%02x%02x...", c[8], c[9], 0, 0);
   1961 	DPRINTFM(UDMASS_BBB, "  data = %d bytes, flags = %x", dlen, flags, 0,
   1962 	    0);
   1963 }
   1964 
   1965 Static void
   1966 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
   1967 {
   1968 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1969 	int sig = UGETDW(csw->dCSWSignature);
   1970 	int tag = UGETDW(csw->dCSWTag);
   1971 	int res = UGETDW(csw->dCSWDataResidue);
   1972 	int status = csw->bCSWStatus;
   1973 
   1974 	DPRINTFM(UDMASS_BBB, "sc %p: CSW %d: sig = 0x%08x, tag = %d", sc, tag,
   1975 	    sig, tag);
   1976 	DPRINTFM(UDMASS_BBB, "  res = %d, status = 0x%02x", res, status, 0, 0);
   1977 }
   1978 
   1979 Static void
   1980 umass_dump_buffer(struct umass_softc *sc, uint8_t *buffer, int buflen,
   1981 		  int printlen)
   1982 {
   1983 	UMASSHIST_FUNC(); UMASSHIST_CALLED();
   1984 	int i;
   1985 
   1986 	DPRINTFM(UDMASS_GEN, "sc %p: buffer %p", sc, buffer, 0, 0);
   1987 	for (i = 0; i < buflen && i < printlen;) {
   1988 		if (i + 3 < buflen && i + 3 < printlen) {
   1989 			DPRINTFM(UDMASS_GEN, "   0x%02x%02x%02x%02x",
   1990 			    buffer[i], buffer[i + 1],
   1991 			    buffer[i + 2], buffer[i + 3]);
   1992 			i += 4;
   1993 		} else if (i + 2 < buflen && i + 2 < printlen) {
   1994 			DPRINTFM(UDMASS_GEN, "   0x%02x%02x%02x",
   1995 			    buffer[i], buffer[i + 1], buffer[i + 2], 0);
   1996 			i += 3;
   1997 		} else if (i + 1 < buflen && i + 2 < printlen) {
   1998 			DPRINTFM(UDMASS_GEN, "   0x%02x%02x",
   1999 			    buffer[i], buffer[i + 1], 0, 0);
   2000 			i += 2;
   2001 		} else {
   2002 			DPRINTFM(UDMASS_GEN, "   0x%02x", buffer[i], 0, 0, 0);
   2003 			i += 1;
   2004 		}
   2005 	}
   2006 }
   2007 #endif
   2008