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