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