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 * When FSG_BUFFHD_STATIC_BUFFER is defined when this file is included
52 * the fsg_buffhd structure's buf field will be an array of FSG_BUFLEN
53 * characters rather then a pointer to void.
57 #include <asm/unaligned.h>
60 /* Thanks to NetChip Technologies for donating this product ID.
62 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
63 * Instead: allocate your own, using normal USB-IF procedures. */
64 #define FSG_VENDOR_ID 0x0525 // NetChip
65 #define FSG_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
68 /*-------------------------------------------------------------------------*/
79 #define VLDBG(lun, fmt, args...) do { } while (0)
80 #endif /* VERBOSE_DEBUG */
82 #define LDBG(lun, fmt, args...) dev_dbg (&(lun)->dev, fmt, ## args)
83 #define LERROR(lun, fmt, args...) dev_err (&(lun)->dev, fmt, ## args)
84 #define LWARN(lun, fmt, args...) dev_warn(&(lun)->dev, fmt, ## args)
85 #define LINFO(lun, fmt, args...) dev_info(&(lun)->dev, fmt, ## args)
87 #define DBG(d, fmt, args...) dev_dbg (&(d)->gadget->dev, fmt, ## args)
88 #define VDBG(d, fmt, args...) dev_vdbg(&(d)->gadget->dev, fmt, ## args)
89 #define ERROR(d, fmt, args...) dev_err (&(d)->gadget->dev, fmt, ## args)
90 #define WARNING(d, fmt, args...) dev_warn(&(d)->gadget->dev, fmt, ## args)
91 #define INFO(d, fmt, args...) dev_info(&(d)->gadget->dev, fmt, ## args)
97 # define dump_msg(fsg, /* const char * */ label, \
98 /* const u8 * */ buf, /* unsigned */ length) do { \
100 DBG(fsg, "%s, length %u:\n", label, length); \
101 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, \
102 16, 1, buf, length, 0); \
106 # define dump_cdb(fsg) do { } while (0)
110 # define dump_msg(fsg, /* const char * */ label, \
111 /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
113 # ifdef VERBOSE_DEBUG
115 #define dump_cdb(fsg) \
116 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE, \
117 16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0) \
121 # define dump_cdb(fsg) do { } while (0)
123 # endif /* VERBOSE_DEBUG */
125 #endif /* DUMP_MSGS */
131 /*-------------------------------------------------------------------------*/
133 /* SCSI device types */
134 #define TYPE_DISK 0x00
135 #define TYPE_CDROM 0x05
137 /* USB protocol value = the transport method */
138 #define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
139 #define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
140 #define USB_PR_BULK 0x50 // Bulk-only
142 /* USB subclass value = the protocol encapsulation */
143 #define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
144 #define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
145 #define USB_SC_QIC 0x03 // QIC-157 (tape)
146 #define USB_SC_UFI 0x04 // UFI (floppy)
147 #define USB_SC_8070 0x05 // SFF-8070i (removable)
148 #define USB_SC_SCSI 0x06 // Transparent SCSI
150 /* Bulk-only data structures */
152 /* Command Block Wrapper */
153 struct fsg_bulk_cb_wrap {
154 __le32 Signature; // Contains 'USBC'
155 u32 Tag; // Unique per command id
156 __le32 DataTransferLength; // Size of the data
157 u8 Flags; // Direction in bit 7
158 u8 Lun; // LUN (normally 0)
159 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
160 u8 CDB[16]; // Command Data Block
163 #define USB_BULK_CB_WRAP_LEN 31
164 #define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
165 #define USB_BULK_IN_FLAG 0x80
167 /* Command Status Wrapper */
168 struct bulk_cs_wrap {
169 __le32 Signature; // Should = 'USBS'
170 u32 Tag; // Same as original command
171 __le32 Residue; // Amount not transferred
172 u8 Status; // See below
175 #define USB_BULK_CS_WRAP_LEN 13
176 #define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
177 #define USB_STATUS_PASS 0
178 #define USB_STATUS_FAIL 1
179 #define USB_STATUS_PHASE_ERROR 2
181 /* Bulk-only class specific requests */
182 #define USB_BULK_RESET_REQUEST 0xff
183 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
186 /* CBI Interrupt data structure */
187 struct interrupt_data {
192 #define CBI_INTERRUPT_DATA_LEN 2
194 /* CBI Accept Device-Specific Command request */
195 #define USB_CBI_ADSC_REQUEST 0x00
198 #define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
200 /* SCSI commands that we recognize */
201 #define SC_FORMAT_UNIT 0x04
202 #define SC_INQUIRY 0x12
203 #define SC_MODE_SELECT_6 0x15
204 #define SC_MODE_SELECT_10 0x55
205 #define SC_MODE_SENSE_6 0x1a
206 #define SC_MODE_SENSE_10 0x5a
207 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
208 #define SC_READ_6 0x08
209 #define SC_READ_10 0x28
210 #define SC_READ_12 0xa8
211 #define SC_READ_CAPACITY 0x25
212 #define SC_READ_FORMAT_CAPACITIES 0x23
213 #define SC_READ_HEADER 0x44
214 #define SC_READ_TOC 0x43
215 #define SC_RELEASE 0x17
216 #define SC_REQUEST_SENSE 0x03
217 #define SC_RESERVE 0x16
218 #define SC_SEND_DIAGNOSTIC 0x1d
219 #define SC_START_STOP_UNIT 0x1b
220 #define SC_SYNCHRONIZE_CACHE 0x35
221 #define SC_TEST_UNIT_READY 0x00
222 #define SC_VERIFY 0x2f
223 #define SC_WRITE_6 0x0a
224 #define SC_WRITE_10 0x2a
225 #define SC_WRITE_12 0xaa
227 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
228 #define SS_NO_SENSE 0
229 #define SS_COMMUNICATION_FAILURE 0x040800
230 #define SS_INVALID_COMMAND 0x052000
231 #define SS_INVALID_FIELD_IN_CDB 0x052400
232 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
233 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
234 #define SS_MEDIUM_NOT_PRESENT 0x023a00
235 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
236 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
237 #define SS_RESET_OCCURRED 0x062900
238 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
239 #define SS_UNRECOVERED_READ_ERROR 0x031100
240 #define SS_WRITE_ERROR 0x030c02
241 #define SS_WRITE_PROTECTED 0x072700
243 #define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
244 #define ASC(x) ((u8) ((x) >> 8))
245 #define ASCQ(x) ((u8) (x))
248 /*-------------------------------------------------------------------------*/
256 unsigned int initially_ro : 1;
258 unsigned int removable : 1;
259 unsigned int cdrom : 1;
260 unsigned int prevent_medium_removal : 1;
261 unsigned int registered : 1;
262 unsigned int info_valid : 1;
266 u32 unit_attention_data;
271 #define fsg_lun_is_open(curlun) ((curlun)->filp != NULL)
273 static struct fsg_lun *fsg_lun_from_dev(struct device *dev)
275 return container_of(dev, struct fsg_lun, dev);
279 /* Big enough to hold our biggest descriptor */
280 #define EP0_BUFSIZE 256
281 #define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
283 /* Number of buffers we will use. 2 is enough for double-buffering */
284 #define FSG_NUM_BUFFERS 2
286 /* Default size of buffer length. */
287 #define FSG_BUFLEN ((u32)16384)
289 /* Maximal number of LUNs supported in mass storage function */
290 #define FSG_MAX_LUNS 8
292 enum fsg_buffer_state {
299 #ifdef FSG_BUFFHD_STATIC_BUFFER
300 char buf[FSG_BUFLEN];
304 enum fsg_buffer_state state;
305 struct fsg_buffhd *next;
307 /* The NetChip 2280 is faster, and handles some protocol faults
308 * better, if we don't submit any short bulk-out read requests.
309 * So we will record the intended request length here. */
310 unsigned int bulk_out_intended_length;
312 struct usb_request *inreq;
314 struct usb_request *outreq;
319 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
320 FSG_STATE_DATA_PHASE,
321 FSG_STATE_STATUS_PHASE,
324 FSG_STATE_ABORT_BULK_OUT,
326 FSG_STATE_INTERFACE_CHANGE,
327 FSG_STATE_CONFIG_CHANGE,
328 FSG_STATE_DISCONNECT,
333 enum data_direction {
334 DATA_DIR_UNKNOWN = 0,
341 /*-------------------------------------------------------------------------*/
344 static inline u32 get_unaligned_be24(u8 *buf)
346 return 0xffffff & (u32) get_unaligned_be32(buf - 1);
350 /*-------------------------------------------------------------------------*/
354 #ifndef FSG_NO_DEVICE_STRINGS
355 FSG_STRING_MANUFACTURER = 1,
365 static struct usb_otg_descriptor
367 .bLength = sizeof fsg_otg_desc,
368 .bDescriptorType = USB_DT_OTG,
370 .bmAttributes = USB_OTG_SRP,
374 /* There is only one interface. */
376 static struct usb_interface_descriptor
378 .bLength = sizeof fsg_intf_desc,
379 .bDescriptorType = USB_DT_INTERFACE,
381 .bNumEndpoints = 2, // Adjusted during fsg_bind()
382 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
383 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
384 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
385 .iInterface = FSG_STRING_INTERFACE,
388 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
389 * and interrupt-in. */
391 static struct usb_endpoint_descriptor
392 fsg_fs_bulk_in_desc = {
393 .bLength = USB_DT_ENDPOINT_SIZE,
394 .bDescriptorType = USB_DT_ENDPOINT,
396 .bEndpointAddress = USB_DIR_IN,
397 .bmAttributes = USB_ENDPOINT_XFER_BULK,
398 /* wMaxPacketSize set by autoconfiguration */
401 static struct usb_endpoint_descriptor
402 fsg_fs_bulk_out_desc = {
403 .bLength = USB_DT_ENDPOINT_SIZE,
404 .bDescriptorType = USB_DT_ENDPOINT,
406 .bEndpointAddress = USB_DIR_OUT,
407 .bmAttributes = USB_ENDPOINT_XFER_BULK,
408 /* wMaxPacketSize set by autoconfiguration */
411 #ifndef FSG_NO_INTR_EP
413 static struct usb_endpoint_descriptor
414 fsg_fs_intr_in_desc = {
415 .bLength = USB_DT_ENDPOINT_SIZE,
416 .bDescriptorType = USB_DT_ENDPOINT,
418 .bEndpointAddress = USB_DIR_IN,
419 .bmAttributes = USB_ENDPOINT_XFER_INT,
420 .wMaxPacketSize = cpu_to_le16(2),
421 .bInterval = 32, // frames -> 32 ms
425 # define FSG_FS_FUNCTION_PRE_EP_ENTRIES 2
427 # define FSG_FS_FUNCTION_PRE_EP_ENTRIES 1
432 static const struct usb_descriptor_header *fsg_fs_function[] = {
434 (struct usb_descriptor_header *) &fsg_otg_desc,
436 (struct usb_descriptor_header *) &fsg_intf_desc,
437 (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
438 (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
439 #ifndef FSG_NO_INTR_EP
440 (struct usb_descriptor_header *) &fsg_fs_intr_in_desc,
447 * USB 2.0 devices need to expose both high speed and full speed
448 * descriptors, unless they only run at full speed.
450 * That means alternate endpoint descriptors (bigger packets)
451 * and a "device qualifier" ... plus more construction options
452 * for the config descriptor.
454 static struct usb_endpoint_descriptor
455 fsg_hs_bulk_in_desc = {
456 .bLength = USB_DT_ENDPOINT_SIZE,
457 .bDescriptorType = USB_DT_ENDPOINT,
459 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
460 .bmAttributes = USB_ENDPOINT_XFER_BULK,
461 .wMaxPacketSize = cpu_to_le16(512),
464 static struct usb_endpoint_descriptor
465 fsg_hs_bulk_out_desc = {
466 .bLength = USB_DT_ENDPOINT_SIZE,
467 .bDescriptorType = USB_DT_ENDPOINT,
469 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
470 .bmAttributes = USB_ENDPOINT_XFER_BULK,
471 .wMaxPacketSize = cpu_to_le16(512),
472 .bInterval = 1, // NAK every 1 uframe
475 #ifndef FSG_NO_INTR_EP
477 static struct usb_endpoint_descriptor
478 fsg_hs_intr_in_desc = {
479 .bLength = USB_DT_ENDPOINT_SIZE,
480 .bDescriptorType = USB_DT_ENDPOINT,
482 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
483 .bmAttributes = USB_ENDPOINT_XFER_INT,
484 .wMaxPacketSize = cpu_to_le16(2),
485 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
489 # define FSG_HS_FUNCTION_PRE_EP_ENTRIES 2
491 # define FSG_HS_FUNCTION_PRE_EP_ENTRIES 1
496 static const struct usb_descriptor_header *fsg_hs_function[] = {
498 (struct usb_descriptor_header *) &fsg_otg_desc,
500 (struct usb_descriptor_header *) &fsg_intf_desc,
501 (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
502 (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
503 #ifndef FSG_NO_INTR_EP
504 (struct usb_descriptor_header *) &fsg_hs_intr_in_desc,
509 /* Maxpacket and other transfer characteristics vary by speed. */
510 static struct usb_endpoint_descriptor *
511 fsg_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
512 struct usb_endpoint_descriptor *hs)
514 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
520 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
521 static struct usb_string fsg_strings[] = {
522 #ifndef FSG_NO_DEVICE_STRINGS
523 {FSG_STRING_MANUFACTURER, fsg_string_manufacturer},
524 {FSG_STRING_PRODUCT, fsg_string_product},
525 {FSG_STRING_SERIAL, fsg_string_serial},
526 {FSG_STRING_CONFIG, fsg_string_config},
528 {FSG_STRING_INTERFACE, fsg_string_interface},
532 static struct usb_gadget_strings fsg_stringtab = {
533 .language = 0x0409, // en-us
534 .strings = fsg_strings,
538 /*-------------------------------------------------------------------------*/
540 /* If the next two routines are called while the gadget is registered,
541 * the caller must own fsg->filesem for writing. */
543 static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
546 struct file *filp = NULL;
548 struct inode *inode = NULL;
553 /* R/W if we can, R/O if we must */
554 ro = curlun->initially_ro;
556 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
557 if (-EROFS == PTR_ERR(filp))
561 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
563 LINFO(curlun, "unable to open backing file: %s\n", filename);
564 return PTR_ERR(filp);
567 if (!(filp->f_mode & FMODE_WRITE))
570 if (filp->f_path.dentry)
571 inode = filp->f_path.dentry->d_inode;
572 if (inode && S_ISBLK(inode->i_mode)) {
573 if (bdev_read_only(inode->i_bdev))
575 } else if (!inode || !S_ISREG(inode->i_mode)) {
576 LINFO(curlun, "invalid file type: %s\n", filename);
580 /* If we can't read the file, it's no good.
581 * If we can't write the file, use it read-only. */
582 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
583 LINFO(curlun, "file not readable: %s\n", filename);
586 if (!(filp->f_op->write || filp->f_op->aio_write))
589 size = i_size_read(inode->i_mapping->host);
591 LINFO(curlun, "unable to find file size: %s\n", filename);
595 num_sectors = size >> 9; // File size in 512-byte blocks
598 num_sectors &= ~3; // Reduce to a multiple of 2048
599 min_sectors = 300*4; // Smallest track is 300 frames
600 if (num_sectors >= 256*60*75*4) {
601 num_sectors = (256*60*75 - 1) * 4;
602 LINFO(curlun, "file too big: %s\n", filename);
603 LINFO(curlun, "using only first %d blocks\n",
607 if (num_sectors < min_sectors) {
608 LINFO(curlun, "file too small: %s\n", filename);
616 curlun->file_length = size;
617 curlun->num_sectors = num_sectors;
618 LDBG(curlun, "open backing file: %s\n", filename);
622 filp_close(filp, current->files);
627 static void fsg_lun_close(struct fsg_lun *curlun)
630 LDBG(curlun, "close backing file\n");
637 /*-------------------------------------------------------------------------*/
639 /* Sync the file data, don't bother with the metadata.
640 * This code was copied from fs/buffer.c:sys_fdatasync(). */
641 static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
643 struct file *filp = curlun->filp;
645 if (curlun->ro || !filp)
647 return vfs_fsync(filp, filp->f_path.dentry, 1);
650 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
653 /* Convert to Minutes-Seconds-Frames */
654 addr >>= 2; /* Convert to 2048-byte frames */
655 addr += 2*75; /* Lead-in occupies 2 seconds */
656 dest[3] = addr % 75; /* Frames */
658 dest[2] = addr % 60; /* Seconds */
660 dest[1] = addr; /* Minutes */
661 dest[0] = 0; /* Reserved */
663 /* Absolute sector */
664 put_unaligned_be32(addr, dest);
669 /*-------------------------------------------------------------------------*/
672 static ssize_t fsg_show_ro(struct device *dev, struct device_attribute *attr,
675 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
677 return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
679 : curlun->initially_ro);
682 static ssize_t fsg_show_file(struct device *dev, struct device_attribute *attr,
685 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
686 struct rw_semaphore *filesem = dev_get_drvdata(dev);
691 if (fsg_lun_is_open(curlun)) { // Get the complete pathname
692 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
698 buf[rc] = '\n'; // Add a newline
701 } else { // No file, return 0 bytes
710 static ssize_t fsg_store_ro(struct device *dev, struct device_attribute *attr,
711 const char *buf, size_t count)
714 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
715 struct rw_semaphore *filesem = dev_get_drvdata(dev);
718 if (sscanf(buf, "%d", &i) != 1)
721 /* Allow the write-enable status to change only while the backing file
724 if (fsg_lun_is_open(curlun)) {
725 LDBG(curlun, "read-only status change prevented\n");
729 curlun->initially_ro = !!i;
730 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
736 static ssize_t fsg_store_file(struct device *dev, struct device_attribute *attr,
737 const char *buf, size_t count)
739 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
740 struct rw_semaphore *filesem = dev_get_drvdata(dev);
743 if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
744 LDBG(curlun, "eject attempt prevented\n");
745 return -EBUSY; // "Door is locked"
748 /* Remove a trailing newline */
749 if (count > 0 && buf[count-1] == '\n')
750 ((char *) buf)[count-1] = 0; // Ugh!
752 /* Eject current medium */
754 if (fsg_lun_is_open(curlun)) {
755 fsg_lun_close(curlun);
756 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
759 /* Load new medium */
760 if (count > 0 && buf[0]) {
761 rc = fsg_lun_open(curlun, buf);
763 curlun->unit_attention_data =
764 SS_NOT_READY_TO_READY_TRANSITION;
767 return (rc < 0 ? rc : count);