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