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