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