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