xref: /netbsd-src/sys/dev/usb/umass.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: umass.c,v 1.148 2013/12/22 18:30:21 mlelstv 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.148 2013/12/22 18:30:21 mlelstv 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, 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), command and
562 	   status data here as auto allocation cannot happen in interrupt
563 	   context */
564 	switch (sc->sc_wire) {
565 	case UMASS_WPROTO_BBB:
566 		sc->data_buffer = usbd_alloc_buffer(
567 			sc->transfer_xfer[XFER_BBB_DATA],
568 			UMASS_MAX_TRANSFER_SIZE);
569 		sc->cmd_buffer = usbd_alloc_buffer(
570 			sc->transfer_xfer[XFER_BBB_CBW],
571 			UMASS_BBB_CBW_SIZE);
572 		sc->s1_buffer = usbd_alloc_buffer(
573 			sc->transfer_xfer[XFER_BBB_CSW1],
574 			UMASS_BBB_CSW_SIZE);
575 		sc->s2_buffer = usbd_alloc_buffer(
576 			sc->transfer_xfer[XFER_BBB_CSW2],
577 			UMASS_BBB_CSW_SIZE);
578 		break;
579 	case UMASS_WPROTO_CBI:
580 	case UMASS_WPROTO_CBI_I:
581 		sc->data_buffer = usbd_alloc_buffer(
582 			sc->transfer_xfer[XFER_CBI_DATA],
583 			UMASS_MAX_TRANSFER_SIZE);
584 		sc->cmd_buffer = usbd_alloc_buffer(
585 			sc->transfer_xfer[XFER_CBI_CB],
586 			sizeof(sc->cbl));
587 		sc->s1_buffer = usbd_alloc_buffer(
588 			sc->transfer_xfer[XFER_CBI_STATUS],
589 			sizeof(sc->sbl));
590 		sc->s2_buffer = usbd_alloc_buffer(
591 			sc->transfer_xfer[XFER_CBI_RESET1],
592 			sizeof(sc->cbl));
593 		break;
594 	default:
595 		break;
596 	}
597 
598 	if (sc->data_buffer == NULL || sc->cmd_buffer == NULL
599 	    || sc->s1_buffer == NULL || sc->s2_buffer == NULL) {
600 		/*
601 		 * partially preallocated buffers are freed with
602 		 * the xfer structures
603 		 */
604 		aprint_error_dev(self, "no buffer memory\n");
605 		umass_disco(sc);
606 		return;
607 	}
608 
609 	/* Initialise the wire protocol specific methods */
610 	switch (sc->sc_wire) {
611 	case UMASS_WPROTO_BBB:
612 		sc->sc_methods = &umass_bbb_methods;
613 		break;
614 	case UMASS_WPROTO_CBI:
615 	case UMASS_WPROTO_CBI_I:
616 		sc->sc_methods = &umass_cbi_methods;
617 		break;
618 	default:
619 		umass_disco(sc);
620 		return;
621 	}
622 
623 	error = 0;
624 	switch (sc->sc_cmd) {
625 	case UMASS_CPROTO_RBC:
626 	case UMASS_CPROTO_SCSI:
627 #if NSCSIBUS > 0
628 		error = umass_scsi_attach(sc);
629 #else
630 		aprint_error_dev(self, "scsibus not configured\n");
631 #endif
632 		break;
633 
634 	case UMASS_CPROTO_UFI:
635 	case UMASS_CPROTO_ATAPI:
636 #if NATAPIBUS > 0
637 		error = umass_atapi_attach(sc);
638 #else
639 		aprint_error_dev(self, "atapibus not configured\n");
640 #endif
641 		break;
642 
643 	case UMASS_CPROTO_ISD_ATA:
644 #if NWD > 0
645 		error = umass_isdata_attach(sc);
646 #else
647 		aprint_error_dev(self, "isdata not configured\n");
648 #endif
649 		break;
650 
651 	default:
652 		aprint_error_dev(self, "command protocol=0x%x not supported\n",
653 		    sc->sc_cmd);
654 		umass_disco(sc);
655 		return;
656 	}
657 	if (error) {
658 		aprint_error_dev(self, "bus attach failed\n");
659 		umass_disco(sc);
660 		return;
661 	}
662 
663 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
664 			   sc->sc_dev);
665 
666 	if (!pmf_device_register(self, NULL, NULL))
667 		aprint_error_dev(self, "couldn't establish power handler\n");
668 
669 	DPRINTF(UDMASS_GEN, ("%s: Attach finished\n", device_xname(sc->sc_dev)));
670 
671 	return;
672 }
673 
674 static void
675 umass_childdet(device_t self, device_t child)
676 {
677 	struct umass_softc *sc = device_private(self);
678 
679 	KASSERTMSG(child == sc->bus->sc_child,
680 		   "assertion child == sc->bus->sc_child failed\n");
681 	sc->bus->sc_child = NULL;
682 }
683 
684 int
685 umass_detach(device_t self, int flags)
686 {
687 	struct umass_softc *sc = device_private(self);
688 	struct umassbus_softc *scbus;
689 	int rv = 0, i;
690 
691 	DPRINTF(UDMASS_USB, ("%s: detached\n", device_xname(sc->sc_dev)));
692 
693 	pmf_device_deregister(self);
694 
695 	/* Abort the pipes to wake up any waiting processes. */
696 	for (i = 0 ; i < UMASS_NEP ; i++) {
697 		if (sc->sc_pipe[i] != NULL)
698 			usbd_abort_pipe(sc->sc_pipe[i]);
699 	}
700 
701 	/* Do we really need reference counting?  Perhaps in ioctl() */
702 	mutex_enter(&sc->sc_lock);
703 	if (--sc->sc_refcnt >= 0) {
704 #ifdef DIAGNOSTIC
705 		aprint_normal_dev(self, "waiting for refcnt\n");
706 #endif
707 		/* Wait for processes to go away. */
708 		usb_detach_wait(sc->sc_dev, &sc->sc_detach_cv, &sc->sc_lock);
709 	}
710 	mutex_exit(&sc->sc_lock);
711 
712 	scbus = sc->bus;
713 	if (scbus != NULL) {
714 		if (scbus->sc_child != NULL)
715 			rv = config_detach(scbus->sc_child, flags);
716 		free(scbus, M_DEVBUF);
717 		sc->bus = NULL;
718 	}
719 
720 	if (rv != 0)
721 		return (rv);
722 
723 	umass_disco(sc);
724 
725 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
726 			   sc->sc_dev);
727 
728 	mutex_destroy(&sc->sc_lock);
729 	cv_destroy(&sc->sc_detach_cv);
730 
731 	return (rv);
732 }
733 
734 int
735 umass_activate(device_t dev, enum devact act)
736 {
737 	struct umass_softc *sc = device_private(dev);
738 
739 	DPRINTF(UDMASS_USB, ("%s: umass_activate: %d\n",
740 	    device_xname(dev), act));
741 
742 	switch (act) {
743 	case DVACT_DEACTIVATE:
744 		sc->sc_dying = 1;
745 		return 0;
746 	default:
747 		return EOPNOTSUPP;
748 	}
749 }
750 
751 Static void
752 umass_disco(struct umass_softc *sc)
753 {
754 	int i;
755 
756 	DPRINTF(UDMASS_GEN, ("umass_disco\n"));
757 
758 	/* Remove all the pipes. */
759 	for (i = 0 ; i < UMASS_NEP ; i++) {
760 		if (sc->sc_pipe[i] != NULL) {
761 			usbd_abort_pipe(sc->sc_pipe[i]);
762 			usbd_close_pipe(sc->sc_pipe[i]);
763 			sc->sc_pipe[i] = NULL;
764 		}
765 	}
766 
767 	/* Some xfers may be queued in the default pipe */
768 	usbd_abort_default_pipe(sc->sc_udev);
769 
770 	/* Free the xfers. */
771 	for (i = 0; i < XFER_NR; i++)
772 		if (sc->transfer_xfer[i] != NULL) {
773 			usbd_free_xfer(sc->transfer_xfer[i]);
774 			sc->transfer_xfer[i] = NULL;
775 		}
776 }
777 
778 /*
779  * Generic functions to handle transfers
780  */
781 
782 Static usbd_status
783 umass_setup_transfer(struct umass_softc *sc, usbd_pipe_handle pipe,
784 			void *buffer, int buflen, int flags,
785 			usbd_xfer_handle xfer)
786 {
787 	usbd_status err;
788 
789 	if (sc->sc_dying)
790 		return (USBD_IOERROR);
791 
792 	/* Initialiase a USB transfer and then schedule it */
793 
794 	usbd_setup_xfer(xfer, pipe, (void *)sc, buffer, buflen,
795 	    flags, sc->timeout, sc->sc_methods->wire_state);
796 
797 	err = usbd_transfer(xfer);
798 	DPRINTF(UDMASS_XFER,("%s: start xfer buffer=%p buflen=%d flags=0x%x "
799 	    "timeout=%d\n", device_xname(sc->sc_dev),
800 	    buffer, buflen, flags, sc->timeout));
801 	if (err && err != USBD_IN_PROGRESS) {
802 		DPRINTF(UDMASS_BBB, ("%s: failed to setup transfer, %s\n",
803 			device_xname(sc->sc_dev), usbd_errstr(err)));
804 		return (err);
805 	}
806 
807 	return (USBD_NORMAL_COMPLETION);
808 }
809 
810 
811 Static usbd_status
812 umass_setup_ctrl_transfer(struct umass_softc *sc, usb_device_request_t *req,
813 	 void *buffer, int buflen, int flags, usbd_xfer_handle xfer)
814 {
815 	usbd_status err;
816 
817 	if (sc->sc_dying)
818 		return (USBD_IOERROR);
819 
820 	/* Initialiase a USB control transfer and then schedule it */
821 
822 	usbd_setup_default_xfer(xfer, sc->sc_udev, (void *) sc, sc->timeout,
823 		req, buffer, buflen, flags, sc->sc_methods->wire_state);
824 
825 	err = usbd_transfer(xfer);
826 	if (err && err != USBD_IN_PROGRESS) {
827 		DPRINTF(UDMASS_BBB, ("%s: failed to setup ctrl transfer, %s\n",
828 			 device_xname(sc->sc_dev), usbd_errstr(err)));
829 
830 		/* do not reset, as this would make us loop */
831 		return (err);
832 	}
833 
834 	return (USBD_NORMAL_COMPLETION);
835 }
836 
837 Static void
838 umass_clear_endpoint_stall(struct umass_softc *sc, int endpt,
839 	usbd_xfer_handle xfer)
840 {
841 	if (sc->sc_dying)
842 		return;
843 
844 	DPRINTF(UDMASS_BBB, ("%s: Clear endpoint 0x%02x stall\n",
845 		device_xname(sc->sc_dev), sc->sc_epaddr[endpt]));
846 
847 	usbd_clear_endpoint_toggle(sc->sc_pipe[endpt]);
848 
849 	sc->sc_req.bmRequestType = UT_WRITE_ENDPOINT;
850 	sc->sc_req.bRequest = UR_CLEAR_FEATURE;
851 	USETW(sc->sc_req.wValue, UF_ENDPOINT_HALT);
852 	USETW(sc->sc_req.wIndex, sc->sc_epaddr[endpt]);
853 	USETW(sc->sc_req.wLength, 0);
854 	umass_setup_ctrl_transfer(sc, &sc->sc_req, NULL, 0, 0, xfer);
855 }
856 
857 #if 0
858 Static void
859 umass_reset(struct umass_softc *sc, transfer_cb_f cb, void *priv)
860 {
861 	sc->transfer_cb = cb;
862 	sc->transfer_priv = priv;
863 
864 	/* The reset is a forced reset, so no error (yet) */
865 	sc->reset(sc, STATUS_CMD_OK);
866 }
867 #endif
868 
869 /*
870  * Bulk protocol specific functions
871  */
872 
873 Static void
874 umass_bbb_reset(struct umass_softc *sc, int status)
875 {
876 	KASSERTMSG(sc->sc_wire & UMASS_WPROTO_BBB,
877 		   "sc->sc_wire == 0x%02x wrong for umass_bbb_reset\n",
878 		   sc->sc_wire);
879 
880 	if (sc->sc_dying)
881 		return;
882 
883 	/*
884 	 * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
885 	 *
886 	 * For Reset Recovery the host shall issue in the following order:
887 	 * a) a Bulk-Only Mass Storage Reset
888 	 * b) a Clear Feature HALT to the Bulk-In endpoint
889 	 * c) a Clear Feature HALT to the Bulk-Out endpoint
890 	 *
891 	 * This is done in 3 steps, states:
892 	 * TSTATE_BBB_RESET1
893 	 * TSTATE_BBB_RESET2
894 	 * TSTATE_BBB_RESET3
895 	 *
896 	 * If the reset doesn't succeed, the device should be port reset.
897 	 */
898 
899 	DPRINTF(UDMASS_BBB, ("%s: Bulk Reset\n",
900 		device_xname(sc->sc_dev)));
901 
902 	sc->transfer_state = TSTATE_BBB_RESET1;
903 	sc->transfer_status = status;
904 
905 	/* reset is a class specific interface write */
906 	sc->sc_req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
907 	sc->sc_req.bRequest = UR_BBB_RESET;
908 	USETW(sc->sc_req.wValue, 0);
909 	USETW(sc->sc_req.wIndex, sc->sc_ifaceno);
910 	USETW(sc->sc_req.wLength, 0);
911 	umass_setup_ctrl_transfer(sc, &sc->sc_req, NULL, 0, 0,
912 				  sc->transfer_xfer[XFER_BBB_RESET1]);
913 }
914 
915 Static void
916 umass_bbb_transfer(struct umass_softc *sc, int lun, void *cmd, int cmdlen,
917 		   void *data, int datalen, int dir, u_int timeout,
918 		   int flags, umass_callback cb, void *priv)
919 {
920 	static int dCBWtag = 42;	/* unique for CBW of transfer */
921 
922 	DPRINTF(UDMASS_BBB,("%s: umass_bbb_transfer cmd=0x%02x\n",
923 		device_xname(sc->sc_dev), *(u_char *)cmd));
924 
925 	KASSERTMSG(sc->sc_wire & UMASS_WPROTO_BBB,
926 		   "sc->sc_wire == 0x%02x wrong for umass_bbb_transfer\n",
927 		   sc->sc_wire);
928 
929 	if (sc->sc_dying)
930 		return;
931 
932 	/* Be a little generous. */
933 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
934 
935 	/*
936 	 * Do a Bulk-Only transfer with cmdlen bytes from cmd, possibly
937 	 * a data phase of datalen bytes from/to the device and finally a
938 	 * csw read phase.
939 	 * If the data direction was inbound a maximum of datalen bytes
940 	 * is stored in the buffer pointed to by data.
941 	 *
942 	 * umass_bbb_transfer initialises the transfer and lets the state
943 	 * machine in umass_bbb_state handle the completion. It uses the
944 	 * following states:
945 	 * TSTATE_BBB_COMMAND
946 	 *   -> TSTATE_BBB_DATA
947 	 *   -> TSTATE_BBB_STATUS
948 	 *   -> TSTATE_BBB_STATUS2
949 	 *   -> TSTATE_BBB_IDLE
950 	 *
951 	 * An error in any of those states will invoke
952 	 * umass_bbb_reset.
953 	 */
954 
955 	/* check the given arguments */
956 	KASSERTMSG(datalen == 0 || data != NULL,
957 		   "%s: datalen > 0, but no buffer",device_xname(sc->sc_dev));
958 	KASSERTMSG(cmdlen <= CBWCDBLENGTH,
959 		   "%s: cmdlen exceeds CDB length in CBW (%d > %d)",
960 			device_xname(sc->sc_dev), cmdlen, CBWCDBLENGTH);
961 	KASSERTMSG(dir == DIR_NONE || datalen > 0,
962 		   "%s: datalen == 0 while direction is not NONE\n",
963 			device_xname(sc->sc_dev));
964 	KASSERTMSG(datalen == 0 || dir != DIR_NONE,
965 		   "%s: direction is NONE while datalen is not zero\n",
966 			device_xname(sc->sc_dev));
967 	/* CTASSERT */
968 	KASSERTMSG(sizeof(umass_bbb_cbw_t) == UMASS_BBB_CBW_SIZE,
969 		   "%s: CBW struct does not have the right size (%zu vs. %u)\n",
970 			device_xname(sc->sc_dev),
971 			sizeof(umass_bbb_cbw_t), UMASS_BBB_CBW_SIZE);
972 	/* CTASSERT */
973 	KASSERTMSG(sizeof(umass_bbb_csw_t) == UMASS_BBB_CSW_SIZE,
974 		   "%s: CSW struct does not have the right size (%zu vs. %u)\n",
975 			device_xname(sc->sc_dev),
976 			sizeof(umass_bbb_csw_t), UMASS_BBB_CSW_SIZE);
977 
978 	/*
979 	 * Determine the direction of the data transfer and the length.
980 	 *
981 	 * dCBWDataTransferLength (datalen) :
982 	 *   This field indicates the number of bytes of data that the host
983 	 *   intends to transfer on the IN or OUT Bulk endpoint(as indicated by
984 	 *   the Direction bit) during the execution of this command. If this
985 	 *   field is set to 0, the device will expect that no data will be
986 	 *   transferred IN or OUT during this command, regardless of the value
987 	 *   of the Direction bit defined in dCBWFlags.
988 	 *
989 	 * dCBWFlags (dir) :
990 	 *   The bits of the Flags field are defined as follows:
991 	 *     Bits 0-6	 reserved
992 	 *     Bit  7	 Direction - this bit shall be ignored if the
993 	 *			     dCBWDataTransferLength field is zero.
994 	 *		 0 = data Out from host to device
995 	 *		 1 = data In from device to host
996 	 */
997 
998 	/* Fill in the Command Block Wrapper */
999 	USETDW(sc->cbw.dCBWSignature, CBWSIGNATURE);
1000 	USETDW(sc->cbw.dCBWTag, dCBWtag);
1001 	dCBWtag++;	/* cannot be done in macro (it will be done 4 times) */
1002 	USETDW(sc->cbw.dCBWDataTransferLength, datalen);
1003 	/* DIR_NONE is treated as DIR_OUT (0x00) */
1004 	sc->cbw.bCBWFlags = (dir == DIR_IN? CBWFLAGS_IN:CBWFLAGS_OUT);
1005 	sc->cbw.bCBWLUN = lun;
1006 	sc->cbw.bCDBLength = cmdlen;
1007 	memcpy(sc->cbw.CBWCDB, cmd, cmdlen);
1008 
1009 	DIF(UDMASS_BBB, umass_bbb_dump_cbw(sc, &sc->cbw));
1010 
1011 	/* store the details for the data transfer phase */
1012 	sc->transfer_dir = dir;
1013 	sc->transfer_data = data;
1014 	sc->transfer_datalen = datalen;
1015 	sc->transfer_actlen = 0;
1016 	sc->transfer_cb = cb;
1017 	sc->transfer_priv = priv;
1018 	sc->transfer_status = STATUS_CMD_OK;
1019 
1020 	/* move from idle to the command state */
1021 	sc->transfer_state = TSTATE_BBB_COMMAND;
1022 
1023 	/* Send the CBW from host to device via bulk-out endpoint. */
1024 	if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
1025 			&sc->cbw, UMASS_BBB_CBW_SIZE, flags,
1026 			sc->transfer_xfer[XFER_BBB_CBW])) {
1027 		umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1028 	}
1029 }
1030 
1031 
1032 Static void
1033 umass_bbb_state(usbd_xfer_handle xfer, usbd_private_handle priv,
1034 		usbd_status err)
1035 {
1036 	struct umass_softc *sc = (struct umass_softc *) priv;
1037 	usbd_xfer_handle next_xfer;
1038 	int residue;
1039 
1040 	KASSERTMSG(sc->sc_wire & UMASS_WPROTO_BBB,
1041 		   "sc->sc_wire == 0x%02x wrong for umass_bbb_state\n",
1042 		   sc->sc_wire);
1043 
1044 	if (sc->sc_dying)
1045 		return;
1046 
1047 	/*
1048 	 * State handling for BBB transfers.
1049 	 *
1050 	 * The subroutine is rather long. It steps through the states given in
1051 	 * Annex A of the Bulk-Only specification.
1052 	 * Each state first does the error handling of the previous transfer
1053 	 * and then prepares the next transfer.
1054 	 * Each transfer is done asynchroneously so after the request/transfer
1055 	 * has been submitted you will find a 'return;'.
1056 	 */
1057 
1058 	DPRINTF(UDMASS_BBB, ("%s: Handling BBB state %d (%s), xfer=%p, %s\n",
1059 		device_xname(sc->sc_dev), sc->transfer_state,
1060 		states[sc->transfer_state], xfer, usbd_errstr(err)));
1061 
1062 	switch (sc->transfer_state) {
1063 
1064 	/***** Bulk Transfer *****/
1065 	case TSTATE_BBB_COMMAND:
1066 		/* Command transport phase, error handling */
1067 		if (err) {
1068 			DPRINTF(UDMASS_BBB, ("%s: failed to send CBW\n",
1069 				device_xname(sc->sc_dev)));
1070 			/* If the device detects that the CBW is invalid, then
1071 			 * the device may STALL both bulk endpoints and require
1072 			 * a Bulk-Reset
1073 			 */
1074 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1075 			return;
1076 		}
1077 
1078 		/* Data transport phase, setup transfer */
1079 		sc->transfer_state = TSTATE_BBB_DATA;
1080 		if (sc->transfer_dir == DIR_IN) {
1081 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
1082 					sc->data_buffer, sc->transfer_datalen,
1083 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
1084 					sc->transfer_xfer[XFER_BBB_DATA]))
1085 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1086 
1087 			return;
1088 		} else if (sc->transfer_dir == DIR_OUT) {
1089 			memcpy(sc->data_buffer, sc->transfer_data,
1090 			       sc->transfer_datalen);
1091 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
1092 					sc->data_buffer, sc->transfer_datalen,
1093 					USBD_NO_COPY,/* fixed length transfer */
1094 					sc->transfer_xfer[XFER_BBB_DATA]))
1095 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1096 
1097 			return;
1098 		} else {
1099 			DPRINTF(UDMASS_BBB, ("%s: no data phase\n",
1100 				device_xname(sc->sc_dev)));
1101 		}
1102 
1103 		/* FALLTHROUGH if no data phase, err == 0 */
1104 	case TSTATE_BBB_DATA:
1105 		/* Command transport phase error handling (ignored if no data
1106 		 * phase (fallthrough from previous state)) */
1107 		if (sc->transfer_dir != DIR_NONE) {
1108 			/* retrieve the length of the transfer that was done */
1109 			usbd_get_xfer_status(xfer, NULL, NULL,
1110 			     &sc->transfer_actlen, NULL);
1111 			DPRINTF(UDMASS_BBB, ("%s: BBB_DATA actlen=%d\n",
1112 				device_xname(sc->sc_dev), sc->transfer_actlen));
1113 
1114 			if (err) {
1115 				DPRINTF(UDMASS_BBB, ("%s: Data-%s %d failed, "
1116 					"%s\n", device_xname(sc->sc_dev),
1117 					(sc->transfer_dir == DIR_IN?"in":"out"),
1118 					sc->transfer_datalen,usbd_errstr(err)));
1119 
1120 				if (err == USBD_STALLED) {
1121 					sc->transfer_state = TSTATE_BBB_DCLEAR;
1122 					umass_clear_endpoint_stall(sc,
1123 					  (sc->transfer_dir == DIR_IN?
1124 					    UMASS_BULKIN:UMASS_BULKOUT),
1125 					  sc->transfer_xfer[XFER_BBB_DCLEAR]);
1126 				} else {
1127 					/* Unless the error is a pipe stall the
1128 					 * error is fatal.
1129 					 */
1130 					umass_bbb_reset(sc,STATUS_WIRE_FAILED);
1131 				}
1132 				return;
1133 			}
1134 		}
1135 
1136 		/* FALLTHROUGH, err == 0 (no data phase or successful) */
1137 	case TSTATE_BBB_DCLEAR: /* stall clear after data phase */
1138 		if (sc->transfer_dir == DIR_IN)
1139 			memcpy(sc->transfer_data, sc->data_buffer,
1140 			       sc->transfer_actlen);
1141 
1142 		DIF(UDMASS_BBB, if (sc->transfer_dir == DIR_IN)
1143 					umass_dump_buffer(sc, sc->transfer_data,
1144 						sc->transfer_datalen, 48));
1145 
1146 		/* FALLTHROUGH, err == 0 (no data phase or successful) */
1147 	case TSTATE_BBB_SCLEAR: /* stall clear after status phase */
1148 		/* Reading of CSW after bulk stall condition in data phase
1149 		 * (TSTATE_BBB_DATA2) or bulk-in stall condition after
1150 		 * reading CSW (TSTATE_BBB_SCLEAR).
1151 		 * In the case of no data phase or successful data phase,
1152 		 * err == 0 and the following if block is passed.
1153 		 */
1154 		if (err) {	/* should not occur */
1155 			printf("%s: BBB bulk-%s stall clear failed, %s\n",
1156 			    device_xname(sc->sc_dev),
1157 			    (sc->transfer_dir == DIR_IN? "in":"out"),
1158 			    usbd_errstr(err));
1159 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1160 			return;
1161 		}
1162 
1163 		/* Status transport phase, setup transfer */
1164 		if (sc->transfer_state == TSTATE_BBB_COMMAND ||
1165 		    sc->transfer_state == TSTATE_BBB_DATA ||
1166 		    sc->transfer_state == TSTATE_BBB_DCLEAR) {
1167 			/* After no data phase, successful data phase and
1168 			 * after clearing bulk-in/-out stall condition
1169 			 */
1170 			sc->transfer_state = TSTATE_BBB_STATUS1;
1171 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW1];
1172 		} else {
1173 			/* After first attempt of fetching CSW */
1174 			sc->transfer_state = TSTATE_BBB_STATUS2;
1175 			next_xfer = sc->transfer_xfer[XFER_BBB_CSW2];
1176 		}
1177 
1178 		/* Read the Command Status Wrapper via bulk-in endpoint. */
1179 		if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
1180 			&sc->csw, UMASS_BBB_CSW_SIZE, 0, next_xfer)) {
1181 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1182 			return;
1183 		}
1184 
1185 		return;
1186 	case TSTATE_BBB_STATUS1:	/* first attempt */
1187 	case TSTATE_BBB_STATUS2:	/* second attempt */
1188 		/* Status transfer, error handling */
1189 		if (err) {
1190 			DPRINTF(UDMASS_BBB, ("%s: Failed to read CSW, %s%s\n",
1191 				device_xname(sc->sc_dev), usbd_errstr(err),
1192 				(sc->transfer_state == TSTATE_BBB_STATUS1?
1193 					", retrying":"")));
1194 
1195 			/* If this was the first attempt at fetching the CSW
1196 			 * retry it, otherwise fail.
1197 			 */
1198 			if (sc->transfer_state == TSTATE_BBB_STATUS1) {
1199 				sc->transfer_state = TSTATE_BBB_SCLEAR;
1200 				umass_clear_endpoint_stall(sc, UMASS_BULKIN,
1201 				    sc->transfer_xfer[XFER_BBB_SCLEAR]);
1202 				return;
1203 			} else {
1204 				umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1205 				return;
1206 			}
1207 		}
1208 
1209 		DIF(UDMASS_BBB, umass_bbb_dump_csw(sc, &sc->csw));
1210 
1211 #ifdef UMASS_DEBUG
1212 		residue = UGETDW(sc->csw.dCSWDataResidue);
1213 		if (residue != sc->transfer_datalen - sc->transfer_actlen)
1214 			printf("%s: dCSWDataResidue=%d req=%d act=%d\n",
1215 			       device_xname(sc->sc_dev), residue,
1216 			       sc->transfer_datalen, sc->transfer_actlen);
1217 #endif
1218 		residue = sc->transfer_datalen - sc->transfer_actlen;
1219 
1220 		/* Translate weird command-status signatures. */
1221 		if ((sc->sc_quirks & UMASS_QUIRK_WRONG_CSWSIG) &&
1222 		    UGETDW(sc->csw.dCSWSignature) == CSWSIGNATURE_OLYMPUS_C1)
1223 			USETDW(sc->csw.dCSWSignature, CSWSIGNATURE);
1224 
1225 		/* Translate invalid command-status tags */
1226 		if (sc->sc_quirks & UMASS_QUIRK_WRONG_CSWTAG)
1227 			USETDW(sc->csw.dCSWTag, UGETDW(sc->cbw.dCBWTag));
1228 
1229 		/* Check CSW and handle any error */
1230 		if (UGETDW(sc->csw.dCSWSignature) != CSWSIGNATURE) {
1231 			/* Invalid CSW: Wrong signature or wrong tag might
1232 			 * indicate that the device is confused -> reset it.
1233 			 */
1234 			printf("%s: Invalid CSW: sig 0x%08x should be 0x%08x\n",
1235 				device_xname(sc->sc_dev),
1236 				UGETDW(sc->csw.dCSWSignature),
1237 				CSWSIGNATURE);
1238 
1239 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1240 			return;
1241 		} else if (UGETDW(sc->csw.dCSWTag)
1242 				!= UGETDW(sc->cbw.dCBWTag)) {
1243 			printf("%s: Invalid CSW: tag %d should be %d\n",
1244 				device_xname(sc->sc_dev),
1245 				UGETDW(sc->csw.dCSWTag),
1246 				UGETDW(sc->cbw.dCBWTag));
1247 
1248 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1249 			return;
1250 
1251 		/* CSW is valid here */
1252 		} else if (sc->csw.bCSWStatus > CSWSTATUS_PHASE) {
1253 			printf("%s: Invalid CSW: status %d > %d\n",
1254 				device_xname(sc->sc_dev),
1255 				sc->csw.bCSWStatus,
1256 				CSWSTATUS_PHASE);
1257 
1258 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1259 			return;
1260 		} else if (sc->csw.bCSWStatus == CSWSTATUS_PHASE) {
1261 			printf("%s: Phase Error, residue = %d\n",
1262 				device_xname(sc->sc_dev), residue);
1263 
1264 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1265 			return;
1266 
1267 		} else if (sc->transfer_actlen > sc->transfer_datalen) {
1268 			/* Buffer overrun! Don't let this go by unnoticed */
1269 			panic("%s: transferred %s %d bytes instead of %d bytes",
1270 			    device_xname(sc->sc_dev),
1271 			    sc->transfer_dir == DIR_IN ? "IN" : "OUT",
1272 			    sc->transfer_actlen, sc->transfer_datalen);
1273 #if 0
1274 		} else if (sc->transfer_datalen - sc->transfer_actlen
1275 			   != residue) {
1276 			DPRINTF(UDMASS_BBB, ("%s: actlen=%d != residue=%d\n",
1277 				device_xname(sc->sc_dev),
1278 				sc->transfer_datalen - sc->transfer_actlen,
1279 				residue));
1280 
1281 			umass_bbb_reset(sc, STATUS_WIRE_FAILED);
1282 			return;
1283 #endif
1284 		} else if (sc->csw.bCSWStatus == CSWSTATUS_FAILED) {
1285 			DPRINTF(UDMASS_BBB, ("%s: Command Failed, res = %d\n",
1286 				device_xname(sc->sc_dev), residue));
1287 
1288 			/* SCSI command failed but transfer was succesful */
1289 			sc->transfer_state = TSTATE_IDLE;
1290 			sc->transfer_cb(sc, sc->transfer_priv, residue,
1291 					STATUS_CMD_FAILED);
1292 
1293 			return;
1294 
1295 		} else {	/* success */
1296 			sc->transfer_state = TSTATE_IDLE;
1297 			sc->transfer_cb(sc, sc->transfer_priv, residue,
1298 					STATUS_CMD_OK);
1299 
1300 			return;
1301 		}
1302 
1303 	/***** Bulk Reset *****/
1304 	case TSTATE_BBB_RESET1:
1305 		if (err)
1306 			printf("%s: BBB reset failed, %s\n",
1307 				device_xname(sc->sc_dev), usbd_errstr(err));
1308 
1309 		sc->transfer_state = TSTATE_BBB_RESET2;
1310 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
1311 			sc->transfer_xfer[XFER_BBB_RESET2]);
1312 
1313 		return;
1314 	case TSTATE_BBB_RESET2:
1315 		if (err)	/* should not occur */
1316 			printf("%s: BBB bulk-in clear stall failed, %s\n",
1317 			       device_xname(sc->sc_dev), usbd_errstr(err));
1318 			/* no error recovery, otherwise we end up in a loop */
1319 
1320 		sc->transfer_state = TSTATE_BBB_RESET3;
1321 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
1322 			sc->transfer_xfer[XFER_BBB_RESET3]);
1323 
1324 		return;
1325 	case TSTATE_BBB_RESET3:
1326 		if (err)	/* should not occur */
1327 			printf("%s: BBB bulk-out clear stall failed, %s\n",
1328 			       device_xname(sc->sc_dev), usbd_errstr(err));
1329 			/* no error recovery, otherwise we end up in a loop */
1330 
1331 		sc->transfer_state = TSTATE_IDLE;
1332 		if (sc->transfer_priv) {
1333 			sc->transfer_cb(sc, sc->transfer_priv,
1334 					sc->transfer_datalen,
1335 					sc->transfer_status);
1336 		}
1337 
1338 		return;
1339 
1340 	/***** Default *****/
1341 	default:
1342 		panic("%s: Unknown state %d",
1343 		      device_xname(sc->sc_dev), sc->transfer_state);
1344 	}
1345 }
1346 
1347 /*
1348  * Command/Bulk/Interrupt (CBI) specific functions
1349  */
1350 
1351 Static int
1352 umass_cbi_adsc(struct umass_softc *sc, char *buffer, int buflen, int flags,
1353 	       usbd_xfer_handle xfer)
1354 {
1355 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
1356 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_adsc\n",
1357 		   sc->sc_wire);
1358 
1359 	if ((sc->sc_cmd == UMASS_CPROTO_RBC) &&
1360 	    (sc->sc_quirks & UMASS_QUIRK_RBC_PAD_TO_12) != 0 && buflen < 12) {
1361 		(void)memset(buffer + buflen, 0, 12 - buflen);
1362 		buflen = 12;
1363 	}
1364 
1365 	sc->sc_req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1366 	sc->sc_req.bRequest = UR_CBI_ADSC;
1367 	USETW(sc->sc_req.wValue, 0);
1368 	USETW(sc->sc_req.wIndex, sc->sc_ifaceno);
1369 	USETW(sc->sc_req.wLength, buflen);
1370 	return umass_setup_ctrl_transfer(sc, &sc->sc_req, buffer,
1371 					 buflen, flags, xfer);
1372 }
1373 
1374 
1375 Static void
1376 umass_cbi_reset(struct umass_softc *sc, int status)
1377 {
1378 	int i;
1379 #	define SEND_DIAGNOSTIC_CMDLEN	12
1380 
1381 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
1382 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_reset\n",
1383 		   sc->sc_wire);
1384 
1385 	if (sc->sc_dying)
1386 		return;
1387 
1388 	/*
1389 	 * Command Block Reset Protocol
1390 	 *
1391 	 * First send a reset request to the device. Then clear
1392 	 * any possibly stalled bulk endpoints.
1393 
1394 	 * This is done in 3 steps, states:
1395 	 * TSTATE_CBI_RESET1
1396 	 * TSTATE_CBI_RESET2
1397 	 * TSTATE_CBI_RESET3
1398 	 *
1399 	 * If the reset doesn't succeed, the device should be port reset.
1400 	 */
1401 
1402 	DPRINTF(UDMASS_CBI, ("%s: CBI Reset\n",
1403 		device_xname(sc->sc_dev)));
1404 
1405 	/* CTASSERT */
1406 	KASSERTMSG(sizeof(sc->cbl) >= SEND_DIAGNOSTIC_CMDLEN,
1407 		   "%s: CBL struct is too small (%zu < %u)\n",
1408 			device_xname(sc->sc_dev),
1409 			sizeof(sc->cbl), SEND_DIAGNOSTIC_CMDLEN);
1410 
1411 	sc->transfer_state = TSTATE_CBI_RESET1;
1412 	sc->transfer_status = status;
1413 
1414 	/* The 0x1d code is the SEND DIAGNOSTIC command. To distingiush between
1415 	 * the two the last 10 bytes of the cbl is filled with 0xff (section
1416 	 * 2.2 of the CBI spec).
1417 	 */
1418 	sc->cbl[0] = 0x1d;	/* Command Block Reset */
1419 	sc->cbl[1] = 0x04;
1420 	for (i = 2; i < SEND_DIAGNOSTIC_CMDLEN; i++)
1421 		sc->cbl[i] = 0xff;
1422 
1423 	umass_cbi_adsc(sc, sc->cbl, SEND_DIAGNOSTIC_CMDLEN, 0,
1424 		       sc->transfer_xfer[XFER_CBI_RESET1]);
1425 	/* XXX if the command fails we should reset the port on the bub */
1426 }
1427 
1428 Static void
1429 umass_cbi_transfer(struct umass_softc *sc, int lun,
1430 		   void *cmd, int cmdlen, void *data, int datalen, int dir,
1431 		   u_int timeout, int flags, umass_callback cb, void *priv)
1432 {
1433 	DPRINTF(UDMASS_CBI,("%s: umass_cbi_transfer cmd=0x%02x, len=%d\n",
1434 		device_xname(sc->sc_dev), *(u_char *)cmd, datalen));
1435 
1436 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
1437 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_transfer\n",
1438 		   sc->sc_wire);
1439 
1440 	if (sc->sc_dying)
1441 		return;
1442 
1443 	/* Be a little generous. */
1444 	sc->timeout = timeout + USBD_DEFAULT_TIMEOUT;
1445 
1446 	/*
1447 	 * Do a CBI transfer with cmdlen bytes from cmd, possibly
1448 	 * a data phase of datalen bytes from/to the device and finally a
1449 	 * csw read phase.
1450 	 * If the data direction was inbound a maximum of datalen bytes
1451 	 * is stored in the buffer pointed to by data.
1452 	 *
1453 	 * umass_cbi_transfer initialises the transfer and lets the state
1454 	 * machine in umass_cbi_state handle the completion. It uses the
1455 	 * following states:
1456 	 * TSTATE_CBI_COMMAND
1457 	 *   -> XXX fill in
1458 	 *
1459 	 * An error in any of those states will invoke
1460 	 * umass_cbi_reset.
1461 	 */
1462 
1463 	/* check the given arguments */
1464 	KASSERTMSG(datalen == 0 || data != NULL,
1465 		   "%s: datalen > 0, but no buffer",device_xname(sc->sc_dev));
1466 	KASSERTMSG(datalen == 0 || dir != DIR_NONE,
1467 		   "%s: direction is NONE while datalen is not zero\n",
1468 			device_xname(sc->sc_dev));
1469 
1470 	/* store the details for the data transfer phase */
1471 	sc->transfer_dir = dir;
1472 	sc->transfer_data = data;
1473 	sc->transfer_datalen = datalen;
1474 	sc->transfer_actlen = 0;
1475 	sc->transfer_cb = cb;
1476 	sc->transfer_priv = priv;
1477 	sc->transfer_status = STATUS_CMD_OK;
1478 
1479 	/* move from idle to the command state */
1480 	sc->transfer_state = TSTATE_CBI_COMMAND;
1481 
1482 	/* Send the Command Block from host to device via control endpoint. */
1483 	if (umass_cbi_adsc(sc, cmd, cmdlen, flags, sc->transfer_xfer[XFER_CBI_CB]))
1484 		umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1485 }
1486 
1487 Static void
1488 umass_cbi_state(usbd_xfer_handle xfer, usbd_private_handle priv,
1489 		usbd_status err)
1490 {
1491 	struct umass_softc *sc = (struct umass_softc *) priv;
1492 
1493 	KASSERTMSG(sc->sc_wire & (UMASS_WPROTO_CBI|UMASS_WPROTO_CBI_I),
1494 		   "sc->sc_wire == 0x%02x wrong for umass_cbi_state\n",
1495 		   sc->sc_wire);
1496 
1497 	if (sc->sc_dying)
1498 		return;
1499 
1500 	/*
1501 	 * State handling for CBI transfers.
1502 	 */
1503 
1504 	DPRINTF(UDMASS_CBI, ("%s: Handling CBI state %d (%s), xfer=%p, %s\n",
1505 		device_xname(sc->sc_dev), sc->transfer_state,
1506 		states[sc->transfer_state], xfer, usbd_errstr(err)));
1507 
1508 	switch (sc->transfer_state) {
1509 
1510 	/***** CBI Transfer *****/
1511 	case TSTATE_CBI_COMMAND:
1512 		if (err == USBD_STALLED) {
1513 			DPRINTF(UDMASS_CBI, ("%s: Command Transport failed\n",
1514 				device_xname(sc->sc_dev)));
1515 			/* Status transport by control pipe (section 2.3.2.1).
1516 			 * The command contained in the command block failed.
1517 			 *
1518 			 * The control pipe has already been unstalled by the
1519 			 * USB stack.
1520 			 * Section 2.4.3.1.1 states that the bulk in endpoints
1521 			 * should not stalled at this point.
1522 			 */
1523 
1524 			sc->transfer_state = TSTATE_IDLE;
1525 			sc->transfer_cb(sc, sc->transfer_priv,
1526 					sc->transfer_datalen,
1527 					STATUS_CMD_FAILED);
1528 
1529 			return;
1530 		} else if (err) {
1531 			DPRINTF(UDMASS_CBI, ("%s: failed to send ADSC\n",
1532 				device_xname(sc->sc_dev)));
1533 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1534 			return;
1535 		}
1536 
1537 		/* Data transport phase, setup transfer */
1538 		sc->transfer_state = TSTATE_CBI_DATA;
1539 		if (sc->transfer_dir == DIR_IN) {
1540 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKIN],
1541 					sc->data_buffer, sc->transfer_datalen,
1542 					USBD_SHORT_XFER_OK | USBD_NO_COPY,
1543 					sc->transfer_xfer[XFER_CBI_DATA]))
1544 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1545 
1546 			return;
1547 		} else if (sc->transfer_dir == DIR_OUT) {
1548 			memcpy(sc->data_buffer, sc->transfer_data,
1549 			       sc->transfer_datalen);
1550 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_BULKOUT],
1551 					sc->data_buffer, sc->transfer_datalen,
1552 					USBD_NO_COPY,/* fixed length transfer */
1553 					sc->transfer_xfer[XFER_CBI_DATA]))
1554 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1555 
1556 			return;
1557 		} else {
1558 			DPRINTF(UDMASS_CBI, ("%s: no data phase\n",
1559 				device_xname(sc->sc_dev)));
1560 		}
1561 
1562 		/* FALLTHROUGH if no data phase, err == 0 */
1563 	case TSTATE_CBI_DATA:
1564 		/* Command transport phase error handling (ignored if no data
1565 		 * phase (fallthrough from previous state)) */
1566 		if (sc->transfer_dir != DIR_NONE) {
1567 			/* retrieve the length of the transfer that was done */
1568 			usbd_get_xfer_status(xfer, NULL, NULL,
1569 			    &sc->transfer_actlen, NULL);
1570 			DPRINTF(UDMASS_CBI, ("%s: CBI_DATA actlen=%d\n",
1571 				device_xname(sc->sc_dev), sc->transfer_actlen));
1572 
1573 			if (err) {
1574 				DPRINTF(UDMASS_CBI, ("%s: Data-%s %d failed, "
1575 					"%s\n", device_xname(sc->sc_dev),
1576 					(sc->transfer_dir == DIR_IN?"in":"out"),
1577 					sc->transfer_datalen,usbd_errstr(err)));
1578 
1579 				if (err == USBD_STALLED) {
1580 					sc->transfer_state = TSTATE_CBI_DCLEAR;
1581 					umass_clear_endpoint_stall(sc,
1582 					  (sc->transfer_dir == DIR_IN?
1583 					    UMASS_BULKIN:UMASS_BULKOUT),
1584 					sc->transfer_xfer[XFER_CBI_DCLEAR]);
1585 				} else {
1586 					/* Unless the error is a pipe stall the
1587 					 * error is fatal.
1588 					 */
1589 					umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1590 				}
1591 				return;
1592 			}
1593 		}
1594 
1595 		if (sc->transfer_dir == DIR_IN)
1596 			memcpy(sc->transfer_data, sc->data_buffer,
1597 			       sc->transfer_actlen);
1598 
1599 		DIF(UDMASS_CBI, if (sc->transfer_dir == DIR_IN)
1600 					umass_dump_buffer(sc, sc->transfer_data,
1601 						sc->transfer_actlen, 48));
1602 
1603 		/* Status phase */
1604 		if (sc->sc_wire == UMASS_WPROTO_CBI_I) {
1605 			sc->transfer_state = TSTATE_CBI_STATUS;
1606 			memset(&sc->sbl, 0, sizeof(sc->sbl));
1607 			if (umass_setup_transfer(sc, sc->sc_pipe[UMASS_INTRIN],
1608 				    &sc->sbl, sizeof(sc->sbl),
1609 				    0,	/* fixed length transfer */
1610 				    sc->transfer_xfer[XFER_CBI_STATUS]))
1611 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1612 		} else {
1613 			/* No command completion interrupt. Request
1614 			 * sense to get status of command.
1615 			 */
1616 			sc->transfer_state = TSTATE_IDLE;
1617 			sc->transfer_cb(sc, sc->transfer_priv,
1618 				sc->transfer_datalen - sc->transfer_actlen,
1619 				STATUS_CMD_UNKNOWN);
1620 		}
1621 		return;
1622 
1623 	case TSTATE_CBI_STATUS:
1624 		if (err) {
1625 			DPRINTF(UDMASS_CBI, ("%s: Status Transport failed\n",
1626 				device_xname(sc->sc_dev)));
1627 			/* Status transport by interrupt pipe (section 2.3.2.2).
1628 			 */
1629 
1630 			if (err == USBD_STALLED) {
1631 				sc->transfer_state = TSTATE_CBI_SCLEAR;
1632 				umass_clear_endpoint_stall(sc, UMASS_INTRIN,
1633 					sc->transfer_xfer[XFER_CBI_SCLEAR]);
1634 			} else {
1635 				umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1636 			}
1637 			return;
1638 		}
1639 
1640 		/* Dissect the information in the buffer */
1641 
1642 		{
1643 			u_int32_t actlen;
1644 			usbd_get_xfer_status(xfer,NULL,NULL,&actlen,NULL);
1645 			DPRINTF(UDMASS_CBI, ("%s: CBI_STATUS actlen=%d\n",
1646 				device_xname(sc->sc_dev), actlen));
1647 			if (actlen != 2)
1648 				break;
1649 		}
1650 
1651 		if (sc->sc_cmd == UMASS_CPROTO_UFI) {
1652 			int status;
1653 
1654 			/* Section 3.4.3.1.3 specifies that the UFI command
1655 			 * protocol returns an ASC and ASCQ in the interrupt
1656 			 * data block.
1657 			 */
1658 
1659 			DPRINTF(UDMASS_CBI, ("%s: UFI CCI, ASC = 0x%02x, "
1660 				"ASCQ = 0x%02x\n",
1661 				device_xname(sc->sc_dev),
1662 				sc->sbl.ufi.asc, sc->sbl.ufi.ascq));
1663 
1664 			if ((sc->sbl.ufi.asc == 0 && sc->sbl.ufi.ascq == 0) ||
1665 			    sc->sc_sense)
1666 				status = STATUS_CMD_OK;
1667 			else
1668 				status = STATUS_CMD_FAILED;
1669 
1670 			/* No autosense, command successful */
1671 			sc->transfer_state = TSTATE_IDLE;
1672 			sc->transfer_cb(sc, sc->transfer_priv,
1673 			    sc->transfer_datalen - sc->transfer_actlen, status);
1674 		} else {
1675 			int status;
1676 
1677 			/* Command Interrupt Data Block */
1678 
1679 			DPRINTF(UDMASS_CBI, ("%s: type=0x%02x, value=0x%02x\n",
1680 				device_xname(sc->sc_dev),
1681 				sc->sbl.common.type, sc->sbl.common.value));
1682 
1683 			if (sc->sbl.common.type == IDB_TYPE_CCI) {
1684 				switch (sc->sbl.common.value & IDB_VALUE_STATUS_MASK) {
1685 				case IDB_VALUE_PASS:
1686 					status = STATUS_CMD_OK;
1687 					break;
1688 				case IDB_VALUE_FAIL:
1689 				case IDB_VALUE_PERSISTENT:
1690 					status = STATUS_CMD_FAILED;
1691 					break;
1692 				case IDB_VALUE_PHASE:
1693 				default: /* XXX: gcc */
1694 					status = STATUS_WIRE_FAILED;
1695 					break;
1696 				}
1697 
1698 				sc->transfer_state = TSTATE_IDLE;
1699 				sc->transfer_cb(sc, sc->transfer_priv,
1700 				    sc->transfer_datalen - sc->transfer_actlen, status);
1701 			}
1702 		}
1703 		return;
1704 
1705 	case TSTATE_CBI_DCLEAR:
1706 		if (err) {	/* should not occur */
1707 			printf("%s: CBI bulk-%s stall clear failed, %s\n",
1708 			    device_xname(sc->sc_dev),
1709 			    (sc->transfer_dir == DIR_IN? "in":"out"),
1710 			    usbd_errstr(err));
1711 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1712 		} else {
1713 			sc->transfer_state = TSTATE_IDLE;
1714 			sc->transfer_cb(sc, sc->transfer_priv,
1715 			    sc->transfer_datalen, STATUS_CMD_FAILED);
1716 		}
1717 		return;
1718 
1719 	case TSTATE_CBI_SCLEAR:
1720 		if (err) {	/* should not occur */
1721 			printf("%s: CBI intr-in stall clear failed, %s\n",
1722 			       device_xname(sc->sc_dev), usbd_errstr(err));
1723 			umass_cbi_reset(sc, STATUS_WIRE_FAILED);
1724 		} else {
1725 			sc->transfer_state = TSTATE_IDLE;
1726 			sc->transfer_cb(sc, sc->transfer_priv,
1727 			    sc->transfer_datalen, STATUS_CMD_FAILED);
1728 		}
1729 		return;
1730 
1731 	/***** CBI Reset *****/
1732 	case TSTATE_CBI_RESET1:
1733 		if (err)
1734 			printf("%s: CBI reset failed, %s\n",
1735 				device_xname(sc->sc_dev), usbd_errstr(err));
1736 
1737 		sc->transfer_state = TSTATE_CBI_RESET2;
1738 		umass_clear_endpoint_stall(sc, UMASS_BULKIN,
1739 			sc->transfer_xfer[XFER_CBI_RESET2]);
1740 
1741 		return;
1742 	case TSTATE_CBI_RESET2:
1743 		if (err)	/* should not occur */
1744 			printf("%s: CBI bulk-in stall clear failed, %s\n",
1745 			       device_xname(sc->sc_dev), usbd_errstr(err));
1746 			/* no error recovery, otherwise we end up in a loop */
1747 
1748 		sc->transfer_state = TSTATE_CBI_RESET3;
1749 		umass_clear_endpoint_stall(sc, UMASS_BULKOUT,
1750 			sc->transfer_xfer[XFER_CBI_RESET3]);
1751 
1752 		return;
1753 	case TSTATE_CBI_RESET3:
1754 		if (err)	/* should not occur */
1755 			printf("%s: CBI bulk-out stall clear failed, %s\n",
1756 			       device_xname(sc->sc_dev), usbd_errstr(err));
1757 			/* no error recovery, otherwise we end up in a loop */
1758 
1759 		sc->transfer_state = TSTATE_IDLE;
1760 		if (sc->transfer_priv) {
1761 			sc->transfer_cb(sc, sc->transfer_priv,
1762 					sc->transfer_datalen,
1763 					sc->transfer_status);
1764 		}
1765 
1766 		return;
1767 
1768 
1769 	/***** Default *****/
1770 	default:
1771 		panic("%s: Unknown state %d",
1772 		      device_xname(sc->sc_dev), sc->transfer_state);
1773 	}
1774 }
1775 
1776 usbd_status
1777 umass_bbb_get_max_lun(struct umass_softc *sc, u_int8_t *maxlun)
1778 {
1779 	usb_device_request_t req;
1780 	usbd_status err;
1781 
1782 	*maxlun = 0;		/* Default to 0. */
1783 
1784 	DPRINTF(UDMASS_BBB, ("%s: Get Max Lun\n", device_xname(sc->sc_dev)));
1785 
1786 	/* The Get Max Lun command is a class-specific request. */
1787 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1788 	req.bRequest = UR_BBB_GET_MAX_LUN;
1789 	USETW(req.wValue, 0);
1790 	USETW(req.wIndex, sc->sc_ifaceno);
1791 	USETW(req.wLength, 1);
1792 
1793 	err = usbd_do_request_flags(sc->sc_udev, &req, maxlun,
1794 	    USBD_SHORT_XFER_OK, 0, USBD_DEFAULT_TIMEOUT);
1795 	switch (err) {
1796 	case USBD_NORMAL_COMPLETION:
1797 		DPRINTF(UDMASS_BBB, ("%s: Max Lun %d\n",
1798 		    device_xname(sc->sc_dev), *maxlun));
1799 		break;
1800 
1801 	case USBD_STALLED:
1802 		/*
1803 		 * Device doesn't support Get Max Lun request.
1804 		 */
1805 		err = USBD_NORMAL_COMPLETION;
1806 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun not supported\n",
1807 		    device_xname(sc->sc_dev)));
1808 		break;
1809 
1810 	case USBD_SHORT_XFER:
1811 		/*
1812 		 * XXX This must mean Get Max Lun is not supported, too!
1813 		 */
1814 		err = USBD_NORMAL_COMPLETION;
1815 		DPRINTF(UDMASS_BBB, ("%s: Get Max Lun SHORT_XFER\n",
1816 		    device_xname(sc->sc_dev)));
1817 		break;
1818 
1819 	default:
1820 		printf("%s: Get Max Lun failed: %s\n",
1821 		    device_xname(sc->sc_dev), usbd_errstr(err));
1822 		/* XXX Should we port_reset the device? */
1823 		break;
1824 	}
1825 
1826 	return (err);
1827 }
1828 
1829 
1830 
1831 
1832 #ifdef UMASS_DEBUG
1833 Static void
1834 umass_bbb_dump_cbw(struct umass_softc *sc, umass_bbb_cbw_t *cbw)
1835 {
1836 	int clen = cbw->bCDBLength;
1837 	int dlen = UGETDW(cbw->dCBWDataTransferLength);
1838 	u_int8_t *c = cbw->CBWCDB;
1839 	int tag = UGETDW(cbw->dCBWTag);
1840 	int flags = cbw->bCBWFlags;
1841 
1842 	DPRINTF(UDMASS_BBB, ("%s: CBW %d: cmdlen=%d "
1843 		"(0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%s), "
1844 		"data = %d bytes, dir = %s\n",
1845 		device_xname(sc->sc_dev), tag, clen,
1846 		c[0], c[1], c[2], c[3], c[4], c[5],
1847 		c[6], c[7], c[8], c[9],
1848 		(clen > 10? "...":""),
1849 		dlen, (flags == CBWFLAGS_IN? "in":
1850 		       (flags == CBWFLAGS_OUT? "out":"<invalid>"))));
1851 }
1852 
1853 Static void
1854 umass_bbb_dump_csw(struct umass_softc *sc, umass_bbb_csw_t *csw)
1855 {
1856 	int sig = UGETDW(csw->dCSWSignature);
1857 	int tag = UGETDW(csw->dCSWTag);
1858 	int res = UGETDW(csw->dCSWDataResidue);
1859 	int status = csw->bCSWStatus;
1860 
1861 	DPRINTF(UDMASS_BBB, ("%s: CSW %d: sig = 0x%08x (%s), tag = %d, "
1862 		"res = %d, status = 0x%02x (%s)\n", device_xname(sc->sc_dev),
1863 		tag, sig, (sig == CSWSIGNATURE?	 "valid":"invalid"),
1864 		tag, res,
1865 		status, (status == CSWSTATUS_GOOD? "good":
1866 			 (status == CSWSTATUS_FAILED? "failed":
1867 			  (status == CSWSTATUS_PHASE? "phase":"<invalid>")))));
1868 }
1869 
1870 Static void
1871 umass_dump_buffer(struct umass_softc *sc, u_int8_t *buffer, int buflen,
1872 		  int printlen)
1873 {
1874 	int i, j;
1875 	char s1[40];
1876 	char s2[40];
1877 	char s3[5];
1878 
1879 	s1[0] = '\0';
1880 	s3[0] = '\0';
1881 
1882 	snprintf(s2, sizeof(s2), " buffer=%p, buflen=%d", buffer, buflen);
1883 	for (i = 0; i < buflen && i < printlen; i++) {
1884 		j = i % 16;
1885 		if (j == 0 && i != 0) {
1886 			DPRINTF(UDMASS_GEN, ("%s: 0x %s%s\n",
1887 				device_xname(sc->sc_dev), s1, s2));
1888 			s2[0] = '\0';
1889 		}
1890 		snprintf(&s1[j * 2], sizeof(s1) - j * 2, "%02x",
1891 		    buffer[i] & 0xff);
1892 	}
1893 	if (buflen > printlen)
1894 		snprintf(s3, sizeof(s3), " ...");
1895 	DPRINTF(UDMASS_GEN, ("%s: 0x %s%s%s\n",
1896 		device_xname(sc->sc_dev), s1, s2, s3));
1897 }
1898 #endif
1899