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