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