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