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