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 (m.nazarewicz@samsung.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.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 * This file requires the following identifiers used in USB strings to
26 * be defined (each of type pointer to char):
27 * - fsg_string_manufacturer -- name of the manufacturer
28 * - fsg_string_product -- name of the product
29 * - fsg_string_config -- name of the configuration
30 * - fsg_string_interface -- name of the interface
31 * The first four are only needed when FSG_DESCRIPTORS_DEVICE_STRINGS
32 * macro is defined prior to including this file.
36 * When FSG_NO_INTR_EP is defined fsg_fs_intr_in_desc and
37 * fsg_hs_intr_in_desc objects as well as
38 * FSG_FS_FUNCTION_PRE_EP_ENTRIES and FSG_HS_FUNCTION_PRE_EP_ENTRIES
39 * macros are not defined.
41 * When FSG_NO_DEVICE_STRINGS is defined FSG_STRING_MANUFACTURER,
42 * FSG_STRING_PRODUCT, FSG_STRING_SERIAL and FSG_STRING_CONFIG are not
43 * defined (as well as corresponding entries in string tables are
44 * missing) and FSG_STRING_INTERFACE has value of zero.
46 * When FSG_NO_OTG is defined fsg_otg_desc won't be defined.
50 * When FSG_BUFFHD_STATIC_BUFFER is defined when this file is included
51 * the fsg_buffhd structure's buf field will be an array of FSG_BUFLEN
52 * characters rather then a pointer to void.
56 #include <linux/usb/storage.h>
57 #include <scsi/scsi.h>
58 #include <asm/unaligned.h>
62 * Thanks to NetChip Technologies for donating this product ID.
64 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
65 * Instead: allocate your own, using normal USB-IF procedures.
67 #define FSG_VENDOR_ID 0x0525 /* NetChip */
68 #define FSG_PRODUCT_ID 0xa4a5 /* Linux-USB File-backed Storage Gadget */
71 /*-------------------------------------------------------------------------*/
82 #define VLDBG(lun, fmt, args...) do { } while (0)
83 #endif /* VERBOSE_DEBUG */
85 #define LDBG(lun, fmt, args...) dev_dbg (&(lun)->dev, fmt, ## args)
86 #define LERROR(lun, fmt, args...) dev_err (&(lun)->dev, fmt, ## args)
87 #define LWARN(lun, fmt, args...) dev_warn(&(lun)->dev, fmt, ## args)
88 #define LINFO(lun, fmt, args...) dev_info(&(lun)->dev, fmt, ## args)
91 * Keep those macros in sync with those in
92 * include/linux/usb/composite.h or else GCC will complain. If they
93 * are identical (the same names of arguments, white spaces in the
94 * same places) GCC will allow redefinition otherwise (even if some
95 * white space is removed or added) warning will be issued.
97 * Those macros are needed here because File Storage Gadget does not
98 * include the composite.h header. For composite gadgets those macros
99 * are redundant since composite.h is included any way.
101 * One could check whether those macros are already defined (which
102 * would indicate composite.h had been included) or not (which would
103 * indicate we were in FSG) but this is not done because a warning is
104 * desired if definitions here differ from the ones in composite.h.
106 * We want the definitions to match and be the same in File Storage
107 * Gadget as well as Mass Storage Function (and so composite gadgets
108 * using MSF). If someone changes them in composite.h it will produce
109 * a warning in this file when building MSF.
111 #define DBG(d, fmt, args...) dev_dbg(&(d)->gadget->dev , fmt , ## args)
112 #define VDBG(d, fmt, args...) dev_vdbg(&(d)->gadget->dev , fmt , ## args)
113 #define ERROR(d, fmt, args...) dev_err(&(d)->gadget->dev , fmt , ## args)
114 #define WARNING(d, fmt, args...) dev_warn(&(d)->gadget->dev , fmt , ## args)
115 #define INFO(d, fmt, args...) dev_info(&(d)->gadget->dev , fmt , ## args)
121 # define dump_msg(fsg, /* const char * */ label, \
122 /* const u8 * */ buf, /* unsigned */ length) do { \
123 if (length < 512) { \
124 DBG(fsg, "%s, length %u:\n", label, length); \
125 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, \
126 16, 1, buf, length, 0); \
130 # define dump_cdb(fsg) do { } while (0)
134 # define dump_msg(fsg, /* const char * */ label, \
135 /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
137 # ifdef VERBOSE_DEBUG
139 # define dump_cdb(fsg) \
140 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE, \
141 16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0) \
145 # define dump_cdb(fsg) do { } while (0)
147 # endif /* VERBOSE_DEBUG */
149 #endif /* DUMP_MSGS */
155 /*-------------------------------------------------------------------------*/
157 /* Bulk-only data structures */
159 /* Command Block Wrapper */
160 struct fsg_bulk_cb_wrap {
161 __le32 Signature; /* Contains 'USBC' */
162 u32 Tag; /* Unique per command id */
163 __le32 DataTransferLength; /* Size of the data */
164 u8 Flags; /* Direction in bit 7 */
165 u8 Lun; /* LUN (normally 0) */
166 u8 Length; /* Of the CDB, <= MAX_COMMAND_SIZE */
167 u8 CDB[16]; /* Command Data Block */
170 #define USB_BULK_CB_WRAP_LEN 31
171 #define USB_BULK_CB_SIG 0x43425355 /* Spells out USBC */
172 #define USB_BULK_IN_FLAG 0x80
174 /* Command Status Wrapper */
175 struct bulk_cs_wrap {
176 __le32 Signature; /* Should = 'USBS' */
177 u32 Tag; /* Same as original command */
178 __le32 Residue; /* Amount not transferred */
179 u8 Status; /* See below */
182 #define USB_BULK_CS_WRAP_LEN 13
183 #define USB_BULK_CS_SIG 0x53425355 /* Spells out 'USBS' */
184 #define USB_STATUS_PASS 0
185 #define USB_STATUS_FAIL 1
186 #define USB_STATUS_PHASE_ERROR 2
188 /* Bulk-only class specific requests */
189 #define USB_BULK_RESET_REQUEST 0xff
190 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
193 /* CBI Interrupt data structure */
194 struct interrupt_data {
199 #define CBI_INTERRUPT_DATA_LEN 2
201 /* CBI Accept Device-Specific Command request */
202 #define USB_CBI_ADSC_REQUEST 0x00
205 /* Length of a SCSI Command Data Block */
206 #define MAX_COMMAND_SIZE 16
208 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
209 #define SS_NO_SENSE 0
210 #define SS_COMMUNICATION_FAILURE 0x040800
211 #define SS_INVALID_COMMAND 0x052000
212 #define SS_INVALID_FIELD_IN_CDB 0x052400
213 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
214 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
215 #define SS_MEDIUM_NOT_PRESENT 0x023a00
216 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
217 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
218 #define SS_RESET_OCCURRED 0x062900
219 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
220 #define SS_UNRECOVERED_READ_ERROR 0x031100
221 #define SS_WRITE_ERROR 0x030c02
222 #define SS_WRITE_PROTECTED 0x072700
224 #define SK(x) ((u8) ((x) >> 16)) /* Sense Key byte, etc. */
225 #define ASC(x) ((u8) ((x) >> 8))
226 #define ASCQ(x) ((u8) (x))
229 /*-------------------------------------------------------------------------*/
237 unsigned int initially_ro:1;
239 unsigned int removable:1;
240 unsigned int cdrom:1;
241 unsigned int prevent_medium_removal:1;
242 unsigned int registered:1;
243 unsigned int info_valid:1;
244 unsigned int nofua:1;
248 u32 unit_attention_data;
250 unsigned int blkbits; /* Bits of logical block size of bound block device */
251 unsigned int blksize; /* logical block size of bound block device */
255 #define fsg_lun_is_open(curlun) ((curlun)->filp != NULL)
257 static struct fsg_lun *fsg_lun_from_dev(struct device *dev)
259 return container_of(dev, struct fsg_lun, dev);
263 /* Big enough to hold our biggest descriptor */
264 #define EP0_BUFSIZE 256
265 #define DELAYED_STATUS (EP0_BUFSIZE + 999) /* An impossibly large value */
267 /* Number of buffers we will use. 2 is enough for double-buffering */
268 #define FSG_NUM_BUFFERS 2
270 /* Default size of buffer length. */
271 #define FSG_BUFLEN ((u32)16384)
273 /* Maximal number of LUNs supported in mass storage function */
274 #define FSG_MAX_LUNS 8
276 enum fsg_buffer_state {
283 #ifdef FSG_BUFFHD_STATIC_BUFFER
284 char buf[FSG_BUFLEN];
288 enum fsg_buffer_state state;
289 struct fsg_buffhd *next;
292 * The NetChip 2280 is faster, and handles some protocol faults
293 * better, if we don't submit any short bulk-out read requests.
294 * So we will record the intended request length here.
296 unsigned int bulk_out_intended_length;
298 struct usb_request *inreq;
300 struct usb_request *outreq;
305 /* This one isn't used anywhere */
306 FSG_STATE_COMMAND_PHASE = -10,
307 FSG_STATE_DATA_PHASE,
308 FSG_STATE_STATUS_PHASE,
311 FSG_STATE_ABORT_BULK_OUT,
313 FSG_STATE_INTERFACE_CHANGE,
314 FSG_STATE_CONFIG_CHANGE,
315 FSG_STATE_DISCONNECT,
320 enum data_direction {
321 DATA_DIR_UNKNOWN = 0,
328 /*-------------------------------------------------------------------------*/
331 static inline u32 get_unaligned_be24(u8 *buf)
333 return 0xffffff & (u32) get_unaligned_be32(buf - 1);
337 /*-------------------------------------------------------------------------*/
341 #ifndef FSG_NO_DEVICE_STRINGS
342 FSG_STRING_MANUFACTURER = 1,
352 static struct usb_otg_descriptor
354 .bLength = sizeof fsg_otg_desc,
355 .bDescriptorType = USB_DT_OTG,
357 .bmAttributes = USB_OTG_SRP,
361 /* There is only one interface. */
363 static struct usb_interface_descriptor
365 .bLength = sizeof fsg_intf_desc,
366 .bDescriptorType = USB_DT_INTERFACE,
368 .bNumEndpoints = 2, /* Adjusted during fsg_bind() */
369 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
370 .bInterfaceSubClass = USB_SC_SCSI, /* Adjusted during fsg_bind() */
371 .bInterfaceProtocol = USB_PR_BULK, /* Adjusted during fsg_bind() */
372 .iInterface = FSG_STRING_INTERFACE,
376 * Three full-speed endpoint descriptors: bulk-in, bulk-out, and
380 static struct usb_endpoint_descriptor
381 fsg_fs_bulk_in_desc = {
382 .bLength = USB_DT_ENDPOINT_SIZE,
383 .bDescriptorType = USB_DT_ENDPOINT,
385 .bEndpointAddress = USB_DIR_IN,
386 .bmAttributes = USB_ENDPOINT_XFER_BULK,
387 /* wMaxPacketSize set by autoconfiguration */
390 static struct usb_endpoint_descriptor
391 fsg_fs_bulk_out_desc = {
392 .bLength = USB_DT_ENDPOINT_SIZE,
393 .bDescriptorType = USB_DT_ENDPOINT,
395 .bEndpointAddress = USB_DIR_OUT,
396 .bmAttributes = USB_ENDPOINT_XFER_BULK,
397 /* wMaxPacketSize set by autoconfiguration */
400 #ifndef FSG_NO_INTR_EP
402 static struct usb_endpoint_descriptor
403 fsg_fs_intr_in_desc = {
404 .bLength = USB_DT_ENDPOINT_SIZE,
405 .bDescriptorType = USB_DT_ENDPOINT,
407 .bEndpointAddress = USB_DIR_IN,
408 .bmAttributes = USB_ENDPOINT_XFER_INT,
409 .wMaxPacketSize = cpu_to_le16(2),
410 .bInterval = 32, /* frames -> 32 ms */
414 # define FSG_FS_FUNCTION_PRE_EP_ENTRIES 2
416 # define FSG_FS_FUNCTION_PRE_EP_ENTRIES 1
421 static struct usb_descriptor_header *fsg_fs_function[] = {
423 (struct usb_descriptor_header *) &fsg_otg_desc,
425 (struct usb_descriptor_header *) &fsg_intf_desc,
426 (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
427 (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
428 #ifndef FSG_NO_INTR_EP
429 (struct usb_descriptor_header *) &fsg_fs_intr_in_desc,
436 * USB 2.0 devices need to expose both high speed and full speed
437 * descriptors, unless they only run at full speed.
439 * That means alternate endpoint descriptors (bigger packets)
440 * and a "device qualifier" ... plus more construction options
441 * for the configuration descriptor.
443 static struct usb_endpoint_descriptor
444 fsg_hs_bulk_in_desc = {
445 .bLength = USB_DT_ENDPOINT_SIZE,
446 .bDescriptorType = USB_DT_ENDPOINT,
448 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
449 .bmAttributes = USB_ENDPOINT_XFER_BULK,
450 .wMaxPacketSize = cpu_to_le16(512),
453 static struct usb_endpoint_descriptor
454 fsg_hs_bulk_out_desc = {
455 .bLength = USB_DT_ENDPOINT_SIZE,
456 .bDescriptorType = USB_DT_ENDPOINT,
458 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
459 .bmAttributes = USB_ENDPOINT_XFER_BULK,
460 .wMaxPacketSize = cpu_to_le16(512),
461 .bInterval = 1, /* NAK every 1 uframe */
464 #ifndef FSG_NO_INTR_EP
466 static struct usb_endpoint_descriptor
467 fsg_hs_intr_in_desc = {
468 .bLength = USB_DT_ENDPOINT_SIZE,
469 .bDescriptorType = USB_DT_ENDPOINT,
471 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
472 .bmAttributes = USB_ENDPOINT_XFER_INT,
473 .wMaxPacketSize = cpu_to_le16(2),
474 .bInterval = 9, /* 2**(9-1) = 256 uframes -> 32 ms */
478 # define FSG_HS_FUNCTION_PRE_EP_ENTRIES 2
480 # define FSG_HS_FUNCTION_PRE_EP_ENTRIES 1
485 static struct usb_descriptor_header *fsg_hs_function[] = {
487 (struct usb_descriptor_header *) &fsg_otg_desc,
489 (struct usb_descriptor_header *) &fsg_intf_desc,
490 (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
491 (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
492 #ifndef FSG_NO_INTR_EP
493 (struct usb_descriptor_header *) &fsg_hs_intr_in_desc,
498 /* Maxpacket and other transfer characteristics vary by speed. */
499 static __maybe_unused struct usb_endpoint_descriptor *
500 fsg_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
501 struct usb_endpoint_descriptor *hs)
503 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
509 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
510 static struct usb_string fsg_strings[] = {
511 #ifndef FSG_NO_DEVICE_STRINGS
512 {FSG_STRING_MANUFACTURER, fsg_string_manufacturer},
513 {FSG_STRING_PRODUCT, fsg_string_product},
514 {FSG_STRING_SERIAL, ""},
515 {FSG_STRING_CONFIG, fsg_string_config},
517 {FSG_STRING_INTERFACE, fsg_string_interface},
521 static struct usb_gadget_strings fsg_stringtab = {
522 .language = 0x0409, /* en-us */
523 .strings = fsg_strings,
527 /*-------------------------------------------------------------------------*/
530 * If the next two routines are called while the gadget is registered,
531 * the caller must own fsg->filesem for writing.
534 static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
537 struct file *filp = NULL;
539 struct inode *inode = NULL;
544 /* R/W if we can, R/O if we must */
545 ro = curlun->initially_ro;
547 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
548 if (PTR_ERR(filp) == -EROFS || PTR_ERR(filp) == -EACCES)
552 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
554 LINFO(curlun, "unable to open backing file: %s\n", filename);
555 return PTR_ERR(filp);
558 if (!(filp->f_mode & FMODE_WRITE))
561 if (filp->f_path.dentry)
562 inode = filp->f_path.dentry->d_inode;
563 if (!inode || (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))) {
564 LINFO(curlun, "invalid file type: %s\n", filename);
569 * If we can't read the file, it's no good.
570 * If we can't write the file, use it read-only.
572 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
573 LINFO(curlun, "file not readable: %s\n", filename);
576 if (!(filp->f_op->write || filp->f_op->aio_write))
579 size = i_size_read(inode->i_mapping->host);
581 LINFO(curlun, "unable to find file size: %s\n", filename);
587 curlun->blksize = 2048;
588 curlun->blkbits = 11;
589 } else if (inode->i_bdev) {
590 curlun->blksize = bdev_logical_block_size(inode->i_bdev);
591 curlun->blkbits = blksize_bits(curlun->blksize);
593 curlun->blksize = 512;
597 num_sectors = size >> curlun->blkbits; /* File size in logic-block-size blocks */
600 min_sectors = 300; /* Smallest track is 300 frames */
601 if (num_sectors >= 256*60*75) {
602 num_sectors = 256*60*75 - 1;
603 LINFO(curlun, "file too big: %s\n", filename);
604 LINFO(curlun, "using only first %d blocks\n",
608 if (num_sectors < min_sectors) {
609 LINFO(curlun, "file too small: %s\n", filename);
617 curlun->file_length = size;
618 curlun->num_sectors = num_sectors;
619 LDBG(curlun, "open backing file: %s\n", filename);
623 filp_close(filp, current->files);
628 static void fsg_lun_close(struct fsg_lun *curlun)
631 LDBG(curlun, "close backing file\n");
638 /*-------------------------------------------------------------------------*/
641 * Sync the file data, don't bother with the metadata.
642 * This code was copied from fs/buffer.c:sys_fdatasync().
644 static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
646 struct file *filp = curlun->filp;
648 if (curlun->ro || !filp)
650 return vfs_fsync(filp, 1);
653 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
656 /* Convert to Minutes-Seconds-Frames */
657 addr >>= 2; /* Convert to 2048-byte frames */
658 addr += 2*75; /* Lead-in occupies 2 seconds */
659 dest[3] = addr % 75; /* Frames */
661 dest[2] = addr % 60; /* Seconds */
663 dest[1] = addr; /* Minutes */
664 dest[0] = 0; /* Reserved */
666 /* Absolute sector */
667 put_unaligned_be32(addr, dest);
672 /*-------------------------------------------------------------------------*/
675 static ssize_t fsg_show_ro(struct device *dev, struct device_attribute *attr,
678 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
680 return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
682 : curlun->initially_ro);
685 static ssize_t fsg_show_nofua(struct device *dev, struct device_attribute *attr,
688 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
690 return sprintf(buf, "%u\n", curlun->nofua);
693 static ssize_t fsg_show_file(struct device *dev, struct device_attribute *attr,
696 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
697 struct rw_semaphore *filesem = dev_get_drvdata(dev);
702 if (fsg_lun_is_open(curlun)) { /* Get the complete pathname */
703 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
709 buf[rc] = '\n'; /* Add a newline */
712 } else { /* No file, return 0 bytes */
721 static ssize_t fsg_store_ro(struct device *dev, struct device_attribute *attr,
722 const char *buf, size_t count)
725 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
726 struct rw_semaphore *filesem = dev_get_drvdata(dev);
729 rc = kstrtouint(buf, 2, &ro);
734 * Allow the write-enable status to change only while the
735 * backing file is closed.
738 if (fsg_lun_is_open(curlun)) {
739 LDBG(curlun, "read-only status change prevented\n");
743 curlun->initially_ro = ro;
744 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
751 static ssize_t fsg_store_nofua(struct device *dev,
752 struct device_attribute *attr,
753 const char *buf, size_t count)
755 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
759 ret = kstrtouint(buf, 2, &nofua);
763 /* Sync data when switching from async mode to sync */
764 if (!nofua && curlun->nofua)
765 fsg_lun_fsync_sub(curlun);
767 curlun->nofua = nofua;
772 static ssize_t fsg_store_file(struct device *dev, struct device_attribute *attr,
773 const char *buf, size_t count)
775 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
776 struct rw_semaphore *filesem = dev_get_drvdata(dev);
779 if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
780 LDBG(curlun, "eject attempt prevented\n");
781 return -EBUSY; /* "Door is locked" */
784 /* Remove a trailing newline */
785 if (count > 0 && buf[count-1] == '\n')
786 ((char *) buf)[count-1] = 0; /* Ugh! */
788 /* Eject current medium */
790 if (fsg_lun_is_open(curlun)) {
791 fsg_lun_close(curlun);
792 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
795 /* Load new medium */
796 if (count > 0 && buf[0]) {
797 rc = fsg_lun_open(curlun, buf);
799 curlun->unit_attention_data =
800 SS_NOT_READY_TO_READY_TRANSITION;
803 return (rc < 0 ? rc : count);