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