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
76enum {
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
86enum {
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
97static uint8_t scsi_test_unit_ready[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
98static uint8_t scsi_inquiry[] = { 0x12, 0x00, 0x00, 0x00, SCSI_INQ_LEN, 0x00 };
99static uint8_t scsi_rezero_init[] =     { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 };
100static uint8_t scsi_start_stop_unit[] = { 0x1b, 0x00, 0x00, 0x00, 0x02, 0x00 };
101static uint8_t scsi_ztestor_eject[] =   { 0x85, 0x01, 0x01, 0x01, 0x18, 0x01,
102					  0x01, 0x01, 0x01, 0x01, 0x00, 0x00 };
103static uint8_t scsi_cmotech_eject[] =   { 0xff, 0x52, 0x44, 0x45, 0x56, 0x43,
104					  0x48, 0x47 };
105static uint8_t scsi_huawei_eject[] =	{ 0x11, 0x06, 0x00, 0x00, 0x00, 0x00,
106					  0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
107					  0x00, 0x00, 0x00, 0x00 };
108static uint8_t scsi_huawei_eject2[] =	{ 0x11, 0x06, 0x20, 0x00, 0x00, 0x01,
109					  0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
110					  0x00, 0x00, 0x00, 0x00 };
111static uint8_t scsi_tct_eject[] =	{ 0x06, 0xf5, 0x04, 0x02, 0x52, 0x70 };
112static uint8_t scsi_sync_cache[] =	{ 0x35, 0x00, 0x00, 0x00, 0x00, 0x00,
113					  0x00, 0x00, 0x00, 0x00 };
114static uint8_t scsi_request_sense[] =	{ 0x03, 0x00, 0x00, 0x00, 0x12, 0x00,
115					  0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
116static uint8_t scsi_read_capacity[] =	{ 0x25, 0x00, 0x00, 0x00, 0x00, 0x00,
117					  0x00, 0x00, 0x00, 0x00 };
118static uint8_t scsi_prevent_removal[] =	{ 0x1e, 0, 0, 0, 1, 0 };
119static 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 */
128struct 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 */
143struct 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
154struct 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
180static usb_callback_t bbb_command_callback;
181static usb_callback_t bbb_data_read_callback;
182static usb_callback_t bbb_data_rd_cs_callback;
183static usb_callback_t bbb_data_write_callback;
184static usb_callback_t bbb_data_wr_cs_callback;
185static usb_callback_t bbb_status_callback;
186static usb_callback_t bbb_raw_write_callback;
187
188static void	bbb_done(struct bbb_transfer *, int);
189static void	bbb_transfer_start(struct bbb_transfer *, uint8_t);
190static void	bbb_data_clear_stall_callback(struct usb_xfer *, uint8_t,
191		    uint8_t);
192static int	bbb_command_start(struct bbb_transfer *, uint8_t, uint8_t,
193		    void *, size_t, void *, size_t, usb_timeout_t);
194static struct bbb_transfer *bbb_attach(struct usb_device *, uint8_t, uint8_t);
195static void	bbb_detach(struct bbb_transfer *);
196
197static const struct usb_config bbb_config[ST_MAX] = {
198	[ST_COMMAND] = {
199		.type = UE_BULK,
200		.endpoint = UE_ADDR_ANY,
201		.direction = UE_DIR_OUT,
202		.bufsize = sizeof(struct bbb_cbw),
203		.callback = &bbb_command_callback,
204		.timeout = 4 * USB_MS_HZ,	/* 4 seconds */
205	},
206
207	[ST_DATA_RD] = {
208		.type = UE_BULK,
209		.endpoint = UE_ADDR_ANY,
210		.direction = UE_DIR_IN,
211		.bufsize = SCSI_MAX_LEN,
212		.flags = {.proxy_buffer = 1,.short_xfer_ok = 1,},
213		.callback = &bbb_data_read_callback,
214		.timeout = 4 * USB_MS_HZ,	/* 4 seconds */
215	},
216
217	[ST_DATA_RD_CS] = {
218		.type = UE_CONTROL,
219		.endpoint = 0x00,	/* Control pipe */
220		.direction = UE_DIR_ANY,
221		.bufsize = sizeof(struct usb_device_request),
222		.callback = &bbb_data_rd_cs_callback,
223		.timeout = 1 * USB_MS_HZ,	/* 1 second  */
224	},
225
226	[ST_DATA_WR] = {
227		.type = UE_BULK,
228		.endpoint = UE_ADDR_ANY,
229		.direction = UE_DIR_OUT,
230		.bufsize = SCSI_MAX_LEN,
231		.flags = {.ext_buffer = 1,.proxy_buffer = 1,},
232		.callback = &bbb_data_write_callback,
233		.timeout = 4 * USB_MS_HZ,	/* 4 seconds */
234	},
235
236	[ST_DATA_WR_CS] = {
237		.type = UE_CONTROL,
238		.endpoint = 0x00,	/* Control pipe */
239		.direction = UE_DIR_ANY,
240		.bufsize = sizeof(struct usb_device_request),
241		.callback = &bbb_data_wr_cs_callback,
242		.timeout = 1 * USB_MS_HZ,	/* 1 second  */
243	},
244
245	[ST_STATUS] = {
246		.type = UE_BULK,
247		.endpoint = UE_ADDR_ANY,
248		.direction = UE_DIR_IN,
249		.bufsize = sizeof(struct bbb_csw),
250		.flags = {.short_xfer_ok = 1,},
251		.callback = &bbb_status_callback,
252		.timeout = 1 * USB_MS_HZ,	/* 1 second  */
253	},
254};
255
256static const struct usb_config bbb_raw_config[1] = {
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
268static void
269bbb_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
277static void
278bbb_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
284static void
285bbb_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
303static void
304bbb_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
341static void
342bbb_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
386static void
387bbb_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
393static void
394bbb_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
438static void
439bbb_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
445static void
446bbb_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
488static void
489bbb_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 *------------------------------------------------------------------------*/
536static int
537bbb_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	USB_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	USB_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 *------------------------------------------------------------------------*/
571static int
572bbb_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	USB_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	USB_MTX_UNLOCK(&sc->mtx);
590	return (sc->error);
591}
592
593static struct bbb_transfer *
594bbb_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
691static void
692bbb_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 *------------------------------------------------------------------------*/
707int
708usb_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
740static uint8_t
741usb_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	/* The Get Max Lun command is a class-specific request. */
748	req.bmRequestType = UT_READ_CLASS_INTERFACE;
749	req.bRequest = 0xFE;		/* GET_MAX_LUN */
750	USETW(req.wValue, 0);
751	req.wIndex[0] = iface_index;
752	req.wIndex[1] = 0;
753	USETW(req.wLength, 1);
754
755	err = usbd_do_request(udev, NULL, &req, &buf);
756	if (err)
757		buf = 0;
758
759	return (buf);
760}
761
762usb_error_t
763usb_msc_auto_quirk(struct usb_device *udev, uint8_t iface_index)
764{
765	struct bbb_transfer *sc;
766	uint8_t timeout;
767	uint8_t is_no_direct;
768	uint8_t sid_type;
769	int err;
770
771	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
772	if (sc == NULL)
773		return (0);
774
775	/*
776	 * Some devices need a delay after that the configuration
777	 * value is set to function properly:
778	 */
779	usb_pause_mtx(NULL, hz);
780
781	if (usb_msc_get_max_lun(udev, iface_index) == 0) {
782		DPRINTF("Device has only got one LUN.\n");
783		usbd_add_dynamic_quirk(udev, UQ_MSC_NO_GETMAXLUN);
784	}
785
786	is_no_direct = 1;
787	for (timeout = 4; timeout != 0; timeout--) {
788		err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
789		    SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
790		    USB_MS_HZ);
791
792		if (err == 0 && sc->actlen > 0) {
793			sid_type = sc->buffer[0] & 0x1F;
794			if (sid_type == 0x00)
795				is_no_direct = 0;
796			break;
797		} else if (err != ERR_CSW_FAILED) {
798			DPRINTF("Device is not responding "
799			    "properly to SCSI INQUIRY command.\n");
800			goto error;	/* non retryable error */
801		}
802		usb_pause_mtx(NULL, hz);
803	}
804
805	if (is_no_direct) {
806		DPRINTF("Device is not direct access.\n");
807		goto done;
808	}
809
810	err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
811	    &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
812	    USB_MS_HZ);
813
814	if (err != 0) {
815		if (err != ERR_CSW_FAILED)
816			goto error;
817		DPRINTF("Test unit ready failed\n");
818	}
819
820	err = bbb_command_start(sc, DIR_OUT, 0, NULL, 0,
821	    &scsi_prevent_removal, sizeof(scsi_prevent_removal),
822	    USB_MS_HZ);
823
824	if (err == 0) {
825		err = bbb_command_start(sc, DIR_OUT, 0, NULL, 0,
826		    &scsi_allow_removal, sizeof(scsi_allow_removal),
827		    USB_MS_HZ);
828	}
829
830	if (err != 0) {
831		if (err != ERR_CSW_FAILED)
832			goto error;
833		DPRINTF("Device doesn't handle prevent and allow removal\n");
834		usbd_add_dynamic_quirk(udev, UQ_MSC_NO_PREVENT_ALLOW);
835	}
836
837	timeout = 1;
838
839retry_sync_cache:
840	err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
841	    &scsi_sync_cache, sizeof(scsi_sync_cache),
842	    USB_MS_HZ);
843
844	if (err != 0) {
845		if (err != ERR_CSW_FAILED)
846			goto error;
847
848		DPRINTF("Device doesn't handle synchronize cache\n");
849
850		usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
851	} else {
852		/*
853		 * Certain Kingston memory sticks fail the first
854		 * read capacity after a synchronize cache command
855		 * has been issued. Disable the synchronize cache
856		 * command for such devices.
857		 */
858
859		err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
860		    &scsi_read_capacity, sizeof(scsi_read_capacity),
861		    USB_MS_HZ);
862
863		if (err != 0) {
864			if (err != ERR_CSW_FAILED)
865				goto error;
866
867			err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
868			    &scsi_read_capacity, sizeof(scsi_read_capacity),
869			    USB_MS_HZ);
870
871			if (err == 0) {
872				if (timeout--)
873					goto retry_sync_cache;
874
875				DPRINTF("Device most likely doesn't "
876				    "handle synchronize cache\n");
877
878				usbd_add_dynamic_quirk(udev,
879				    UQ_MSC_NO_SYNC_CACHE);
880			} else {
881				if (err != ERR_CSW_FAILED)
882					goto error;
883			}
884		}
885	}
886
887	/* clear sense status of any failed commands on the device */
888
889	err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
890	    SCSI_INQ_LEN, &scsi_inquiry, sizeof(scsi_inquiry),
891	    USB_MS_HZ);
892
893	DPRINTF("Inquiry = %d\n", err);
894
895	if (err != 0) {
896		if (err != ERR_CSW_FAILED)
897			goto error;
898	}
899
900	err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
901	    SCSI_SENSE_LEN, &scsi_request_sense,
902	    sizeof(scsi_request_sense), USB_MS_HZ);
903
904	DPRINTF("Request sense = %d\n", err);
905
906	if (err != 0) {
907		if (err != ERR_CSW_FAILED)
908			goto error;
909	}
910
911done:
912	bbb_detach(sc);
913	return (0);
914
915error:
916 	bbb_detach(sc);
917
918	DPRINTF("Device did not respond, enabling all quirks\n");
919
920	usbd_add_dynamic_quirk(udev, UQ_MSC_NO_SYNC_CACHE);
921	usbd_add_dynamic_quirk(udev, UQ_MSC_NO_PREVENT_ALLOW);
922	usbd_add_dynamic_quirk(udev, UQ_MSC_NO_TEST_UNIT_READY);
923
924	/* Need to re-enumerate the device */
925	usbd_req_re_enumerate(udev, NULL);
926
927	return (USB_ERR_STALLED);
928}
929
930usb_error_t
931usb_msc_eject(struct usb_device *udev, uint8_t iface_index, int method)
932{
933	struct bbb_transfer *sc;
934	usb_error_t err;
935
936	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
937	if (sc == NULL)
938		return (USB_ERR_INVAL);
939
940	switch (method) {
941	case MSC_EJECT_STOPUNIT:
942		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
943		    &scsi_test_unit_ready, sizeof(scsi_test_unit_ready),
944		    USB_MS_HZ);
945		DPRINTF("Test unit ready status: %s\n", usbd_errstr(err));
946		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
947		    &scsi_start_stop_unit, sizeof(scsi_start_stop_unit),
948		    USB_MS_HZ);
949		break;
950	case MSC_EJECT_REZERO:
951		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
952		    &scsi_rezero_init, sizeof(scsi_rezero_init),
953		    USB_MS_HZ);
954		break;
955	case MSC_EJECT_ZTESTOR:
956		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
957		    &scsi_ztestor_eject, sizeof(scsi_ztestor_eject),
958		    USB_MS_HZ);
959		break;
960	case MSC_EJECT_CMOTECH:
961		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
962		    &scsi_cmotech_eject, sizeof(scsi_cmotech_eject),
963		    USB_MS_HZ);
964		break;
965	case MSC_EJECT_HUAWEI:
966		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
967		    &scsi_huawei_eject, sizeof(scsi_huawei_eject),
968		    USB_MS_HZ);
969		break;
970	case MSC_EJECT_HUAWEI2:
971		err = bbb_command_start(sc, DIR_IN, 0, NULL, 0,
972		    &scsi_huawei_eject2, sizeof(scsi_huawei_eject2),
973		    USB_MS_HZ);
974		break;
975	case MSC_EJECT_TCT:
976		/*
977		 * TCTMobile needs DIR_IN flag. To get it, we
978		 * supply a dummy data with the command.
979		 */
980		err = bbb_command_start(sc, DIR_IN, 0, sc->buffer,
981		    sc->buffer_size, &scsi_tct_eject,
982		    sizeof(scsi_tct_eject), USB_MS_HZ);
983		break;
984	default:
985		DPRINTF("Unknown eject method (%d)\n", method);
986		bbb_detach(sc);
987		return (USB_ERR_INVAL);
988	}
989
990	DPRINTF("Eject CD command status: %s\n", usbd_errstr(err));
991
992	bbb_detach(sc);
993	return (0);
994}
995
996usb_error_t
997usb_dymo_eject(struct usb_device *udev, uint8_t iface_index)
998{
999	static const uint8_t data[3] = { 0x1b, 0x5a, 0x01 };
1000	struct bbb_transfer *sc;
1001	usb_error_t err;
1002
1003	sc = bbb_attach(udev, iface_index, UICLASS_HID);
1004	if (sc == NULL)
1005		return (USB_ERR_INVAL);
1006	err = bbb_raw_write(sc, data, sizeof(data), USB_MS_HZ);
1007	bbb_detach(sc);
1008	return (err);
1009}
1010
1011usb_error_t
1012usb_msc_read_10(struct usb_device *udev, uint8_t iface_index,
1013    uint32_t lba, uint32_t blocks, void *buffer)
1014{
1015	struct bbb_transfer *sc;
1016	uint8_t cmd[10];
1017	usb_error_t err;
1018
1019	cmd[0] = 0x28;		/* READ_10 */
1020	cmd[1] = 0;
1021	cmd[2] = lba >> 24;
1022	cmd[3] = lba >> 16;
1023	cmd[4] = lba >> 8;
1024	cmd[5] = lba >> 0;
1025	cmd[6] = 0;
1026	cmd[7] = blocks >> 8;
1027	cmd[8] = blocks;
1028	cmd[9] = 0;
1029
1030	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1031	if (sc == NULL)
1032		return (USB_ERR_INVAL);
1033
1034	err = bbb_command_start(sc, DIR_IN, 0, buffer,
1035	    blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
1036
1037	bbb_detach(sc);
1038
1039	return (err);
1040}
1041
1042usb_error_t
1043usb_msc_write_10(struct usb_device *udev, uint8_t iface_index,
1044    uint32_t lba, uint32_t blocks, void *buffer)
1045{
1046	struct bbb_transfer *sc;
1047	uint8_t cmd[10];
1048	usb_error_t err;
1049
1050	cmd[0] = 0x2a;		/* WRITE_10 */
1051	cmd[1] = 0;
1052	cmd[2] = lba >> 24;
1053	cmd[3] = lba >> 16;
1054	cmd[4] = lba >> 8;
1055	cmd[5] = lba >> 0;
1056	cmd[6] = 0;
1057	cmd[7] = blocks >> 8;
1058	cmd[8] = blocks;
1059	cmd[9] = 0;
1060
1061	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1062	if (sc == NULL)
1063		return (USB_ERR_INVAL);
1064
1065	err = bbb_command_start(sc, DIR_OUT, 0, buffer,
1066	    blocks * SCSI_FIXED_BLOCK_SIZE, cmd, 10, USB_MS_HZ);
1067
1068	bbb_detach(sc);
1069
1070	return (err);
1071}
1072
1073usb_error_t
1074usb_msc_read_capacity(struct usb_device *udev, uint8_t iface_index,
1075    uint32_t *lba_last, uint32_t *block_size)
1076{
1077	struct bbb_transfer *sc;
1078	usb_error_t err;
1079
1080	sc = bbb_attach(udev, iface_index, UICLASS_MASS);
1081	if (sc == NULL)
1082		return (USB_ERR_INVAL);
1083
1084	err = bbb_command_start(sc, DIR_IN, 0, sc->buffer, 8,
1085	    &scsi_read_capacity, sizeof(scsi_read_capacity),
1086	    USB_MS_HZ);
1087
1088	*lba_last =
1089	    (sc->buffer[0] << 24) |
1090	    (sc->buffer[1] << 16) |
1091	    (sc->buffer[2] << 8) |
1092	    (sc->buffer[3]);
1093
1094	*block_size =
1095	    (sc->buffer[4] << 24) |
1096	    (sc->buffer[5] << 16) |
1097	    (sc->buffer[6] << 8) |
1098	    (sc->buffer[7]);
1099
1100	/* we currently only support one block size */
1101	if (*block_size != SCSI_FIXED_BLOCK_SIZE)
1102		err = USB_ERR_INVAL;
1103
1104	bbb_detach(sc);
1105
1106	return (err);
1107}
1108