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