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