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