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_serial -- product's serial
30 * - fsg_string_config -- name of the configuration
31 * - fsg_string_interface -- name of the interface
32 * The first four are only needed when FSG_DESCRIPTORS_DEVICE_STRINGS
33 * macro is defined prior to including this file.
37 * When FSG_NO_INTR_EP is defined fsg_fs_intr_in_desc and
38 * fsg_hs_intr_in_desc objects as well as
39 * FSG_FS_FUNCTION_PRE_EP_ENTRIES and FSG_HS_FUNCTION_PRE_EP_ENTRIES
40 * macros are not defined.
42 * When FSG_NO_DEVICE_STRINGS is defined FSG_STRING_MANUFACTURER,
43 * FSG_STRING_PRODUCT, FSG_STRING_SERIAL and FSG_STRING_CONFIG are not
44 * defined (as well as corresponding entries in string tables are
45 * missing) and FSG_STRING_INTERFACE has value of zero.
47 * When FSG_NO_OTG is defined fsg_otg_desc won't be defined.
51 #include <asm/unaligned.h>
54 /* Thanks to NetChip Technologies for donating this product ID.
56 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
57 * Instead: allocate your own, using normal USB-IF procedures. */
58 #define FSG_VENDOR_ID 0x0525 // NetChip
59 #define FSG_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
62 /*-------------------------------------------------------------------------*/
73 #define VLDBG(lun, fmt, args...) do { } while (0)
74 #endif /* VERBOSE_DEBUG */
76 #define LDBG(lun, fmt, args...) dev_dbg (&(lun)->dev, fmt, ## args)
77 #define LERROR(lun, fmt, args...) dev_err (&(lun)->dev, fmt, ## args)
78 #define LWARN(lun, fmt, args...) dev_warn(&(lun)->dev, fmt, ## args)
79 #define LINFO(lun, fmt, args...) dev_info(&(lun)->dev, fmt, ## args)
81 #define DBG(d, fmt, args...) dev_dbg (&(d)->gadget->dev, fmt, ## args)
82 #define VDBG(d, fmt, args...) dev_vdbg(&(d)->gadget->dev, fmt, ## args)
83 #define ERROR(d, fmt, args...) dev_err (&(d)->gadget->dev, fmt, ## args)
84 #define WARNING(d, fmt, args...) dev_warn(&(d)->gadget->dev, fmt, ## args)
85 #define INFO(d, fmt, args...) dev_info(&(d)->gadget->dev, fmt, ## args)
91 # define dump_msg(fsg, /* const char * */ label, \
92 /* const u8 * */ buf, /* unsigned */ length) do { \
94 DBG(fsg, "%s, length %u:\n", label, length); \
95 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, \
96 16, 1, buf, length, 0); \
100 # define dump_cdb(fsg) do { } while (0)
104 # define dump_msg(fsg, /* const char * */ label, \
105 /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
107 # ifdef VERBOSE_DEBUG
109 #define dump_cdb(fsg) \
110 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE, \
111 16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0) \
115 # define dump_cdb(fsg) do { } while (0)
117 # endif /* VERBOSE_DEBUG */
119 #endif /* DUMP_MSGS */
125 /*-------------------------------------------------------------------------*/
127 /* SCSI device types */
128 #define TYPE_DISK 0x00
129 #define TYPE_CDROM 0x05
131 /* USB protocol value = the transport method */
132 #define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
133 #define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
134 #define USB_PR_BULK 0x50 // Bulk-only
136 /* USB subclass value = the protocol encapsulation */
137 #define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
138 #define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
139 #define USB_SC_QIC 0x03 // QIC-157 (tape)
140 #define USB_SC_UFI 0x04 // UFI (floppy)
141 #define USB_SC_8070 0x05 // SFF-8070i (removable)
142 #define USB_SC_SCSI 0x06 // Transparent SCSI
144 /* Bulk-only data structures */
146 /* Command Block Wrapper */
147 struct fsg_bulk_cb_wrap {
148 __le32 Signature; // Contains 'USBC'
149 u32 Tag; // Unique per command id
150 __le32 DataTransferLength; // Size of the data
151 u8 Flags; // Direction in bit 7
152 u8 Lun; // LUN (normally 0)
153 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
154 u8 CDB[16]; // Command Data Block
157 #define USB_BULK_CB_WRAP_LEN 31
158 #define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
159 #define USB_BULK_IN_FLAG 0x80
161 /* Command Status Wrapper */
162 struct bulk_cs_wrap {
163 __le32 Signature; // Should = 'USBS'
164 u32 Tag; // Same as original command
165 __le32 Residue; // Amount not transferred
166 u8 Status; // See below
169 #define USB_BULK_CS_WRAP_LEN 13
170 #define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
171 #define USB_STATUS_PASS 0
172 #define USB_STATUS_FAIL 1
173 #define USB_STATUS_PHASE_ERROR 2
175 /* Bulk-only class specific requests */
176 #define USB_BULK_RESET_REQUEST 0xff
177 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
180 /* CBI Interrupt data structure */
181 struct interrupt_data {
186 #define CBI_INTERRUPT_DATA_LEN 2
188 /* CBI Accept Device-Specific Command request */
189 #define USB_CBI_ADSC_REQUEST 0x00
192 #define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
194 /* SCSI commands that we recognize */
195 #define SC_FORMAT_UNIT 0x04
196 #define SC_INQUIRY 0x12
197 #define SC_MODE_SELECT_6 0x15
198 #define SC_MODE_SELECT_10 0x55
199 #define SC_MODE_SENSE_6 0x1a
200 #define SC_MODE_SENSE_10 0x5a
201 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
202 #define SC_READ_6 0x08
203 #define SC_READ_10 0x28
204 #define SC_READ_12 0xa8
205 #define SC_READ_CAPACITY 0x25
206 #define SC_READ_FORMAT_CAPACITIES 0x23
207 #define SC_READ_HEADER 0x44
208 #define SC_READ_TOC 0x43
209 #define SC_RELEASE 0x17
210 #define SC_REQUEST_SENSE 0x03
211 #define SC_RESERVE 0x16
212 #define SC_SEND_DIAGNOSTIC 0x1d
213 #define SC_START_STOP_UNIT 0x1b
214 #define SC_SYNCHRONIZE_CACHE 0x35
215 #define SC_TEST_UNIT_READY 0x00
216 #define SC_VERIFY 0x2f
217 #define SC_WRITE_6 0x0a
218 #define SC_WRITE_10 0x2a
219 #define SC_WRITE_12 0xaa
221 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
222 #define SS_NO_SENSE 0
223 #define SS_COMMUNICATION_FAILURE 0x040800
224 #define SS_INVALID_COMMAND 0x052000
225 #define SS_INVALID_FIELD_IN_CDB 0x052400
226 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
227 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
228 #define SS_MEDIUM_NOT_PRESENT 0x023a00
229 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
230 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
231 #define SS_RESET_OCCURRED 0x062900
232 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
233 #define SS_UNRECOVERED_READ_ERROR 0x031100
234 #define SS_WRITE_ERROR 0x030c02
235 #define SS_WRITE_PROTECTED 0x072700
237 #define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
238 #define ASC(x) ((u8) ((x) >> 8))
239 #define ASCQ(x) ((u8) (x))
242 /*-------------------------------------------------------------------------*/
250 unsigned int initially_ro : 1;
252 unsigned int removable : 1;
253 unsigned int cdrom : 1;
254 unsigned int prevent_medium_removal : 1;
255 unsigned int registered : 1;
256 unsigned int info_valid : 1;
260 u32 unit_attention_data;
265 #define fsg_lun_is_open(curlun) ((curlun)->filp != NULL)
267 static struct fsg_lun *fsg_lun_from_dev(struct device *dev)
269 return container_of(dev, struct fsg_lun, dev);
273 /* Big enough to hold our biggest descriptor */
274 #define EP0_BUFSIZE 256
275 #define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
277 /* Number of buffers we will use. 2 is enough for double-buffering */
278 #define FSG_NUM_BUFFERS 2
280 /* Default size of buffer length. */
281 #define FSG_BUFLEN ((u32)16384)
283 /* Maximal number of LUNs supported in mass storage function */
284 #define FSG_MAX_LUNS 8
286 enum fsg_buffer_state {
294 enum fsg_buffer_state state;
295 struct fsg_buffhd *next;
297 /* The NetChip 2280 is faster, and handles some protocol faults
298 * better, if we don't submit any short bulk-out read requests.
299 * So we will record the intended request length here. */
300 unsigned int bulk_out_intended_length;
302 struct usb_request *inreq;
304 struct usb_request *outreq;
309 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
310 FSG_STATE_DATA_PHASE,
311 FSG_STATE_STATUS_PHASE,
314 FSG_STATE_ABORT_BULK_OUT,
316 FSG_STATE_INTERFACE_CHANGE,
317 FSG_STATE_CONFIG_CHANGE,
318 FSG_STATE_DISCONNECT,
323 enum data_direction {
324 DATA_DIR_UNKNOWN = 0,
331 /*-------------------------------------------------------------------------*/
334 static inline u32 get_unaligned_be24(u8 *buf)
336 return 0xffffff & (u32) get_unaligned_be32(buf - 1);
340 /*-------------------------------------------------------------------------*/
344 #ifndef FSG_NO_DEVICE_STRINGS
345 FSG_STRING_MANUFACTURER = 1,
355 static struct usb_otg_descriptor
357 .bLength = sizeof fsg_otg_desc,
358 .bDescriptorType = USB_DT_OTG,
360 .bmAttributes = USB_OTG_SRP,
364 /* There is only one interface. */
366 static struct usb_interface_descriptor
368 .bLength = sizeof fsg_intf_desc,
369 .bDescriptorType = USB_DT_INTERFACE,
371 .bNumEndpoints = 2, // Adjusted during fsg_bind()
372 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
373 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
374 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
375 .iInterface = FSG_STRING_INTERFACE,
378 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
379 * and interrupt-in. */
381 static struct usb_endpoint_descriptor
382 fsg_fs_bulk_in_desc = {
383 .bLength = USB_DT_ENDPOINT_SIZE,
384 .bDescriptorType = USB_DT_ENDPOINT,
386 .bEndpointAddress = USB_DIR_IN,
387 .bmAttributes = USB_ENDPOINT_XFER_BULK,
388 /* wMaxPacketSize set by autoconfiguration */
391 static struct usb_endpoint_descriptor
392 fsg_fs_bulk_out_desc = {
393 .bLength = USB_DT_ENDPOINT_SIZE,
394 .bDescriptorType = USB_DT_ENDPOINT,
396 .bEndpointAddress = USB_DIR_OUT,
397 .bmAttributes = USB_ENDPOINT_XFER_BULK,
398 /* wMaxPacketSize set by autoconfiguration */
401 #ifndef FSG_NO_INTR_EP
403 static struct usb_endpoint_descriptor
404 fsg_fs_intr_in_desc = {
405 .bLength = USB_DT_ENDPOINT_SIZE,
406 .bDescriptorType = USB_DT_ENDPOINT,
408 .bEndpointAddress = USB_DIR_IN,
409 .bmAttributes = USB_ENDPOINT_XFER_INT,
410 .wMaxPacketSize = cpu_to_le16(2),
411 .bInterval = 32, // frames -> 32 ms
415 # define FSG_FS_FUNCTION_PRE_EP_ENTRIES 2
417 # define FSG_FS_FUNCTION_PRE_EP_ENTRIES 1
422 static const struct usb_descriptor_header *fsg_fs_function[] = {
424 (struct usb_descriptor_header *) &fsg_otg_desc,
426 (struct usb_descriptor_header *) &fsg_intf_desc,
427 (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
428 (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
429 #ifndef FSG_NO_INTR_EP
430 (struct usb_descriptor_header *) &fsg_fs_intr_in_desc,
437 * USB 2.0 devices need to expose both high speed and full speed
438 * descriptors, unless they only run at full speed.
440 * That means alternate endpoint descriptors (bigger packets)
441 * and a "device qualifier" ... plus more construction options
442 * for the config descriptor.
444 static struct usb_endpoint_descriptor
445 fsg_hs_bulk_in_desc = {
446 .bLength = USB_DT_ENDPOINT_SIZE,
447 .bDescriptorType = USB_DT_ENDPOINT,
449 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
450 .bmAttributes = USB_ENDPOINT_XFER_BULK,
451 .wMaxPacketSize = cpu_to_le16(512),
454 static struct usb_endpoint_descriptor
455 fsg_hs_bulk_out_desc = {
456 .bLength = USB_DT_ENDPOINT_SIZE,
457 .bDescriptorType = USB_DT_ENDPOINT,
459 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
460 .bmAttributes = USB_ENDPOINT_XFER_BULK,
461 .wMaxPacketSize = cpu_to_le16(512),
462 .bInterval = 1, // NAK every 1 uframe
465 #ifndef FSG_NO_INTR_EP
467 static struct usb_endpoint_descriptor
468 fsg_hs_intr_in_desc = {
469 .bLength = USB_DT_ENDPOINT_SIZE,
470 .bDescriptorType = USB_DT_ENDPOINT,
472 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
473 .bmAttributes = USB_ENDPOINT_XFER_INT,
474 .wMaxPacketSize = cpu_to_le16(2),
475 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
479 # define FSG_HS_FUNCTION_PRE_EP_ENTRIES 2
481 # define FSG_HS_FUNCTION_PRE_EP_ENTRIES 1
486 static const struct usb_descriptor_header *fsg_hs_function[] = {
488 (struct usb_descriptor_header *) &fsg_otg_desc,
490 (struct usb_descriptor_header *) &fsg_intf_desc,
491 (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
492 (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
493 #ifndef FSG_NO_INTR_EP
494 (struct usb_descriptor_header *) &fsg_hs_intr_in_desc,
499 /* Maxpacket and other transfer characteristics vary by speed. */
500 static struct usb_endpoint_descriptor *
501 fsg_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
502 struct usb_endpoint_descriptor *hs)
504 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
510 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
511 static struct usb_string fsg_strings[] = {
512 #ifndef FSG_NO_DEVICE_STRINGS
513 {FSG_STRING_MANUFACTURER, fsg_string_manufacturer},
514 {FSG_STRING_PRODUCT, fsg_string_product},
515 {FSG_STRING_SERIAL, fsg_string_serial},
516 {FSG_STRING_CONFIG, fsg_string_config},
518 {FSG_STRING_INTERFACE, fsg_string_interface},
522 static struct usb_gadget_strings fsg_stringtab = {
523 .language = 0x0409, // en-us
524 .strings = fsg_strings,
528 /*-------------------------------------------------------------------------*/
530 /* If the next two routines are called while the gadget is registered,
531 * the caller must own fsg->filesem for writing. */
533 static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
536 struct file *filp = NULL;
538 struct inode *inode = NULL;
543 /* R/W if we can, R/O if we must */
544 ro = curlun->initially_ro;
546 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
547 if (-EROFS == PTR_ERR(filp))
551 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
553 LINFO(curlun, "unable to open backing file: %s\n", filename);
554 return PTR_ERR(filp);
557 if (!(filp->f_mode & FMODE_WRITE))
560 if (filp->f_path.dentry)
561 inode = filp->f_path.dentry->d_inode;
562 if (inode && S_ISBLK(inode->i_mode)) {
563 if (bdev_read_only(inode->i_bdev))
565 } else if (!inode || !S_ISREG(inode->i_mode)) {
566 LINFO(curlun, "invalid file type: %s\n", filename);
570 /* If we can't read the file, it's no good.
571 * 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);
585 num_sectors = size >> 9; // File size in 512-byte blocks
588 num_sectors &= ~3; // Reduce to a multiple of 2048
589 min_sectors = 300*4; // Smallest track is 300 frames
590 if (num_sectors >= 256*60*75*4) {
591 num_sectors = (256*60*75 - 1) * 4;
592 LINFO(curlun, "file too big: %s\n", filename);
593 LINFO(curlun, "using only first %d blocks\n",
597 if (num_sectors < min_sectors) {
598 LINFO(curlun, "file too small: %s\n", filename);
606 curlun->file_length = size;
607 curlun->num_sectors = num_sectors;
608 LDBG(curlun, "open backing file: %s\n", filename);
612 filp_close(filp, current->files);
617 static void fsg_lun_close(struct fsg_lun *curlun)
620 LDBG(curlun, "close backing file\n");
627 /*-------------------------------------------------------------------------*/
629 /* Sync the file data, don't bother with the metadata.
630 * This code was copied from fs/buffer.c:sys_fdatasync(). */
631 static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
633 struct file *filp = curlun->filp;
635 if (curlun->ro || !filp)
637 return vfs_fsync(filp, filp->f_path.dentry, 1);
640 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
643 /* Convert to Minutes-Seconds-Frames */
644 addr >>= 2; /* Convert to 2048-byte frames */
645 addr += 2*75; /* Lead-in occupies 2 seconds */
646 dest[3] = addr % 75; /* Frames */
648 dest[2] = addr % 60; /* Seconds */
650 dest[1] = addr; /* Minutes */
651 dest[0] = 0; /* Reserved */
653 /* Absolute sector */
654 put_unaligned_be32(addr, dest);
659 /*-------------------------------------------------------------------------*/
662 static ssize_t fsg_show_ro(struct device *dev, struct device_attribute *attr,
665 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
667 return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
669 : curlun->initially_ro);
672 static ssize_t fsg_show_file(struct device *dev, struct device_attribute *attr,
675 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
676 struct rw_semaphore *filesem = dev_get_drvdata(dev);
681 if (fsg_lun_is_open(curlun)) { // Get the complete pathname
682 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
688 buf[rc] = '\n'; // Add a newline
691 } else { // No file, return 0 bytes
700 static ssize_t fsg_store_ro(struct device *dev, struct device_attribute *attr,
701 const char *buf, size_t count)
704 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
705 struct rw_semaphore *filesem = dev_get_drvdata(dev);
708 if (sscanf(buf, "%d", &i) != 1)
711 /* Allow the write-enable status to change only while the backing file
714 if (fsg_lun_is_open(curlun)) {
715 LDBG(curlun, "read-only status change prevented\n");
719 curlun->initially_ro = !!i;
720 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
726 static ssize_t fsg_store_file(struct device *dev, struct device_attribute *attr,
727 const char *buf, size_t count)
729 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
730 struct rw_semaphore *filesem = dev_get_drvdata(dev);
733 if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
734 LDBG(curlun, "eject attempt prevented\n");
735 return -EBUSY; // "Door is locked"
738 /* Remove a trailing newline */
739 if (count > 0 && buf[count-1] == '\n')
740 ((char *) buf)[count-1] = 0; // Ugh!
742 /* Eject current medium */
744 if (fsg_lun_is_open(curlun)) {
745 fsg_lun_close(curlun);
746 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
749 /* Load new medium */
750 if (count > 0 && buf[0]) {
751 rc = fsg_lun_open(curlun, buf);
753 curlun->unit_attention_data =
754 SS_NOT_READY_TO_READY_TRANSITION;
757 return (rc < 0 ? rc : count);