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