USB: g_file_storage: per-LUN ro, removable and cdrom flags handling changed
[safe/jmp/linux-2.6] / drivers / usb / gadget / storage_common.c
1 /*
2  * storage_common.c -- Common definitions for mass storage functionality
3  *
4  * Copyright (C) 2003-2008 Alan Stern
5  * Copyeight (C) 2009 Samsung Electronics
6  * Author: Michal Nazarewicz (m.nazarewicz@samsung.com)
7  *
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.
12  *
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.
17  *
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
21  */
22
23
24 /*
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.
34  */
35
36
37 #include <asm/unaligned.h>
38
39
40 /*-------------------------------------------------------------------------*/
41
42
43 #ifndef DEBUG
44 #undef VERBOSE_DEBUG
45 #undef DUMP_MSGS
46 #endif /* !DEBUG */
47
48 #ifdef VERBOSE_DEBUG
49 #define VLDBG   LDBG
50 #else
51 #define VLDBG(lun, fmt, args...) do { } while (0)
52 #endif /* VERBOSE_DEBUG */
53
54 #define LDBG(lun, fmt, args...)   dev_dbg (&(lun)->dev, fmt, ## args)
55 #define LERROR(lun, fmt, args...) dev_err (&(lun)->dev, fmt, ## args)
56 #define LWARN(lun, fmt, args...)  dev_warn(&(lun)->dev, fmt, ## args)
57 #define LINFO(lun, fmt, args...)  dev_info(&(lun)->dev, fmt, ## args)
58
59 #define DBG(d, fmt, args...)      dev_dbg (&(d)->gadget->dev, fmt, ## args)
60 #define VDBG(d, fmt, args...)     dev_vdbg(&(d)->gadget->dev, fmt, ## args)
61 #define ERROR(d, fmt, args...)    dev_err (&(d)->gadget->dev, fmt, ## args)
62 #define WARNING(d, fmt, args...)  dev_warn(&(d)->gadget->dev, fmt, ## args)
63 #define INFO(d, fmt, args...)     dev_info(&(d)->gadget->dev, fmt, ## args)
64
65
66
67 #ifdef DUMP_MSGS
68
69 #  define dump_msg(fsg, /* const char * */ label,                       \
70                  /* const u8 * */ buf, /* unsigned */ length) do {      \
71         if (length < 512) {                                             \
72                 DBG(fsg, "%s, length %u:\n", label, length);            \
73                 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,      \
74                                16, 1, buf, length, 0);                  \
75         }                                                               \
76 } while (0)
77
78 #  define dump_cdb(fsg) do { } while (0)
79
80 #else
81
82 #  define dump_msg(fsg, /* const char * */ label, \
83                  /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
84
85 #  ifdef VERBOSE_DEBUG
86
87 #define dump_cdb(fsg)                                                   \
88         print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,      \
89                        16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0)         \
90
91 #  else
92
93 #    define dump_cdb(fsg) do { } while (0)
94
95 #  endif /* VERBOSE_DEBUG */
96
97 #endif /* DUMP_MSGS */
98
99
100
101
102
103 /*-------------------------------------------------------------------------*/
104
105 /* SCSI device types */
106 #define TYPE_DISK       0x00
107 #define TYPE_CDROM      0x05
108
109 /* USB protocol value = the transport method */
110 #define USB_PR_CBI      0x00            // Control/Bulk/Interrupt
111 #define USB_PR_CB       0x01            // Control/Bulk w/o interrupt
112 #define USB_PR_BULK     0x50            // Bulk-only
113
114 /* USB subclass value = the protocol encapsulation */
115 #define USB_SC_RBC      0x01            // Reduced Block Commands (flash)
116 #define USB_SC_8020     0x02            // SFF-8020i, MMC-2, ATAPI (CD-ROM)
117 #define USB_SC_QIC      0x03            // QIC-157 (tape)
118 #define USB_SC_UFI      0x04            // UFI (floppy)
119 #define USB_SC_8070     0x05            // SFF-8070i (removable)
120 #define USB_SC_SCSI     0x06            // Transparent SCSI
121
122 /* Bulk-only data structures */
123
124 /* Command Block Wrapper */
125 struct fsg_bulk_cb_wrap {
126         __le32  Signature;              // Contains 'USBC'
127         u32     Tag;                    // Unique per command id
128         __le32  DataTransferLength;     // Size of the data
129         u8      Flags;                  // Direction in bit 7
130         u8      Lun;                    // LUN (normally 0)
131         u8      Length;                 // Of the CDB, <= MAX_COMMAND_SIZE
132         u8      CDB[16];                // Command Data Block
133 };
134
135 #define USB_BULK_CB_WRAP_LEN    31
136 #define USB_BULK_CB_SIG         0x43425355      // Spells out USBC
137 #define USB_BULK_IN_FLAG        0x80
138
139 /* Command Status Wrapper */
140 struct bulk_cs_wrap {
141         __le32  Signature;              // Should = 'USBS'
142         u32     Tag;                    // Same as original command
143         __le32  Residue;                // Amount not transferred
144         u8      Status;                 // See below
145 };
146
147 #define USB_BULK_CS_WRAP_LEN    13
148 #define USB_BULK_CS_SIG         0x53425355      // Spells out 'USBS'
149 #define USB_STATUS_PASS         0
150 #define USB_STATUS_FAIL         1
151 #define USB_STATUS_PHASE_ERROR  2
152
153 /* Bulk-only class specific requests */
154 #define USB_BULK_RESET_REQUEST          0xff
155 #define USB_BULK_GET_MAX_LUN_REQUEST    0xfe
156
157
158 /* CBI Interrupt data structure */
159 struct interrupt_data {
160         u8      bType;
161         u8      bValue;
162 };
163
164 #define CBI_INTERRUPT_DATA_LEN          2
165
166 /* CBI Accept Device-Specific Command request */
167 #define USB_CBI_ADSC_REQUEST            0x00
168
169
170 #define MAX_COMMAND_SIZE        16      // Length of a SCSI Command Data Block
171
172 /* SCSI commands that we recognize */
173 #define SC_FORMAT_UNIT                  0x04
174 #define SC_INQUIRY                      0x12
175 #define SC_MODE_SELECT_6                0x15
176 #define SC_MODE_SELECT_10               0x55
177 #define SC_MODE_SENSE_6                 0x1a
178 #define SC_MODE_SENSE_10                0x5a
179 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
180 #define SC_READ_6                       0x08
181 #define SC_READ_10                      0x28
182 #define SC_READ_12                      0xa8
183 #define SC_READ_CAPACITY                0x25
184 #define SC_READ_FORMAT_CAPACITIES       0x23
185 #define SC_READ_HEADER                  0x44
186 #define SC_READ_TOC                     0x43
187 #define SC_RELEASE                      0x17
188 #define SC_REQUEST_SENSE                0x03
189 #define SC_RESERVE                      0x16
190 #define SC_SEND_DIAGNOSTIC              0x1d
191 #define SC_START_STOP_UNIT              0x1b
192 #define SC_SYNCHRONIZE_CACHE            0x35
193 #define SC_TEST_UNIT_READY              0x00
194 #define SC_VERIFY                       0x2f
195 #define SC_WRITE_6                      0x0a
196 #define SC_WRITE_10                     0x2a
197 #define SC_WRITE_12                     0xaa
198
199 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
200 #define SS_NO_SENSE                             0
201 #define SS_COMMUNICATION_FAILURE                0x040800
202 #define SS_INVALID_COMMAND                      0x052000
203 #define SS_INVALID_FIELD_IN_CDB                 0x052400
204 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE   0x052100
205 #define SS_LOGICAL_UNIT_NOT_SUPPORTED           0x052500
206 #define SS_MEDIUM_NOT_PRESENT                   0x023a00
207 #define SS_MEDIUM_REMOVAL_PREVENTED             0x055302
208 #define SS_NOT_READY_TO_READY_TRANSITION        0x062800
209 #define SS_RESET_OCCURRED                       0x062900
210 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED      0x053900
211 #define SS_UNRECOVERED_READ_ERROR               0x031100
212 #define SS_WRITE_ERROR                          0x030c02
213 #define SS_WRITE_PROTECTED                      0x072700
214
215 #define SK(x)           ((u8) ((x) >> 16))      // Sense Key byte, etc.
216 #define ASC(x)          ((u8) ((x) >> 8))
217 #define ASCQ(x)         ((u8) (x))
218
219
220 /*-------------------------------------------------------------------------*/
221
222
223 struct fsg_lun {
224         struct file     *filp;
225         loff_t          file_length;
226         loff_t          num_sectors;
227
228         unsigned int    initially_ro : 1;
229         unsigned int    ro : 1;
230         unsigned int    removable : 1;
231         unsigned int    cdrom : 1;
232         unsigned int    prevent_medium_removal : 1;
233         unsigned int    registered : 1;
234         unsigned int    info_valid : 1;
235
236         u32             sense_data;
237         u32             sense_data_info;
238         u32             unit_attention_data;
239
240         struct device   dev;
241 };
242
243 #define fsg_lun_is_open(curlun) ((curlun)->filp != NULL)
244
245 static struct fsg_lun *fsg_lun_from_dev(struct device *dev)
246 {
247         return container_of(dev, struct fsg_lun, dev);
248 }
249
250
251 /* Big enough to hold our biggest descriptor */
252 #define EP0_BUFSIZE     256
253 #define DELAYED_STATUS  (EP0_BUFSIZE + 999)     // An impossibly large value
254
255 /* Number of buffers we will use.  2 is enough for double-buffering */
256 #define FSG_NUM_BUFFERS 2
257
258 enum fsg_buffer_state {
259         BUF_STATE_EMPTY = 0,
260         BUF_STATE_FULL,
261         BUF_STATE_BUSY
262 };
263
264 struct fsg_buffhd {
265         void                            *buf;
266         enum fsg_buffer_state           state;
267         struct fsg_buffhd               *next;
268
269         /* The NetChip 2280 is faster, and handles some protocol faults
270          * better, if we don't submit any short bulk-out read requests.
271          * So we will record the intended request length here. */
272         unsigned int                    bulk_out_intended_length;
273
274         struct usb_request              *inreq;
275         int                             inreq_busy;
276         struct usb_request              *outreq;
277         int                             outreq_busy;
278 };
279
280 enum fsg_state {
281         FSG_STATE_COMMAND_PHASE = -10,          // This one isn't used anywhere
282         FSG_STATE_DATA_PHASE,
283         FSG_STATE_STATUS_PHASE,
284
285         FSG_STATE_IDLE = 0,
286         FSG_STATE_ABORT_BULK_OUT,
287         FSG_STATE_RESET,
288         FSG_STATE_INTERFACE_CHANGE,
289         FSG_STATE_CONFIG_CHANGE,
290         FSG_STATE_DISCONNECT,
291         FSG_STATE_EXIT,
292         FSG_STATE_TERMINATED
293 };
294
295 enum data_direction {
296         DATA_DIR_UNKNOWN = 0,
297         DATA_DIR_FROM_HOST,
298         DATA_DIR_TO_HOST,
299         DATA_DIR_NONE
300 };
301
302
303 /*-------------------------------------------------------------------------*/
304
305
306 static inline u32 get_unaligned_be24(u8 *buf)
307 {
308         return 0xffffff & (u32) get_unaligned_be32(buf - 1);
309 }
310
311
312 /*-------------------------------------------------------------------------*/
313
314
315 enum {
316         FSG_STRING_MANUFACTURER = 1,
317         FSG_STRING_PRODUCT,
318         FSG_STRING_SERIAL,
319         FSG_STRING_CONFIG,
320         FSG_STRING_INTERFACE
321 };
322
323
324 static struct usb_otg_descriptor
325 fsg_otg_desc = {
326         .bLength =              sizeof fsg_otg_desc,
327         .bDescriptorType =      USB_DT_OTG,
328
329         .bmAttributes =         USB_OTG_SRP,
330 };
331
332 /* There is only one interface. */
333
334 static struct usb_interface_descriptor
335 fsg_intf_desc = {
336         .bLength =              sizeof fsg_intf_desc,
337         .bDescriptorType =      USB_DT_INTERFACE,
338
339         .bNumEndpoints =        2,              // Adjusted during fsg_bind()
340         .bInterfaceClass =      USB_CLASS_MASS_STORAGE,
341         .bInterfaceSubClass =   USB_SC_SCSI,    // Adjusted during fsg_bind()
342         .bInterfaceProtocol =   USB_PR_BULK,    // Adjusted during fsg_bind()
343         .iInterface =           FSG_STRING_INTERFACE,
344 };
345
346 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
347  * and interrupt-in. */
348
349 static struct usb_endpoint_descriptor
350 fsg_fs_bulk_in_desc = {
351         .bLength =              USB_DT_ENDPOINT_SIZE,
352         .bDescriptorType =      USB_DT_ENDPOINT,
353
354         .bEndpointAddress =     USB_DIR_IN,
355         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
356         /* wMaxPacketSize set by autoconfiguration */
357 };
358
359 static struct usb_endpoint_descriptor
360 fsg_fs_bulk_out_desc = {
361         .bLength =              USB_DT_ENDPOINT_SIZE,
362         .bDescriptorType =      USB_DT_ENDPOINT,
363
364         .bEndpointAddress =     USB_DIR_OUT,
365         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
366         /* wMaxPacketSize set by autoconfiguration */
367 };
368
369 static struct usb_endpoint_descriptor
370 fsg_fs_intr_in_desc = {
371         .bLength =              USB_DT_ENDPOINT_SIZE,
372         .bDescriptorType =      USB_DT_ENDPOINT,
373
374         .bEndpointAddress =     USB_DIR_IN,
375         .bmAttributes =         USB_ENDPOINT_XFER_INT,
376         .wMaxPacketSize =       cpu_to_le16(2),
377         .bInterval =            32,     // frames -> 32 ms
378 };
379
380 static const struct usb_descriptor_header *fsg_fs_function[] = {
381         (struct usb_descriptor_header *) &fsg_otg_desc,
382         (struct usb_descriptor_header *) &fsg_intf_desc,
383         (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
384         (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
385         (struct usb_descriptor_header *) &fsg_fs_intr_in_desc,
386         NULL,
387 };
388 #define FSG_FS_FUNCTION_PRE_EP_ENTRIES  2
389
390
391 /*
392  * USB 2.0 devices need to expose both high speed and full speed
393  * descriptors, unless they only run at full speed.
394  *
395  * That means alternate endpoint descriptors (bigger packets)
396  * and a "device qualifier" ... plus more construction options
397  * for the config descriptor.
398  */
399 static struct usb_endpoint_descriptor
400 fsg_hs_bulk_in_desc = {
401         .bLength =              USB_DT_ENDPOINT_SIZE,
402         .bDescriptorType =      USB_DT_ENDPOINT,
403
404         /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
405         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
406         .wMaxPacketSize =       cpu_to_le16(512),
407 };
408
409 static struct usb_endpoint_descriptor
410 fsg_hs_bulk_out_desc = {
411         .bLength =              USB_DT_ENDPOINT_SIZE,
412         .bDescriptorType =      USB_DT_ENDPOINT,
413
414         /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
415         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
416         .wMaxPacketSize =       cpu_to_le16(512),
417         .bInterval =            1,      // NAK every 1 uframe
418 };
419
420 static struct usb_endpoint_descriptor
421 fsg_hs_intr_in_desc = {
422         .bLength =              USB_DT_ENDPOINT_SIZE,
423         .bDescriptorType =      USB_DT_ENDPOINT,
424
425         /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
426         .bmAttributes =         USB_ENDPOINT_XFER_INT,
427         .wMaxPacketSize =       cpu_to_le16(2),
428         .bInterval =            9,      // 2**(9-1) = 256 uframes -> 32 ms
429 };
430
431 static const struct usb_descriptor_header *fsg_hs_function[] = {
432         (struct usb_descriptor_header *) &fsg_otg_desc,
433         (struct usb_descriptor_header *) &fsg_intf_desc,
434         (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
435         (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
436         (struct usb_descriptor_header *) &fsg_hs_intr_in_desc,
437         NULL,
438 };
439 #define FSG_HS_FUNCTION_PRE_EP_ENTRIES  2
440
441 /* Maxpacket and other transfer characteristics vary by speed. */
442 static struct usb_endpoint_descriptor *
443 fsg_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
444                 struct usb_endpoint_descriptor *hs)
445 {
446         if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
447                 return hs;
448         return fs;
449 }
450
451
452 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
453 static struct usb_string                fsg_strings[] = {
454         {FSG_STRING_MANUFACTURER,       fsg_string_manufacturer},
455         {FSG_STRING_PRODUCT,            fsg_string_product},
456         {FSG_STRING_SERIAL,             fsg_string_serial},
457         {FSG_STRING_CONFIG,             fsg_string_config},
458         {FSG_STRING_INTERFACE,          fsg_string_interface},
459         {}
460 };
461
462 static struct usb_gadget_strings        fsg_stringtab = {
463         .language       = 0x0409,               // en-us
464         .strings        = fsg_strings,
465 };
466
467
468  /*-------------------------------------------------------------------------*/
469
470 /* If the next two routines are called while the gadget is registered,
471  * the caller must own fsg->filesem for writing. */
472
473 static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
474 {
475         int                             ro;
476         struct file                     *filp = NULL;
477         int                             rc = -EINVAL;
478         struct inode                    *inode = NULL;
479         loff_t                          size;
480         loff_t                          num_sectors;
481         loff_t                          min_sectors;
482
483         /* R/W if we can, R/O if we must */
484         ro = curlun->initially_ro;
485         if (!ro) {
486                 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
487                 if (-EROFS == PTR_ERR(filp))
488                         ro = 1;
489         }
490         if (ro)
491                 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
492         if (IS_ERR(filp)) {
493                 LINFO(curlun, "unable to open backing file: %s\n", filename);
494                 return PTR_ERR(filp);
495         }
496
497         if (!(filp->f_mode & FMODE_WRITE))
498                 ro = 1;
499
500         if (filp->f_path.dentry)
501                 inode = filp->f_path.dentry->d_inode;
502         if (inode && S_ISBLK(inode->i_mode)) {
503                 if (bdev_read_only(inode->i_bdev))
504                         ro = 1;
505         } else if (!inode || !S_ISREG(inode->i_mode)) {
506                 LINFO(curlun, "invalid file type: %s\n", filename);
507                 goto out;
508         }
509
510         /* If we can't read the file, it's no good.
511          * If we can't write the file, use it read-only. */
512         if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
513                 LINFO(curlun, "file not readable: %s\n", filename);
514                 goto out;
515         }
516         if (!(filp->f_op->write || filp->f_op->aio_write))
517                 ro = 1;
518
519         size = i_size_read(inode->i_mapping->host);
520         if (size < 0) {
521                 LINFO(curlun, "unable to find file size: %s\n", filename);
522                 rc = (int) size;
523                 goto out;
524         }
525         num_sectors = size >> 9;        // File size in 512-byte blocks
526         min_sectors = 1;
527         if (curlun->cdrom) {
528                 num_sectors &= ~3;      // Reduce to a multiple of 2048
529                 min_sectors = 300*4;    // Smallest track is 300 frames
530                 if (num_sectors >= 256*60*75*4) {
531                         num_sectors = (256*60*75 - 1) * 4;
532                         LINFO(curlun, "file too big: %s\n", filename);
533                         LINFO(curlun, "using only first %d blocks\n",
534                                         (int) num_sectors);
535                 }
536         }
537         if (num_sectors < min_sectors) {
538                 LINFO(curlun, "file too small: %s\n", filename);
539                 rc = -ETOOSMALL;
540                 goto out;
541         }
542
543         get_file(filp);
544         curlun->ro = ro;
545         curlun->filp = filp;
546         curlun->file_length = size;
547         curlun->num_sectors = num_sectors;
548         LDBG(curlun, "open backing file: %s\n", filename);
549         rc = 0;
550
551 out:
552         filp_close(filp, current->files);
553         return rc;
554 }
555
556
557 static void fsg_lun_close(struct fsg_lun *curlun)
558 {
559         if (curlun->filp) {
560                 LDBG(curlun, "close backing file\n");
561                 fput(curlun->filp);
562                 curlun->filp = NULL;
563         }
564 }
565
566
567 /*-------------------------------------------------------------------------*/
568
569 /* Sync the file data, don't bother with the metadata.
570  * This code was copied from fs/buffer.c:sys_fdatasync(). */
571 static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
572 {
573         struct file     *filp = curlun->filp;
574
575         if (curlun->ro || !filp)
576                 return 0;
577         return vfs_fsync(filp, filp->f_path.dentry, 1);
578 }
579
580 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
581 {
582         if (msf) {
583                 /* Convert to Minutes-Seconds-Frames */
584                 addr >>= 2;             /* Convert to 2048-byte frames */
585                 addr += 2*75;           /* Lead-in occupies 2 seconds */
586                 dest[3] = addr % 75;    /* Frames */
587                 addr /= 75;
588                 dest[2] = addr % 60;    /* Seconds */
589                 addr /= 60;
590                 dest[1] = addr;         /* Minutes */
591                 dest[0] = 0;            /* Reserved */
592         } else {
593                 /* Absolute sector */
594                 put_unaligned_be32(addr, dest);
595         }
596 }