2 * storage_common.c -- Common definitions for mass storage functionality
4 * Copyright (C) 2003-2008 Alan Stern
5 * Copyeight (C) 2009 Samsung Electronics
6 * Author: Michal Nazarewicz (mina86@mina86.com)
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
15 * This file requires the following identifiers used in USB strings to
16 * be defined (each of type pointer to char):
17 * - fsg_string_interface -- name of the interface
21 * When USB_GADGET_DEBUG_FILES is defined the module param num_buffers
22 * sets the number of pipeline buffers (length of the fsg_buffhd array).
23 * The valid range of num_buffers is: num >= 2 && num <= 4.
27 #include <linux/usb/storage.h>
28 #include <scsi/scsi.h>
29 #include <asm/unaligned.h>
33 * Thanks to NetChip Technologies for donating this product ID.
35 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
36 * Instead: allocate your own, using normal USB-IF procedures.
38 #define FSG_VENDOR_ID 0x0525 /* NetChip */
39 #define FSG_PRODUCT_ID 0xa4a5 /* Linux-USB File-backed Storage Gadget */
42 /*-------------------------------------------------------------------------*/
53 #define VLDBG(lun, fmt, args...) do { } while (0)
54 #endif /* VERBOSE_DEBUG */
56 #define LDBG(lun, fmt, args...) dev_dbg(&(lun)->dev, fmt, ## args)
57 #define LERROR(lun, fmt, args...) dev_err(&(lun)->dev, fmt, ## args)
58 #define LWARN(lun, fmt, args...) dev_warn(&(lun)->dev, fmt, ## args)
59 #define LINFO(lun, fmt, args...) dev_info(&(lun)->dev, fmt, ## args)
64 # define dump_msg(fsg, /* const char * */ label, \
65 /* const u8 * */ buf, /* unsigned */ length) do { \
67 DBG(fsg, "%s, length %u:\n", label, length); \
68 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, \
69 16, 1, buf, length, 0); \
73 # define dump_cdb(fsg) do { } while (0)
77 # define dump_msg(fsg, /* const char * */ label, \
78 /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
82 # define dump_cdb(fsg) \
83 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE, \
84 16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0) \
88 # define dump_cdb(fsg) do { } while (0)
90 # endif /* VERBOSE_DEBUG */
92 #endif /* DUMP_MSGS */
94 /*-------------------------------------------------------------------------*/
96 /* Length of a SCSI Command Data Block */
97 #define MAX_COMMAND_SIZE 16
99 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
100 #define SS_NO_SENSE 0
101 #define SS_COMMUNICATION_FAILURE 0x040800
102 #define SS_INVALID_COMMAND 0x052000
103 #define SS_INVALID_FIELD_IN_CDB 0x052400
104 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
105 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
106 #define SS_MEDIUM_NOT_PRESENT 0x023a00
107 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
108 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
109 #define SS_RESET_OCCURRED 0x062900
110 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
111 #define SS_UNRECOVERED_READ_ERROR 0x031100
112 #define SS_WRITE_ERROR 0x030c02
113 #define SS_WRITE_PROTECTED 0x072700
115 #define SK(x) ((u8) ((x) >> 16)) /* Sense Key byte, etc. */
116 #define ASC(x) ((u8) ((x) >> 8))
117 #define ASCQ(x) ((u8) (x))
120 /*-------------------------------------------------------------------------*/
128 unsigned int initially_ro:1;
130 unsigned int removable:1;
131 unsigned int cdrom:1;
132 unsigned int prevent_medium_removal:1;
133 unsigned int registered:1;
134 unsigned int info_valid:1;
135 unsigned int nofua:1;
139 u32 unit_attention_data;
141 unsigned int blkbits; /* Bits of logical block size of bound block device */
142 unsigned int blksize; /* logical block size of bound block device */
144 #ifdef CONFIG_USB_MSC_PROFILING
148 unsigned long rbytes;
149 unsigned long wbytes;
157 static inline bool fsg_lun_is_open(struct fsg_lun *curlun)
159 return curlun->filp != NULL;
162 static inline struct fsg_lun *fsg_lun_from_dev(struct device *dev)
164 return container_of(dev, struct fsg_lun, dev);
168 /* Big enough to hold our biggest descriptor */
169 #define EP0_BUFSIZE 256
170 #define DELAYED_STATUS (EP0_BUFSIZE + 999) /* An impossibly large value */
172 #ifdef CONFIG_USB_CSW_HACK
173 #define fsg_num_buffers 4
175 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
177 static unsigned int fsg_num_buffers = CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS;
178 module_param_named(num_buffers, fsg_num_buffers, uint, S_IRUGO);
179 MODULE_PARM_DESC(num_buffers, "Number of pipeline buffers");
184 * Number of buffers we will use.
185 * 2 is usually enough for good buffering pipeline
187 #define fsg_num_buffers CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS
189 #endif /* CONFIG_USB_DEBUG */
190 #endif /* CONFIG_USB_CSW_HACK */
192 /* check if fsg_num_buffers is within a valid range */
193 static inline int fsg_num_buffers_validate(void)
195 if (fsg_num_buffers >= 2 && fsg_num_buffers <= 4)
197 pr_err("fsg_num_buffers %u is out of range (%d to %d)\n",
198 fsg_num_buffers, 2 , 4);
202 /* Default size of buffer length. */
203 #define FSG_BUFLEN ((u32)65536)
205 /* Maximal number of LUNs supported in mass storage function */
206 #define FSG_MAX_LUNS 8
208 enum fsg_buffer_state {
216 enum fsg_buffer_state state;
217 struct fsg_buffhd *next;
220 * The NetChip 2280 is faster, and handles some protocol faults
221 * better, if we don't submit any short bulk-out read requests.
222 * So we will record the intended request length here.
224 unsigned int bulk_out_intended_length;
226 struct usb_request *inreq;
228 struct usb_request *outreq;
233 /* This one isn't used anywhere */
234 FSG_STATE_COMMAND_PHASE = -10,
235 FSG_STATE_DATA_PHASE,
236 FSG_STATE_STATUS_PHASE,
239 FSG_STATE_ABORT_BULK_OUT,
241 FSG_STATE_INTERFACE_CHANGE,
242 FSG_STATE_CONFIG_CHANGE,
243 FSG_STATE_DISCONNECT,
248 enum data_direction {
249 DATA_DIR_UNKNOWN = 0,
256 /*-------------------------------------------------------------------------*/
259 static inline u32 get_unaligned_be24(u8 *buf)
261 return 0xffffff & (u32) get_unaligned_be32(buf - 1);
265 /*-------------------------------------------------------------------------*/
273 /* There is only one interface. */
275 static struct usb_interface_descriptor
277 .bLength = sizeof fsg_intf_desc,
278 .bDescriptorType = USB_DT_INTERFACE,
280 .bNumEndpoints = 2, /* Adjusted during fsg_bind() */
281 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
282 .bInterfaceSubClass = USB_SC_SCSI, /* Adjusted during fsg_bind() */
283 .bInterfaceProtocol = USB_PR_BULK, /* Adjusted during fsg_bind() */
284 .iInterface = FSG_STRING_INTERFACE,
288 * Three full-speed endpoint descriptors: bulk-in, bulk-out, and
292 static struct usb_endpoint_descriptor
293 fsg_fs_bulk_in_desc = {
294 .bLength = USB_DT_ENDPOINT_SIZE,
295 .bDescriptorType = USB_DT_ENDPOINT,
297 .bEndpointAddress = USB_DIR_IN,
298 .bmAttributes = USB_ENDPOINT_XFER_BULK,
299 /* wMaxPacketSize set by autoconfiguration */
302 static struct usb_endpoint_descriptor
303 fsg_fs_bulk_out_desc = {
304 .bLength = USB_DT_ENDPOINT_SIZE,
305 .bDescriptorType = USB_DT_ENDPOINT,
307 .bEndpointAddress = USB_DIR_OUT,
308 .bmAttributes = USB_ENDPOINT_XFER_BULK,
309 /* wMaxPacketSize set by autoconfiguration */
312 static struct usb_descriptor_header *fsg_fs_function[] = {
313 (struct usb_descriptor_header *) &fsg_intf_desc,
314 (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
315 (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
321 * USB 2.0 devices need to expose both high speed and full speed
322 * descriptors, unless they only run at full speed.
324 * That means alternate endpoint descriptors (bigger packets)
325 * and a "device qualifier" ... plus more construction options
326 * for the configuration descriptor.
328 static struct usb_endpoint_descriptor
329 fsg_hs_bulk_in_desc = {
330 .bLength = USB_DT_ENDPOINT_SIZE,
331 .bDescriptorType = USB_DT_ENDPOINT,
333 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
334 .bmAttributes = USB_ENDPOINT_XFER_BULK,
335 .wMaxPacketSize = cpu_to_le16(512),
338 static struct usb_endpoint_descriptor
339 fsg_hs_bulk_out_desc = {
340 .bLength = USB_DT_ENDPOINT_SIZE,
341 .bDescriptorType = USB_DT_ENDPOINT,
343 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
344 .bmAttributes = USB_ENDPOINT_XFER_BULK,
345 .wMaxPacketSize = cpu_to_le16(512),
346 .bInterval = 1, /* NAK every 1 uframe */
350 static struct usb_descriptor_header *fsg_hs_function[] = {
351 (struct usb_descriptor_header *) &fsg_intf_desc,
352 (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
353 (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
357 static struct usb_endpoint_descriptor
358 fsg_ss_bulk_in_desc = {
359 .bLength = USB_DT_ENDPOINT_SIZE,
360 .bDescriptorType = USB_DT_ENDPOINT,
362 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
363 .bmAttributes = USB_ENDPOINT_XFER_BULK,
364 .wMaxPacketSize = cpu_to_le16(1024),
367 static struct usb_ss_ep_comp_descriptor fsg_ss_bulk_in_comp_desc = {
368 .bLength = sizeof(fsg_ss_bulk_in_comp_desc),
369 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
371 /*.bMaxBurst = DYNAMIC, */
374 static struct usb_endpoint_descriptor
375 fsg_ss_bulk_out_desc = {
376 .bLength = USB_DT_ENDPOINT_SIZE,
377 .bDescriptorType = USB_DT_ENDPOINT,
379 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
380 .bmAttributes = USB_ENDPOINT_XFER_BULK,
381 .wMaxPacketSize = cpu_to_le16(1024),
384 static struct usb_ss_ep_comp_descriptor fsg_ss_bulk_out_comp_desc = {
385 .bLength = sizeof(fsg_ss_bulk_in_comp_desc),
386 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
388 /*.bMaxBurst = DYNAMIC, */
391 static struct usb_descriptor_header *fsg_ss_function[] = {
392 (struct usb_descriptor_header *) &fsg_intf_desc,
393 (struct usb_descriptor_header *) &fsg_ss_bulk_in_desc,
394 (struct usb_descriptor_header *) &fsg_ss_bulk_in_comp_desc,
395 (struct usb_descriptor_header *) &fsg_ss_bulk_out_desc,
396 (struct usb_descriptor_header *) &fsg_ss_bulk_out_comp_desc,
400 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
401 static struct usb_string fsg_strings[] = {
402 {FSG_STRING_INTERFACE, fsg_string_interface},
406 static struct usb_gadget_strings fsg_stringtab = {
407 .language = 0x0409, /* en-us */
408 .strings = fsg_strings,
412 /*-------------------------------------------------------------------------*/
415 * If the next two routines are called while the gadget is registered,
416 * the caller must own fsg->filesem for writing.
419 static void fsg_lun_close(struct fsg_lun *curlun)
422 LDBG(curlun, "close backing file\n");
429 static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
432 struct file *filp = NULL;
434 struct inode *inode = NULL;
438 unsigned int blkbits;
439 unsigned int blksize;
441 /* R/W if we can, R/O if we must */
442 ro = curlun->initially_ro;
444 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
445 if (PTR_ERR(filp) == -EROFS || PTR_ERR(filp) == -EACCES)
449 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
451 LINFO(curlun, "unable to open backing file: %s\n", filename);
452 return PTR_ERR(filp);
455 if (!(filp->f_mode & FMODE_WRITE))
458 inode = file_inode(filp);
459 if ((!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))) {
460 LINFO(curlun, "invalid file type: %s\n", filename);
465 * If we can't read the file, it's no good.
466 * If we can't write the file, use it read-only.
468 if (!(filp->f_op->read || filp->f_op->aio_read)) {
469 LINFO(curlun, "file not readable: %s\n", filename);
472 if (!(filp->f_op->write || filp->f_op->aio_write))
475 size = i_size_read(inode->i_mapping->host);
477 LINFO(curlun, "unable to find file size: %s\n", filename);
485 } else if (inode->i_bdev) {
486 blksize = bdev_logical_block_size(inode->i_bdev);
487 blkbits = blksize_bits(blksize);
493 num_sectors = size >> blkbits; /* File size in logic-block-size blocks */
496 min_sectors = 300; /* Smallest track is 300 frames */
497 if (num_sectors >= 256*60*75) {
498 num_sectors = 256*60*75 - 1;
499 LINFO(curlun, "file too big: %s\n", filename);
500 LINFO(curlun, "using only first %d blocks\n",
504 if (num_sectors < min_sectors) {
505 LINFO(curlun, "file too small: %s\n", filename);
510 if (fsg_lun_is_open(curlun))
511 fsg_lun_close(curlun);
513 curlun->blksize = blksize;
514 curlun->blkbits = blkbits;
517 curlun->file_length = size;
518 curlun->num_sectors = num_sectors;
519 LDBG(curlun, "open backing file: %s\n", filename);
528 /*-------------------------------------------------------------------------*/
531 * Sync the file data, don't bother with the metadata.
532 * This code was copied from fs/buffer.c:sys_fdatasync().
534 static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
536 struct file *filp = curlun->filp;
538 if (curlun->ro || !filp)
540 return vfs_fsync(filp, 1);
543 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
546 /* Convert to Minutes-Seconds-Frames */
547 addr >>= 2; /* Convert to 2048-byte frames */
548 addr += 2*75; /* Lead-in occupies 2 seconds */
549 dest[3] = addr % 75; /* Frames */
551 dest[2] = addr % 60; /* Seconds */
553 dest[1] = addr; /* Minutes */
554 dest[0] = 0; /* Reserved */
556 /* Absolute sector */
557 put_unaligned_be32(addr, dest);
562 /*-------------------------------------------------------------------------*/
565 static ssize_t fsg_show_ro(struct device *dev, struct device_attribute *attr,
568 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
570 return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
572 : curlun->initially_ro);
575 static ssize_t fsg_show_nofua(struct device *dev, struct device_attribute *attr,
578 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
580 return sprintf(buf, "%u\n", curlun->nofua);
583 #ifdef CONFIG_USB_MSC_PROFILING
584 static ssize_t fsg_show_perf(struct device *dev, struct device_attribute *attr,
587 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
588 unsigned long rbytes, wbytes;
589 int64_t rtime, wtime;
591 spin_lock(&curlun->lock);
592 rbytes = curlun->perf.rbytes;
593 wbytes = curlun->perf.wbytes;
594 rtime = ktime_to_us(curlun->perf.rtime);
595 wtime = ktime_to_us(curlun->perf.wtime);
596 spin_unlock(&curlun->lock);
598 return snprintf(buf, PAGE_SIZE, "Write performance :"
599 "%lu bytes in %lld microseconds\n"
601 "%lu bytes in %lld microseconds\n",
602 wbytes, wtime, rbytes, rtime);
604 static ssize_t fsg_store_perf(struct device *dev, struct device_attribute *attr,
605 const char *buf, size_t count)
607 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
610 sscanf(buf, "%d", &value);
612 spin_lock(&curlun->lock);
613 memset(&curlun->perf, 0, sizeof(curlun->perf));
614 spin_unlock(&curlun->lock);
620 static ssize_t fsg_show_file(struct device *dev, struct device_attribute *attr,
623 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
624 struct rw_semaphore *filesem = dev_get_drvdata(dev);
629 if (fsg_lun_is_open(curlun)) { /* Get the complete pathname */
630 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
636 buf[rc] = '\n'; /* Add a newline */
639 } else { /* No file, return 0 bytes */
648 static ssize_t fsg_store_ro(struct device *dev, struct device_attribute *attr,
649 const char *buf, size_t count)
652 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
653 struct rw_semaphore *filesem = dev_get_drvdata(dev);
656 rc = kstrtouint(buf, 2, &ro);
661 * Allow the write-enable status to change only while the
662 * backing file is closed.
665 if (fsg_lun_is_open(curlun)) {
666 LDBG(curlun, "read-only status change prevented\n");
670 curlun->initially_ro = ro;
671 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
678 static ssize_t fsg_store_nofua(struct device *dev,
679 struct device_attribute *attr,
680 const char *buf, size_t count)
682 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
686 ret = kstrtouint(buf, 2, &nofua);
690 /* Sync data when switching from async mode to sync */
691 if (!nofua && curlun->nofua)
692 fsg_lun_fsync_sub(curlun);
694 curlun->nofua = nofua;
699 static ssize_t fsg_store_file(struct device *dev, struct device_attribute *attr,
700 const char *buf, size_t count)
702 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
703 struct rw_semaphore *filesem = dev_get_drvdata(dev);
706 #ifndef CONFIG_USB_G_ANDROID
707 if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
708 LDBG(curlun, "eject attempt prevented\n");
709 return -EBUSY; /* "Door is locked" */
713 /* Remove a trailing newline */
714 if (count > 0 && buf[count-1] == '\n')
715 ((char *) buf)[count-1] = 0; /* Ugh! */
717 /* Load new medium */
719 if (count > 0 && buf[0]) {
720 LDBG(curlun, "fsg_lun_open\n");
721 /* fsg_lun_open() will close existing file if any. */
722 rc = fsg_lun_open(curlun, buf);
724 curlun->unit_attention_data =
725 SS_NOT_READY_TO_READY_TRANSITION;
726 } else if (fsg_lun_is_open(curlun)) {
727 LDBG(curlun, "fsg_lun_open\n");
728 fsg_lun_close(curlun);
729 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
732 return (rc < 0 ? rc : count);