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