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