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