storage_common.c 24.7 KB
Newer Older
1 2 3 4 5 6
/*
 * storage_common.c -- Common definitions for mass storage functionality
 *
 * Copyright (C) 2003-2008 Alan Stern
 * Copyeight (C) 2009 Samsung Electronics
 * Author: Michal Nazarewicz (m.nazarewicz@samsung.com)
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */


/*
 * This file requires the following identifiers used in USB strings to
 * be defined (each of type pointer to char):
 *  - fsg_string_manufacturer -- name of the manufacturer
 *  - fsg_string_product      -- name of the product
 *  - fsg_string_config       -- name of the configuration
 *  - fsg_string_interface    -- name of the interface
 * The first four are only needed when FSG_DESCRIPTORS_DEVICE_STRINGS
 * macro is defined prior to including this file.
24 25
 */

26 27 28 29 30 31 32 33 34 35 36 37 38 39
/*
 * When FSG_NO_INTR_EP is defined fsg_fs_intr_in_desc and
 * fsg_hs_intr_in_desc objects as well as
 * FSG_FS_FUNCTION_PRE_EP_ENTRIES and FSG_HS_FUNCTION_PRE_EP_ENTRIES
 * macros are not defined.
 *
 * When FSG_NO_DEVICE_STRINGS is defined FSG_STRING_MANUFACTURER,
 * FSG_STRING_PRODUCT, FSG_STRING_SERIAL and FSG_STRING_CONFIG are not
 * defined (as well as corresponding entries in string tables are
 * missing) and FSG_STRING_INTERFACE has value of zero.
 *
 * When FSG_NO_OTG is defined fsg_otg_desc won't be defined.
 */

40 41 42 43 44 45
/*
 * When FSG_BUFFHD_STATIC_BUFFER is defined when this file is included
 * the fsg_buffhd structure's buf field will be an array of FSG_BUFLEN
 * characters rather then a pointer to void.
 */

46 47 48 49 50 51
/*
 * When USB_GADGET_DEBUG_FILES is defined the module param num_buffers
 * sets the number of pipeline buffers (length of the fsg_buffhd array).
 * The valid range of num_buffers is: num >= 2 && num <= 4.
 */

52

53
#include <linux/usb/storage.h>
54 55
#include <scsi/scsi.h>
#include <asm/unaligned.h>
56

57

58 59
/*
 * Thanks to NetChip Technologies for donating this product ID.
60 61
 *
 * DO NOT REUSE THESE IDs with any other driver!!  Ever!!
62 63
 * Instead:  allocate your own, using normal USB-IF procedures.
 */
64 65
#define FSG_VENDOR_ID	0x0525	/* NetChip */
#define FSG_PRODUCT_ID	0xa4a5	/* Linux-USB File-backed Storage Gadget */
66 67


68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
/*-------------------------------------------------------------------------*/


#ifndef DEBUG
#undef VERBOSE_DEBUG
#undef DUMP_MSGS
#endif /* !DEBUG */

#ifdef VERBOSE_DEBUG
#define VLDBG	LDBG
#else
#define VLDBG(lun, fmt, args...) do { } while (0)
#endif /* VERBOSE_DEBUG */

#define LDBG(lun, fmt, args...)   dev_dbg (&(lun)->dev, fmt, ## args)
#define LERROR(lun, fmt, args...) dev_err (&(lun)->dev, fmt, ## args)
#define LWARN(lun, fmt, args...)  dev_warn(&(lun)->dev, fmt, ## args)
#define LINFO(lun, fmt, args...)  dev_info(&(lun)->dev, fmt, ## args)

87 88 89
/*
 * Keep those macros in sync with those in
 * include/linux/usb/composite.h or else GCC will complain.  If they
90 91
 * are identical (the same names of arguments, white spaces in the
 * same places) GCC will allow redefinition otherwise (even if some
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
 * white space is removed or added) warning will be issued.
 *
 * Those macros are needed here because File Storage Gadget does not
 * include the composite.h header.  For composite gadgets those macros
 * are redundant since composite.h is included any way.
 *
 * One could check whether those macros are already defined (which
 * would indicate composite.h had been included) or not (which would
 * indicate we were in FSG) but this is not done because a warning is
 * desired if definitions here differ from the ones in composite.h.
 *
 * We want the definitions to match and be the same in File Storage
 * Gadget as well as Mass Storage Function (and so composite gadgets
 * using MSF).  If someone changes them in composite.h it will produce
 * a warning in this file when building MSF.
 */
108 109 110 111 112
#define DBG(d, fmt, args...)     dev_dbg(&(d)->gadget->dev , fmt , ## args)
#define VDBG(d, fmt, args...)    dev_vdbg(&(d)->gadget->dev , fmt , ## args)
#define ERROR(d, fmt, args...)   dev_err(&(d)->gadget->dev , fmt , ## args)
#define WARNING(d, fmt, args...) dev_warn(&(d)->gadget->dev , fmt , ## args)
#define INFO(d, fmt, args...)    dev_info(&(d)->gadget->dev , fmt , ## args)
113 114 115 116 117 118



#ifdef DUMP_MSGS

#  define dump_msg(fsg, /* const char * */ label,			\
119
		   /* const u8 * */ buf, /* unsigned */ length) do {	\
120 121 122 123 124 125 126 127 128 129 130 131
	if (length < 512) {						\
		DBG(fsg, "%s, length %u:\n", label, length);		\
		print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,	\
			       16, 1, buf, length, 0);			\
	}								\
} while (0)

#  define dump_cdb(fsg) do { } while (0)

#else

#  define dump_msg(fsg, /* const char * */ label, \
132
		   /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
133 134 135

#  ifdef VERBOSE_DEBUG

136
#    define dump_cdb(fsg)						\
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
	print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,	\
		       16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0)		\

#  else

#    define dump_cdb(fsg) do { } while (0)

#  endif /* VERBOSE_DEBUG */

#endif /* DUMP_MSGS */





/*-------------------------------------------------------------------------*/

/* Bulk-only data structures */

/* Command Block Wrapper */
157
struct fsg_bulk_cb_wrap {
158 159 160 161 162 163 164
	__le32	Signature;		/* Contains 'USBC' */
	u32	Tag;			/* Unique per command id */
	__le32	DataTransferLength;	/* Size of the data */
	u8	Flags;			/* Direction in bit 7 */
	u8	Lun;			/* LUN (normally 0) */
	u8	Length;			/* Of the CDB, <= MAX_COMMAND_SIZE */
	u8	CDB[16];		/* Command Data Block */
165 166 167
};

#define USB_BULK_CB_WRAP_LEN	31
168
#define USB_BULK_CB_SIG		0x43425355	/* Spells out USBC */
169 170 171 172
#define USB_BULK_IN_FLAG	0x80

/* Command Status Wrapper */
struct bulk_cs_wrap {
173 174 175 176
	__le32	Signature;		/* Should = 'USBS' */
	u32	Tag;			/* Same as original command */
	__le32	Residue;		/* Amount not transferred */
	u8	Status;			/* See below */
177 178 179
};

#define USB_BULK_CS_WRAP_LEN	13
180
#define USB_BULK_CS_SIG		0x53425355	/* Spells out 'USBS' */
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
#define USB_STATUS_PASS		0
#define USB_STATUS_FAIL		1
#define USB_STATUS_PHASE_ERROR	2

/* Bulk-only class specific requests */
#define USB_BULK_RESET_REQUEST		0xff
#define USB_BULK_GET_MAX_LUN_REQUEST	0xfe


/* CBI Interrupt data structure */
struct interrupt_data {
	u8	bType;
	u8	bValue;
};

#define CBI_INTERRUPT_DATA_LEN		2

/* CBI Accept Device-Specific Command request */
#define USB_CBI_ADSC_REQUEST		0x00


202 203
/* Length of a SCSI Command Data Block */
#define MAX_COMMAND_SIZE	16
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
#define SS_NO_SENSE				0
#define SS_COMMUNICATION_FAILURE		0x040800
#define SS_INVALID_COMMAND			0x052000
#define SS_INVALID_FIELD_IN_CDB			0x052400
#define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE	0x052100
#define SS_LOGICAL_UNIT_NOT_SUPPORTED		0x052500
#define SS_MEDIUM_NOT_PRESENT			0x023a00
#define SS_MEDIUM_REMOVAL_PREVENTED		0x055302
#define SS_NOT_READY_TO_READY_TRANSITION	0x062800
#define SS_RESET_OCCURRED			0x062900
#define SS_SAVING_PARAMETERS_NOT_SUPPORTED	0x053900
#define SS_UNRECOVERED_READ_ERROR		0x031100
#define SS_WRITE_ERROR				0x030c02
#define SS_WRITE_PROTECTED			0x072700

221
#define SK(x)		((u8) ((x) >> 16))	/* Sense Key byte, etc. */
222 223 224 225 226 227 228
#define ASC(x)		((u8) ((x) >> 8))
#define ASCQ(x)		((u8) (x))


/*-------------------------------------------------------------------------*/


229
struct fsg_lun {
230 231 232 233
	struct file	*filp;
	loff_t		file_length;
	loff_t		num_sectors;

234 235 236 237 238 239 240
	unsigned int	initially_ro:1;
	unsigned int	ro:1;
	unsigned int	removable:1;
	unsigned int	cdrom:1;
	unsigned int	prevent_medium_removal:1;
	unsigned int	registered:1;
	unsigned int	info_valid:1;
241
	unsigned int	nofua:1;
242 243 244 245 246

	u32		sense_data;
	u32		sense_data_info;
	u32		unit_attention_data;

247 248
	unsigned int	blkbits;	/* Bits of logical block size of bound block device */
	unsigned int	blksize;	/* logical block size of bound block device */
249 250 251
	struct device	dev;
};

252
#define fsg_lun_is_open(curlun)	((curlun)->filp != NULL)
253

254
static struct fsg_lun *fsg_lun_from_dev(struct device *dev)
255
{
256
	return container_of(dev, struct fsg_lun, dev);
257 258 259 260 261
}


/* Big enough to hold our biggest descriptor */
#define EP0_BUFSIZE	256
262
#define DELAYED_STATUS	(EP0_BUFSIZE + 999)	/* An impossibly large value */
263

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
#ifdef CONFIG_USB_GADGET_DEBUG_FILES

static unsigned int fsg_num_buffers = CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS;
module_param_named(num_buffers, fsg_num_buffers, uint, S_IRUGO);
MODULE_PARM_DESC(num_buffers, "Number of pipeline buffers");

#else

/*
 * Number of buffers we will use.
 * 2 is usually enough for good buffering pipeline
 */
#define fsg_num_buffers	CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS

#endif /* CONFIG_USB_DEBUG */

/* check if fsg_num_buffers is within a valid range */
static inline int fsg_num_buffers_validate(void)
{
	if (fsg_num_buffers >= 2 && fsg_num_buffers <= 4)
		return 0;
	pr_err("fsg_num_buffers %u is out of range (%d to %d)\n",
	       fsg_num_buffers, 2 ,4);
	return -EINVAL;
}
289

290 291 292 293 294 295
/* Default size of buffer length. */
#define FSG_BUFLEN	((u32)16384)

/* Maximal number of LUNs supported in mass storage function */
#define FSG_MAX_LUNS	8

296 297 298 299 300 301 302
enum fsg_buffer_state {
	BUF_STATE_EMPTY = 0,
	BUF_STATE_FULL,
	BUF_STATE_BUSY
};

struct fsg_buffhd {
303 304 305
#ifdef FSG_BUFFHD_STATIC_BUFFER
	char				buf[FSG_BUFLEN];
#else
306
	void				*buf;
307
#endif
308 309 310
	enum fsg_buffer_state		state;
	struct fsg_buffhd		*next;

311 312 313 314 315 316 317
	/*
	 * The NetChip 2280 is faster, and handles some protocol faults
	 * better, if we don't submit any short bulk-out read requests.
	 * So we will record the intended request length here.
	 */
	unsigned int			bulk_out_intended_length;

318 319 320 321 322 323 324
	struct usb_request		*inreq;
	int				inreq_busy;
	struct usb_request		*outreq;
	int				outreq_busy;
};

enum fsg_state {
325 326
	/* This one isn't used anywhere */
	FSG_STATE_COMMAND_PHASE = -10,
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
	FSG_STATE_DATA_PHASE,
	FSG_STATE_STATUS_PHASE,

	FSG_STATE_IDLE = 0,
	FSG_STATE_ABORT_BULK_OUT,
	FSG_STATE_RESET,
	FSG_STATE_INTERFACE_CHANGE,
	FSG_STATE_CONFIG_CHANGE,
	FSG_STATE_DISCONNECT,
	FSG_STATE_EXIT,
	FSG_STATE_TERMINATED
};

enum data_direction {
	DATA_DIR_UNKNOWN = 0,
	DATA_DIR_FROM_HOST,
	DATA_DIR_TO_HOST,
	DATA_DIR_NONE
};


/*-------------------------------------------------------------------------*/


static inline u32 get_unaligned_be24(u8 *buf)
{
	return 0xffffff & (u32) get_unaligned_be32(buf - 1);
}


/*-------------------------------------------------------------------------*/


360
enum {
361
#ifndef FSG_NO_DEVICE_STRINGS
362 363 364 365
	FSG_STRING_MANUFACTURER	= 1,
	FSG_STRING_PRODUCT,
	FSG_STRING_SERIAL,
	FSG_STRING_CONFIG,
366
#endif
367 368
	FSG_STRING_INTERFACE
};
369 370


371
#ifndef FSG_NO_OTG
372
static struct usb_otg_descriptor
373 374
fsg_otg_desc = {
	.bLength =		sizeof fsg_otg_desc,
375 376 377 378
	.bDescriptorType =	USB_DT_OTG,

	.bmAttributes =		USB_OTG_SRP,
};
379
#endif
380 381 382 383

/* There is only one interface. */

static struct usb_interface_descriptor
384 385
fsg_intf_desc = {
	.bLength =		sizeof fsg_intf_desc,
386 387
	.bDescriptorType =	USB_DT_INTERFACE,

388
	.bNumEndpoints =	2,		/* Adjusted during fsg_bind() */
389
	.bInterfaceClass =	USB_CLASS_MASS_STORAGE,
390 391
	.bInterfaceSubClass =	USB_SC_SCSI,	/* Adjusted during fsg_bind() */
	.bInterfaceProtocol =	USB_PR_BULK,	/* Adjusted during fsg_bind() */
392
	.iInterface =		FSG_STRING_INTERFACE,
393 394
};

395 396 397 398
/*
 * Three full-speed endpoint descriptors: bulk-in, bulk-out, and
 * interrupt-in.
 */
399 400

static struct usb_endpoint_descriptor
401
fsg_fs_bulk_in_desc = {
402 403 404 405 406 407 408 409 410
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	/* wMaxPacketSize set by autoconfiguration */
};

static struct usb_endpoint_descriptor
411
fsg_fs_bulk_out_desc = {
412 413 414 415 416 417 418 419
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bEndpointAddress =	USB_DIR_OUT,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	/* wMaxPacketSize set by autoconfiguration */
};

420 421
#ifndef FSG_NO_INTR_EP

422
static struct usb_endpoint_descriptor
423
fsg_fs_intr_in_desc = {
424 425 426 427 428 429
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	cpu_to_le16(2),
430
	.bInterval =		32,	/* frames -> 32 ms */
431 432
};

433 434 435 436 437 438 439 440
#ifndef FSG_NO_OTG
#  define FSG_FS_FUNCTION_PRE_EP_ENTRIES	2
#else
#  define FSG_FS_FUNCTION_PRE_EP_ENTRIES	1
#endif

#endif

441
static struct usb_descriptor_header *fsg_fs_function[] = {
442
#ifndef FSG_NO_OTG
443
	(struct usb_descriptor_header *) &fsg_otg_desc,
444
#endif
445 446 447
	(struct usb_descriptor_header *) &fsg_intf_desc,
	(struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
	(struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
448
#ifndef FSG_NO_INTR_EP
449
	(struct usb_descriptor_header *) &fsg_fs_intr_in_desc,
450
#endif
451 452 453 454 455 456 457 458 459 460
	NULL,
};


/*
 * USB 2.0 devices need to expose both high speed and full speed
 * descriptors, unless they only run at full speed.
 *
 * That means alternate endpoint descriptors (bigger packets)
 * and a "device qualifier" ... plus more construction options
461
 * for the configuration descriptor.
462 463
 */
static struct usb_endpoint_descriptor
464
fsg_hs_bulk_in_desc = {
465 466 467 468 469 470 471 472 473
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	/* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	cpu_to_le16(512),
};

static struct usb_endpoint_descriptor
474
fsg_hs_bulk_out_desc = {
475 476 477 478 479 480
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	/* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	cpu_to_le16(512),
481
	.bInterval =		1,	/* NAK every 1 uframe */
482 483
};

484 485
#ifndef FSG_NO_INTR_EP

486
static struct usb_endpoint_descriptor
487
fsg_hs_intr_in_desc = {
488 489 490 491 492 493
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	/* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	cpu_to_le16(2),
494
	.bInterval =		9,	/* 2**(9-1) = 256 uframes -> 32 ms */
495 496
};

497 498 499 500 501 502 503 504
#ifndef FSG_NO_OTG
#  define FSG_HS_FUNCTION_PRE_EP_ENTRIES	2
#else
#  define FSG_HS_FUNCTION_PRE_EP_ENTRIES	1
#endif

#endif

505
static struct usb_descriptor_header *fsg_hs_function[] = {
506
#ifndef FSG_NO_OTG
507
	(struct usb_descriptor_header *) &fsg_otg_desc,
508
#endif
509 510 511
	(struct usb_descriptor_header *) &fsg_intf_desc,
	(struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
	(struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
512
#ifndef FSG_NO_INTR_EP
513
	(struct usb_descriptor_header *) &fsg_hs_intr_in_desc,
514
#endif
515 516 517
	NULL,
};

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
static struct usb_endpoint_descriptor
fsg_ss_bulk_in_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	/* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	cpu_to_le16(1024),
};

static struct usb_ss_ep_comp_descriptor fsg_ss_bulk_in_comp_desc = {
	.bLength =		sizeof(fsg_ss_bulk_in_comp_desc),
	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,

	/*.bMaxBurst =		DYNAMIC, */
};

static struct usb_endpoint_descriptor
fsg_ss_bulk_out_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	/* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	cpu_to_le16(1024),
};

static struct usb_ss_ep_comp_descriptor fsg_ss_bulk_out_comp_desc = {
	.bLength =		sizeof(fsg_ss_bulk_in_comp_desc),
	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,

	/*.bMaxBurst =		DYNAMIC, */
};

#ifndef FSG_NO_INTR_EP

static struct usb_endpoint_descriptor
fsg_ss_intr_in_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	/* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	cpu_to_le16(2),
	.bInterval =		9,	/* 2**(9-1) = 256 uframes -> 32 ms */
};

static struct usb_ss_ep_comp_descriptor fsg_ss_intr_in_comp_desc = {
	.bLength =		sizeof(fsg_ss_bulk_in_comp_desc),
	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,

	.wBytesPerInterval =	cpu_to_le16(2),
};

#ifndef FSG_NO_OTG
#  define FSG_SS_FUNCTION_PRE_EP_ENTRIES	2
#else
#  define FSG_SS_FUNCTION_PRE_EP_ENTRIES	1
#endif

#endif

static __maybe_unused struct usb_ext_cap_descriptor fsg_ext_cap_desc = {
	.bLength =		USB_DT_USB_EXT_CAP_SIZE,
	.bDescriptorType =	USB_DT_DEVICE_CAPABILITY,
	.bDevCapabilityType =	USB_CAP_TYPE_EXT,

	.bmAttributes =		cpu_to_le32(USB_LPM_SUPPORT),
};

static __maybe_unused struct usb_ss_cap_descriptor fsg_ss_cap_desc = {
	.bLength =		USB_DT_USB_SS_CAP_SIZE,
	.bDescriptorType =	USB_DT_DEVICE_CAPABILITY,
	.bDevCapabilityType =	USB_SS_CAP_TYPE,

	/* .bmAttributes = LTM is not supported yet */

	.wSpeedSupported =	cpu_to_le16(USB_LOW_SPEED_OPERATION
		| USB_FULL_SPEED_OPERATION
		| USB_HIGH_SPEED_OPERATION
		| USB_5GBPS_OPERATION),
	.bFunctionalitySupport = USB_LOW_SPEED_OPERATION,
	.bU1devExitLat =	USB_DEFAULT_U1_DEV_EXIT_LAT,
	.bU2DevExitLat =	USB_DEFAULT_U2_DEV_EXIT_LAT,
};

static __maybe_unused struct usb_bos_descriptor fsg_bos_desc = {
	.bLength =		USB_DT_BOS_SIZE,
	.bDescriptorType =	USB_DT_BOS,

	.wTotalLength =		USB_DT_BOS_SIZE
				+ USB_DT_USB_EXT_CAP_SIZE
				+ USB_DT_USB_SS_CAP_SIZE,

	.bNumDeviceCaps =	2,
};

static struct usb_descriptor_header *fsg_ss_function[] = {
#ifndef FSG_NO_OTG
	(struct usb_descriptor_header *) &fsg_otg_desc,
#endif
	(struct usb_descriptor_header *) &fsg_intf_desc,
	(struct usb_descriptor_header *) &fsg_ss_bulk_in_desc,
	(struct usb_descriptor_header *) &fsg_ss_bulk_in_comp_desc,
	(struct usb_descriptor_header *) &fsg_ss_bulk_out_desc,
	(struct usb_descriptor_header *) &fsg_ss_bulk_out_comp_desc,
#ifndef FSG_NO_INTR_EP
	(struct usb_descriptor_header *) &fsg_ss_intr_in_desc,
	(struct usb_descriptor_header *) &fsg_ss_intr_in_comp_desc,
#endif
	NULL,
};

631
/* Maxpacket and other transfer characteristics vary by speed. */
632
static __maybe_unused struct usb_endpoint_descriptor *
633
fsg_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
634 635
		struct usb_endpoint_descriptor *hs,
		struct usb_endpoint_descriptor *ss)
636
{
637 638 639
	if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
		return ss;
	else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
640 641 642 643 644 645
		return hs;
	return fs;
}


/* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
646
static struct usb_string		fsg_strings[] = {
647
#ifndef FSG_NO_DEVICE_STRINGS
648 649
	{FSG_STRING_MANUFACTURER,	fsg_string_manufacturer},
	{FSG_STRING_PRODUCT,		fsg_string_product},
650
	{FSG_STRING_SERIAL,		""},
651
	{FSG_STRING_CONFIG,		fsg_string_config},
652
#endif
653
	{FSG_STRING_INTERFACE,		fsg_string_interface},
654 655 656
	{}
};

657
static struct usb_gadget_strings	fsg_stringtab = {
658
	.language	= 0x0409,		/* en-us */
659
	.strings	= fsg_strings,
660 661 662 663 664
};


 /*-------------------------------------------------------------------------*/

665 666 667 668
/*
 * If the next two routines are called while the gadget is registered,
 * the caller must own fsg->filesem for writing.
 */
669

670
static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
671 672 673 674 675 676 677 678 679 680
{
	int				ro;
	struct file			*filp = NULL;
	int				rc = -EINVAL;
	struct inode			*inode = NULL;
	loff_t				size;
	loff_t				num_sectors;
	loff_t				min_sectors;

	/* R/W if we can, R/O if we must */
681
	ro = curlun->initially_ro;
682 683
	if (!ro) {
		filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
684
		if (PTR_ERR(filp) == -EROFS || PTR_ERR(filp) == -EACCES)
685 686 687 688 689 690 691 692 693 694 695 696 697 698
			ro = 1;
	}
	if (ro)
		filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
	if (IS_ERR(filp)) {
		LINFO(curlun, "unable to open backing file: %s\n", filename);
		return PTR_ERR(filp);
	}

	if (!(filp->f_mode & FMODE_WRITE))
		ro = 1;

	if (filp->f_path.dentry)
		inode = filp->f_path.dentry->d_inode;
699
	if (!inode || (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))) {
700 701 702 703
		LINFO(curlun, "invalid file type: %s\n", filename);
		goto out;
	}

704 705 706 707
	/*
	 * If we can't read the file, it's no good.
	 * If we can't write the file, use it read-only.
	 */
708 709 710 711 712 713 714 715 716 717 718 719 720
	if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
		LINFO(curlun, "file not readable: %s\n", filename);
		goto out;
	}
	if (!(filp->f_op->write || filp->f_op->aio_write))
		ro = 1;

	size = i_size_read(inode->i_mapping->host);
	if (size < 0) {
		LINFO(curlun, "unable to find file size: %s\n", filename);
		rc = (int) size;
		goto out;
	}
721 722 723 724 725 726 727 728 729 730 731 732 733

	if (curlun->cdrom) {
		curlun->blksize = 2048;
		curlun->blkbits = 11;
	} else if (inode->i_bdev) {
		curlun->blksize = bdev_logical_block_size(inode->i_bdev);
		curlun->blkbits = blksize_bits(curlun->blksize);
	} else {
		curlun->blksize = 512;
		curlun->blkbits = 9;
	}

	num_sectors = size >> curlun->blkbits; /* File size in logic-block-size blocks */
734
	min_sectors = 1;
735
	if (curlun->cdrom) {
736 737 738
		min_sectors = 300;	/* Smallest track is 300 frames */
		if (num_sectors >= 256*60*75) {
			num_sectors = 256*60*75 - 1;
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
			LINFO(curlun, "file too big: %s\n", filename);
			LINFO(curlun, "using only first %d blocks\n",
					(int) num_sectors);
		}
	}
	if (num_sectors < min_sectors) {
		LINFO(curlun, "file too small: %s\n", filename);
		rc = -ETOOSMALL;
		goto out;
	}

	get_file(filp);
	curlun->ro = ro;
	curlun->filp = filp;
	curlun->file_length = size;
	curlun->num_sectors = num_sectors;
	LDBG(curlun, "open backing file: %s\n", filename);
	rc = 0;

out:
	filp_close(filp, current->files);
	return rc;
}


764
static void fsg_lun_close(struct fsg_lun *curlun)
765 766 767 768 769 770 771 772 773 774 775
{
	if (curlun->filp) {
		LDBG(curlun, "close backing file\n");
		fput(curlun->filp);
		curlun->filp = NULL;
	}
}


/*-------------------------------------------------------------------------*/

776 777 778 779
/*
 * Sync the file data, don't bother with the metadata.
 * This code was copied from fs/buffer.c:sys_fdatasync().
 */
780
static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
781 782 783 784 785
{
	struct file	*filp = curlun->filp;

	if (curlun->ro || !filp)
		return 0;
786
	return vfs_fsync(filp, 1);
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
}

static void store_cdrom_address(u8 *dest, int msf, u32 addr)
{
	if (msf) {
		/* Convert to Minutes-Seconds-Frames */
		addr >>= 2;		/* Convert to 2048-byte frames */
		addr += 2*75;		/* Lead-in occupies 2 seconds */
		dest[3] = addr % 75;	/* Frames */
		addr /= 75;
		dest[2] = addr % 60;	/* Seconds */
		addr /= 60;
		dest[1] = addr;		/* Minutes */
		dest[0] = 0;		/* Reserved */
	} else {
		/* Absolute sector */
		put_unaligned_be32(addr, dest);
	}
}
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820


/*-------------------------------------------------------------------------*/


static ssize_t fsg_show_ro(struct device *dev, struct device_attribute *attr,
			   char *buf)
{
	struct fsg_lun	*curlun = fsg_lun_from_dev(dev);

	return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
				  ? curlun->ro
				  : curlun->initially_ro);
}

821 822 823 824 825 826 827 828
static ssize_t fsg_show_nofua(struct device *dev, struct device_attribute *attr,
			      char *buf)
{
	struct fsg_lun	*curlun = fsg_lun_from_dev(dev);

	return sprintf(buf, "%u\n", curlun->nofua);
}

829 830 831 832 833 834 835 836 837
static ssize_t fsg_show_file(struct device *dev, struct device_attribute *attr,
			     char *buf)
{
	struct fsg_lun	*curlun = fsg_lun_from_dev(dev);
	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
	char		*p;
	ssize_t		rc;

	down_read(filesem);
838
	if (fsg_lun_is_open(curlun)) {	/* Get the complete pathname */
839 840 841 842 843 844
		p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
		if (IS_ERR(p))
			rc = PTR_ERR(p);
		else {
			rc = strlen(p);
			memmove(buf, p, rc);
845
			buf[rc] = '\n';		/* Add a newline */
846 847
			buf[++rc] = 0;
		}
848
	} else {				/* No file, return 0 bytes */
849 850 851 852 853 854 855 856 857 858 859
		*buf = 0;
		rc = 0;
	}
	up_read(filesem);
	return rc;
}


static ssize_t fsg_store_ro(struct device *dev, struct device_attribute *attr,
			    const char *buf, size_t count)
{
860
	ssize_t		rc;
861 862
	struct fsg_lun	*curlun = fsg_lun_from_dev(dev);
	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
863
	unsigned	ro;
864

865 866 867
	rc = kstrtouint(buf, 2, &ro);
	if (rc)
		return rc;
868

869 870 871 872
	/*
	 * Allow the write-enable status to change only while the
	 * backing file is closed.
	 */
873 874 875 876 877
	down_read(filesem);
	if (fsg_lun_is_open(curlun)) {
		LDBG(curlun, "read-only status change prevented\n");
		rc = -EBUSY;
	} else {
878 879
		curlun->ro = ro;
		curlun->initially_ro = ro;
880
		LDBG(curlun, "read-only status set to %d\n", curlun->ro);
881
		rc = count;
882 883 884 885 886
	}
	up_read(filesem);
	return rc;
}

887 888 889 890 891
static ssize_t fsg_store_nofua(struct device *dev,
			       struct device_attribute *attr,
			       const char *buf, size_t count)
{
	struct fsg_lun	*curlun = fsg_lun_from_dev(dev);
892 893
	unsigned	nofua;
	int		ret;
894

895 896 897
	ret = kstrtouint(buf, 2, &nofua);
	if (ret)
		return ret;
898 899 900 901 902 903 904 905 906 907

	/* Sync data when switching from async mode to sync */
	if (!nofua && curlun->nofua)
		fsg_lun_fsync_sub(curlun);

	curlun->nofua = nofua;

	return count;
}

908 909 910 911 912 913 914 915 916
static ssize_t fsg_store_file(struct device *dev, struct device_attribute *attr,
			      const char *buf, size_t count)
{
	struct fsg_lun	*curlun = fsg_lun_from_dev(dev);
	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
	int		rc = 0;

	if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
		LDBG(curlun, "eject attempt prevented\n");
917
		return -EBUSY;				/* "Door is locked" */
918 919 920 921
	}

	/* Remove a trailing newline */
	if (count > 0 && buf[count-1] == '\n')
922
		((char *) buf)[count-1] = 0;		/* Ugh! */
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940

	/* Eject current medium */
	down_write(filesem);
	if (fsg_lun_is_open(curlun)) {
		fsg_lun_close(curlun);
		curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
	}

	/* Load new medium */
	if (count > 0 && buf[0]) {
		rc = fsg_lun_open(curlun, buf);
		if (rc == 0)
			curlun->unit_attention_data =
					SS_NOT_READY_TO_READY_TRANSITION;
	}
	up_write(filesem);
	return (rc < 0 ? rc : count);
}