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