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