USB: g_file_storage: more code from file_storage.c moved to storage_common.c
[safe/jmp/linux-2.6] / drivers / usb / gadget / storage_common.c
1 /*
2  * storage_common.c -- Common definitions for mass storage functionality
3  *
4  * Copyright (C) 2003-2008 Alan Stern
5  * Copyeight (C) 2009 Samsung Electronics
6  * Author: Michal Nazarewicz (m.nazarewicz@samsung.com)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23
24 /*
25  * This file requires the following identifiers used in USB strings to
26  * be defined (each of type pointer to char):
27  *  - fsg_string_manufacturer -- name of the manufacturer
28  *  - fsg_string_product      -- name of the product
29  *  - fsg_string_serial       -- product's serial
30  *  - fsg_string_config       -- name of the configuration
31  *  - fsg_string_interface    -- name of the interface
32  * The first four are only needed when FSG_DESCRIPTORS_DEVICE_STRINGS
33  * macro is defined prior to including this file.
34  */
35
36
37 #include <asm/unaligned.h>
38
39
40 /* Thanks to NetChip Technologies for donating this product ID.
41  *
42  * DO NOT REUSE THESE IDs with any other driver!!  Ever!!
43  * Instead:  allocate your own, using normal USB-IF procedures. */
44 #define FSG_VENDOR_ID   0x0525  // NetChip
45 #define FSG_PRODUCT_ID  0xa4a5  // Linux-USB File-backed Storage Gadget
46
47
48 /*-------------------------------------------------------------------------*/
49
50
51 #ifndef DEBUG
52 #undef VERBOSE_DEBUG
53 #undef DUMP_MSGS
54 #endif /* !DEBUG */
55
56 #ifdef VERBOSE_DEBUG
57 #define VLDBG   LDBG
58 #else
59 #define VLDBG(lun, fmt, args...) do { } while (0)
60 #endif /* VERBOSE_DEBUG */
61
62 #define LDBG(lun, fmt, args...)   dev_dbg (&(lun)->dev, fmt, ## args)
63 #define LERROR(lun, fmt, args...) dev_err (&(lun)->dev, fmt, ## args)
64 #define LWARN(lun, fmt, args...)  dev_warn(&(lun)->dev, fmt, ## args)
65 #define LINFO(lun, fmt, args...)  dev_info(&(lun)->dev, fmt, ## args)
66
67 #define DBG(d, fmt, args...)      dev_dbg (&(d)->gadget->dev, fmt, ## args)
68 #define VDBG(d, fmt, args...)     dev_vdbg(&(d)->gadget->dev, fmt, ## args)
69 #define ERROR(d, fmt, args...)    dev_err (&(d)->gadget->dev, fmt, ## args)
70 #define WARNING(d, fmt, args...)  dev_warn(&(d)->gadget->dev, fmt, ## args)
71 #define INFO(d, fmt, args...)     dev_info(&(d)->gadget->dev, fmt, ## args)
72
73
74
75 #ifdef DUMP_MSGS
76
77 #  define dump_msg(fsg, /* const char * */ label,                       \
78                  /* const u8 * */ buf, /* unsigned */ length) do {      \
79         if (length < 512) {                                             \
80                 DBG(fsg, "%s, length %u:\n", label, length);            \
81                 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,      \
82                                16, 1, buf, length, 0);                  \
83         }                                                               \
84 } while (0)
85
86 #  define dump_cdb(fsg) do { } while (0)
87
88 #else
89
90 #  define dump_msg(fsg, /* const char * */ label, \
91                  /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
92
93 #  ifdef VERBOSE_DEBUG
94
95 #define dump_cdb(fsg)                                                   \
96         print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,      \
97                        16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0)         \
98
99 #  else
100
101 #    define dump_cdb(fsg) do { } while (0)
102
103 #  endif /* VERBOSE_DEBUG */
104
105 #endif /* DUMP_MSGS */
106
107
108
109
110
111 /*-------------------------------------------------------------------------*/
112
113 /* SCSI device types */
114 #define TYPE_DISK       0x00
115 #define TYPE_CDROM      0x05
116
117 /* USB protocol value = the transport method */
118 #define USB_PR_CBI      0x00            // Control/Bulk/Interrupt
119 #define USB_PR_CB       0x01            // Control/Bulk w/o interrupt
120 #define USB_PR_BULK     0x50            // Bulk-only
121
122 /* USB subclass value = the protocol encapsulation */
123 #define USB_SC_RBC      0x01            // Reduced Block Commands (flash)
124 #define USB_SC_8020     0x02            // SFF-8020i, MMC-2, ATAPI (CD-ROM)
125 #define USB_SC_QIC      0x03            // QIC-157 (tape)
126 #define USB_SC_UFI      0x04            // UFI (floppy)
127 #define USB_SC_8070     0x05            // SFF-8070i (removable)
128 #define USB_SC_SCSI     0x06            // Transparent SCSI
129
130 /* Bulk-only data structures */
131
132 /* Command Block Wrapper */
133 struct fsg_bulk_cb_wrap {
134         __le32  Signature;              // Contains 'USBC'
135         u32     Tag;                    // Unique per command id
136         __le32  DataTransferLength;     // Size of the data
137         u8      Flags;                  // Direction in bit 7
138         u8      Lun;                    // LUN (normally 0)
139         u8      Length;                 // Of the CDB, <= MAX_COMMAND_SIZE
140         u8      CDB[16];                // Command Data Block
141 };
142
143 #define USB_BULK_CB_WRAP_LEN    31
144 #define USB_BULK_CB_SIG         0x43425355      // Spells out USBC
145 #define USB_BULK_IN_FLAG        0x80
146
147 /* Command Status Wrapper */
148 struct bulk_cs_wrap {
149         __le32  Signature;              // Should = 'USBS'
150         u32     Tag;                    // Same as original command
151         __le32  Residue;                // Amount not transferred
152         u8      Status;                 // See below
153 };
154
155 #define USB_BULK_CS_WRAP_LEN    13
156 #define USB_BULK_CS_SIG         0x53425355      // Spells out 'USBS'
157 #define USB_STATUS_PASS         0
158 #define USB_STATUS_FAIL         1
159 #define USB_STATUS_PHASE_ERROR  2
160
161 /* Bulk-only class specific requests */
162 #define USB_BULK_RESET_REQUEST          0xff
163 #define USB_BULK_GET_MAX_LUN_REQUEST    0xfe
164
165
166 /* CBI Interrupt data structure */
167 struct interrupt_data {
168         u8      bType;
169         u8      bValue;
170 };
171
172 #define CBI_INTERRUPT_DATA_LEN          2
173
174 /* CBI Accept Device-Specific Command request */
175 #define USB_CBI_ADSC_REQUEST            0x00
176
177
178 #define MAX_COMMAND_SIZE        16      // Length of a SCSI Command Data Block
179
180 /* SCSI commands that we recognize */
181 #define SC_FORMAT_UNIT                  0x04
182 #define SC_INQUIRY                      0x12
183 #define SC_MODE_SELECT_6                0x15
184 #define SC_MODE_SELECT_10               0x55
185 #define SC_MODE_SENSE_6                 0x1a
186 #define SC_MODE_SENSE_10                0x5a
187 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
188 #define SC_READ_6                       0x08
189 #define SC_READ_10                      0x28
190 #define SC_READ_12                      0xa8
191 #define SC_READ_CAPACITY                0x25
192 #define SC_READ_FORMAT_CAPACITIES       0x23
193 #define SC_READ_HEADER                  0x44
194 #define SC_READ_TOC                     0x43
195 #define SC_RELEASE                      0x17
196 #define SC_REQUEST_SENSE                0x03
197 #define SC_RESERVE                      0x16
198 #define SC_SEND_DIAGNOSTIC              0x1d
199 #define SC_START_STOP_UNIT              0x1b
200 #define SC_SYNCHRONIZE_CACHE            0x35
201 #define SC_TEST_UNIT_READY              0x00
202 #define SC_VERIFY                       0x2f
203 #define SC_WRITE_6                      0x0a
204 #define SC_WRITE_10                     0x2a
205 #define SC_WRITE_12                     0xaa
206
207 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
208 #define SS_NO_SENSE                             0
209 #define SS_COMMUNICATION_FAILURE                0x040800
210 #define SS_INVALID_COMMAND                      0x052000
211 #define SS_INVALID_FIELD_IN_CDB                 0x052400
212 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE   0x052100
213 #define SS_LOGICAL_UNIT_NOT_SUPPORTED           0x052500
214 #define SS_MEDIUM_NOT_PRESENT                   0x023a00
215 #define SS_MEDIUM_REMOVAL_PREVENTED             0x055302
216 #define SS_NOT_READY_TO_READY_TRANSITION        0x062800
217 #define SS_RESET_OCCURRED                       0x062900
218 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED      0x053900
219 #define SS_UNRECOVERED_READ_ERROR               0x031100
220 #define SS_WRITE_ERROR                          0x030c02
221 #define SS_WRITE_PROTECTED                      0x072700
222
223 #define SK(x)           ((u8) ((x) >> 16))      // Sense Key byte, etc.
224 #define ASC(x)          ((u8) ((x) >> 8))
225 #define ASCQ(x)         ((u8) (x))
226
227
228 /*-------------------------------------------------------------------------*/
229
230
231 struct fsg_lun {
232         struct file     *filp;
233         loff_t          file_length;
234         loff_t          num_sectors;
235
236         unsigned int    initially_ro : 1;
237         unsigned int    ro : 1;
238         unsigned int    removable : 1;
239         unsigned int    cdrom : 1;
240         unsigned int    prevent_medium_removal : 1;
241         unsigned int    registered : 1;
242         unsigned int    info_valid : 1;
243
244         u32             sense_data;
245         u32             sense_data_info;
246         u32             unit_attention_data;
247
248         struct device   dev;
249 };
250
251 #define fsg_lun_is_open(curlun) ((curlun)->filp != NULL)
252
253 static struct fsg_lun *fsg_lun_from_dev(struct device *dev)
254 {
255         return container_of(dev, struct fsg_lun, dev);
256 }
257
258
259 /* Big enough to hold our biggest descriptor */
260 #define EP0_BUFSIZE     256
261 #define DELAYED_STATUS  (EP0_BUFSIZE + 999)     // An impossibly large value
262
263 /* Number of buffers we will use.  2 is enough for double-buffering */
264 #define FSG_NUM_BUFFERS 2
265
266 /* Default size of buffer length. */
267 #define FSG_BUFLEN      ((u32)16384)
268
269 /* Maximal number of LUNs supported in mass storage function */
270 #define FSG_MAX_LUNS    8
271
272 enum fsg_buffer_state {
273         BUF_STATE_EMPTY = 0,
274         BUF_STATE_FULL,
275         BUF_STATE_BUSY
276 };
277
278 struct fsg_buffhd {
279         void                            *buf;
280         enum fsg_buffer_state           state;
281         struct fsg_buffhd               *next;
282
283         /* The NetChip 2280 is faster, and handles some protocol faults
284          * better, if we don't submit any short bulk-out read requests.
285          * So we will record the intended request length here. */
286         unsigned int                    bulk_out_intended_length;
287
288         struct usb_request              *inreq;
289         int                             inreq_busy;
290         struct usb_request              *outreq;
291         int                             outreq_busy;
292 };
293
294 enum fsg_state {
295         FSG_STATE_COMMAND_PHASE = -10,          // This one isn't used anywhere
296         FSG_STATE_DATA_PHASE,
297         FSG_STATE_STATUS_PHASE,
298
299         FSG_STATE_IDLE = 0,
300         FSG_STATE_ABORT_BULK_OUT,
301         FSG_STATE_RESET,
302         FSG_STATE_INTERFACE_CHANGE,
303         FSG_STATE_CONFIG_CHANGE,
304         FSG_STATE_DISCONNECT,
305         FSG_STATE_EXIT,
306         FSG_STATE_TERMINATED
307 };
308
309 enum data_direction {
310         DATA_DIR_UNKNOWN = 0,
311         DATA_DIR_FROM_HOST,
312         DATA_DIR_TO_HOST,
313         DATA_DIR_NONE
314 };
315
316
317 /*-------------------------------------------------------------------------*/
318
319
320 static inline u32 get_unaligned_be24(u8 *buf)
321 {
322         return 0xffffff & (u32) get_unaligned_be32(buf - 1);
323 }
324
325
326 /*-------------------------------------------------------------------------*/
327
328
329 enum {
330         FSG_STRING_MANUFACTURER = 1,
331         FSG_STRING_PRODUCT,
332         FSG_STRING_SERIAL,
333         FSG_STRING_CONFIG,
334         FSG_STRING_INTERFACE
335 };
336
337
338 static struct usb_otg_descriptor
339 fsg_otg_desc = {
340         .bLength =              sizeof fsg_otg_desc,
341         .bDescriptorType =      USB_DT_OTG,
342
343         .bmAttributes =         USB_OTG_SRP,
344 };
345
346 /* There is only one interface. */
347
348 static struct usb_interface_descriptor
349 fsg_intf_desc = {
350         .bLength =              sizeof fsg_intf_desc,
351         .bDescriptorType =      USB_DT_INTERFACE,
352
353         .bNumEndpoints =        2,              // Adjusted during fsg_bind()
354         .bInterfaceClass =      USB_CLASS_MASS_STORAGE,
355         .bInterfaceSubClass =   USB_SC_SCSI,    // Adjusted during fsg_bind()
356         .bInterfaceProtocol =   USB_PR_BULK,    // Adjusted during fsg_bind()
357         .iInterface =           FSG_STRING_INTERFACE,
358 };
359
360 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
361  * and interrupt-in. */
362
363 static struct usb_endpoint_descriptor
364 fsg_fs_bulk_in_desc = {
365         .bLength =              USB_DT_ENDPOINT_SIZE,
366         .bDescriptorType =      USB_DT_ENDPOINT,
367
368         .bEndpointAddress =     USB_DIR_IN,
369         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
370         /* wMaxPacketSize set by autoconfiguration */
371 };
372
373 static struct usb_endpoint_descriptor
374 fsg_fs_bulk_out_desc = {
375         .bLength =              USB_DT_ENDPOINT_SIZE,
376         .bDescriptorType =      USB_DT_ENDPOINT,
377
378         .bEndpointAddress =     USB_DIR_OUT,
379         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
380         /* wMaxPacketSize set by autoconfiguration */
381 };
382
383 static struct usb_endpoint_descriptor
384 fsg_fs_intr_in_desc = {
385         .bLength =              USB_DT_ENDPOINT_SIZE,
386         .bDescriptorType =      USB_DT_ENDPOINT,
387
388         .bEndpointAddress =     USB_DIR_IN,
389         .bmAttributes =         USB_ENDPOINT_XFER_INT,
390         .wMaxPacketSize =       cpu_to_le16(2),
391         .bInterval =            32,     // frames -> 32 ms
392 };
393
394 static const struct usb_descriptor_header *fsg_fs_function[] = {
395         (struct usb_descriptor_header *) &fsg_otg_desc,
396         (struct usb_descriptor_header *) &fsg_intf_desc,
397         (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
398         (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
399         (struct usb_descriptor_header *) &fsg_fs_intr_in_desc,
400         NULL,
401 };
402 #define FSG_FS_FUNCTION_PRE_EP_ENTRIES  2
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 config 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 static struct usb_endpoint_descriptor
435 fsg_hs_intr_in_desc = {
436         .bLength =              USB_DT_ENDPOINT_SIZE,
437         .bDescriptorType =      USB_DT_ENDPOINT,
438
439         /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
440         .bmAttributes =         USB_ENDPOINT_XFER_INT,
441         .wMaxPacketSize =       cpu_to_le16(2),
442         .bInterval =            9,      // 2**(9-1) = 256 uframes -> 32 ms
443 };
444
445 static const struct usb_descriptor_header *fsg_hs_function[] = {
446         (struct usb_descriptor_header *) &fsg_otg_desc,
447         (struct usb_descriptor_header *) &fsg_intf_desc,
448         (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
449         (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
450         (struct usb_descriptor_header *) &fsg_hs_intr_in_desc,
451         NULL,
452 };
453 #define FSG_HS_FUNCTION_PRE_EP_ENTRIES  2
454
455 /* Maxpacket and other transfer characteristics vary by speed. */
456 static struct usb_endpoint_descriptor *
457 fsg_ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
458                 struct usb_endpoint_descriptor *hs)
459 {
460         if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
461                 return hs;
462         return fs;
463 }
464
465
466 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
467 static struct usb_string                fsg_strings[] = {
468         {FSG_STRING_MANUFACTURER,       fsg_string_manufacturer},
469         {FSG_STRING_PRODUCT,            fsg_string_product},
470         {FSG_STRING_SERIAL,             fsg_string_serial},
471         {FSG_STRING_CONFIG,             fsg_string_config},
472         {FSG_STRING_INTERFACE,          fsg_string_interface},
473         {}
474 };
475
476 static struct usb_gadget_strings        fsg_stringtab = {
477         .language       = 0x0409,               // en-us
478         .strings        = fsg_strings,
479 };
480
481
482  /*-------------------------------------------------------------------------*/
483
484 /* If the next two routines are called while the gadget is registered,
485  * the caller must own fsg->filesem for writing. */
486
487 static int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
488 {
489         int                             ro;
490         struct file                     *filp = NULL;
491         int                             rc = -EINVAL;
492         struct inode                    *inode = NULL;
493         loff_t                          size;
494         loff_t                          num_sectors;
495         loff_t                          min_sectors;
496
497         /* R/W if we can, R/O if we must */
498         ro = curlun->initially_ro;
499         if (!ro) {
500                 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
501                 if (-EROFS == PTR_ERR(filp))
502                         ro = 1;
503         }
504         if (ro)
505                 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
506         if (IS_ERR(filp)) {
507                 LINFO(curlun, "unable to open backing file: %s\n", filename);
508                 return PTR_ERR(filp);
509         }
510
511         if (!(filp->f_mode & FMODE_WRITE))
512                 ro = 1;
513
514         if (filp->f_path.dentry)
515                 inode = filp->f_path.dentry->d_inode;
516         if (inode && S_ISBLK(inode->i_mode)) {
517                 if (bdev_read_only(inode->i_bdev))
518                         ro = 1;
519         } else if (!inode || !S_ISREG(inode->i_mode)) {
520                 LINFO(curlun, "invalid file type: %s\n", filename);
521                 goto out;
522         }
523
524         /* If we can't read the file, it's no good.
525          * If we can't write the file, use it read-only. */
526         if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
527                 LINFO(curlun, "file not readable: %s\n", filename);
528                 goto out;
529         }
530         if (!(filp->f_op->write || filp->f_op->aio_write))
531                 ro = 1;
532
533         size = i_size_read(inode->i_mapping->host);
534         if (size < 0) {
535                 LINFO(curlun, "unable to find file size: %s\n", filename);
536                 rc = (int) size;
537                 goto out;
538         }
539         num_sectors = size >> 9;        // File size in 512-byte blocks
540         min_sectors = 1;
541         if (curlun->cdrom) {
542                 num_sectors &= ~3;      // Reduce to a multiple of 2048
543                 min_sectors = 300*4;    // Smallest track is 300 frames
544                 if (num_sectors >= 256*60*75*4) {
545                         num_sectors = (256*60*75 - 1) * 4;
546                         LINFO(curlun, "file too big: %s\n", filename);
547                         LINFO(curlun, "using only first %d blocks\n",
548                                         (int) num_sectors);
549                 }
550         }
551         if (num_sectors < min_sectors) {
552                 LINFO(curlun, "file too small: %s\n", filename);
553                 rc = -ETOOSMALL;
554                 goto out;
555         }
556
557         get_file(filp);
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         rc = 0;
564
565 out:
566         filp_close(filp, current->files);
567         return rc;
568 }
569
570
571 static void fsg_lun_close(struct fsg_lun *curlun)
572 {
573         if (curlun->filp) {
574                 LDBG(curlun, "close backing file\n");
575                 fput(curlun->filp);
576                 curlun->filp = NULL;
577         }
578 }
579
580
581 /*-------------------------------------------------------------------------*/
582
583 /* Sync the file data, don't bother with the metadata.
584  * This code was copied from fs/buffer.c:sys_fdatasync(). */
585 static int fsg_lun_fsync_sub(struct fsg_lun *curlun)
586 {
587         struct file     *filp = curlun->filp;
588
589         if (curlun->ro || !filp)
590                 return 0;
591         return vfs_fsync(filp, filp->f_path.dentry, 1);
592 }
593
594 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
595 {
596         if (msf) {
597                 /* Convert to Minutes-Seconds-Frames */
598                 addr >>= 2;             /* Convert to 2048-byte frames */
599                 addr += 2*75;           /* Lead-in occupies 2 seconds */
600                 dest[3] = addr % 75;    /* Frames */
601                 addr /= 75;
602                 dest[2] = addr % 60;    /* Seconds */
603                 addr /= 60;
604                 dest[1] = addr;         /* Minutes */
605                 dest[0] = 0;            /* Reserved */
606         } else {
607                 /* Absolute sector */
608                 put_unaligned_be32(addr, dest);
609         }
610 }
611
612
613 /*-------------------------------------------------------------------------*/
614
615
616 static ssize_t fsg_show_ro(struct device *dev, struct device_attribute *attr,
617                            char *buf)
618 {
619         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
620
621         return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
622                                   ? curlun->ro
623                                   : curlun->initially_ro);
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 = count;
658         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
659         struct rw_semaphore     *filesem = dev_get_drvdata(dev);
660         int             i;
661
662         if (sscanf(buf, "%d", &i) != 1)
663                 return -EINVAL;
664
665         /* Allow the write-enable status to change only while the backing file
666          * is closed. */
667         down_read(filesem);
668         if (fsg_lun_is_open(curlun)) {
669                 LDBG(curlun, "read-only status change prevented\n");
670                 rc = -EBUSY;
671         } else {
672                 curlun->ro = !!i;
673                 curlun->initially_ro = !!i;
674                 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
675         }
676         up_read(filesem);
677         return rc;
678 }
679
680 static ssize_t fsg_store_file(struct device *dev, struct device_attribute *attr,
681                               const char *buf, size_t count)
682 {
683         struct fsg_lun  *curlun = fsg_lun_from_dev(dev);
684         struct rw_semaphore     *filesem = dev_get_drvdata(dev);
685         int             rc = 0;
686
687         if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
688                 LDBG(curlun, "eject attempt prevented\n");
689                 return -EBUSY;                          // "Door is locked"
690         }
691
692         /* Remove a trailing newline */
693         if (count > 0 && buf[count-1] == '\n')
694                 ((char *) buf)[count-1] = 0;            // Ugh!
695
696         /* Eject current medium */
697         down_write(filesem);
698         if (fsg_lun_is_open(curlun)) {
699                 fsg_lun_close(curlun);
700                 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
701         }
702
703         /* Load new medium */
704         if (count > 0 && buf[0]) {
705                 rc = fsg_lun_open(curlun, buf);
706                 if (rc == 0)
707                         curlun->unit_attention_data =
708                                         SS_NOT_READY_TO_READY_TRANSITION;
709         }
710         up_write(filesem);
711         return (rc < 0 ? rc : count);
712 }