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