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