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