e576678fb62135dcf843e6eda1638430a80d90d2
[platform/adaptation/renesas_rcar/renesas_kernel.git] / 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 (mina86@mina86.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
14
15 /*
16  * This file requires the following identifiers used in USB strings to
17  * be defined (each of type pointer to char):
18  *  - fsg_string_manufacturer -- name of the manufacturer
19  *  - fsg_string_product      -- name of the product
20  *  - fsg_string_config       -- name of the configuration
21  *  - fsg_string_interface    -- name of the interface
22  * The first four are only needed when FSG_DESCRIPTORS_DEVICE_STRINGS
23  * macro is defined prior to including this file.
24  */
25
26 /*
27  * When FSG_NO_INTR_EP is defined fsg_fs_intr_in_desc and
28  * fsg_hs_intr_in_desc objects as well as
29  * FSG_FS_FUNCTION_PRE_EP_ENTRIES and FSG_HS_FUNCTION_PRE_EP_ENTRIES
30  * macros are not defined.
31  *
32  * When FSG_NO_DEVICE_STRINGS is defined FSG_STRING_MANUFACTURER,
33  * FSG_STRING_PRODUCT, FSG_STRING_SERIAL and FSG_STRING_CONFIG are not
34  * defined (as well as corresponding entries in string tables are
35  * missing) and FSG_STRING_INTERFACE has value of zero.
36  *
37  * When FSG_NO_OTG is defined fsg_otg_desc won't be defined.
38  */
39
40 /*
41  * When USB_GADGET_DEBUG_FILES is defined the module param num_buffers
42  * sets the number of pipeline buffers (length of the fsg_buffhd array).
43  * The valid range of num_buffers is: num >= 2 && num <= 4.
44  */
45
46
47 #include <linux/usb/storage.h>
48 #include <scsi/scsi.h>
49 #include <asm/unaligned.h>
50
51
52 /*
53  * Thanks to NetChip Technologies for donating this product ID.
54  *
55  * DO NOT REUSE THESE IDs with any other driver!!  Ever!!
56  * Instead:  allocate your own, using normal USB-IF procedures.
57  */
58 #define FSG_VENDOR_ID   0x0525  /* NetChip */
59 #define FSG_PRODUCT_ID  0xa4a5  /* Linux-USB File-backed Storage Gadget */
60
61
62 /*-------------------------------------------------------------------------*/
63
64
65 #ifndef DEBUG
66 #undef VERBOSE_DEBUG
67 #undef DUMP_MSGS
68 #endif /* !DEBUG */
69
70 #ifdef VERBOSE_DEBUG
71 #define VLDBG   LDBG
72 #else
73 #define VLDBG(lun, fmt, args...) do { } while (0)
74 #endif /* VERBOSE_DEBUG */
75
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)
80
81 /*
82  * Keep those macros in sync with those in
83  * include/linux/usb/composite.h or else GCC will complain.  If they
84  * are identical (the same names of arguments, white spaces in the
85  * same places) GCC will allow redefinition otherwise (even if some
86  * white space is removed or added) warning will be issued.
87  *
88  * Those macros are needed here because File Storage Gadget does not
89  * include the composite.h header.  For composite gadgets those macros
90  * are redundant since composite.h is included any way.
91  *
92  * One could check whether those macros are already defined (which
93  * would indicate composite.h had been included) or not (which would
94  * indicate we were in FSG) but this is not done because a warning is
95  * desired if definitions here differ from the ones in composite.h.
96  *
97  * We want the definitions to match and be the same in File Storage
98  * Gadget as well as Mass Storage Function (and so composite gadgets
99  * using MSF).  If someone changes them in composite.h it will produce
100  * a warning in this file when building MSF.
101  */
102 #define DBG(d, fmt, args...)     dev_dbg(&(d)->gadget->dev , fmt , ## args)
103 #define VDBG(d, fmt, args...)    dev_vdbg(&(d)->gadget->dev , fmt , ## args)
104 #define ERROR(d, fmt, args...)   dev_err(&(d)->gadget->dev , fmt , ## args)
105 #define WARNING(d, fmt, args...) dev_warn(&(d)->gadget->dev , fmt , ## args)
106 #define INFO(d, fmt, args...)    dev_info(&(d)->gadget->dev , fmt , ## args)
107
108
109
110 #ifdef DUMP_MSGS
111
112 #  define dump_msg(fsg, /* const char * */ label,                       \
113                    /* const u8 * */ buf, /* unsigned */ length) do {    \
114         if (length < 512) {                                             \
115                 DBG(fsg, "%s, length %u:\n", label, length);            \
116                 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,      \
117                                16, 1, buf, length, 0);                  \
118         }                                                               \
119 } while (0)
120
121 #  define dump_cdb(fsg) do { } while (0)
122
123 #else
124
125 #  define dump_msg(fsg, /* const char * */ label, \
126                    /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
127
128 #  ifdef VERBOSE_DEBUG
129
130 #    define dump_cdb(fsg)                                               \
131         print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,      \
132                        16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0)         \
133
134 #  else
135
136 #    define dump_cdb(fsg) do { } while (0)
137
138 #  endif /* VERBOSE_DEBUG */
139
140 #endif /* DUMP_MSGS */
141
142 /*-------------------------------------------------------------------------*/
143
144 /* CBI Interrupt data structure */
145 struct interrupt_data {
146         u8      bType;
147         u8      bValue;
148 };
149
150 #define CBI_INTERRUPT_DATA_LEN          2
151
152 /* CBI Accept Device-Specific Command request */
153 #define USB_CBI_ADSC_REQUEST            0x00
154
155
156 /* Length of a SCSI Command Data Block */
157 #define MAX_COMMAND_SIZE        16
158
159 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
160 #define SS_NO_SENSE                             0
161 #define SS_COMMUNICATION_FAILURE                0x040800
162 #define SS_INVALID_COMMAND                      0x052000
163 #define SS_INVALID_FIELD_IN_CDB                 0x052400
164 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE   0x052100
165 #define SS_LOGICAL_UNIT_NOT_SUPPORTED           0x052500
166 #define SS_MEDIUM_NOT_PRESENT                   0x023a00
167 #define SS_MEDIUM_REMOVAL_PREVENTED             0x055302
168 #define SS_NOT_READY_TO_READY_TRANSITION        0x062800
169 #define SS_RESET_OCCURRED                       0x062900
170 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED      0x053900
171 #define SS_UNRECOVERED_READ_ERROR               0x031100
172 #define SS_WRITE_ERROR                          0x030c02
173 #define SS_WRITE_PROTECTED                      0x072700
174
175 #define SK(x)           ((u8) ((x) >> 16))      /* Sense Key byte, etc. */
176 #define ASC(x)          ((u8) ((x) >> 8))
177 #define ASCQ(x)         ((u8) (x))
178
179
180 /*-------------------------------------------------------------------------*/
181
182
183 struct fsg_lun {
184         struct file     *filp;
185         loff_t          file_length;
186         loff_t          num_sectors;
187
188         unsigned int    initially_ro:1;
189         unsigned int    ro:1;
190         unsigned int    removable:1;
191         unsigned int    cdrom:1;
192         unsigned int    prevent_medium_removal:1;
193         unsigned int    registered:1;
194         unsigned int    info_valid:1;
195         unsigned int    nofua:1;
196
197         u32             sense_data;
198         u32             sense_data_info;
199         u32             unit_attention_data;
200
201         unsigned int    blkbits;        /* Bits of logical block size of bound block device */
202         unsigned int    blksize;        /* logical block size of bound block device */
203         struct device   dev;
204 };
205
206 #define fsg_lun_is_open(curlun) ((curlun)->filp != NULL)
207
208 static struct fsg_lun *fsg_lun_from_dev(struct device *dev)
209 {
210         return container_of(dev, struct fsg_lun, dev);
211 }
212
213
214 /* Big enough to hold our biggest descriptor */
215 #define EP0_BUFSIZE     256
216 #define DELAYED_STATUS  (EP0_BUFSIZE + 999)     /* An impossibly large value */
217
218 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
219
220 static unsigned int fsg_num_buffers = CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS;
221 module_param_named(num_buffers, fsg_num_buffers, uint, S_IRUGO);
222 MODULE_PARM_DESC(num_buffers, "Number of pipeline buffers");
223
224 #else
225
226 /*
227  * Number of buffers we will use.
228  * 2 is usually enough for good buffering pipeline
229  */
230 #define fsg_num_buffers CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS
231
232 #endif /* CONFIG_USB_DEBUG */
233
234 /* check if fsg_num_buffers is within a valid range */
235 static inline int fsg_num_buffers_validate(void)
236 {
237         if (fsg_num_buffers >= 2 && fsg_num_buffers <= 4)
238                 return 0;
239         pr_err("fsg_num_buffers %u is out of range (%d to %d)\n",
240                fsg_num_buffers, 2 ,4);
241         return -EINVAL;
242 }
243
244 /* Default size of buffer length. */
245 #define FSG_BUFLEN      ((u32)16384)
246
247 /* Maximal number of LUNs supported in mass storage function */
248 #define FSG_MAX_LUNS    8
249
250 enum fsg_buffer_state {
251         BUF_STATE_EMPTY = 0,
252         BUF_STATE_FULL,
253         BUF_STATE_BUSY
254 };
255
256 struct fsg_buffhd {
257         void                            *buf;
258         enum fsg_buffer_state           state;
259         struct fsg_buffhd               *next;
260
261         /*
262          * The NetChip 2280 is faster, and handles some protocol faults
263          * better, if we don't submit any short bulk-out read requests.
264          * So we will record the intended request length here.
265          */
266         unsigned int                    bulk_out_intended_length;
267
268         struct usb_request              *inreq;
269         int                             inreq_busy;
270         struct usb_request              *outreq;
271         int                             outreq_busy;
272 };
273
274 enum fsg_state {
275         /* This one isn't used anywhere */
276         FSG_STATE_COMMAND_PHASE = -10,
277         FSG_STATE_DATA_PHASE,
278         FSG_STATE_STATUS_PHASE,
279
280         FSG_STATE_IDLE = 0,
281         FSG_STATE_ABORT_BULK_OUT,
282         FSG_STATE_RESET,
283         FSG_STATE_INTERFACE_CHANGE,
284         FSG_STATE_CONFIG_CHANGE,
285         FSG_STATE_DISCONNECT,
286         FSG_STATE_EXIT,
287         FSG_STATE_TERMINATED
288 };
289
290 enum data_direction {
291         DATA_DIR_UNKNOWN = 0,
292         DATA_DIR_FROM_HOST,
293         DATA_DIR_TO_HOST,
294         DATA_DIR_NONE
295 };
296
297
298 /*-------------------------------------------------------------------------*/
299
300
301 static inline u32 get_unaligned_be24(u8 *buf)
302 {
303         return 0xffffff & (u32) get_unaligned_be32(buf - 1);
304 }
305
306
307 /*-------------------------------------------------------------------------*/
308
309
310 enum {
311 #ifndef FSG_NO_DEVICE_STRINGS
312         FSG_STRING_MANUFACTURER = 1,
313         FSG_STRING_PRODUCT,
314         FSG_STRING_SERIAL,
315         FSG_STRING_CONFIG,
316 #endif
317         FSG_STRING_INTERFACE
318 };
319
320
321 #ifndef FSG_NO_OTG
322 static struct usb_otg_descriptor
323 fsg_otg_desc = {
324         .bLength =              sizeof fsg_otg_desc,
325         .bDescriptorType =      USB_DT_OTG,
326
327         .bmAttributes =         USB_OTG_SRP,
328 };
329 #endif
330
331 /* There is only one interface. */
332
333 static struct usb_interface_descriptor
334 fsg_intf_desc = {
335         .bLength =              sizeof fsg_intf_desc,
336         .bDescriptorType =      USB_DT_INTERFACE,
337
338         .bNumEndpoints =        2,              /* Adjusted during fsg_bind() */
339         .bInterfaceClass =      USB_CLASS_MASS_STORAGE,
340         .bInterfaceSubClass =   USB_SC_SCSI,    /* Adjusted during fsg_bind() */
341         .bInterfaceProtocol =   USB_PR_BULK,    /* Adjusted during fsg_bind() */
342         .iInterface =           FSG_STRING_INTERFACE,
343 };
344
345 /*
346  * Three full-speed endpoint descriptors: bulk-in, bulk-out, and
347  * interrupt-in.
348  */
349
350 static struct usb_endpoint_descriptor
351 fsg_fs_bulk_in_desc = {
352         .bLength =              USB_DT_ENDPOINT_SIZE,
353         .bDescriptorType =      USB_DT_ENDPOINT,
354
355         .bEndpointAddress =     USB_DIR_IN,
356         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
357         /* wMaxPacketSize set by autoconfiguration */
358 };
359
360 static struct usb_endpoint_descriptor
361 fsg_fs_bulk_out_desc = {
362         .bLength =              USB_DT_ENDPOINT_SIZE,
363         .bDescriptorType =      USB_DT_ENDPOINT,
364
365         .bEndpointAddress =     USB_DIR_OUT,
366         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
367         /* wMaxPacketSize set by autoconfiguration */
368 };
369
370 #ifndef FSG_NO_INTR_EP
371
372 static struct usb_endpoint_descriptor
373 fsg_fs_intr_in_desc = {
374         .bLength =              USB_DT_ENDPOINT_SIZE,
375         .bDescriptorType =      USB_DT_ENDPOINT,
376
377         .bEndpointAddress =     USB_DIR_IN,
378         .bmAttributes =         USB_ENDPOINT_XFER_INT,
379         .wMaxPacketSize =       cpu_to_le16(2),
380         .bInterval =            32,     /* frames -> 32 ms */
381 };
382
383 #ifndef FSG_NO_OTG
384 #  define FSG_FS_FUNCTION_PRE_EP_ENTRIES        2
385 #else
386 #  define FSG_FS_FUNCTION_PRE_EP_ENTRIES        1
387 #endif
388
389 #endif
390
391 static struct usb_descriptor_header *fsg_fs_function[] = {
392 #ifndef FSG_NO_OTG
393         (struct usb_descriptor_header *) &fsg_otg_desc,
394 #endif
395         (struct usb_descriptor_header *) &fsg_intf_desc,
396         (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
397         (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
398 #ifndef FSG_NO_INTR_EP
399         (struct usb_descriptor_header *) &fsg_fs_intr_in_desc,
400 #endif
401         NULL,
402 };
403
404
405 /*
406  * USB 2.0 devices need to expose both high speed and full speed
407  * descriptors, unless they only run at full speed.
408  *
409  * That means alternate endpoint descriptors (bigger packets)
410  * and a "device qualifier" ... plus more construction options
411  * for the configuration descriptor.
412  */
413 static struct usb_endpoint_descriptor
414 fsg_hs_bulk_in_desc = {
415         .bLength =              USB_DT_ENDPOINT_SIZE,
416         .bDescriptorType =      USB_DT_ENDPOINT,
417
418         /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
419         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
420         .wMaxPacketSize =       cpu_to_le16(512),
421 };
422
423 static struct usb_endpoint_descriptor
424 fsg_hs_bulk_out_desc = {
425         .bLength =              USB_DT_ENDPOINT_SIZE,
426         .bDescriptorType =      USB_DT_ENDPOINT,
427
428         /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
429         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
430         .wMaxPacketSize =       cpu_to_le16(512),
431         .bInterval =            1,      /* NAK every 1 uframe */
432 };
433
434 #ifndef FSG_NO_INTR_EP
435
436 static struct usb_endpoint_descriptor
437 fsg_hs_intr_in_desc = {
438         .bLength =              USB_DT_ENDPOINT_SIZE,
439         .bDescriptorType =      USB_DT_ENDPOINT,
440
441         /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
442         .bmAttributes =         USB_ENDPOINT_XFER_INT,
443         .wMaxPacketSize =       cpu_to_le16(2),
444         .bInterval =            9,      /* 2**(9-1) = 256 uframes -> 32 ms */
445 };
446
447 #ifndef FSG_NO_OTG
448 #  define FSG_HS_FUNCTION_PRE_EP_ENTRIES        2
449 #else
450 #  define FSG_HS_FUNCTION_PRE_EP_ENTRIES        1
451 #endif
452
453 #endif
454
455 static struct usb_descriptor_header *fsg_hs_function[] = {
456 #ifndef FSG_NO_OTG
457         (struct usb_descriptor_header *) &fsg_otg_desc,
458 #endif
459         (struct usb_descriptor_header *) &fsg_intf_desc,
460         (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
461         (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
462 #ifndef FSG_NO_INTR_EP
463         (struct usb_descriptor_header *) &fsg_hs_intr_in_desc,
464 #endif
465         NULL,
466 };
467
468 static struct usb_endpoint_descriptor
469 fsg_ss_bulk_in_desc = {
470         .bLength =              USB_DT_ENDPOINT_SIZE,
471         .bDescriptorType =      USB_DT_ENDPOINT,
472
473         /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
474         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
475         .wMaxPacketSize =       cpu_to_le16(1024),
476 };
477
478 static struct usb_ss_ep_comp_descriptor fsg_ss_bulk_in_comp_desc = {
479         .bLength =              sizeof(fsg_ss_bulk_in_comp_desc),
480         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
481
482         /*.bMaxBurst =          DYNAMIC, */
483 };
484
485 static struct usb_endpoint_descriptor
486 fsg_ss_bulk_out_desc = {
487         .bLength =              USB_DT_ENDPOINT_SIZE,
488         .bDescriptorType =      USB_DT_ENDPOINT,
489
490         /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
491         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
492         .wMaxPacketSize =       cpu_to_le16(1024),
493 };
494
495 static struct usb_ss_ep_comp_descriptor fsg_ss_bulk_out_comp_desc = {
496         .bLength =              sizeof(fsg_ss_bulk_in_comp_desc),
497         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
498
499         /*.bMaxBurst =          DYNAMIC, */
500 };
501
502 #ifndef FSG_NO_INTR_EP
503
504 static struct usb_endpoint_descriptor
505 fsg_ss_intr_in_desc = {
506         .bLength =              USB_DT_ENDPOINT_SIZE,
507         .bDescriptorType =      USB_DT_ENDPOINT,
508
509         /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
510         .bmAttributes =         USB_ENDPOINT_XFER_INT,
511         .wMaxPacketSize =       cpu_to_le16(2),
512         .bInterval =            9,      /* 2**(9-1) = 256 uframes -> 32 ms */
513 };
514
515 static struct usb_ss_ep_comp_descriptor fsg_ss_intr_in_comp_desc = {
516         .bLength =              sizeof(fsg_ss_bulk_in_comp_desc),
517         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
518
519         .wBytesPerInterval =    cpu_to_le16(2),
520 };
521
522 #ifndef FSG_NO_OTG
523 #  define FSG_SS_FUNCTION_PRE_EP_ENTRIES        2
524 #else
525 #  define FSG_SS_FUNCTION_PRE_EP_ENTRIES        1
526 #endif
527
528 #endif
529
530 static __maybe_unused struct usb_ext_cap_descriptor fsg_ext_cap_desc = {
531         .bLength =              USB_DT_USB_EXT_CAP_SIZE,
532         .bDescriptorType =      USB_DT_DEVICE_CAPABILITY,
533         .bDevCapabilityType =   USB_CAP_TYPE_EXT,
534
535         .bmAttributes =         cpu_to_le32(USB_LPM_SUPPORT),
536 };
537
538 static __maybe_unused struct usb_ss_cap_descriptor fsg_ss_cap_desc = {
539         .bLength =              USB_DT_USB_SS_CAP_SIZE,
540         .bDescriptorType =      USB_DT_DEVICE_CAPABILITY,
541         .bDevCapabilityType =   USB_SS_CAP_TYPE,
542
543         /* .bmAttributes = LTM is not supported yet */
544
545         .wSpeedSupported =      cpu_to_le16(USB_LOW_SPEED_OPERATION
546                 | USB_FULL_SPEED_OPERATION
547                 | USB_HIGH_SPEED_OPERATION
548                 | USB_5GBPS_OPERATION),
549         .bFunctionalitySupport = USB_LOW_SPEED_OPERATION,
550         .bU1devExitLat =        USB_DEFAULT_U1_DEV_EXIT_LAT,
551         .bU2DevExitLat =        cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT),
552 };
553
554 static __maybe_unused struct usb_bos_descriptor fsg_bos_desc = {
555         .bLength =              USB_DT_BOS_SIZE,
556         .bDescriptorType =      USB_DT_BOS,
557
558         .wTotalLength =         cpu_to_le16(USB_DT_BOS_SIZE
559                                 + USB_DT_USB_EXT_CAP_SIZE
560                                 + USB_DT_USB_SS_CAP_SIZE),
561
562         .bNumDeviceCaps =       2,
563 };
564
565 static struct usb_descriptor_header *fsg_ss_function[] = {
566 #ifndef FSG_NO_OTG
567         (struct usb_descriptor_header *) &fsg_otg_desc,
568 #endif
569         (struct usb_descriptor_header *) &fsg_intf_desc,
570         (struct usb_descriptor_header *) &fsg_ss_bulk_in_desc,
571         (struct usb_descriptor_header *) &fsg_ss_bulk_in_comp_desc,
572         (struct usb_descriptor_header *) &fsg_ss_bulk_out_desc,
573         (struct usb_descriptor_header *) &fsg_ss_bulk_out_comp_desc,
574 #ifndef FSG_NO_INTR_EP
575         (struct usb_descriptor_header *) &fsg_ss_intr_in_desc,
576         (struct usb_descriptor_header *) &fsg_ss_intr_in_comp_desc,
577 #endif
578         NULL,
579 };
580
581 /* Maxpacket and other transfer characteristics vary by speed. */
582 static __maybe_unused struct usb_endpoint_descriptor *
583 fsg_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
584                 struct usb_endpoint_descriptor *hs,
585                 struct usb_endpoint_descriptor *ss)
586 {
587         if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
588                 return ss;
589         else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
590                 return hs;
591         return fs;
592 }
593
594
595 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
596 static struct usb_string                fsg_strings[] = {
597 #ifndef FSG_NO_DEVICE_STRINGS
598         {FSG_STRING_MANUFACTURER,       fsg_string_manufacturer},
599         {FSG_STRING_PRODUCT,            fsg_string_product},
600         {FSG_STRING_SERIAL,             ""},
601         {FSG_STRING_CONFIG,             fsg_string_config},
602 #endif
603         {FSG_STRING_INTERFACE,          fsg_string_interface},
604         {}
605 };
606
607 static struct usb_gadget_strings        fsg_stringtab = {
608         .language       = 0x0409,               /* en-us */
609         .strings        = fsg_strings,
610 };
611
612
613  /*-------------------------------------------------------------------------*/
614
615 /*
616  * If the next two routines are called while the gadget is registered,
617  * the caller must own fsg->filesem for writing.
618  */
619
620 static void fsg_lun_close(struct fsg_lun *curlun)
621 {
622         if (curlun->filp) {
623                 LDBG(curlun, "close backing file\n");
624                 fput(curlun->filp);
625                 curlun->filp = NULL;
626         }
627 }
628
629
630 static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
631 {
632         int                             ro;
633         struct file                     *filp = NULL;
634         int                             rc = -EINVAL;
635         struct inode                    *inode = NULL;
636         loff_t                          size;
637         loff_t                          num_sectors;
638         loff_t                          min_sectors;
639         unsigned int                    blkbits;
640         unsigned int                    blksize;
641
642         /* R/W if we can, R/O if we must */
643         ro = curlun->initially_ro;
644         if (!ro) {
645                 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
646                 if (PTR_ERR(filp) == -EROFS || PTR_ERR(filp) == -EACCES)
647                         ro = 1;
648         }
649         if (ro)
650                 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
651         if (IS_ERR(filp)) {
652                 LINFO(curlun, "unable to open backing file: %s\n", filename);
653                 return PTR_ERR(filp);
654         }
655
656         if (!(filp->f_mode & FMODE_WRITE))
657                 ro = 1;
658
659         if (filp->f_path.dentry)
660                 inode = filp->f_path.dentry->d_inode;
661         if (!inode || (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))) {
662                 LINFO(curlun, "invalid file type: %s\n", filename);
663                 goto out;
664         }
665
666         /*
667          * If we can't read the file, it's no good.
668          * If we can't write the file, use it read-only.
669          */
670         if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
671                 LINFO(curlun, "file not readable: %s\n", filename);
672                 goto out;
673         }
674         if (!(filp->f_op->write || filp->f_op->aio_write))
675                 ro = 1;
676
677         size = i_size_read(inode->i_mapping->host);
678         if (size < 0) {
679                 LINFO(curlun, "unable to find file size: %s\n", filename);
680                 rc = (int) size;
681                 goto out;
682         }
683
684         if (curlun->cdrom) {
685                 blksize = 2048;
686                 blkbits = 11;
687         } else if (inode->i_bdev) {
688                 blksize = bdev_logical_block_size(inode->i_bdev);
689                 blkbits = blksize_bits(blksize);
690         } else {
691                 blksize = 512;
692                 blkbits = 9;
693         }
694
695         num_sectors = size >> blkbits; /* File size in logic-block-size blocks */
696         min_sectors = 1;
697         if (curlun->cdrom) {
698                 min_sectors = 300;      /* Smallest track is 300 frames */
699                 if (num_sectors >= 256*60*75) {
700                         num_sectors = 256*60*75 - 1;
701                         LINFO(curlun, "file too big: %s\n", filename);
702                         LINFO(curlun, "using only first %d blocks\n",
703                                         (int) num_sectors);
704                 }
705         }
706         if (num_sectors < min_sectors) {
707                 LINFO(curlun, "file too small: %s\n", filename);
708                 rc = -ETOOSMALL;
709                 goto out;
710         }
711
712         if (fsg_lun_is_open(curlun))
713                 fsg_lun_close(curlun);
714
715         get_file(filp);
716         curlun->blksize = blksize;
717         curlun->blkbits = blkbits;
718         curlun->ro = ro;
719         curlun->filp = filp;
720         curlun->file_length = size;
721         curlun->num_sectors = num_sectors;
722         LDBG(curlun, "open backing file: %s\n", filename);
723         rc = 0;
724
725 out:
726         filp_close(filp, current->files);
727         return rc;
728 }
729
730
731 /*-------------------------------------------------------------------------*/
732
733 /*
734  * Sync the file data, don't bother with the metadata.
735  * This code was copied from fs/buffer.c:sys_fdatasync().
736  */
737 static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
738 {
739         struct file     *filp = curlun->filp;
740
741         if (curlun->ro || !filp)
742                 return 0;
743         return vfs_fsync(filp, 1);
744 }
745
746 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
747 {
748         if (msf) {
749                 /* Convert to Minutes-Seconds-Frames */
750                 addr >>= 2;             /* Convert to 2048-byte frames */
751                 addr += 2*75;           /* Lead-in occupies 2 seconds */
752                 dest[3] = addr % 75;    /* Frames */
753                 addr /= 75;
754                 dest[2] = addr % 60;    /* Seconds */
755                 addr /= 60;
756                 dest[1] = addr;         /* Minutes */
757                 dest[0] = 0;            /* Reserved */
758         } else {
759                 /* Absolute sector */
760                 put_unaligned_be32(addr, dest);
761         }
762 }
763
764
765 /*-------------------------------------------------------------------------*/
766
767
768 static ssize_t fsg_show_ro(struct device *dev, struct device_attribute *attr,
769                            char *buf)
770 {
771         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
772
773         return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
774                                   ? curlun->ro
775                                   : curlun->initially_ro);
776 }
777
778 static ssize_t fsg_show_nofua(struct device *dev, struct device_attribute *attr,
779                               char *buf)
780 {
781         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
782
783         return sprintf(buf, "%u\n", curlun->nofua);
784 }
785
786 static ssize_t fsg_show_file(struct device *dev, struct device_attribute *attr,
787                              char *buf)
788 {
789         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
790         struct rw_semaphore     *filesem = dev_get_drvdata(dev);
791         char            *p;
792         ssize_t         rc;
793
794         down_read(filesem);
795         if (fsg_lun_is_open(curlun)) {  /* Get the complete pathname */
796                 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
797                 if (IS_ERR(p))
798                         rc = PTR_ERR(p);
799                 else {
800                         rc = strlen(p);
801                         memmove(buf, p, rc);
802                         buf[rc] = '\n';         /* Add a newline */
803                         buf[++rc] = 0;
804                 }
805         } else {                                /* No file, return 0 bytes */
806                 *buf = 0;
807                 rc = 0;
808         }
809         up_read(filesem);
810         return rc;
811 }
812
813
814 static ssize_t fsg_store_ro(struct device *dev, struct device_attribute *attr,
815                             const char *buf, size_t count)
816 {
817         ssize_t         rc;
818         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
819         struct rw_semaphore     *filesem = dev_get_drvdata(dev);
820         unsigned        ro;
821
822         rc = kstrtouint(buf, 2, &ro);
823         if (rc)
824                 return rc;
825
826         /*
827          * Allow the write-enable status to change only while the
828          * backing file is closed.
829          */
830         down_read(filesem);
831         if (fsg_lun_is_open(curlun)) {
832                 LDBG(curlun, "read-only status change prevented\n");
833                 rc = -EBUSY;
834         } else {
835                 curlun->ro = ro;
836                 curlun->initially_ro = ro;
837                 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
838                 rc = count;
839         }
840         up_read(filesem);
841         return rc;
842 }
843
844 static ssize_t fsg_store_nofua(struct device *dev,
845                                struct device_attribute *attr,
846                                const char *buf, size_t count)
847 {
848         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
849         unsigned        nofua;
850         int             ret;
851
852         ret = kstrtouint(buf, 2, &nofua);
853         if (ret)
854                 return ret;
855
856         /* Sync data when switching from async mode to sync */
857         if (!nofua && curlun->nofua)
858                 fsg_lun_fsync_sub(curlun);
859
860         curlun->nofua = nofua;
861
862         return count;
863 }
864
865 static ssize_t fsg_store_file(struct device *dev, struct device_attribute *attr,
866                               const char *buf, size_t count)
867 {
868         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
869         struct rw_semaphore     *filesem = dev_get_drvdata(dev);
870         int             rc = 0;
871
872         if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
873                 LDBG(curlun, "eject attempt prevented\n");
874                 return -EBUSY;                          /* "Door is locked" */
875         }
876
877         /* Remove a trailing newline */
878         if (count > 0 && buf[count-1] == '\n')
879                 ((char *) buf)[count-1] = 0;            /* Ugh! */
880
881
882         /* Load new medium */
883         down_write(filesem);
884         if (count > 0 && buf[0]) {
885                 /* fsg_lun_open() will close existing file if any. */
886                 rc = fsg_lun_open(curlun, buf);
887                 if (rc == 0)
888                         curlun->unit_attention_data =
889                                         SS_NOT_READY_TO_READY_TRANSITION;
890         } else if (fsg_lun_is_open(curlun)) {
891                 fsg_lun_close(curlun);
892                 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
893         }
894         up_write(filesem);
895         return (rc < 0 ? rc : count);
896 }