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