xref: /freebsd/sys/dev/usb/usb_msctest.c (revision d9a42747950146bf03cda7f6e25d219253f8a57a)
1 /* $FreeBSD$ */
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4  *
5  * Copyright (c) 2008-2022 Hans Petter Selasky.
6  * Copyright (c) 2021-2022 Idwer Vollering.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * The following file contains code that will detect USB autoinstall
32  * disks.
33  */
34 
35 #ifdef USB_GLOBAL_INCLUDE_FILE
36 #include USB_GLOBAL_INCLUDE_FILE
37 #else
38 #include <sys/stdint.h>
39 #include <sys/stddef.h>
40 #include <sys/param.h>
41 #include <sys/queue.h>
42 #include <sys/types.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/bus.h>
46 #include <sys/module.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/condvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/sx.h>
52 #include <sys/unistd.h>
53 #include <sys/callout.h>
54 #include <sys/malloc.h>
55 #include <sys/priv.h>
56 
57 #include <dev/usb/usb.h>
58 #include <dev/usb/usbdi.h>
59 #include <dev/usb/usbdi_util.h>
60 
61 #define	USB_DEBUG_VAR usb_debug
62 
63 #include <dev/usb/usb_busdma.h>
64 #include <dev/usb/usb_process.h>
65 #include <dev/usb/usb_transfer.h>
66 #include <dev/usb/usb_msctest.h>
67 #include <dev/usb/usb_debug.h>
68 #include <dev/usb/usb_device.h>
69 #include <dev/usb/usb_request.h>
70 #include <dev/usb/usb_util.h>
71 #include <dev/usb/quirk/usb_quirk.h>
72 #endif			/* USB_GLOBAL_INCLUDE_FILE */
73 
74 enum {
75 	ST_COMMAND,
76 	ST_DATA_RD,
77 	ST_DATA_RD_CS,
78 	ST_DATA_WR,
79 	ST_DATA_WR_CS,
80 	ST_STATUS,
81 	ST_MAX,
82 };
83 
84 enum {
85 	DIR_IN,
86 	DIR_OUT,
87 	DIR_NONE,
88 };
89 
90 #define	SCSI_MAX_LEN	MAX(SCSI_FIXED_BLOCK_SIZE, USB_MSCTEST_BULK_SIZE)
91 #define	SCSI_INQ_LEN	0x24
92 #define	SCSI_SENSE_LEN	0xFF
93 #define	SCSI_FIXED_BLOCK_SIZE 512	/* bytes */
94 
95 static uint8_t scsi_test_unit_ready[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
96 static uint8_t scsi_inquiry[] = { 0x12, 0x00, 0x00, 0x00, SCSI_INQ_LEN, 0x00 };
97 static uint8_t scsi_rezero_init[] =     { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };
98 static uint8_t scsi_start_unit[] = { 0x1b, 0x00, 0x00, 0x00, 0x01, 0x00 };
99 static uint8_t scsi_stop_unit[] = { 0x1b, 0x00, 0x00, 0x00, 0x02, 0x00 };
100 static uint8_t scsi_ztestor_eject[] =   { 0x85, 0x01, 0x01, 0x01, 0x18, 0x01,
101 					  0x01, 0x01, 0x01, 0x01, 0x00, 0x00 };
102 static uint8_t scsi_cmotech_eject[] =   { 0xff, 0x52, 0x44, 0x45, 0x56, 0x43,
103 					  0x48, 0x47 };
104 static uint8_t scsi_huawei_eject[] =	{ 0x11, 0x06, 0x00, 0x00, 0x00, 0x00,
105 					  0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
106 					  0x00, 0x00, 0x00, 0x00 };
107 static uint8_t scsi_huawei_eject2[] =	{ 0x11, 0x06, 0x20, 0x00, 0x00, 0x01,
108 					  0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
109 					  0x00, 0x00, 0x00, 0x00 };
110 static uint8_t scsi_huawei_eject3[] =	{ 0x11, 0x06, 0x20, 0x00, 0x00, 0x01,
111 					  0x01, 0x00, 0x01, 0x00, 0x00, 0x00,
112 					  0x00, 0x00, 0x00, 0x00 };
113 static uint8_t scsi_huawei_eject4[] =	{ 0x11, 0x06, 0x30, 0x00, 0x00, 0x00,
114 					  0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
115 					  0x00, 0x00, 0x00, 0x00 };
116 static uint8_t scsi_tct_eject[] =	{ 0x06, 0xf5, 0x04, 0x02, 0x52, 0x70 };
117 static uint8_t scsi_sync_cache[] =	{ 0x35, 0x00, 0x00, 0x00, 0x00, 0x00,
118 					  0x00, 0x00, 0x00, 0x00 };
119 static uint8_t scsi_request_sense[] =	{ 0x03, 0x00, 0x00, 0x00, 0x12, 0x00,
120 					  0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
121 static uint8_t scsi_read_capacity[] =	{ 0x25, 0x00, 0x00, 0x00, 0x00, 0x00,
122 					  0x00, 0x00, 0x00, 0x00 };
123 static uint8_t scsi_prevent_removal[] =	{ 0x1e, 0, 0, 0, 1, 0 };
124 static uint8_t scsi_allow_removal[] =	{ 0x1e, 0, 0, 0, 0, 0 };
125 
126 #ifndef USB_MSCTEST_BULK_SIZE
127 #define	USB_MSCTEST_BULK_SIZE	64	/* dummy */
128 #endif
129 
130 #define	ERR_CSW_FAILED		-1
131 
132 /* Command Block Wrapper */
133 struct bbb_cbw {
134 	uDWord	dCBWSignature;
135 #define	CBWSIGNATURE	0x43425355
136 	uDWord	dCBWTag;
137 	uDWord	dCBWDataTransferLength;
138 	uByte	bCBWFlags;
139 #define	CBWFLAGS_OUT	0x00
140 #define	CBWFLAGS_IN	0x80
141 	uByte	bCBWLUN;
142 	uByte	bCDBLength;
143 #define	CBWCDBLENGTH	16
144 	uByte	CBWCDB[CBWCDBLENGTH];
145 } __packed;
146 
147 /* Command Status Wrapper */
148 struct bbb_csw {
149 	uDWord	dCSWSignature;
150 #define	CSWSIGNATURE	0x53425355
151 	uDWord	dCSWTag;
152 	uDWord	dCSWDataResidue;
153 	uByte	bCSWStatus;
154 #define	CSWSTATUS_GOOD	0x0
155 #define	CSWSTATUS_FAILED	0x1
156 #define	CSWSTATUS_PHASE	0x2
157 } __packed;
158 
159 struct bbb_transfer {
160 	struct mtx mtx;
161 	struct cv cv;
162 	struct bbb_cbw *cbw;
163 	struct bbb_csw *csw;
164 
165 	struct usb_xfer *xfer[ST_MAX];
166 
167 	uint8_t *data_ptr;
168 
169 	usb_size_t data_len;		/* bytes */
170 	usb_size_t data_rem;		/* bytes */
171 	usb_timeout_t data_timeout;	/* ms */
172 	usb_frlength_t actlen;		/* bytes */
173 	usb_frlength_t buffer_size;    	/* bytes */
174 
175 	uint8_t	cmd_len;		/* bytes */
176 	uint8_t	dir;
177 	uint8_t	lun;
178 	uint8_t	state;
179 	uint8_t	status_try;
180 	int	error;
181 
182 	uint8_t	*buffer;
183 };
184 
185 static usb_callback_t bbb_command_callback;
186 static usb_callback_t bbb_data_read_callback;
187 static usb_callback_t bbb_data_rd_cs_callback;
188 static usb_callback_t bbb_data_write_callback;
189 static usb_callback_t bbb_data_wr_cs_callback;
190 static usb_callback_t bbb_status_callback;
191 static usb_callback_t bbb_raw_write_callback;
192 
193 static void	bbb_done(struct bbb_transfer *, int);
194 static void	bbb_transfer_start(struct bbb_transfer *, uint8_t);
195 static void	bbb_data_clear_stall_callback(struct usb_xfer *, uint8_t,
196 		    uint8_t);
197 static int	bbb_command_start(struct bbb_transfer *, uint8_t, uint8_t,
198 		    void *, size_t, void *, size_t, usb_timeout_t);
199 static struct bbb_transfer *bbb_attach(struct usb_device *, uint8_t, uint8_t);
200 static void	bbb_detach(struct bbb_transfer *);
201 
202 static const struct usb_config bbb_config[ST_MAX] = {
203 	[ST_COMMAND] = {
204 		.type = UE_BULK,
205 		.endpoint = UE_ADDR_ANY,
206 		.direction = UE_DIR_OUT,
207 		.bufsize = sizeof(struct bbb_cbw),
208 		.callback = &bbb_command_callback,
209 		.timeout = 4 * USB_MS_HZ,	/* 4 seconds */
210 	},
211 
212 	[ST_DATA_RD] = {
213 		.type = UE_BULK,
214 		.endpoint = UE_ADDR_ANY,
215 		.direction = UE_DIR_IN,
216 		.bufsize = SCSI_MAX_LEN,
217 		.flags = {.proxy_buffer = 1,.short_xfer_ok = 1,},
218 		.callback = &bbb_data_read_callback,
219 		.timeout = 4 * USB_MS_HZ,	/* 4 seconds */
220 	},
221 
222 	[ST_DATA_RD_CS] = {
223 		.type = UE_CONTROL,
224 		.endpoint = 0x00,	/* Control pipe */
225 		.direction = UE_DIR_ANY,
226 		.bufsize = sizeof(struct usb_device_request),
227 		.callback = &bbb_data_rd_cs_callback,
228 		.timeout = 1 * USB_MS_HZ,	/* 1 second  */
229 	},
230 
231 	[ST_DATA_WR] = {
232 		.type = UE_BULK,
233 		.endpoint = UE_ADDR_ANY,
234 		.direction = UE_DIR_OUT,
235 		.bufsize = SCSI_MAX_LEN,
236 		.flags = {.ext_buffer = 1,.proxy_buffer = 1,},
237 		.callback = &bbb_data_write_callback,
238 		.timeout = 4 * USB_MS_HZ,	/* 4 seconds */
239 	},
240 
241 	[ST_DATA_WR_CS] = {
242 		.type = UE_CONTROL,
243 		.endpoint = 0x00,	/* Control pipe */
244 		.direction = UE_DIR_ANY,
245 		.bufsize = sizeof(struct usb_device_request),
246 		.callback = &bbb_data_wr_cs_callback,
247 		.timeout = 1 * USB_MS_HZ,	/* 1 second  */
248 	},
249 
250 	[ST_STATUS] = {
251 		.type = UE_BULK,
252 		.endpoint = UE_ADDR_ANY,
253 		.direction = UE_DIR_IN,
254 		.bufsize = sizeof(struct bbb_csw),
255 		.flags = {.short_xfer_ok = 1,},
256 		.callback = &bbb_status_callback,
257 		.timeout = 1 * USB_MS_HZ,	/* 1 second  */
258 	},
259 };
260 
261 static const struct usb_config bbb_raw_config[1] = {
262 	[0] = {
263 		.type = UE_BULK_INTR,
264 		.endpoint = UE_ADDR_ANY,
265 		.direction = UE_DIR_OUT,
266 		.bufsize = SCSI_MAX_LEN,
267 		.flags = {.ext_buffer = 1,.proxy_buffer = 1,},
268 		.callback = &bbb_raw_write_callback,
269 		.timeout = 1 * USB_MS_HZ,	/* 1 second */
270 	},
271 };
272 
273 static void
274 bbb_done(struct bbb_transfer *sc, int error)
275 {
276 	sc->error = error;
277 	sc->state = ST_COMMAND;
278 	sc->status_try = 1;
279 	cv_signal(&sc->cv);
280 }
281 
282 static void
283 bbb_transfer_start(struct bbb_transfer *sc, uint8_t xfer_index)
284 {
285 	sc->state = xfer_index;
286 	usbd_transfer_start(sc->xfer[xfer_index]);
287 }
288 
289 static void
290 bbb_data_clear_stall_callback(struct usb_xfer *xfer,
291     uint8_t next_xfer, uint8_t stall_xfer)
292 {
293 	struct bbb_transfer *sc = usbd_xfer_softc(xfer);
294 
295 	if (usbd_clear_stall_callback(xfer, sc->xfer[stall_xfer])) {
296 		switch (USB_GET_STATE(xfer)) {
297 		case USB_ST_SETUP:
298 		case USB_ST_TRANSFERRED:
299 			bbb_transfer_start(sc, next_xfer);
300 			break;
301 		default:
302 			bbb_done(sc, USB_ERR_STALLED);
303 			break;
304 		}
305 	}
306 }
307 
308 static void
309 bbb_command_callback(struct usb_xfer *xfer, usb_error_t error)
310 {
311 	struct bbb_transfer *sc = usbd_xfer_softc(xfer);
312 	uint32_t tag;
313 
314 	switch (USB_GET_STATE(xfer)) {
315 	case USB_ST_TRANSFERRED:
316 		bbb_transfer_start
317 		    (sc, ((sc->dir == DIR_IN) ? ST_DATA_RD :
318 		    (sc->dir == DIR_OUT) ? ST_DATA_WR :
319 		    ST_STATUS));
320 		break;
321 
322 	case USB_ST_SETUP:
323 		sc->status_try = 0;
324 		tag = UGETDW(sc->cbw->dCBWTag) + 1;
325 		USETDW(sc->cbw->dCBWSignature, CBWSIGNATURE);
326 		USETDW(sc->cbw->dCBWTag, tag);
327 		USETDW(sc->cbw->dCBWDataTransferLength, (uint32_t)sc->data_len);
328 		sc->cbw->bCBWFlags = ((sc->dir == DIR_IN) ? CBWFLAGS_IN : CBWFLAGS_OUT);
329 		sc->cbw->bCBWLUN = sc->lun;
330 		sc->cbw->bCDBLength = sc->cmd_len;
331 		if (sc->cbw->bCDBLength > sizeof(sc->cbw->CBWCDB)) {
332 			sc->cbw->bCDBLength = sizeof(sc->cbw->CBWCDB);
333 			DPRINTFN(0, "Truncating long command\n");
334 		}
335 		usbd_xfer_set_frame_len(xfer, 0,
336 		    sizeof(struct bbb_cbw));
337 		usbd_transfer_submit(xfer);
338 		break;
339 
340 	default:			/* Error */
341 		bbb_done(sc, error);
342 		break;
343 	}
344 }
345 
346 static void
347 bbb_data_read_callback(struct usb_xfer *xfer, usb_error_t error)
348 {
349 	struct bbb_transfer *sc = usbd_xfer_softc(xfer);
350 	usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
351 	int actlen, sumlen;
352 
353 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
354 
355 	switch (USB_GET_STATE(xfer)) {
356 	case USB_ST_TRANSFERRED:
357 		sc->data_rem -= actlen;
358 		sc->data_ptr += actlen;
359 		sc->actlen += actlen;
360 
361 		if (actlen < sumlen) {
362 			/* short transfer */
363 			sc->data_rem = 0;
364 		}
365 	case USB_ST_SETUP:
366 		DPRINTF("max_bulk=%d, data_rem=%d\n",
367 		    max_bulk, sc->data_rem);
368 
369 		if (sc->data_rem == 0) {
370 			bbb_transfer_start(sc, ST_STATUS);
371 			break;
372 		}
373 		if (max_bulk > sc->data_rem) {
374 			max_bulk = sc->data_rem;
375 		}
376 		usbd_xfer_set_timeout(xfer, sc->data_timeout);
377 		usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
378 		usbd_transfer_submit(xfer);
379 		break;
380 
381 	default:			/* Error */
382 		if (error == USB_ERR_CANCELLED) {
383 			bbb_done(sc, error);
384 		} else {
385 			bbb_transfer_start(sc, ST_DATA_RD_CS);
386 		}
387 		break;
388 	}
389 }
390 
391 static void
392 bbb_data_rd_cs_callback(struct usb_xfer *xfer, usb_error_t error)
393 {
394 	bbb_data_clear_stall_callback(xfer, ST_STATUS,
395 	    ST_DATA_RD);
396 }
397 
398 static void
399 bbb_data_write_callback(struct usb_xfer *xfer, usb_error_t error)
400 {
401 	struct bbb_transfer *sc = usbd_xfer_softc(xfer);
402 	usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
403 	int actlen, sumlen;
404 
405 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
406 
407 	switch (USB_GET_STATE(xfer)) {
408 	case USB_ST_TRANSFERRED:
409 		sc->data_rem -= actlen;
410 		sc->data_ptr += actlen;
411 		sc->actlen += actlen;
412 
413 		if (actlen < sumlen) {
414 			/* short transfer */
415 			sc->data_rem = 0;
416 		}
417 	case USB_ST_SETUP:
418 		DPRINTF("max_bulk=%d, data_rem=%d\n",
419 		    max_bulk, sc->data_rem);
420 
421 		if (sc->data_rem == 0) {
422 			bbb_transfer_start(sc, ST_STATUS);
423 			break;
424 		}
425 		if (max_bulk > sc->data_rem) {
426 			max_bulk = sc->data_rem;
427 		}
428 		usbd_xfer_set_timeout(xfer, sc->data_timeout);
429 		usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
430 		usbd_transfer_submit(xfer);
431 		break;
432 
433 	default:			/* Error */
434 		if (error == USB_ERR_CANCELLED) {
435 			bbb_done(sc, error);
436 		} else {
437 			bbb_transfer_start(sc, ST_DATA_WR_CS);
438 		}
439 		break;
440 	}
441 }
442 
443 static void
444 bbb_data_wr_cs_callback(struct usb_xfer *xfer, usb_error_t error)
445 {
446 	bbb_data_clear_stall_callback(xfer, ST_STATUS,
447 	    ST_DATA_WR);
448 }
449 
450 static void
451 bbb_status_callback(struct usb_xfer *xfer, usb_error_t error)
452 {
453 	struct bbb_transfer *sc = usbd_xfer_softc(xfer);
454 	int actlen;
455 	int sumlen;
456 
457 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
458 
459 	switch (USB_GET_STATE(xfer)) {
460 	case USB_ST_TRANSFERRED:
461 
462 		/* very simple status check */
463 
464 		if (actlen < (int)sizeof(struct bbb_csw)) {
465 			bbb_done(sc, USB_ERR_SHORT_XFER);
466 		} else if (sc->csw->bCSWStatus == CSWSTATUS_GOOD) {
467 			bbb_done(sc, 0);	/* success */
468 		} else {
469 			bbb_done(sc, ERR_CSW_FAILED);	/* error */
470 		}
471 		break;
472 
473 	case USB_ST_SETUP:
474 		usbd_xfer_set_frame_len(xfer, 0,
475 		    sizeof(struct bbb_csw));
476 		usbd_transfer_submit(xfer);
477 		break;
478 
479 	default:
480 		DPRINTF("Failed to read CSW: %s, try %d\n",
481 		    usbd_errstr(error), sc->status_try);
482 
483 		if (error == USB_ERR_CANCELLED || sc->status_try) {
484 			bbb_done(sc, error);
485 		} else {
486 			sc->status_try = 1;
487 			bbb_transfer_start(sc, ST_DATA_RD_CS);
488 		}
489 		break;
490 	}
491 }
492 
493 static void
494 bbb_raw_write_callback(struct usb_xfer *xfer, usb_error_t error)
495 {
496 	struct bbb_transfer *sc = usbd_xfer_softc(xfer);
497 	usb_frlength_t max_bulk = usbd_xfer_max_len(xfer);
498 	int actlen, sumlen;
499 
500 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
501 
502 	switch (USB_GET_STATE(xfer)) {
503 	case USB_ST_TRANSFERRED:
504 		sc->data_rem -= actlen;
505 		sc->data_ptr += actlen;
506 		sc->actlen += actlen;
507 
508 		if (actlen < sumlen) {
509 			/* short transfer */
510 			sc->data_rem = 0;
511 		}
512 	case USB_ST_SETUP:
513 		DPRINTF("max_bulk=%d, data_rem=%d\n",
514 		    max_bulk, sc->data_rem);
515 
516 		if (sc->data_rem == 0) {
517 			bbb_done(sc, 0);
518 			break;
519 		}
520 		if (max_bulk > sc->data_rem) {
521 			max_bulk = sc->data_rem;
522 		}
523 		usbd_xfer_set_timeout(xfer, sc->data_timeout);
524 		usbd_xfer_set_frame_data(xfer, 0, sc->data_ptr, max_bulk);
525 		usbd_transfer_submit(xfer);
526 		break;
527 
528 	default:			/* Error */
529 		bbb_done(sc, error);
530 		break;
531 	}
532 }
533 
534 /*------------------------------------------------------------------------*
535  *	bbb_command_start - execute a SCSI command synchronously
536  *
537  * Return values
538  * 0: Success
539  * Else: Failure
540  *------------------------------------------------------------------------*/
541 static int
542 bbb_command_start(struct bbb_transfer *sc, uint8_t dir, uint8_t lun,
543     void *data_ptr, size_t data_len, void *cmd_ptr, size_t cmd_len,
544     usb_timeout_t data_timeout)
545 {
546 	sc->lun = lun;
547 	sc->dir = data_len ? dir : DIR_NONE;
548 	sc->data_ptr = data_ptr;
549 	sc->data_len = data_len;
550 	sc->data_rem = data_len;
551 	sc->data_timeout = (data_timeout + USB_MS_HZ);
552 	sc->actlen = 0;
553 	sc->error = 0;
554 	sc->cmd_len = cmd_len;
555 	memset(&sc->cbw->CBWCDB, 0, sizeof(sc->cbw->CBWCDB));
556 	memcpy(&sc->cbw->CBWCDB, cmd_ptr, cmd_len);
557 	DPRINTFN(1, "SCSI cmd = %*D\n", (int)cmd_len, (char *)sc->cbw->CBWCDB, ":");
558 
559 	USB_MTX_LOCK(&sc->mtx);
560 	usbd_transfer_start(sc->xfer[sc->state]);
561 
562 	while (usbd_transfer_pending(sc->xfer[sc->state])) {
563 		cv_wait(&sc->cv, &sc->mtx);
564 	}
565 	USB_MTX_UNLOCK(&sc->mtx);
566 	return (sc->error);
567 }
568 
569 /*------------------------------------------------------------------------*
570  *	bbb_raw_write - write a raw BULK message synchronously
571  *
572  * Return values
573  * 0: Success
574  * Else: Failure
575  *------------------------------------------------------------------------*/
576 static int
577 bbb_raw_write(struct bbb_transfer *sc, const void *data_ptr, size_t data_len,
578     usb_timeout_t data_timeout)
579 {
580 	sc->data_ptr = __DECONST(void *, data_ptr);
581 	sc->data_len = data_len;
582 	sc->data_rem = data_len;
583 	sc->data_timeout = (data_timeout + USB_MS_HZ);
584 	sc->actlen = 0;
585 	sc->error = 0;
586 
587 	DPRINTFN(1, "BULK DATA = %*D\n", (int)data_len,
588 	    (const char *)data_ptr, ":");
589 
590 	USB_MTX_LOCK(&sc->mtx);
591 	usbd_transfer_start(sc->xfer[0]);
592 	while (usbd_transfer_pending(sc->xfer[0]))
593 		cv_wait(&sc->cv, &sc->mtx);
594 	USB_MTX_UNLOCK(&sc->mtx);
595 	return (sc->error);
596 }
597 
598 static struct bbb_transfer *
599 bbb_attach(struct usb_device *udev, uint8_t iface_index,
600     uint8_t bInterfaceClass)
601 {
602 	struct usb_interface *iface;
603 	struct usb_interface_descriptor *id;
604 	const struct usb_config *pconfig;
605 	struct bbb_transfer *sc;
606 	usb_error_t err;
607 	int nconfig;
608 
609 #if USB_HAVE_MSCTEST_DETACH
610 	uint8_t do_unlock;
611 
612 	/* Prevent re-enumeration */
613 	do_unlock = usbd_enum_lock(udev);
614 
615 	/*
616 	 * Make sure any driver which is hooked up to this interface,
617 	 * like umass is gone:
618 	 */
619 	usb_detach_device(udev, iface_index, 0);
620 
621 	if (do_unlock)
622 		usbd_enum_unlock(udev);
623 #endif
624 
625 	iface = usbd_get_iface(udev, iface_index);
626 	if (iface == NULL)
627 		return (NULL);
628 
629 	id = iface->idesc;
630 	if (id == NULL || id->bInterfaceClass != bInterfaceClass)
631 		return (NULL);
632 
633 	switch (id->bInterfaceClass) {
634 	case UICLASS_MASS:
635 		switch (id->bInterfaceSubClass) {
636 		case UISUBCLASS_SCSI:
637 		case UISUBCLASS_UFI:
638 		case UISUBCLASS_SFF8020I:
639 		case UISUBCLASS_SFF8070I:
640 			break;
641 		default:
642 			return (NULL);
643 		}
644 		switch (id->bInterfaceProtocol) {
645 		case UIPROTO_MASS_BBB_OLD:
646 		case UIPROTO_MASS_BBB:
647 			break;
648 		default:
649 			return (NULL);
650 		}
651 		pconfig = bbb_config;
652 		nconfig = ST_MAX;
653 		break;
654 	case UICLASS_HID:
655 		switch (id->bInterfaceSubClass) {
656 		case 0:
657 			break;
658 		default:
659 			return (NULL);
660 		}
661 		pconfig = bbb_raw_config;
662 		nconfig = 1;
663 		break;
664 	default:
665 		return (NULL);
666 	}
667 
668 	sc = malloc(sizeof(*sc), M_USB, M_WAITOK | M_ZERO);
669 	mtx_init(&sc->mtx, "USB autoinstall", NULL, MTX_DEF);
670 	cv_init(&sc->cv, "WBBB");
671 
672 	err = usbd_transfer_setup(udev, &iface_index, sc->xfer, pconfig,
673 	    nconfig, sc, &sc->mtx);
674 	if (err) {
675 		bbb_detach(sc);
676 		return (NULL);
677 	}
678 	switch (id->bInterfaceClass) {
679 	case UICLASS_MASS:
680 		/* store pointer to DMA buffers */
681 		sc->buffer = usbd_xfer_get_frame_buffer(
682 		    sc->xfer[ST_DATA_RD], 0);
683 		sc->buffer_size =
684 		    usbd_xfer_max_len(sc->xfer[ST_DATA_RD]);
685 		sc->cbw = usbd_xfer_get_frame_buffer(
686 		    sc->xfer[ST_COMMAND], 0);
687 		sc->csw = usbd_xfer_get_frame_buffer(
688 		    sc->xfer[ST_STATUS], 0);
689 		break;
690 	default:
691 		break;
692 	}
693 	return (sc);
694 }
695 
696 static void
697 bbb_detach(struct bbb_transfer *sc)
698 {
699 	usbd_transfer_unsetup(sc->xfer, ST_MAX);
700 	mtx_destroy(&sc->mtx);
701 	cv_destroy(&sc->cv);
702 	free(sc, M_USB);
703 }
704 
705 /*------------------------------------------------------------------------*
706  *	usb_iface_is_cdrom
707  *
708  * Return values:
709  * 1: This interface is an auto install disk (CD-ROM)
710  * 0: Not an auto install disk.
711  *------------------------------------------------------------------------*/
712 int
713 usb_iface_is_cdrom(struct usb_device *udev, uint8_t iface_index)
714 {
715 	struct bbb_transfer *sc;
716 	uint8_t timeout;
717 	uint8_t is_cdrom;
718 	uint8_t sid_type;
719 	int err;
720 
721 	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
722 	if (sc == NULL)
723 		return (0);
724 
725 	is_cdrom = 0;
726 	timeout = 4;	/* tries */
727 	while (--timeout) {
728 		err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
729 		    SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
730 		    USB_MS_HZ);
731 
732 		if (err == 0 && sc->actlen > 0) {
733 			sid_type = sc->buffer[0] & 0x1F;
734 			if (sid_type == 0x05)
735 				is_cdrom = 1;
736 			break;
737 		} else if (err != ERR_CSW_FAILED)
738 			break;	/* non retryable error */
739 		usb_pause_mtx(NULL, hz);
740 	}
741 	bbb_detach(sc);
742 	return (is_cdrom);
743 }
744 
745 static uint8_t
746 usb_msc_get_max_lun(struct usb_device *udev, uint8_t iface_index)
747 {
748 	struct usb_device_request req;
749 	usb_error_t err;
750 	uint8_t buf = 0;
751 
752 	/* The Get Max Lun command is a class-specific request. */
753 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
754 	req.bRequest = 0xFE;		/* GET_MAX_LUN */
755 	USETW(req.wValue, 0);
756 	req.wIndex[0] = iface_index;
757 	req.wIndex[1] = 0;
758 	USETW(req.wLength, 1);
759 
760 	err = usbd_do_request(udev, NULL, &req, &buf);
761 	if (err)
762 		buf = 0;
763 
764 	return (buf);
765 }
766 
767 #define	USB_ADD_QUIRK(udev, any, which) do { \
768 	if (usb_get_manufacturer(udev) != NULL && usb_get_product(udev) != NULL) { \
769 		DPRINTFN(0, #which " set for USB mass storage device %s %s (0x%04x:0x%04x)\n", \
770 			usb_get_manufacturer(udev), \
771 			usb_get_product(udev), \
772 			UGETW(udev->ddesc.idVendor), \
773 			UGETW(udev->ddesc.idProduct)); \
774 	} else { \
775 		DPRINTFN(0, #which " set for USB mass storage device, 0x%04x:0x%04x\n", \
776 			UGETW(udev->ddesc.idVendor), \
777 			UGETW(udev->ddesc.idProduct)); \
778 	} \
779 	usbd_add_dynamic_quirk(udev, which); \
780 	any = 1; \
781 } while (0)
782 
783 usb_error_t
784 usb_msc_auto_quirk(struct usb_device *udev, uint8_t iface_index,
785     const struct usb_attach_arg *uaa)
786 {
787 	struct bbb_transfer *sc;
788 	uint8_t timeout;
789 	uint8_t is_no_direct;
790 	uint8_t sid_type;
791 	uint8_t any_quirk;
792 	int err;
793 
794 	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
795 	if (sc == NULL)
796 		return (0);
797 
798 	any_quirk = 0;
799 
800 	/*
801 	 * Some devices need a delay after that the configuration
802 	 * value is set to function properly:
803 	 */
804 	usb_pause_mtx(NULL, hz);
805 
806 	if (usb_test_quirk(uaa, UQ_MSC_NO_GETMAXLUN) == 0 &&
807 	    usb_msc_get_max_lun(udev, iface_index) == 0) {
808 		DPRINTF("Device has only got one LUN.\n");
809 		USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_GETMAXLUN);
810 	}
811 
812 	is_no_direct = 1;
813 	for (timeout = 4; timeout != 0; timeout--) {
814 		err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
815 		    SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
816 		    USB_MS_HZ);
817 
818 		if (err == 0 && sc->actlen > 0) {
819 			sid_type = sc->buffer[0] & 0x1F;
820 			if (sid_type == 0x00)
821 				is_no_direct = 0;
822 			break;
823 		} else if (err != ERR_CSW_FAILED) {
824 			DPRINTF("Device is not responding "
825 			    "properly to SCSI INQUIRY command.\n");
826 			goto error;	/* non retryable error */
827 		}
828 		usb_pause_mtx(NULL, hz);
829 	}
830 
831 	if (is_no_direct) {
832 		DPRINTF("Device is not direct access.\n");
833 		goto done;
834 	}
835 
836 	if (usb_test_quirk(uaa, UQ_MSC_NO_TEST_UNIT_READY) == 0) {
837 		err = bbb_command_start(sc, DIR_NONE, 0, NULL, 0,
838 		    &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
839 		    USB_MS_HZ);
840 
841 		if (err != 0) {
842 			if (err != ERR_CSW_FAILED)
843 				goto error;
844 			USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_TEST_UNIT_READY);
845 		}
846 	}
847 
848 	if (usb_test_quirk(uaa, UQ_MSC_NO_PREVENT_ALLOW) == 0) {
849 		err = bbb_command_start(sc, DIR_NONE, 0, NULL, 0,
850 		    &scsi_prevent_removal, sizeof(scsi_prevent_removal),
851 		    USB_MS_HZ);
852 
853 		if (err == 0) {
854 			err = bbb_command_start(sc, DIR_NONE, 0, NULL, 0,
855 			    &scsi_allow_removal, sizeof(scsi_allow_removal),
856 			    USB_MS_HZ);
857 		}
858 
859 		if (err != 0) {
860 			if (err != ERR_CSW_FAILED)
861 				goto error;
862 			USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_PREVENT_ALLOW);
863 		}
864 	}
865 
866 	timeout = 1;
867 
868 retry_sync_cache:
869 	err = bbb_command_start(sc, DIR_NONE, 0, NULL, 0,
870 	    &scsi_sync_cache, sizeof(scsi_sync_cache),
871 	    USB_MS_HZ);
872 
873 	if (err != 0) {
874 		if (err != ERR_CSW_FAILED)
875 			goto error;
876 
877 		USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_SYNC_CACHE);
878 	} else {
879 		/*
880 		 * Certain Kingston memory sticks fail the first
881 		 * read capacity after a synchronize cache command
882 		 * has been issued. Disable the synchronize cache
883 		 * command for such devices.
884 		 */
885 
886 		err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
887 		    &scsi_read_capacity, sizeof(scsi_read_capacity),
888 		    USB_MS_HZ);
889 
890 		if (err != 0) {
891 			if (err != ERR_CSW_FAILED)
892 				goto error;
893 
894 			err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
895 			    &scsi_read_capacity, sizeof(scsi_read_capacity),
896 			    USB_MS_HZ);
897 
898 			if (err == 0) {
899 				if (timeout--)
900 					goto retry_sync_cache;
901 
902 				USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_SYNC_CACHE);
903 			} else {
904 				if (err != ERR_CSW_FAILED)
905 					goto error;
906 			}
907 		}
908 	}
909 
910 	if (usb_test_quirk(uaa, UQ_MSC_NO_START_STOP) == 0) {
911 		err = bbb_command_start(sc, DIR_NONE, 0, NULL, 0,
912 		    &scsi_start_unit, sizeof(scsi_start_unit),
913 		    USB_MS_HZ);
914 
915 		if (err != 0) {
916 			if (err != ERR_CSW_FAILED)
917 				goto error;
918 			USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_START_STOP);
919 		}
920 	}
921 
922 	/* clear sense status of any failed commands on the device */
923 
924 	err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
925 	    SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
926 	    USB_MS_HZ);
927 
928 	DPRINTF("Inquiry = %d\n", err);
929 
930 	if (err != 0) {
931 		if (err != ERR_CSW_FAILED)
932 			goto error;
933 	}
934 
935 	err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
936 	    SCSI_SENSE_LEN, &scsi_request_sense,
937 	    sizeof(scsi_request_sense), USB_MS_HZ);
938 
939 	DPRINTF("Request sense = %d\n", err);
940 
941 	if (err != 0) {
942 		if (err != ERR_CSW_FAILED)
943 			goto error;
944 	}
945 	goto done;
946 
947 error:
948 	/* Apply most quirks */
949 	USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_SYNC_CACHE);
950 	USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_PREVENT_ALLOW);
951 	USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_TEST_UNIT_READY);
952 	USB_ADD_QUIRK(udev, any_quirk, UQ_MSC_NO_START_STOP);
953 done:
954 	bbb_detach(sc);
955 
956 	if (any_quirk) {
957 		/* Unconfigure device, to clear software data toggle. */
958 		usbd_set_config_index(udev, USB_UNCONFIG_INDEX);
959 
960 		/* Need to re-enumerate the device to clear its state. */
961 		usbd_req_re_enumerate(udev, NULL);
962 		return (USB_ERR_STALLED);
963 	}
964 
965 	/* No quirks were added, continue as usual. */
966 	return (0);
967 }
968 
969 usb_error_t
970 usb_msc_eject(struct usb_device *udev, uint8_t iface_index, int method)
971 {
972 	struct bbb_transfer *sc;
973 	usb_error_t err __usbdebug_used;
974 
975 	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
976 	if (sc == NULL)
977 		return (USB_ERR_INVAL);
978 
979 	switch (method) {
980 	case MSC_EJECT_STOPUNIT:
981 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
982 		    &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
983 		    USB_MS_HZ);
984 		DPRINTF("Test unit ready status: %s\n", usbd_errstr(err));
985 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
986 		    &scsi_stop_unit, sizeof(scsi_stop_unit),
987 		    USB_MS_HZ);
988 		break;
989 	case MSC_EJECT_REZERO:
990 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
991 		    &scsi_rezero_init, sizeof(scsi_rezero_init),
992 		    USB_MS_HZ);
993 		break;
994 	case MSC_EJECT_ZTESTOR:
995 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
996 		    &scsi_ztestor_eject, sizeof(scsi_ztestor_eject),
997 		    USB_MS_HZ);
998 		break;
999 	case MSC_EJECT_CMOTECH:
1000 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
1001 		    &scsi_cmotech_eject, sizeof(scsi_cmotech_eject),
1002 		    USB_MS_HZ);
1003 		break;
1004 	case MSC_EJECT_HUAWEI:
1005 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
1006 		    &scsi_huawei_eject, sizeof(scsi_huawei_eject),
1007 		    USB_MS_HZ);
1008 		break;
1009 	case MSC_EJECT_HUAWEI2:
1010 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
1011 		    &scsi_huawei_eject2, sizeof(scsi_huawei_eject2),
1012 		    USB_MS_HZ);
1013 		break;
1014 	case MSC_EJECT_HUAWEI3:
1015 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
1016 		    &scsi_huawei_eject3, sizeof(scsi_huawei_eject3),
1017 		    USB_MS_HZ);
1018 		break;
1019 	case MSC_EJECT_HUAWEI4:
1020 		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
1021 		    &scsi_huawei_eject4, sizeof(scsi_huawei_eject4),
1022 		    USB_MS_HZ);
1023 		break;
1024 	case MSC_EJECT_TCT:
1025 		/*
1026 		 * TCTMobile needs DIR_IN flag. To get it, we
1027 		 * supply a dummy data with the command.
1028 		 */
1029 		err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
1030 		    sc->buffer_size, &scsi_tct_eject,
1031 		    sizeof(scsi_tct_eject), USB_MS_HZ);
1032 		break;
1033 	default:
1034 		DPRINTF("Unknown eject method (%d)\n", method);
1035 		bbb_detach(sc);
1036 		return (USB_ERR_INVAL);
1037 	}
1038 
1039 	DPRINTF("Eject CD command status: %s\n", usbd_errstr(err));
1040 
1041 	bbb_detach(sc);
1042 	return (0);
1043 }
1044 
1045 usb_error_t
1046 usb_dymo_eject(struct usb_device *udev, uint8_t iface_index)
1047 {
1048 	static const uint8_t data[3] = { 0x1b, 0x5a, 0x01 };
1049 	struct bbb_transfer *sc;
1050 	usb_error_t err;
1051 
1052 	sc = bbb_attach(udev, iface_index, UICLASS_HID);
1053 	if (sc == NULL)
1054 		return (USB_ERR_INVAL);
1055 	err = bbb_raw_write(sc, data, sizeof(data), USB_MS_HZ);
1056 	bbb_detach(sc);
1057 	return (err);
1058 }
1059 
1060 usb_error_t
1061 usb_msc_read_10(struct usb_device *udev, uint8_t iface_index,
1062     uint32_t lba, uint32_t blocks, void *buffer)
1063 {
1064 	struct bbb_transfer *sc;
1065 	uint8_t cmd[10];
1066 	usb_error_t err;
1067 
1068 	cmd[0] = 0x28;		/* READ_10 */
1069 	cmd[1] = 0;
1070 	cmd[2] = lba >> 24;
1071 	cmd[3] = lba >> 16;
1072 	cmd[4] = lba >> 8;
1073 	cmd[5] = lba >> 0;
1074 	cmd[6] = 0;
1075 	cmd[7] = blocks >> 8;
1076 	cmd[8] = blocks;
1077 	cmd[9] = 0;
1078 
1079 	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1080 	if (sc == NULL)
1081 		return (USB_ERR_INVAL);
1082 
1083 	err = bbb_command_start(sc, DIR_IN, 0, buffer,
1084 	    blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
1085 
1086 	bbb_detach(sc);
1087 
1088 	return (err);
1089 }
1090 
1091 usb_error_t
1092 usb_msc_write_10(struct usb_device *udev, uint8_t iface_index,
1093     uint32_t lba, uint32_t blocks, void *buffer)
1094 {
1095 	struct bbb_transfer *sc;
1096 	uint8_t cmd[10];
1097 	usb_error_t err;
1098 
1099 	cmd[0] = 0x2a;		/* WRITE_10 */
1100 	cmd[1] = 0;
1101 	cmd[2] = lba >> 24;
1102 	cmd[3] = lba >> 16;
1103 	cmd[4] = lba >> 8;
1104 	cmd[5] = lba >> 0;
1105 	cmd[6] = 0;
1106 	cmd[7] = blocks >> 8;
1107 	cmd[8] = blocks;
1108 	cmd[9] = 0;
1109 
1110 	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1111 	if (sc == NULL)
1112 		return (USB_ERR_INVAL);
1113 
1114 	err = bbb_command_start(sc, DIR_OUT, 0, buffer,
1115 	    blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
1116 
1117 	bbb_detach(sc);
1118 
1119 	return (err);
1120 }
1121 
1122 usb_error_t
1123 usb_msc_read_capacity(struct usb_device *udev, uint8_t iface_index,
1124     uint32_t *lba_last, uint32_t *block_size)
1125 {
1126 	struct bbb_transfer *sc;
1127 	usb_error_t err;
1128 
1129 	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1130 	if (sc == NULL)
1131 		return (USB_ERR_INVAL);
1132 
1133 	err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
1134 	    &scsi_read_capacity, sizeof(scsi_read_capacity),
1135 	    USB_MS_HZ);
1136 
1137 	*lba_last =
1138 	    (sc->buffer[0] << 24) |
1139 	    (sc->buffer[1] << 16) |
1140 	    (sc->buffer[2] << 8) |
1141 	    (sc->buffer[3]);
1142 
1143 	*block_size =
1144 	    (sc->buffer[4] << 24) |
1145 	    (sc->buffer[5] << 16) |
1146 	    (sc->buffer[6] << 8) |
1147 	    (sc->buffer[7]);
1148 
1149 	/* we currently only support one block size */
1150 	if (*block_size != SCSI_FIXED_BLOCK_SIZE)
1151 		err = USB_ERR_INVAL;
1152 
1153 	bbb_detach(sc);
1154 
1155 	return (err);
1156 }
1157