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