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