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