ustorage_fs.c revision 190173
1/* $FreeBSD: head/sys/dev/usb/storage/ustorage_fs.c 190173 2009-03-20 18:59:53Z thompsa $ */
2/*-
3 * Copyright (C) 2003-2005 Alan Stern
4 * Copyright (C) 2008 Hans Petter Selasky
5 * 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 *    without modification.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. The names of the above-listed copyright holders may not be used
17 *    to endorse or promote products derived from this software without
18 *    specific prior written permission.
19 *
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
22 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
23 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/*
35 * NOTE: Much of the SCSI statemachine handling code derives from the
36 * Linux USB gadget stack.
37 */
38#include "usbdevs.h"
39#include <dev/usb/usb.h>
40#include <dev/usb/usb_mfunc.h>
41#include <dev/usb/usb_error.h>
42#include <dev/usb/usb_defs.h>
43
44#define	USB_DEBUG_VAR ustorage_fs_debug
45
46#include <dev/usb/usb_core.h>
47#include <dev/usb/usb_util.h>
48#include <dev/usb/usb_busdma.h>
49#include <dev/usb/usb_debug.h>
50#include <dev/usb/usb_process.h>
51#include <dev/usb/usb_device.h>
52
53#if USB_DEBUG
54static int ustorage_fs_debug = 0;
55
56SYSCTL_NODE(_hw_usb2, OID_AUTO, ustorage_fs, CTLFLAG_RW, 0, "USB ustorage_fs");
57SYSCTL_INT(_hw_usb2_ustorage_fs, OID_AUTO, debug, CTLFLAG_RW,
58    &ustorage_fs_debug, 0, "ustorage_fs debug level");
59#endif
60
61/* Define some limits */
62
63#define	USTORAGE_FS_BULK_SIZE (1UL << 17)
64#define	USTORAGE_FS_MAX_LUN 8
65
66/*
67 * The SCSI ID string must be exactly 28 characters long
68 * exluding the terminating zero.
69 */
70#ifndef USTORAGE_FS_ID_STRING
71#define	USTORAGE_FS_ID_STRING \
72	"FreeBSD " /* 8 */ \
73	"File-Stor Gadget" /* 16 */ \
74	"0101" /* 4 */
75#endif
76
77/*
78 * The following macro defines the number of
79 * sectors to be allocated for the RAM disk:
80 */
81#ifndef USTORAGE_FS_RAM_SECT
82#define	USTORAGE_FS_RAM_SECT (1UL << 13)
83#endif
84
85static uint8_t *ustorage_fs_ramdisk;
86
87/* USB transfer definitions */
88
89#define	USTORAGE_FS_T_BBB_COMMAND     0
90#define	USTORAGE_FS_T_BBB_DATA_DUMP   1
91#define	USTORAGE_FS_T_BBB_DATA_READ   2
92#define	USTORAGE_FS_T_BBB_DATA_WRITE  3
93#define	USTORAGE_FS_T_BBB_STATUS      4
94#define	USTORAGE_FS_T_BBB_MAX         5
95
96/* USB data stage direction */
97
98#define	DIR_NONE	0
99#define	DIR_READ	1
100#define	DIR_WRITE	2
101
102/* USB interface specific control request */
103
104#define	UR_BBB_RESET		0xff	/* Bulk-Only reset */
105#define	UR_BBB_GET_MAX_LUN	0xfe	/* Get maximum lun */
106
107/* Command Block Wrapper */
108typedef struct {
109	uDWord	dCBWSignature;
110#define	CBWSIGNATURE	0x43425355
111	uDWord	dCBWTag;
112	uDWord	dCBWDataTransferLength;
113	uByte	bCBWFlags;
114#define	CBWFLAGS_OUT	0x00
115#define	CBWFLAGS_IN	0x80
116	uByte	bCBWLUN;
117	uByte	bCDBLength;
118#define	CBWCDBLENGTH	16
119	uByte	CBWCDB[CBWCDBLENGTH];
120} __packed ustorage_fs_bbb_cbw_t;
121
122#define	USTORAGE_FS_BBB_CBW_SIZE	31
123
124/* Command Status Wrapper */
125typedef struct {
126	uDWord	dCSWSignature;
127#define	CSWSIGNATURE	0x53425355
128	uDWord	dCSWTag;
129	uDWord	dCSWDataResidue;
130	uByte	bCSWStatus;
131#define	CSWSTATUS_GOOD	0x0
132#define	CSWSTATUS_FAILED	0x1
133#define	CSWSTATUS_PHASE	0x2
134} __packed ustorage_fs_bbb_csw_t;
135
136#define	USTORAGE_FS_BBB_CSW_SIZE	13
137
138struct ustorage_fs_lun {
139
140	void   *memory_image;
141
142	uint32_t num_sectors;
143	uint32_t sense_data;
144	uint32_t sense_data_info;
145	uint32_t unit_attention_data;
146
147	uint8_t	read_only:1;
148	uint8_t	prevent_medium_removal:1;
149	uint8_t	info_valid:1;
150	uint8_t	removable:1;
151};
152
153struct ustorage_fs_softc {
154
155	ustorage_fs_bbb_cbw_t sc_cbw;	/* Command Wrapper Block */
156	ustorage_fs_bbb_csw_t sc_csw;	/* Command Status Block */
157
158	struct mtx sc_mtx;
159
160	struct ustorage_fs_lun sc_lun[USTORAGE_FS_MAX_LUN];
161
162	struct {
163		uint8_t *data_ptr;
164		struct ustorage_fs_lun *currlun;
165
166		uint32_t data_rem;	/* bytes, as reported by the command
167					 * block wrapper */
168		uint32_t offset;	/* bytes */
169
170		uint8_t	cbw_dir;
171		uint8_t	cmd_dir;
172		uint8_t	lun;
173		uint8_t	cmd_data[CBWCDBLENGTH];
174		uint8_t	cmd_len;
175		uint8_t	data_short:1;
176		uint8_t	data_error:1;
177	}	sc_transfer;
178
179	device_t sc_dev;
180	struct usb2_device *sc_udev;
181	struct usb2_xfer *sc_xfer[USTORAGE_FS_T_BBB_MAX];
182
183	uint32_t sc_unit;
184
185	uint8_t	sc_name[16];
186	uint8_t	sc_iface_no;		/* interface number */
187	uint8_t	sc_last_lun;
188	uint8_t	sc_last_xfer_index;
189	uint8_t	sc_qdata[1024];
190};
191
192/* prototypes */
193
194static device_probe_t ustorage_fs_probe;
195static device_attach_t ustorage_fs_attach;
196static device_detach_t ustorage_fs_detach;
197static device_suspend_t ustorage_fs_suspend;
198static device_resume_t ustorage_fs_resume;
199static device_shutdown_t ustorage_fs_shutdown;
200static usb_handle_request_t ustorage_fs_handle_request;
201
202static usb2_callback_t ustorage_fs_t_bbb_command_callback;
203static usb2_callback_t ustorage_fs_t_bbb_data_dump_callback;
204static usb2_callback_t ustorage_fs_t_bbb_data_read_callback;
205static usb2_callback_t ustorage_fs_t_bbb_data_write_callback;
206static usb2_callback_t ustorage_fs_t_bbb_status_callback;
207
208static void ustorage_fs_transfer_start(struct ustorage_fs_softc *sc, uint8_t xfer_index);
209static void ustorage_fs_transfer_stop(struct ustorage_fs_softc *sc);
210
211static uint8_t ustorage_fs_verify(struct ustorage_fs_softc *sc);
212static uint8_t ustorage_fs_inquiry(struct ustorage_fs_softc *sc);
213static uint8_t ustorage_fs_request_sense(struct ustorage_fs_softc *sc);
214static uint8_t ustorage_fs_read_capacity(struct ustorage_fs_softc *sc);
215static uint8_t ustorage_fs_mode_sense(struct ustorage_fs_softc *sc);
216static uint8_t ustorage_fs_start_stop(struct ustorage_fs_softc *sc);
217static uint8_t ustorage_fs_prevent_allow(struct ustorage_fs_softc *sc);
218static uint8_t ustorage_fs_read_format_capacities(struct ustorage_fs_softc *sc);
219static uint8_t ustorage_fs_mode_select(struct ustorage_fs_softc *sc);
220static uint8_t ustorage_fs_min_len(struct ustorage_fs_softc *sc, uint32_t len, uint32_t mask);
221static uint8_t ustorage_fs_read(struct ustorage_fs_softc *sc);
222static uint8_t ustorage_fs_write(struct ustorage_fs_softc *sc);
223static uint8_t ustorage_fs_check_cmd(struct ustorage_fs_softc *sc, uint8_t cmd_size, uint16_t mask, uint8_t needs_medium);
224static uint8_t ustorage_fs_do_cmd(struct ustorage_fs_softc *sc);
225
226static device_method_t ustorage_fs_methods[] = {
227	/* USB interface */
228	DEVMETHOD(usb_handle_request, ustorage_fs_handle_request),
229
230	/* Device interface */
231	DEVMETHOD(device_probe, ustorage_fs_probe),
232	DEVMETHOD(device_attach, ustorage_fs_attach),
233	DEVMETHOD(device_detach, ustorage_fs_detach),
234	DEVMETHOD(device_suspend, ustorage_fs_suspend),
235	DEVMETHOD(device_resume, ustorage_fs_resume),
236	DEVMETHOD(device_shutdown, ustorage_fs_shutdown),
237
238	{0, 0}
239};
240
241static driver_t ustorage_fs_driver = {
242	.name = "ustorage_fs",
243	.methods = ustorage_fs_methods,
244	.size = sizeof(struct ustorage_fs_softc),
245};
246
247static devclass_t ustorage_fs_devclass;
248
249DRIVER_MODULE(ustorage_fs, uhub, ustorage_fs_driver, ustorage_fs_devclass, NULL, 0);
250MODULE_VERSION(ustorage_fs, 0);
251MODULE_DEPEND(ustorage_fs, usb, 1, 1, 1);
252
253struct usb2_config ustorage_fs_bbb_config[USTORAGE_FS_T_BBB_MAX] = {
254
255	[USTORAGE_FS_T_BBB_COMMAND] = {
256		.type = UE_BULK,
257		.endpoint = UE_ADDR_ANY,
258		.direction = UE_DIR_OUT,
259		.md.bufsize = sizeof(ustorage_fs_bbb_cbw_t),
260		.md.flags = {.ext_buffer = 1,},
261		.md.callback = &ustorage_fs_t_bbb_command_callback,
262	},
263
264	[USTORAGE_FS_T_BBB_DATA_DUMP] = {
265		.type = UE_BULK,
266		.endpoint = UE_ADDR_ANY,
267		.direction = UE_DIR_OUT,
268		.md.bufsize = 0,	/* use wMaxPacketSize */
269		.md.flags = {.proxy_buffer = 1,.short_xfer_ok = 1,},
270		.md.callback = &ustorage_fs_t_bbb_data_dump_callback,
271	},
272
273	[USTORAGE_FS_T_BBB_DATA_READ] = {
274		.type = UE_BULK,
275		.endpoint = UE_ADDR_ANY,
276		.direction = UE_DIR_OUT,
277		.md.bufsize = USTORAGE_FS_BULK_SIZE,
278		.md.flags = {.proxy_buffer = 1,.short_xfer_ok = 1,.ext_buffer = 1},
279		.md.callback = &ustorage_fs_t_bbb_data_read_callback,
280	},
281
282	[USTORAGE_FS_T_BBB_DATA_WRITE] = {
283		.type = UE_BULK,
284		.endpoint = UE_ADDR_ANY,
285		.direction = UE_DIR_IN,
286		.md.bufsize = USTORAGE_FS_BULK_SIZE,
287		.md.flags = {.proxy_buffer = 1,.short_xfer_ok = 1,.ext_buffer = 1},
288		.md.callback = &ustorage_fs_t_bbb_data_write_callback,
289	},
290
291	[USTORAGE_FS_T_BBB_STATUS] = {
292		.type = UE_BULK,
293		.endpoint = UE_ADDR_ANY,
294		.direction = UE_DIR_IN,
295		.md.bufsize = sizeof(ustorage_fs_bbb_csw_t),
296		.md.flags = {.short_xfer_ok = 1,.ext_buffer = 1,},
297		.md.callback = &ustorage_fs_t_bbb_status_callback,
298	},
299};
300
301/*
302 * USB device probe/attach/detach
303 */
304
305static int
306ustorage_fs_probe(device_t dev)
307{
308	struct usb2_attach_arg *uaa = device_get_ivars(dev);
309	struct usb2_interface_descriptor *id;
310
311	if (uaa->usb2_mode != USB_MODE_DEVICE) {
312		return (ENXIO);
313	}
314	if (uaa->use_generic == 0) {
315		/* give other drivers a try first */
316		return (ENXIO);
317	}
318	/* Check for a standards compliant device */
319	id = usb2_get_interface_descriptor(uaa->iface);
320	if ((id == NULL) ||
321	    (id->bInterfaceClass != UICLASS_MASS) ||
322	    (id->bInterfaceSubClass != UISUBCLASS_SCSI) ||
323	    (id->bInterfaceProtocol != UIPROTO_MASS_BBB)) {
324		return (ENXIO);
325	}
326	return (0);
327}
328
329static int
330ustorage_fs_attach(device_t dev)
331{
332	struct ustorage_fs_softc *sc = device_get_softc(dev);
333	struct usb2_attach_arg *uaa = device_get_ivars(dev);
334	struct usb2_interface_descriptor *id;
335	int err;
336
337	/*
338	 * NOTE: the softc struct is bzero-ed in device_set_driver.
339	 * We can safely call ustorage_fs_detach without specifically
340	 * initializing the struct.
341	 */
342
343	sc->sc_dev = dev;
344	sc->sc_udev = uaa->device;
345	sc->sc_unit = device_get_unit(dev);
346
347	if (sc->sc_unit == 0) {
348		if (ustorage_fs_ramdisk == NULL) {
349			/*
350			 * allocate a memory image for our ramdisk until
351			 * further
352			 */
353			ustorage_fs_ramdisk =
354			    malloc(USTORAGE_FS_RAM_SECT << 9, M_USB, M_ZERO | M_WAITOK);
355			if (ustorage_fs_ramdisk == NULL) {
356				return (ENOMEM);
357			}
358		}
359		sc->sc_lun[0].memory_image = ustorage_fs_ramdisk;
360		sc->sc_lun[0].num_sectors = USTORAGE_FS_RAM_SECT;
361		sc->sc_lun[0].removable = 1;
362	}
363	snprintf(sc->sc_name, sizeof(sc->sc_name),
364	    "%s", device_get_nameunit(dev));
365
366	device_set_usb2_desc(dev);
367
368	mtx_init(&sc->sc_mtx, "USTORAGE_FS lock",
369	    NULL, (MTX_DEF | MTX_RECURSE));
370
371	/* get interface index */
372
373	id = usb2_get_interface_descriptor(uaa->iface);
374	if (id == NULL) {
375		device_printf(dev, "failed to get "
376		    "interface number\n");
377		goto detach;
378	}
379	sc->sc_iface_no = id->bInterfaceNumber;
380
381	err = usb2_transfer_setup(uaa->device,
382	    &uaa->info.bIfaceIndex, sc->sc_xfer, ustorage_fs_bbb_config,
383	    USTORAGE_FS_T_BBB_MAX, sc, &sc->sc_mtx);
384	if (err) {
385		device_printf(dev, "could not setup required "
386		    "transfers, %s\n", usb2_errstr(err));
387		goto detach;
388	}
389	/* start Mass Storage State Machine */
390
391	mtx_lock(&sc->sc_mtx);
392	ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_COMMAND);
393	mtx_unlock(&sc->sc_mtx);
394
395	return (0);			/* success */
396
397detach:
398	ustorage_fs_detach(dev);
399	return (ENXIO);			/* failure */
400}
401
402static int
403ustorage_fs_detach(device_t dev)
404{
405	struct ustorage_fs_softc *sc = device_get_softc(dev);
406
407	/* teardown our statemachine */
408
409	usb2_transfer_unsetup(sc->sc_xfer, USTORAGE_FS_T_BBB_MAX);
410
411	mtx_destroy(&sc->sc_mtx);
412
413	return (0);			/* success */
414}
415
416static int
417ustorage_fs_suspend(device_t dev)
418{
419	device_printf(dev, "suspending\n");
420	return (0);			/* success */
421}
422
423static int
424ustorage_fs_resume(device_t dev)
425{
426	device_printf(dev, "resuming\n");
427	return (0);			/* success */
428}
429
430static int
431ustorage_fs_shutdown(device_t dev)
432{
433	return (0);			/* success */
434}
435
436/*
437 * Generic functions to handle transfers
438 */
439
440static void
441ustorage_fs_transfer_start(struct ustorage_fs_softc *sc, uint8_t xfer_index)
442{
443	if (sc->sc_xfer[xfer_index]) {
444		sc->sc_last_xfer_index = xfer_index;
445		usb2_transfer_start(sc->sc_xfer[xfer_index]);
446	}
447}
448
449static void
450ustorage_fs_transfer_stop(struct ustorage_fs_softc *sc)
451{
452	usb2_transfer_stop(sc->sc_xfer[sc->sc_last_xfer_index]);
453	mtx_unlock(&sc->sc_mtx);
454	usb2_transfer_drain(sc->sc_xfer[sc->sc_last_xfer_index]);
455	mtx_lock(&sc->sc_mtx);
456}
457
458static int
459ustorage_fs_handle_request(device_t dev,
460    const void *preq, void **pptr, uint16_t *plen,
461    uint16_t offset, uint8_t is_complete)
462{
463	struct ustorage_fs_softc *sc = device_get_softc(dev);
464	const struct usb2_device_request *req = preq;
465
466	if (!is_complete) {
467		if (req->bRequest == UR_BBB_RESET) {
468			*plen = 0;
469			mtx_lock(&sc->sc_mtx);
470			ustorage_fs_transfer_stop(sc);
471			sc->sc_transfer.data_error = 1;
472			ustorage_fs_transfer_start(sc,
473			    USTORAGE_FS_T_BBB_COMMAND);
474			mtx_unlock(&sc->sc_mtx);
475			return (0);
476		} else if (req->bRequest == UR_BBB_GET_MAX_LUN) {
477			if (offset == 0) {
478				*plen = 1;
479				*pptr = &sc->sc_last_lun;
480			} else {
481				*plen = 0;
482			}
483			return (0);
484		}
485	}
486	return (ENXIO);			/* use builtin handler */
487}
488
489static void
490ustorage_fs_t_bbb_command_callback(struct usb2_xfer *xfer)
491{
492	struct ustorage_fs_softc *sc = xfer->priv_sc;
493	uint32_t tag;
494	uint8_t error = 0;
495
496	DPRINTF("\n");
497
498	switch (USB_GET_STATE(xfer)) {
499	case USB_ST_TRANSFERRED:
500
501		tag = UGETDW(sc->sc_cbw.dCBWSignature);
502
503		if (tag != CBWSIGNATURE) {
504			/* do nothing */
505			DPRINTF("invalid signature 0x%08x\n", tag);
506			break;
507		}
508		tag = UGETDW(sc->sc_cbw.dCBWTag);
509
510		/* echo back tag */
511		USETDW(sc->sc_csw.dCSWTag, tag);
512
513		/* reset status */
514		sc->sc_csw.bCSWStatus = 0;
515
516		/* reset data offset, data length and data remainder */
517		sc->sc_transfer.offset = 0;
518		sc->sc_transfer.data_rem =
519		    UGETDW(sc->sc_cbw.dCBWDataTransferLength);
520
521		/* reset data flags */
522		sc->sc_transfer.data_short = 0;
523
524		/* extract LUN */
525		sc->sc_transfer.lun = sc->sc_cbw.bCBWLUN;
526
527		if (sc->sc_transfer.data_rem == 0) {
528			sc->sc_transfer.cbw_dir = DIR_NONE;
529		} else {
530			if (sc->sc_cbw.bCBWFlags & CBWFLAGS_IN) {
531				sc->sc_transfer.cbw_dir = DIR_WRITE;
532			} else {
533				sc->sc_transfer.cbw_dir = DIR_READ;
534			}
535		}
536
537		sc->sc_transfer.cmd_len = sc->sc_cbw.bCDBLength;
538		if ((sc->sc_transfer.cmd_len > sizeof(sc->sc_cbw.CBWCDB)) ||
539		    (sc->sc_transfer.cmd_len == 0)) {
540			/* just halt - this is invalid */
541			DPRINTF("invalid command length %d bytes\n",
542			    sc->sc_transfer.cmd_len);
543			break;
544		}
545		bcopy(sc->sc_cbw.CBWCDB, sc->sc_transfer.cmd_data,
546		    sc->sc_transfer.cmd_len);
547
548		bzero(sc->sc_cbw.CBWCDB + sc->sc_transfer.cmd_len,
549		    sizeof(sc->sc_cbw.CBWCDB) - sc->sc_transfer.cmd_len);
550
551		error = ustorage_fs_do_cmd(sc);
552		if (error) {
553			/* got an error */
554			DPRINTF("command failed\n");
555			break;
556		}
557		if ((sc->sc_transfer.data_rem > 0) &&
558		    (sc->sc_transfer.cbw_dir != sc->sc_transfer.cmd_dir)) {
559			/* contradicting data transfer direction */
560			error = 1;
561			DPRINTF("data direction mismatch\n");
562			break;
563		}
564		switch (sc->sc_transfer.cbw_dir) {
565		case DIR_READ:
566			ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_DATA_READ);
567			break;
568		case DIR_WRITE:
569			ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_DATA_WRITE);
570			break;
571		default:
572			ustorage_fs_transfer_start(sc,
573			    USTORAGE_FS_T_BBB_STATUS);
574			break;
575		}
576		break;
577
578	case USB_ST_SETUP:
579tr_setup:
580		if (sc->sc_transfer.data_error) {
581			sc->sc_transfer.data_error = 0;
582			xfer->flags.stall_pipe = 1;
583			DPRINTF("stall pipe\n");
584		} else {
585			xfer->flags.stall_pipe = 0;
586		}
587
588		xfer->frlengths[0] = sizeof(sc->sc_cbw);
589		usb2_set_frame_data(xfer, &sc->sc_cbw, 0);
590		usb2_start_hardware(xfer);
591		break;
592
593	default:			/* Error */
594		DPRINTF("error\n");
595		if (xfer->error == USB_ERR_CANCELLED) {
596			break;
597		}
598		/* If the pipe is already stalled, don't do another stall */
599		if (!xfer->pipe->is_stalled) {
600			sc->sc_transfer.data_error = 1;
601		}
602		/* try again */
603		goto tr_setup;
604	}
605	if (error) {
606		if (sc->sc_csw.bCSWStatus == 0) {
607			/* set some default error code */
608			sc->sc_csw.bCSWStatus = CSWSTATUS_FAILED;
609		}
610		if (sc->sc_transfer.cbw_dir == DIR_READ) {
611			/* dump all data */
612			ustorage_fs_transfer_start(sc,
613			    USTORAGE_FS_T_BBB_DATA_DUMP);
614			return;
615		}
616		if (sc->sc_transfer.cbw_dir == DIR_WRITE) {
617			/* need to stall before status */
618			sc->sc_transfer.data_error = 1;
619		}
620		ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_STATUS);
621	}
622}
623
624static void
625ustorage_fs_t_bbb_data_dump_callback(struct usb2_xfer *xfer)
626{
627	struct ustorage_fs_softc *sc = xfer->priv_sc;
628	uint32_t max_bulk = xfer->max_data_length;
629
630	DPRINTF("\n");
631
632	switch (USB_GET_STATE(xfer)) {
633	case USB_ST_TRANSFERRED:
634		sc->sc_transfer.data_rem -= xfer->actlen;
635		sc->sc_transfer.offset += xfer->actlen;
636
637		if ((xfer->actlen != xfer->sumlen) ||
638		    (sc->sc_transfer.data_rem == 0)) {
639			/* short transfer or end of data */
640			ustorage_fs_transfer_start(sc,
641			    USTORAGE_FS_T_BBB_STATUS);
642			break;
643		}
644		/* Fallthrough */
645
646	case USB_ST_SETUP:
647tr_setup:
648		if (max_bulk > sc->sc_transfer.data_rem) {
649			max_bulk = sc->sc_transfer.data_rem;
650		}
651		if (sc->sc_transfer.data_error) {
652			sc->sc_transfer.data_error = 0;
653			xfer->flags.stall_pipe = 1;
654		} else {
655			xfer->flags.stall_pipe = 0;
656		}
657		xfer->frlengths[0] = max_bulk;
658		usb2_start_hardware(xfer);
659		break;
660
661	default:			/* Error */
662		if (xfer->error == USB_ERR_CANCELLED) {
663			break;
664		}
665		/*
666		 * If the pipe is already stalled, don't do another stall:
667		 */
668		if (!xfer->pipe->is_stalled) {
669			sc->sc_transfer.data_error = 1;
670		}
671		/* try again */
672		goto tr_setup;
673	}
674}
675
676static void
677ustorage_fs_t_bbb_data_read_callback(struct usb2_xfer *xfer)
678{
679	struct ustorage_fs_softc *sc = xfer->priv_sc;
680	uint32_t max_bulk = xfer->max_data_length;
681
682	DPRINTF("\n");
683
684	switch (USB_GET_STATE(xfer)) {
685	case USB_ST_TRANSFERRED:
686		sc->sc_transfer.data_rem -= xfer->actlen;
687		sc->sc_transfer.data_ptr += xfer->actlen;
688		sc->sc_transfer.offset += xfer->actlen;
689
690		if ((xfer->actlen != xfer->sumlen) ||
691		    (sc->sc_transfer.data_rem == 0)) {
692			/* short transfer or end of data */
693			ustorage_fs_transfer_start(sc,
694			    USTORAGE_FS_T_BBB_STATUS);
695			break;
696		}
697		/* Fallthrough */
698
699	case USB_ST_SETUP:
700tr_setup:
701		if (max_bulk > sc->sc_transfer.data_rem) {
702			max_bulk = sc->sc_transfer.data_rem;
703		}
704		if (sc->sc_transfer.data_error) {
705			sc->sc_transfer.data_error = 0;
706			xfer->flags.stall_pipe = 1;
707		} else {
708			xfer->flags.stall_pipe = 0;
709		}
710
711		xfer->frlengths[0] = max_bulk;
712		usb2_set_frame_data(xfer, sc->sc_transfer.data_ptr, 0);
713		usb2_start_hardware(xfer);
714		break;
715
716	default:			/* Error */
717		if (xfer->error == USB_ERR_CANCELLED) {
718			break;
719		}
720		/* If the pipe is already stalled, don't do another stall */
721		if (!xfer->pipe->is_stalled) {
722			sc->sc_transfer.data_error = 1;
723		}
724		/* try again */
725		goto tr_setup;
726	}
727}
728
729static void
730ustorage_fs_t_bbb_data_write_callback(struct usb2_xfer *xfer)
731{
732	struct ustorage_fs_softc *sc = xfer->priv_sc;
733	uint32_t max_bulk = xfer->max_data_length;
734
735	DPRINTF("\n");
736
737	switch (USB_GET_STATE(xfer)) {
738	case USB_ST_TRANSFERRED:
739		sc->sc_transfer.data_rem -= xfer->actlen;
740		sc->sc_transfer.data_ptr += xfer->actlen;
741		sc->sc_transfer.offset += xfer->actlen;
742
743		if ((xfer->actlen != xfer->sumlen) ||
744		    (sc->sc_transfer.data_rem == 0)) {
745			/* short transfer or end of data */
746			ustorage_fs_transfer_start(sc,
747			    USTORAGE_FS_T_BBB_STATUS);
748			break;
749		}
750	case USB_ST_SETUP:
751tr_setup:
752		if (max_bulk >= sc->sc_transfer.data_rem) {
753			max_bulk = sc->sc_transfer.data_rem;
754			if (sc->sc_transfer.data_short) {
755				xfer->flags.force_short_xfer = 1;
756			} else {
757				xfer->flags.force_short_xfer = 0;
758			}
759		} else {
760			xfer->flags.force_short_xfer = 0;
761		}
762
763		if (sc->sc_transfer.data_error) {
764			sc->sc_transfer.data_error = 0;
765			xfer->flags.stall_pipe = 1;
766		} else {
767			xfer->flags.stall_pipe = 0;
768		}
769
770		xfer->frlengths[0] = max_bulk;
771		usb2_set_frame_data(xfer, sc->sc_transfer.data_ptr, 0);
772		usb2_start_hardware(xfer);
773		break;
774
775	default:			/* Error */
776		if (xfer->error == USB_ERR_CANCELLED) {
777			break;
778		}
779		/*
780		 * If the pipe is already stalled, don't do another
781		 * stall
782		 */
783		if (!xfer->pipe->is_stalled) {
784			sc->sc_transfer.data_error = 1;
785		}
786		/* try again */
787		goto tr_setup;
788	}
789}
790
791static void
792ustorage_fs_t_bbb_status_callback(struct usb2_xfer *xfer)
793{
794	struct ustorage_fs_softc *sc = xfer->priv_sc;
795
796	DPRINTF("\n");
797
798	switch (USB_GET_STATE(xfer)) {
799	case USB_ST_TRANSFERRED:
800		ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_COMMAND);
801		break;
802
803	case USB_ST_SETUP:
804tr_setup:
805		USETDW(sc->sc_csw.dCSWSignature, CSWSIGNATURE);
806		USETDW(sc->sc_csw.dCSWDataResidue, sc->sc_transfer.data_rem);
807
808		if (sc->sc_transfer.data_error) {
809			sc->sc_transfer.data_error = 0;
810			xfer->flags.stall_pipe = 1;
811		} else {
812			xfer->flags.stall_pipe = 0;
813		}
814
815		xfer->frlengths[0] = sizeof(sc->sc_csw);
816		usb2_set_frame_data(xfer, &sc->sc_csw, 0);
817		usb2_start_hardware(xfer);
818		break;
819
820	default:
821		if (xfer->error == USB_ERR_CANCELLED) {
822			break;
823		}
824		/* If the pipe is already stalled, don't do another stall */
825		if (!xfer->pipe->is_stalled) {
826			sc->sc_transfer.data_error = 1;
827		}
828		/* try again */
829		goto tr_setup;
830	}
831}
832
833/* SCSI commands that we recognize */
834#define	SC_FORMAT_UNIT			0x04
835#define	SC_INQUIRY			0x12
836#define	SC_MODE_SELECT_6		0x15
837#define	SC_MODE_SELECT_10		0x55
838#define	SC_MODE_SENSE_6			0x1a
839#define	SC_MODE_SENSE_10		0x5a
840#define	SC_PREVENT_ALLOW_MEDIUM_REMOVAL	0x1e
841#define	SC_READ_6			0x08
842#define	SC_READ_10			0x28
843#define	SC_READ_12			0xa8
844#define	SC_READ_CAPACITY		0x25
845#define	SC_READ_FORMAT_CAPACITIES	0x23
846#define	SC_RELEASE			0x17
847#define	SC_REQUEST_SENSE		0x03
848#define	SC_RESERVE			0x16
849#define	SC_SEND_DIAGNOSTIC		0x1d
850#define	SC_START_STOP_UNIT		0x1b
851#define	SC_SYNCHRONIZE_CACHE		0x35
852#define	SC_TEST_UNIT_READY		0x00
853#define	SC_VERIFY			0x2f
854#define	SC_WRITE_6			0x0a
855#define	SC_WRITE_10			0x2a
856#define	SC_WRITE_12			0xaa
857
858/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
859#define	SS_NO_SENSE				0
860#define	SS_COMMUNICATION_FAILURE		0x040800
861#define	SS_INVALID_COMMAND			0x052000
862#define	SS_INVALID_FIELD_IN_CDB			0x052400
863#define	SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE	0x052100
864#define	SS_LOGICAL_UNIT_NOT_SUPPORTED		0x052500
865#define	SS_MEDIUM_NOT_PRESENT			0x023a00
866#define	SS_MEDIUM_REMOVAL_PREVENTED		0x055302
867#define	SS_NOT_READY_TO_READY_TRANSITION	0x062800
868#define	SS_RESET_OCCURRED			0x062900
869#define	SS_SAVING_PARAMETERS_NOT_SUPPORTED	0x053900
870#define	SS_UNRECOVERED_READ_ERROR		0x031100
871#define	SS_WRITE_ERROR				0x030c02
872#define	SS_WRITE_PROTECTED			0x072700
873
874#define	SK(x)		((uint8_t) ((x) >> 16))	/* Sense Key byte, etc. */
875#define	ASC(x)		((uint8_t) ((x) >> 8))
876#define	ASCQ(x)		((uint8_t) (x))
877
878/* Routines for unaligned data access */
879
880static uint16_t
881get_be16(uint8_t *buf)
882{
883	return ((uint16_t)buf[0] << 8) | ((uint16_t)buf[1]);
884}
885
886static uint32_t
887get_be32(uint8_t *buf)
888{
889	return ((uint32_t)buf[0] << 24) | ((uint32_t)buf[1] << 16) |
890	((uint32_t)buf[2] << 8) | ((uint32_t)buf[3]);
891}
892
893static void
894put_be16(uint8_t *buf, uint16_t val)
895{
896	buf[0] = val >> 8;
897	buf[1] = val;
898}
899
900static void
901put_be32(uint8_t *buf, uint32_t val)
902{
903	buf[0] = val >> 24;
904	buf[1] = val >> 16;
905	buf[2] = val >> 8;
906	buf[3] = val & 0xff;
907}
908
909/*------------------------------------------------------------------------*
910 *	ustorage_fs_verify
911 *
912 * Returns:
913 *    0: Success
914 * Else: Failure
915 *------------------------------------------------------------------------*/
916static uint8_t
917ustorage_fs_verify(struct ustorage_fs_softc *sc)
918{
919	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
920	uint32_t lba;
921	uint32_t vlen;
922	uint64_t file_offset;
923	uint64_t amount_left;
924
925	/*
926	 * Get the starting Logical Block Address
927	 */
928	lba = get_be32(&sc->sc_transfer.cmd_data[2]);
929
930	/*
931	 * We allow DPO (Disable Page Out = don't save data in the cache)
932	 * but we don't implement it.
933	 */
934	if ((sc->sc_transfer.cmd_data[1] & ~0x10) != 0) {
935		currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
936		return (1);
937	}
938	vlen = get_be16(&sc->sc_transfer.cmd_data[7]);
939	if (vlen == 0) {
940		goto done;
941	}
942	/* No default reply */
943
944	/* Prepare to carry out the file verify */
945	amount_left = vlen;
946	amount_left <<= 9;
947	file_offset = lba;
948	file_offset <<= 9;
949
950	/* Range check */
951	vlen += lba;
952
953	if ((vlen < lba) ||
954	    (vlen > currlun->num_sectors) ||
955	    (lba >= currlun->num_sectors)) {
956		currlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
957		return (1);
958	}
959	/* XXX TODO: verify that data is readable */
960done:
961	return (ustorage_fs_min_len(sc, 0, 0 - 1));
962}
963
964/*------------------------------------------------------------------------*
965 *	ustorage_fs_inquiry
966 *
967 * Returns:
968 *    0: Success
969 * Else: Failure
970 *------------------------------------------------------------------------*/
971static uint8_t
972ustorage_fs_inquiry(struct ustorage_fs_softc *sc)
973{
974	uint8_t *buf = sc->sc_transfer.data_ptr;
975
976	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
977
978	if (!sc->sc_transfer.currlun) {
979		/* Unsupported LUNs are okay */
980		memset(buf, 0, 36);
981		buf[0] = 0x7f;
982		/* Unsupported, no device - type */
983		return (ustorage_fs_min_len(sc, 36, 0 - 1));
984	}
985	memset(buf, 0, 8);
986	/* Non - removable, direct - access device */
987	if (currlun->removable)
988		buf[1] = 0x80;
989	buf[2] = 2;
990	/* ANSI SCSI level 2 */
991	buf[3] = 2;
992	/* SCSI - 2 INQUIRY data format */
993	buf[4] = 31;
994	/* Additional length */
995	/* No special options */
996	/* Copy in ID string */
997	memcpy(buf + 8, USTORAGE_FS_ID_STRING, 28);
998
999	return (ustorage_fs_min_len(sc, 36, 0 - 1));
1000}
1001
1002/*------------------------------------------------------------------------*
1003 *	ustorage_fs_request_sense
1004 *
1005 * Returns:
1006 *    0: Success
1007 * Else: Failure
1008 *------------------------------------------------------------------------*/
1009static uint8_t
1010ustorage_fs_request_sense(struct ustorage_fs_softc *sc)
1011{
1012	uint8_t *buf = sc->sc_transfer.data_ptr;
1013	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1014	uint32_t sd;
1015	uint32_t sdinfo;
1016	uint8_t valid;
1017
1018	/*
1019	 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1020	 *
1021	 * If a REQUEST SENSE command is received from an initiator
1022	 * with a pending unit attention condition (before the target
1023	 * generates the contingent allegiance condition), then the
1024	 * target shall either:
1025	 *   a) report any pending sense data and preserve the unit
1026	 *	attention condition on the logical unit, or,
1027	 *   b) report the unit attention condition, may discard any
1028	 *	pending sense data, and clear the unit attention
1029	 *	condition on the logical unit for that initiator.
1030	 *
1031	 * FSG normally uses option a); enable this code to use option b).
1032	 */
1033#if 0
1034	if (currlun && currlun->unit_attention_data != SS_NO_SENSE) {
1035		currlun->sense_data = currlun->unit_attention_data;
1036		currlun->unit_attention_data = SS_NO_SENSE;
1037	}
1038#endif
1039
1040	if (!currlun) {
1041		/* Unsupported LUNs are okay */
1042		sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1043		sdinfo = 0;
1044		valid = 0;
1045	} else {
1046		sd = currlun->sense_data;
1047		sdinfo = currlun->sense_data_info;
1048		valid = currlun->info_valid << 7;
1049		currlun->sense_data = SS_NO_SENSE;
1050		currlun->sense_data_info = 0;
1051		currlun->info_valid = 0;
1052	}
1053
1054	memset(buf, 0, 18);
1055	buf[0] = valid | 0x70;
1056	/* Valid, current error */
1057	buf[2] = SK(sd);
1058	put_be32(&buf[3], sdinfo);
1059	/* Sense information */
1060	buf[7] = 18 - 8;
1061	/* Additional sense length */
1062	buf[12] = ASC(sd);
1063	buf[13] = ASCQ(sd);
1064	return (ustorage_fs_min_len(sc, 18, 0 - 1));
1065}
1066
1067
1068/*------------------------------------------------------------------------*
1069 *	ustorage_fs_read_capacity
1070 *
1071 * Returns:
1072 *    0: Success
1073 * Else: Failure
1074 *------------------------------------------------------------------------*/
1075static uint8_t
1076ustorage_fs_read_capacity(struct ustorage_fs_softc *sc)
1077{
1078	uint8_t *buf = sc->sc_transfer.data_ptr;
1079	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1080	uint32_t lba = get_be32(&sc->sc_transfer.cmd_data[2]);
1081	uint8_t pmi = sc->sc_transfer.cmd_data[8];
1082
1083	/* Check the PMI and LBA fields */
1084	if ((pmi > 1) || ((pmi == 0) && (lba != 0))) {
1085		currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1086		return (1);
1087	}
1088	put_be32(&buf[0], currlun->num_sectors - 1);
1089	/* Max logical block */
1090	put_be32(&buf[4], 512);
1091	/* Block length */
1092	return (ustorage_fs_min_len(sc, 8, 0 - 1));
1093}
1094
1095
1096/*------------------------------------------------------------------------*
1097 *	ustorage_fs_mode_sense
1098 *
1099 * Returns:
1100 *    0: Success
1101 * Else: Failure
1102 *------------------------------------------------------------------------*/
1103static uint8_t
1104ustorage_fs_mode_sense(struct ustorage_fs_softc *sc)
1105{
1106	uint8_t *buf = sc->sc_transfer.data_ptr;
1107	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1108	uint8_t *buf0;
1109	uint16_t len;
1110	uint16_t limit;
1111	uint8_t mscmnd = sc->sc_transfer.cmd_data[0];
1112	uint8_t pc;
1113	uint8_t page_code;
1114	uint8_t changeable_values;
1115	uint8_t all_pages;
1116
1117	buf0 = buf;
1118
1119	if ((sc->sc_transfer.cmd_data[1] & ~0x08) != 0) {
1120		/* Mask away DBD */
1121		currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1122		return (1);
1123	}
1124	pc = sc->sc_transfer.cmd_data[2] >> 6;
1125	page_code = sc->sc_transfer.cmd_data[2] & 0x3f;
1126	if (pc == 3) {
1127		currlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1128		return (1);
1129	}
1130	changeable_values = (pc == 1);
1131	all_pages = (page_code == 0x3f);
1132
1133	/*
1134	 * Write the mode parameter header.  Fixed values are: default
1135	 * medium type, no cache control (DPOFUA), and no block descriptors.
1136	 * The only variable value is the WriteProtect bit.  We will fill in
1137	 * the mode data length later.
1138	 */
1139	memset(buf, 0, 8);
1140	if (mscmnd == SC_MODE_SENSE_6) {
1141		buf[2] = (currlun->read_only ? 0x80 : 0x00);
1142		/* WP, DPOFUA */
1143		buf += 4;
1144		limit = 255;
1145	} else {
1146		/* SC_MODE_SENSE_10 */
1147		buf[3] = (currlun->read_only ? 0x80 : 0x00);
1148		/* WP, DPOFUA */
1149		buf += 8;
1150		limit = 65535;
1151		/* Should really be mod_data.buflen */
1152	}
1153
1154	/* No block descriptors */
1155
1156	/*
1157	 * The mode pages, in numerical order.
1158	 */
1159	if ((page_code == 0x08) || all_pages) {
1160		buf[0] = 0x08;
1161		/* Page code */
1162		buf[1] = 10;
1163		/* Page length */
1164		memset(buf + 2, 0, 10);
1165		/* None of the fields are changeable */
1166
1167		if (!changeable_values) {
1168			buf[2] = 0x04;
1169			/* Write cache enable, */
1170			/* Read cache not disabled */
1171			/* No cache retention priorities */
1172			put_be16(&buf[4], 0xffff);
1173			/* Don 't disable prefetch */
1174			/* Minimum prefetch = 0 */
1175			put_be16(&buf[8], 0xffff);
1176			/* Maximum prefetch */
1177			put_be16(&buf[10], 0xffff);
1178			/* Maximum prefetch ceiling */
1179		}
1180		buf += 12;
1181	}
1182	/*
1183	 * Check that a valid page was requested and the mode data length
1184	 * isn't too long.
1185	 */
1186	len = buf - buf0;
1187	if (len > limit) {
1188		currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1189		return (1);
1190	}
1191	/* Store the mode data length */
1192	if (mscmnd == SC_MODE_SENSE_6)
1193		buf0[0] = len - 1;
1194	else
1195		put_be16(buf0, len - 2);
1196	return (ustorage_fs_min_len(sc, len, 0 - 1));
1197}
1198
1199/*------------------------------------------------------------------------*
1200 *	ustorage_fs_start_stop
1201 *
1202 * Returns:
1203 *    0: Success
1204 * Else: Failure
1205 *------------------------------------------------------------------------*/
1206static uint8_t
1207ustorage_fs_start_stop(struct ustorage_fs_softc *sc)
1208{
1209	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1210	uint8_t loej;
1211	uint8_t start;
1212	uint8_t immed;
1213
1214	if (!currlun->removable) {
1215		currlun->sense_data = SS_INVALID_COMMAND;
1216		return (1);
1217	}
1218	immed = sc->sc_transfer.cmd_data[1] & 0x01;
1219	loej = sc->sc_transfer.cmd_data[4] & 0x02;
1220	start = sc->sc_transfer.cmd_data[4] & 0x01;
1221
1222	if (immed || loej || start) {
1223		/* compile fix */
1224	}
1225	return (0);
1226}
1227
1228/*------------------------------------------------------------------------*
1229 *	ustorage_fs_prevent_allow
1230 *
1231 * Returns:
1232 *    0: Success
1233 * Else: Failure
1234 *------------------------------------------------------------------------*/
1235static uint8_t
1236ustorage_fs_prevent_allow(struct ustorage_fs_softc *sc)
1237{
1238	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1239	uint8_t prevent;
1240
1241	if (!currlun->removable) {
1242		currlun->sense_data = SS_INVALID_COMMAND;
1243		return (1);
1244	}
1245	prevent = sc->sc_transfer.cmd_data[4] & 0x01;
1246	if ((sc->sc_transfer.cmd_data[4] & ~0x01) != 0) {
1247		/* Mask away Prevent */
1248		currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1249		return (1);
1250	}
1251	if (currlun->prevent_medium_removal && !prevent) {
1252		//fsync_sub(currlun);
1253	}
1254	currlun->prevent_medium_removal = prevent;
1255	return (0);
1256}
1257
1258/*------------------------------------------------------------------------*
1259 *	ustorage_fs_read_format_capacities
1260 *
1261 * Returns:
1262 *    0: Success
1263 * Else: Failure
1264 *------------------------------------------------------------------------*/
1265static uint8_t
1266ustorage_fs_read_format_capacities(struct ustorage_fs_softc *sc)
1267{
1268	uint8_t *buf = sc->sc_transfer.data_ptr;
1269	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1270
1271	buf[0] = buf[1] = buf[2] = 0;
1272	buf[3] = 8;
1273	/* Only the Current / Maximum Capacity Descriptor */
1274	buf += 4;
1275
1276	put_be32(&buf[0], currlun->num_sectors);
1277	/* Number of blocks */
1278	put_be32(&buf[4], 512);
1279	/* Block length */
1280	buf[4] = 0x02;
1281	/* Current capacity */
1282	return (ustorage_fs_min_len(sc, 12, 0 - 1));
1283}
1284
1285/*------------------------------------------------------------------------*
1286 *	ustorage_fs_mode_select
1287 *
1288 * Return values:
1289 *    0: Success
1290 * Else: Failure
1291 *------------------------------------------------------------------------*/
1292static uint8_t
1293ustorage_fs_mode_select(struct ustorage_fs_softc *sc)
1294{
1295	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1296
1297	/* We don't support MODE SELECT */
1298	currlun->sense_data = SS_INVALID_COMMAND;
1299	return (1);
1300}
1301
1302/*------------------------------------------------------------------------*
1303 *	ustorage_fs_synchronize_cache
1304 *
1305 * Return values:
1306 *    0: Success
1307 * Else: Failure
1308 *------------------------------------------------------------------------*/
1309static uint8_t
1310ustorage_fs_synchronize_cache(struct ustorage_fs_softc *sc)
1311{
1312#if 0
1313	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1314	uint8_t rc;
1315
1316	/*
1317	 * We ignore the requested LBA and write out all dirty data buffers.
1318	 */
1319	rc = 0;
1320	if (rc) {
1321		currlun->sense_data = SS_WRITE_ERROR;
1322	}
1323#endif
1324	return (0);
1325}
1326
1327/*------------------------------------------------------------------------*
1328 *	ustorage_fs_read - read data from disk
1329 *
1330 * Return values:
1331 *    0: Success
1332 * Else: Failure
1333 *------------------------------------------------------------------------*/
1334static uint8_t
1335ustorage_fs_read(struct ustorage_fs_softc *sc)
1336{
1337	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1338	uint64_t file_offset;
1339	uint32_t lba;
1340	uint32_t len;
1341
1342	/*
1343	 * Get the starting Logical Block Address and check that it's not
1344	 * too big
1345	 */
1346	if (sc->sc_transfer.cmd_data[0] == SC_READ_6) {
1347		lba = (((uint32_t)sc->sc_transfer.cmd_data[1]) << 16) |
1348		    get_be16(&sc->sc_transfer.cmd_data[2]);
1349	} else {
1350		lba = get_be32(&sc->sc_transfer.cmd_data[2]);
1351
1352		/*
1353		 * We allow DPO (Disable Page Out = don't save data in the
1354		 * cache) and FUA (Force Unit Access = don't read from the
1355		 * cache), but we don't implement them.
1356		 */
1357		if ((sc->sc_transfer.cmd_data[1] & ~0x18) != 0) {
1358			currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1359			return (1);
1360		}
1361	}
1362	len = sc->sc_transfer.data_rem >> 9;
1363	len += lba;
1364
1365	if ((len < lba) ||
1366	    (len > currlun->num_sectors) ||
1367	    (lba >= currlun->num_sectors)) {
1368		currlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1369		return (1);
1370	}
1371	file_offset = lba;
1372	file_offset <<= 9;
1373
1374	sc->sc_transfer.data_ptr =
1375	    USB_ADD_BYTES(currlun->memory_image, (uint32_t)file_offset);
1376
1377	return (0);
1378}
1379
1380/*------------------------------------------------------------------------*
1381 *	ustorage_fs_write - write data to disk
1382 *
1383 * Return values:
1384 *    0: Success
1385 * Else: Failure
1386 *------------------------------------------------------------------------*/
1387static uint8_t
1388ustorage_fs_write(struct ustorage_fs_softc *sc)
1389{
1390	struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun;
1391	uint64_t file_offset;
1392	uint32_t lba;
1393	uint32_t len;
1394
1395	if (currlun->read_only) {
1396		currlun->sense_data = SS_WRITE_PROTECTED;
1397		return (1);
1398	}
1399	/* XXX clear SYNC */
1400
1401	/*
1402	 * Get the starting Logical Block Address and check that it's not
1403	 * too big.
1404	 */
1405	if (sc->sc_transfer.cmd_data[0] == SC_WRITE_6)
1406		lba = (((uint32_t)sc->sc_transfer.cmd_data[1]) << 16) |
1407		    get_be16(&sc->sc_transfer.cmd_data[2]);
1408	else {
1409		lba = get_be32(&sc->sc_transfer.cmd_data[2]);
1410
1411		/*
1412		 * We allow DPO (Disable Page Out = don't save data in the
1413		 * cache) and FUA (Force Unit Access = write directly to the
1414		 * medium).  We don't implement DPO; we implement FUA by
1415		 * performing synchronous output.
1416		 */
1417		if ((sc->sc_transfer.cmd_data[1] & ~0x18) != 0) {
1418			currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1419			return (1);
1420		}
1421		if (sc->sc_transfer.cmd_data[1] & 0x08) {
1422			/* FUA */
1423			/* XXX set SYNC flag here */
1424		}
1425	}
1426
1427	len = sc->sc_transfer.data_rem >> 9;
1428	len += lba;
1429
1430	if ((len < lba) ||
1431	    (len > currlun->num_sectors) ||
1432	    (lba >= currlun->num_sectors)) {
1433		currlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1434		return (1);
1435	}
1436	file_offset = lba;
1437	file_offset <<= 9;
1438
1439	sc->sc_transfer.data_ptr =
1440	    USB_ADD_BYTES(currlun->memory_image, (uint32_t)file_offset);
1441
1442	return (0);
1443}
1444
1445/*------------------------------------------------------------------------*
1446 *	ustorage_fs_min_len
1447 *
1448 * Return values:
1449 *    0: Success
1450 * Else: Failure
1451 *------------------------------------------------------------------------*/
1452static uint8_t
1453ustorage_fs_min_len(struct ustorage_fs_softc *sc, uint32_t len, uint32_t mask)
1454{
1455	if (len != sc->sc_transfer.data_rem) {
1456
1457		if (sc->sc_transfer.cbw_dir == DIR_READ) {
1458			/*
1459			 * there must be something wrong about this SCSI
1460			 * command
1461			 */
1462			sc->sc_csw.bCSWStatus = CSWSTATUS_PHASE;
1463			return (1);
1464		}
1465		/* compute the minimum length */
1466
1467		if (sc->sc_transfer.data_rem > len) {
1468			/* data ends prematurely */
1469			sc->sc_transfer.data_rem = len;
1470			sc->sc_transfer.data_short = 1;
1471		}
1472		/* check length alignment */
1473
1474		if (sc->sc_transfer.data_rem & ~mask) {
1475			/* data ends prematurely */
1476			sc->sc_transfer.data_rem &= mask;
1477			sc->sc_transfer.data_short = 1;
1478		}
1479	}
1480	return (0);
1481}
1482
1483/*------------------------------------------------------------------------*
1484 *	ustorage_fs_check_cmd - check command routine
1485 *
1486 * Check whether the command is properly formed and whether its data
1487 * size and direction agree with the values we already have.
1488 *
1489 * Return values:
1490 *    0: Success
1491 * Else: Failure
1492 *------------------------------------------------------------------------*/
1493static uint8_t
1494ustorage_fs_check_cmd(struct ustorage_fs_softc *sc, uint8_t min_cmd_size,
1495    uint16_t mask, uint8_t needs_medium)
1496{
1497	struct ustorage_fs_lun *currlun;
1498	uint8_t lun = (sc->sc_transfer.cmd_data[1] >> 5);
1499	uint8_t i;
1500
1501	/* Verify the length of the command itself */
1502	if (min_cmd_size > sc->sc_transfer.cmd_len) {
1503		DPRINTF("%u > %u\n",
1504		    min_cmd_size, sc->sc_transfer.cmd_len);
1505		sc->sc_csw.bCSWStatus = CSWSTATUS_PHASE;
1506		return (1);
1507	}
1508	/* Mask away the LUN */
1509	sc->sc_transfer.cmd_data[1] &= 0x1f;
1510
1511	/* Check if LUN is correct */
1512	if (lun != sc->sc_transfer.lun) {
1513
1514	}
1515	/* Check the LUN */
1516	if (sc->sc_transfer.lun <= sc->sc_last_lun) {
1517		sc->sc_transfer.currlun = currlun =
1518		    sc->sc_lun + sc->sc_transfer.lun;
1519		if (sc->sc_transfer.cmd_data[0] != SC_REQUEST_SENSE) {
1520			currlun->sense_data = SS_NO_SENSE;
1521			currlun->sense_data_info = 0;
1522			currlun->info_valid = 0;
1523		}
1524		/*
1525		 * If a unit attention condition exists, only INQUIRY
1526		 * and REQUEST SENSE commands are allowed. Anything
1527		 * else must fail!
1528		 */
1529		if ((currlun->unit_attention_data != SS_NO_SENSE) &&
1530		    (sc->sc_transfer.cmd_data[0] != SC_INQUIRY) &&
1531		    (sc->sc_transfer.cmd_data[0] != SC_REQUEST_SENSE)) {
1532			currlun->sense_data = currlun->unit_attention_data;
1533			currlun->unit_attention_data = SS_NO_SENSE;
1534			return (1);
1535		}
1536	} else {
1537		sc->sc_transfer.currlun = currlun = NULL;
1538
1539		/*
1540		 * INQUIRY and REQUEST SENSE commands are explicitly allowed
1541		 * to use unsupported LUNs; all others may not.
1542		 */
1543		if ((sc->sc_transfer.cmd_data[0] != SC_INQUIRY) &&
1544		    (sc->sc_transfer.cmd_data[0] != SC_REQUEST_SENSE)) {
1545			return (1);
1546		}
1547	}
1548
1549	/*
1550	 * Check that only command bytes listed in the mask are
1551	 * non-zero.
1552	 */
1553	for (i = 0; i != min_cmd_size; i++) {
1554		if (sc->sc_transfer.cmd_data[i] && !(mask & (1UL << i))) {
1555			if (currlun) {
1556				currlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1557			}
1558			return (1);
1559		}
1560	}
1561
1562	/*
1563	 * If the medium isn't mounted and the command needs to access
1564	 * it, return an error.
1565	 */
1566	if (currlun && (!currlun->memory_image) && needs_medium) {
1567		currlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1568		return (1);
1569	}
1570	return (0);
1571}
1572
1573/*------------------------------------------------------------------------*
1574 *	ustorage_fs_do_cmd - do command
1575 *
1576 * Return values:
1577 *    0: Success
1578 * Else: Failure
1579 *------------------------------------------------------------------------*/
1580static uint8_t
1581ustorage_fs_do_cmd(struct ustorage_fs_softc *sc)
1582{
1583	uint8_t error = 1;
1584	uint8_t i;
1585	uint32_t temp;
1586
1587	/* set default data transfer pointer */
1588	sc->sc_transfer.data_ptr = sc->sc_qdata;
1589
1590	DPRINTF("cmd_data[0]=0x%02x, data_rem=0x%08x\n",
1591	    sc->sc_transfer.cmd_data[0], sc->sc_transfer.data_rem);
1592
1593	switch (sc->sc_transfer.cmd_data[0]) {
1594	case SC_INQUIRY:
1595		sc->sc_transfer.cmd_dir = DIR_WRITE;
1596		error = ustorage_fs_min_len(sc, sc->sc_transfer.cmd_data[4], 0 - 1);
1597		if (error) {
1598			break;
1599		}
1600		error = ustorage_fs_check_cmd(sc, 6,
1601		    (1UL << 4) | 1, 0);
1602		if (error) {
1603			break;
1604		}
1605		error = ustorage_fs_inquiry(sc);
1606
1607		break;
1608
1609	case SC_MODE_SELECT_6:
1610		sc->sc_transfer.cmd_dir = DIR_READ;
1611		error = ustorage_fs_min_len(sc, sc->sc_transfer.cmd_data[4], 0 - 1);
1612		if (error) {
1613			break;
1614		}
1615		error = ustorage_fs_check_cmd(sc, 6,
1616		    (1UL << 1) | (1UL << 4) | 1, 0);
1617		if (error) {
1618			break;
1619		}
1620		error = ustorage_fs_mode_select(sc);
1621
1622		break;
1623
1624	case SC_MODE_SELECT_10:
1625		sc->sc_transfer.cmd_dir = DIR_READ;
1626		error = ustorage_fs_min_len(sc,
1627		    get_be16(&sc->sc_transfer.cmd_data[7]), 0 - 1);
1628		if (error) {
1629			break;
1630		}
1631		error = ustorage_fs_check_cmd(sc, 10,
1632		    (1UL << 1) | (3UL << 7) | 1, 0);
1633		if (error) {
1634			break;
1635		}
1636		error = ustorage_fs_mode_select(sc);
1637
1638		break;
1639
1640	case SC_MODE_SENSE_6:
1641		sc->sc_transfer.cmd_dir = DIR_WRITE;
1642		error = ustorage_fs_min_len(sc, sc->sc_transfer.cmd_data[4], 0 - 1);
1643		if (error) {
1644			break;
1645		}
1646		error = ustorage_fs_check_cmd(sc, 6,
1647		    (1UL << 1) | (1UL << 2) | (1UL << 4) | 1, 0);
1648		if (error) {
1649			break;
1650		}
1651		error = ustorage_fs_mode_sense(sc);
1652
1653		break;
1654
1655	case SC_MODE_SENSE_10:
1656		sc->sc_transfer.cmd_dir = DIR_WRITE;
1657		error = ustorage_fs_min_len(sc,
1658		    get_be16(&sc->sc_transfer.cmd_data[7]), 0 - 1);
1659		if (error) {
1660			break;
1661		}
1662		error = ustorage_fs_check_cmd(sc, 10,
1663		    (1UL << 1) | (1UL << 2) | (3UL << 7) | 1, 0);
1664		if (error) {
1665			break;
1666		}
1667		error = ustorage_fs_mode_sense(sc);
1668
1669		break;
1670
1671	case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1672		error = ustorage_fs_min_len(sc, 0, 0 - 1);
1673		if (error) {
1674			break;
1675		}
1676		error = ustorage_fs_check_cmd(sc, 6,
1677		    (1UL << 4) | 1, 0);
1678		if (error) {
1679			break;
1680		}
1681		error = ustorage_fs_prevent_allow(sc);
1682
1683		break;
1684
1685	case SC_READ_6:
1686		i = sc->sc_transfer.cmd_data[4];
1687		sc->sc_transfer.cmd_dir = DIR_WRITE;
1688		temp = ((i == 0) ? 256UL : i);
1689		error = ustorage_fs_min_len(sc, temp << 9, 0 - (1UL << 9));
1690		if (error) {
1691			break;
1692		}
1693		error = ustorage_fs_check_cmd(sc, 6,
1694		    (7UL << 1) | (1UL << 4) | 1, 1);
1695		if (error) {
1696			break;
1697		}
1698		error = ustorage_fs_read(sc);
1699
1700		break;
1701
1702	case SC_READ_10:
1703		sc->sc_transfer.cmd_dir = DIR_WRITE;
1704		temp = get_be16(&sc->sc_transfer.cmd_data[7]);
1705		error = ustorage_fs_min_len(sc, temp << 9, 0 - (1UL << 9));
1706		if (error) {
1707			break;
1708		}
1709		error = ustorage_fs_check_cmd(sc, 10,
1710		    (1UL << 1) | (0xfUL << 2) | (3UL << 7) | 1, 1);
1711		if (error) {
1712			break;
1713		}
1714		error = ustorage_fs_read(sc);
1715
1716		break;
1717
1718	case SC_READ_12:
1719		sc->sc_transfer.cmd_dir = DIR_WRITE;
1720		temp = get_be32(&sc->sc_transfer.cmd_data[6]);
1721		if (temp >= (1UL << (32 - 9))) {
1722			/* numerical overflow */
1723			sc->sc_csw.bCSWStatus = CSWSTATUS_FAILED;
1724			error = 1;
1725			break;
1726		}
1727		error = ustorage_fs_min_len(sc, temp << 9, 0 - (1UL << 9));
1728		if (error) {
1729			break;
1730		}
1731		error = ustorage_fs_check_cmd(sc, 12,
1732		    (1UL << 1) | (0xfUL << 2) | (0xfUL << 6) | 1, 1);
1733		if (error) {
1734			break;
1735		}
1736		error = ustorage_fs_read(sc);
1737
1738		break;
1739
1740	case SC_READ_CAPACITY:
1741		sc->sc_transfer.cmd_dir = DIR_WRITE;
1742		error = ustorage_fs_check_cmd(sc, 10,
1743		    (0xfUL << 2) | (1UL << 8) | 1, 1);
1744		if (error) {
1745			break;
1746		}
1747		error = ustorage_fs_read_capacity(sc);
1748
1749		break;
1750
1751	case SC_READ_FORMAT_CAPACITIES:
1752		sc->sc_transfer.cmd_dir = DIR_WRITE;
1753		error = ustorage_fs_min_len(sc,
1754		    get_be16(&sc->sc_transfer.cmd_data[7]), 0 - 1);
1755		if (error) {
1756			break;
1757		}
1758		error = ustorage_fs_check_cmd(sc, 10,
1759		    (3UL << 7) | 1, 1);
1760		if (error) {
1761			break;
1762		}
1763		error = ustorage_fs_read_format_capacities(sc);
1764
1765		break;
1766
1767	case SC_REQUEST_SENSE:
1768		sc->sc_transfer.cmd_dir = DIR_WRITE;
1769		error = ustorage_fs_min_len(sc, sc->sc_transfer.cmd_data[4], 0 - 1);
1770		if (error) {
1771			break;
1772		}
1773		error = ustorage_fs_check_cmd(sc, 6,
1774		    (1UL << 4) | 1, 0);
1775		if (error) {
1776			break;
1777		}
1778		error = ustorage_fs_request_sense(sc);
1779
1780		break;
1781
1782	case SC_START_STOP_UNIT:
1783		error = ustorage_fs_min_len(sc, 0, 0 - 1);
1784		if (error) {
1785			break;
1786		}
1787		error = ustorage_fs_check_cmd(sc, 6,
1788		    (1UL << 1) | (1UL << 4) | 1, 0);
1789		if (error) {
1790			break;
1791		}
1792		error = ustorage_fs_start_stop(sc);
1793
1794		break;
1795
1796	case SC_SYNCHRONIZE_CACHE:
1797		error = ustorage_fs_min_len(sc, 0, 0 - 1);
1798		if (error) {
1799			break;
1800		}
1801		error = ustorage_fs_check_cmd(sc, 10,
1802		    (0xfUL << 2) | (3UL << 7) | 1, 1);
1803		if (error) {
1804			break;
1805		}
1806		error = ustorage_fs_synchronize_cache(sc);
1807
1808		break;
1809
1810	case SC_TEST_UNIT_READY:
1811		error = ustorage_fs_min_len(sc, 0, 0 - 1);
1812		if (error) {
1813			break;
1814		}
1815		error = ustorage_fs_check_cmd(sc, 6,
1816		    0 | 1, 1);
1817		break;
1818
1819		/*
1820		 * Although optional, this command is used by MS-Windows.
1821		 * We support a minimal version: BytChk must be 0.
1822		 */
1823	case SC_VERIFY:
1824		error = ustorage_fs_min_len(sc, 0, 0 - 1);
1825		if (error) {
1826			break;
1827		}
1828		error = ustorage_fs_check_cmd(sc, 10,
1829		    (1UL << 1) | (0xfUL << 2) | (3UL << 7) | 1, 1);
1830		if (error) {
1831			break;
1832		}
1833		error = ustorage_fs_verify(sc);
1834
1835		break;
1836
1837	case SC_WRITE_6:
1838		i = sc->sc_transfer.cmd_data[4];
1839		sc->sc_transfer.cmd_dir = DIR_READ;
1840		temp = ((i == 0) ? 256UL : i);
1841		error = ustorage_fs_min_len(sc, temp << 9, 0 - (1UL << 9));
1842		if (error) {
1843			break;
1844		}
1845		error = ustorage_fs_check_cmd(sc, 6,
1846		    (7UL << 1) | (1UL << 4) | 1, 1);
1847		if (error) {
1848			break;
1849		}
1850		error = ustorage_fs_write(sc);
1851
1852		break;
1853
1854	case SC_WRITE_10:
1855		sc->sc_transfer.cmd_dir = DIR_READ;
1856		temp = get_be16(&sc->sc_transfer.cmd_data[7]);
1857		error = ustorage_fs_min_len(sc, temp << 9, 0 - (1UL << 9));
1858		if (error) {
1859			break;
1860		}
1861		error = ustorage_fs_check_cmd(sc, 10,
1862		    (1UL << 1) | (0xfUL << 2) | (3UL << 7) | 1, 1);
1863		if (error) {
1864			break;
1865		}
1866		error = ustorage_fs_write(sc);
1867
1868		break;
1869
1870	case SC_WRITE_12:
1871		sc->sc_transfer.cmd_dir = DIR_READ;
1872		temp = get_be32(&sc->sc_transfer.cmd_data[6]);
1873		if (temp >= (1UL << (32 - 9))) {
1874			/* numerical overflow */
1875			sc->sc_csw.bCSWStatus = CSWSTATUS_FAILED;
1876			error = 1;
1877			break;
1878		}
1879		error = ustorage_fs_min_len(sc, temp << 9, 0 - (1UL << 9));
1880		if (error) {
1881			break;
1882		}
1883		error = ustorage_fs_check_cmd(sc, 12,
1884		    (1UL << 1) | (0xfUL << 2) | (0xfUL << 6) | 1, 1);
1885		if (error) {
1886			break;
1887		}
1888		error = ustorage_fs_write(sc);
1889
1890		break;
1891
1892		/*
1893		 * Some mandatory commands that we recognize but don't
1894		 * implement.  They don't mean much in this setting.
1895		 * It's left as an exercise for anyone interested to
1896		 * implement RESERVE and RELEASE in terms of Posix
1897		 * locks.
1898		 */
1899	case SC_FORMAT_UNIT:
1900	case SC_RELEASE:
1901	case SC_RESERVE:
1902	case SC_SEND_DIAGNOSTIC:
1903		/* Fallthrough */
1904
1905	default:
1906		error = ustorage_fs_min_len(sc, 0, 0 - 1);
1907		if (error) {
1908			break;
1909		}
1910		error = ustorage_fs_check_cmd(sc, sc->sc_transfer.cmd_len,
1911		    0xff, 0);
1912		if (error) {
1913			break;
1914		}
1915		sc->sc_transfer.currlun->sense_data =
1916		    SS_INVALID_COMMAND;
1917		error = 1;
1918
1919		break;
1920	}
1921	return (error);
1922}
1923