OSDN Git Service

d81ce9ebf8421fb781829a9d08810d087645a4bc
[android-x86/kernel.git] / drivers / usb / gadget / f_mass_storage.c
1 /*
2  * drivers/usb/gadget/f_mass_storage.c
3  *
4  * Function Driver for USB Mass Storage
5  *
6  * Copyright (C) 2008 Google, Inc.
7  * Author: Mike Lockwood <lockwood@android.com>
8  *
9  * Based heavily on the file_storage gadget driver in
10  * drivers/usb/gadget/file_storage.c and licensed under the same terms:
11  *
12  * Copyright (C) 2003-2007 Alan Stern
13  * All rights reserved.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions, and the following disclaimer,
20  *    without modification.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. The names of the above-listed copyright holders may not be used
25  *    to endorse or promote products derived from this software without
26  *    specific prior written permission.
27  *
28  * ALTERNATIVELY, this software may be distributed under the terms of the
29  * GNU General Public License ("GPL") as published by the Free Software
30  * Foundation, either version 2 of that License or (at your option) any
31  * later version.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
34  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
35  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
36  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
38  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
39  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
40  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  */
45
46 /* #define DEBUG */
47 /* #define VERBOSE_DEBUG */
48 /* #define DUMP_MSGS */
49
50
51 #include <linux/blkdev.h>
52 #include <linux/completion.h>
53 #include <linux/dcache.h>
54 #include <linux/delay.h>
55 #include <linux/device.h>
56 #include <linux/fcntl.h>
57 #include <linux/file.h>
58 #include <linux/fs.h>
59 #include <linux/kref.h>
60 #include <linux/kthread.h>
61 #include <linux/limits.h>
62 #include <linux/rwsem.h>
63 #include <linux/slab.h>
64 #include <linux/spinlock.h>
65 #include <linux/string.h>
66 #include <linux/switch.h>
67 #include <linux/freezer.h>
68 #include <linux/utsname.h>
69 #include <linux/wakelock.h>
70 #include <linux/platform_device.h>
71
72 #include <linux/usb_usual.h>
73 #include <linux/usb/ch9.h>
74 #include <linux/usb/composite.h>
75 #include <linux/usb/gadget.h>
76 #include <linux/usb/android.h>
77
78 #include "f_mass_storage.h"
79 #include "gadget_chips.h"
80
81
82 #define BULK_BUFFER_SIZE           4096
83
84 /*-------------------------------------------------------------------------*/
85
86 #define DRIVER_NAME             "usb_mass_storage"
87 #define MAX_LUNS                8
88
89 static const char shortname[] = DRIVER_NAME;
90
91 #ifdef DEBUG
92 #define LDBG(lun, fmt, args...) \
93         dev_dbg(&(lun)->dev , fmt , ## args)
94 #define MDBG(fmt,args...) \
95         printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
96 #else
97 #define LDBG(lun, fmt, args...) \
98         do { } while (0)
99 #define MDBG(fmt,args...) \
100         do { } while (0)
101 #undef VERBOSE_DEBUG
102 #undef DUMP_MSGS
103 #endif /* DEBUG */
104
105 #ifdef VERBOSE_DEBUG
106 #define VLDBG   LDBG
107 #else
108 #define VLDBG(lun, fmt, args...) \
109         do { } while (0)
110 #endif /* VERBOSE_DEBUG */
111
112 #define LERROR(lun, fmt, args...) \
113         dev_err(&(lun)->dev , fmt , ## args)
114 #define LWARN(lun, fmt, args...) \
115         dev_warn(&(lun)->dev , fmt , ## args)
116 #define LINFO(lun, fmt, args...) \
117         dev_info(&(lun)->dev , fmt , ## args)
118
119 #define MINFO(fmt,args...) \
120         printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
121
122 #undef DBG
123 #undef VDBG
124 #undef ERROR
125 #undef WARNING
126 #undef INFO
127 #define DBG(d, fmt, args...) \
128         dev_dbg(&(d)->cdev->gadget->dev , fmt , ## args)
129 #define VDBG(d, fmt, args...) \
130         dev_vdbg(&(d)->cdev->gadget->dev , fmt , ## args)
131 #define ERROR(d, fmt, args...) \
132         dev_err(&(d)->cdev->gadget->dev , fmt , ## args)
133 #define WARNING(d, fmt, args...) \
134         dev_warn(&(d)->cdev->gadget->dev , fmt , ## args)
135 #define INFO(d, fmt, args...) \
136         dev_info(&(d)->cdev->gadget->dev , fmt , ## args)
137
138
139 /*-------------------------------------------------------------------------*/
140
141 /* Bulk-only data structures */
142
143 /* Command Block Wrapper */
144 struct bulk_cb_wrap {
145         __le32  Signature;              /* Contains 'USBC' */
146         u32     Tag;                    /* Unique per command id */
147         __le32  DataTransferLength;     /* Size of the data */
148         u8      Flags;                  /* Direction in bit 7 */
149         u8      Lun;                    /* LUN (normally 0) */
150         u8      Length;                 /* Of the CDB, <= MAX_COMMAND_SIZE */
151         u8      CDB[16];                /* Command Data Block */
152 };
153
154 #define USB_BULK_CB_WRAP_LEN    31
155 #define USB_BULK_CB_SIG         0x43425355      /* Spells out USBC */
156 #define USB_BULK_IN_FLAG        0x80
157
158 /* Command Status Wrapper */
159 struct bulk_cs_wrap {
160         __le32  Signature;              /* Should = 'USBS' */
161         u32     Tag;                    /* Same as original command */
162         __le32  Residue;                /* Amount not transferred */
163         u8      Status;                 /* See below */
164 };
165
166 #define USB_BULK_CS_WRAP_LEN    13
167 #define USB_BULK_CS_SIG         0x53425355      /* Spells out 'USBS' */
168 #define USB_STATUS_PASS         0
169 #define USB_STATUS_FAIL         1
170 #define USB_STATUS_PHASE_ERROR  2
171
172 /* Bulk-only class specific requests */
173 #define USB_BULK_RESET_REQUEST          0xff
174 #define USB_BULK_GET_MAX_LUN_REQUEST    0xfe
175
176 /* Length of a SCSI Command Data Block */
177 #define MAX_COMMAND_SIZE        16
178
179 /* SCSI commands that we recognize */
180 #define SC_FORMAT_UNIT                  0x04
181 #define SC_INQUIRY                      0x12
182 #define SC_MODE_SELECT_6                0x15
183 #define SC_MODE_SELECT_10               0x55
184 #define SC_MODE_SENSE_6                 0x1a
185 #define SC_MODE_SENSE_10                0x5a
186 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
187 #define SC_READ_6                       0x08
188 #define SC_READ_10                      0x28
189 #define SC_READ_12                      0xa8
190 #define SC_READ_CAPACITY                0x25
191 #define SC_READ_FORMAT_CAPACITIES       0x23
192 #define SC_RELEASE                      0x17
193 #define SC_REQUEST_SENSE                0x03
194 #define SC_RESERVE                      0x16
195 #define SC_SEND_DIAGNOSTIC              0x1d
196 #define SC_START_STOP_UNIT              0x1b
197 #define SC_SYNCHRONIZE_CACHE            0x35
198 #define SC_TEST_UNIT_READY              0x00
199 #define SC_VERIFY                       0x2f
200 #define SC_WRITE_6                      0x0a
201 #define SC_WRITE_10                     0x2a
202 #define SC_WRITE_12                     0xaa
203
204 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
205 #define SS_NO_SENSE                             0
206 #define SS_COMMUNICATION_FAILURE                0x040800
207 #define SS_INVALID_COMMAND                      0x052000
208 #define SS_INVALID_FIELD_IN_CDB                 0x052400
209 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE   0x052100
210 #define SS_LOGICAL_UNIT_NOT_SUPPORTED           0x052500
211 #define SS_MEDIUM_NOT_PRESENT                   0x023a00
212 #define SS_MEDIUM_REMOVAL_PREVENTED             0x055302
213 #define SS_NOT_READY_TO_READY_TRANSITION        0x062800
214 #define SS_RESET_OCCURRED                       0x062900
215 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED      0x053900
216 #define SS_UNRECOVERED_READ_ERROR               0x031100
217 #define SS_WRITE_ERROR                          0x030c02
218 #define SS_WRITE_PROTECTED                      0x072700
219
220 #define SK(x)           ((u8) ((x) >> 16))      /* Sense Key byte, etc. */
221 #define ASC(x)          ((u8) ((x) >> 8))
222 #define ASCQ(x)         ((u8) (x))
223
224
225 /*-------------------------------------------------------------------------*/
226
227 struct lun {
228         struct file     *filp;
229         loff_t          file_length;
230         loff_t          num_sectors;
231
232         unsigned int    ro : 1;
233         unsigned int    prevent_medium_removal : 1;
234         unsigned int    registered : 1;
235         unsigned int    info_valid : 1;
236
237         u32             sense_data;
238         u32             sense_data_info;
239         u32             unit_attention_data;
240
241         struct device   dev;
242 };
243
244 #define backing_file_is_open(curlun)    ((curlun)->filp != NULL)
245
246
247 static struct lun *dev_to_lun(struct device *dev)
248 {
249         return container_of(dev, struct lun, dev);
250 }
251
252 /* Big enough to hold our biggest descriptor */
253 #define EP0_BUFSIZE     256
254 #define DELAYED_STATUS  (EP0_BUFSIZE + 999)     /* An impossibly large value */
255
256 /* Number of buffers we will use.  2 is enough for double-buffering */
257 #define NUM_BUFFERS     2
258
259 enum fsg_buffer_state {
260         BUF_STATE_EMPTY = 0,
261         BUF_STATE_FULL,
262         BUF_STATE_BUSY
263 };
264
265 struct fsg_buffhd {
266         void                            *buf;
267         enum fsg_buffer_state           state;
268         struct fsg_buffhd               *next;
269
270         /* The NetChip 2280 is faster, and handles some protocol faults
271          * better, if we don't submit any short bulk-out read requests.
272          * So we will record the intended request length here. */
273         unsigned int                    bulk_out_intended_length;
274
275         struct usb_request              *inreq;
276         int                             inreq_busy;
277         struct usb_request              *outreq;
278         int                             outreq_busy;
279 };
280
281 enum fsg_state {
282         /* This one isn't used anywhere */
283         FSG_STATE_COMMAND_PHASE = -10,
284
285         FSG_STATE_DATA_PHASE,
286         FSG_STATE_STATUS_PHASE,
287
288         FSG_STATE_IDLE = 0,
289         FSG_STATE_ABORT_BULK_OUT,
290         FSG_STATE_RESET,
291         FSG_STATE_CONFIG_CHANGE,
292         FSG_STATE_EXIT,
293         FSG_STATE_TERMINATED
294 };
295
296 enum data_direction {
297         DATA_DIR_UNKNOWN = 0,
298         DATA_DIR_FROM_HOST,
299         DATA_DIR_TO_HOST,
300         DATA_DIR_NONE
301 };
302
303 struct fsg_dev {
304         struct usb_function function;
305         struct usb_composite_dev *cdev;
306
307         /* optional "usb_mass_storage" platform device */
308         struct platform_device *pdev;
309
310         /* lock protects: state and all the req_busy's */
311         spinlock_t              lock;
312
313         /* filesem protects: backing files in use */
314         struct rw_semaphore     filesem;
315
316         /* reference counting: wait until all LUNs are released */
317         struct kref             ref;
318
319         unsigned int            bulk_out_maxpacket;
320         enum fsg_state          state;          /* For exception handling */
321
322         u8                      config, new_config;
323
324         unsigned int            running : 1;
325         unsigned int            bulk_in_enabled : 1;
326         unsigned int            bulk_out_enabled : 1;
327         unsigned int            phase_error : 1;
328         unsigned int            short_packet_received : 1;
329         unsigned int            bad_lun_okay : 1;
330
331         unsigned long           atomic_bitflags;
332 #define REGISTERED              0
333 #define CLEAR_BULK_HALTS        1
334 #define SUSPENDED               2
335
336         struct usb_ep           *bulk_in;
337         struct usb_ep           *bulk_out;
338
339         struct fsg_buffhd       *next_buffhd_to_fill;
340         struct fsg_buffhd       *next_buffhd_to_drain;
341         struct fsg_buffhd       buffhds[NUM_BUFFERS];
342
343         int                     thread_wakeup_needed;
344         struct completion       thread_notifier;
345         struct task_struct      *thread_task;
346
347         int                     cmnd_size;
348         u8                      cmnd[MAX_COMMAND_SIZE];
349         enum data_direction     data_dir;
350         u32                     data_size;
351         u32                     data_size_from_cmnd;
352         u32                     tag;
353         unsigned int            lun;
354         u32                     residue;
355         u32                     usb_amount_left;
356
357         unsigned int            nluns;
358         struct lun              *luns;
359         struct lun              *curlun;
360
361         u32                             buf_size;
362         const char              *vendor;
363         const char              *product;
364         int                             release;
365
366         struct switch_dev sdev;
367
368         struct wake_lock wake_lock;
369 };
370
371 static inline struct fsg_dev *func_to_dev(struct usb_function *f)
372 {
373         return container_of(f, struct fsg_dev, function);
374 }
375
376 static int exception_in_progress(struct fsg_dev *fsg)
377 {
378         return (fsg->state > FSG_STATE_IDLE);
379 }
380
381 /* Make bulk-out requests be divisible by the maxpacket size */
382 static void set_bulk_out_req_length(struct fsg_dev *fsg,
383                 struct fsg_buffhd *bh, unsigned int length)
384 {
385         unsigned int    rem;
386
387         bh->bulk_out_intended_length = length;
388         rem = length % fsg->bulk_out_maxpacket;
389         if (rem > 0)
390                 length += fsg->bulk_out_maxpacket - rem;
391         bh->outreq->length = length;
392 }
393
394 static struct fsg_dev                   *the_fsg;
395
396 static void     close_backing_file(struct fsg_dev *fsg, struct lun *curlun);
397 static void     close_all_backing_files(struct fsg_dev *fsg);
398
399
400 /*-------------------------------------------------------------------------*/
401
402 #ifdef DUMP_MSGS
403
404 static void dump_msg(struct fsg_dev *fsg, const char *label,
405                 const u8 *buf, unsigned int length)
406 {
407         if (length < 512) {
408                 DBG(fsg, "%s, length %u:\n", label, length);
409                 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
410                                 16, 1, buf, length, 0);
411         }
412 }
413
414 static void dump_cdb(struct fsg_dev *fsg)
415 {}
416
417 #else
418
419 static void dump_msg(struct fsg_dev *fsg, const char *label,
420                 const u8 *buf, unsigned int length)
421 {}
422
423 #ifdef VERBOSE_DEBUG
424
425 static void dump_cdb(struct fsg_dev *fsg)
426 {
427         print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,
428                         16, 1, fsg->cmnd, fsg->cmnd_size, 0);
429 }
430
431 #else
432
433 static void dump_cdb(struct fsg_dev *fsg)
434 {}
435
436 #endif /* VERBOSE_DEBUG */
437 #endif /* DUMP_MSGS */
438
439
440 /*-------------------------------------------------------------------------*/
441
442 /* Routines for unaligned data access */
443
444 static u16 get_be16(u8 *buf)
445 {
446         return ((u16) buf[0] << 8) | ((u16) buf[1]);
447 }
448
449 static u32 get_be32(u8 *buf)
450 {
451         return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
452                         ((u32) buf[2] << 8) | ((u32) buf[3]);
453 }
454
455 static void put_be16(u8 *buf, u16 val)
456 {
457         buf[0] = val >> 8;
458         buf[1] = val;
459 }
460
461 static void put_be32(u8 *buf, u32 val)
462 {
463         buf[0] = val >> 24;
464         buf[1] = val >> 16;
465         buf[2] = val >> 8;
466         buf[3] = val & 0xff;
467 }
468
469 /*-------------------------------------------------------------------------*/
470
471 /*
472  * DESCRIPTORS ... most are static, but strings and (full) configuration
473  * descriptors are built on demand.  Also the (static) config and interface
474  * descriptors are adjusted during fsg_bind().
475  */
476
477 /* There is only one interface. */
478
479 static struct usb_interface_descriptor
480 intf_desc = {
481         .bLength =              sizeof intf_desc,
482         .bDescriptorType =      USB_DT_INTERFACE,
483
484         .bNumEndpoints =        2,              /* Adjusted during fsg_bind() */
485         .bInterfaceClass =      USB_CLASS_MASS_STORAGE,
486         .bInterfaceSubClass =   US_SC_SCSI,
487         .bInterfaceProtocol =   US_PR_BULK,
488 };
489
490 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
491  * and interrupt-in. */
492
493 static struct usb_endpoint_descriptor
494 fs_bulk_in_desc = {
495         .bLength =              USB_DT_ENDPOINT_SIZE,
496         .bDescriptorType =      USB_DT_ENDPOINT,
497
498         .bEndpointAddress =     USB_DIR_IN,
499         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
500         /* wMaxPacketSize set by autoconfiguration */
501 };
502
503 static struct usb_endpoint_descriptor
504 fs_bulk_out_desc = {
505         .bLength =              USB_DT_ENDPOINT_SIZE,
506         .bDescriptorType =      USB_DT_ENDPOINT,
507
508         .bEndpointAddress =     USB_DIR_OUT,
509         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
510         /* wMaxPacketSize set by autoconfiguration */
511 };
512
513 static struct usb_descriptor_header *fs_function[] = {
514         (struct usb_descriptor_header *) &intf_desc,
515         (struct usb_descriptor_header *) &fs_bulk_in_desc,
516         (struct usb_descriptor_header *) &fs_bulk_out_desc,
517         NULL,
518 };
519 #define FS_FUNCTION_PRE_EP_ENTRIES      2
520
521
522 static struct usb_endpoint_descriptor
523 hs_bulk_in_desc = {
524         .bLength =              USB_DT_ENDPOINT_SIZE,
525         .bDescriptorType =      USB_DT_ENDPOINT,
526
527         /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
528         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
529         .wMaxPacketSize =       __constant_cpu_to_le16(512),
530 };
531
532 static struct usb_endpoint_descriptor
533 hs_bulk_out_desc = {
534         .bLength =              USB_DT_ENDPOINT_SIZE,
535         .bDescriptorType =      USB_DT_ENDPOINT,
536
537         /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
538         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
539         .wMaxPacketSize =       __constant_cpu_to_le16(512),
540         .bInterval =            1,      /* NAK every 1 uframe */
541 };
542
543
544 static struct usb_descriptor_header *hs_function[] = {
545         (struct usb_descriptor_header *) &intf_desc,
546         (struct usb_descriptor_header *) &hs_bulk_in_desc,
547         (struct usb_descriptor_header *) &hs_bulk_out_desc,
548         NULL,
549 };
550
551 /* Maxpacket and other transfer characteristics vary by speed. */
552 static struct usb_endpoint_descriptor *
553 ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
554                 struct usb_endpoint_descriptor *hs)
555 {
556         if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
557                 return hs;
558         return fs;
559 }
560
561 /*-------------------------------------------------------------------------*/
562
563 /* These routines may be called in process context or in_irq */
564
565 /* Caller must hold fsg->lock */
566 static void wakeup_thread(struct fsg_dev *fsg)
567 {
568         /* Tell the main thread that something has happened */
569         fsg->thread_wakeup_needed = 1;
570         if (fsg->thread_task)
571                 wake_up_process(fsg->thread_task);
572 }
573
574
575 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
576 {
577         unsigned long           flags;
578
579         DBG(fsg, "raise_exception %d\n", (int)new_state);
580         /* Do nothing if a higher-priority exception is already in progress.
581          * If a lower-or-equal priority exception is in progress, preempt it
582          * and notify the main thread by sending it a signal. */
583         spin_lock_irqsave(&fsg->lock, flags);
584         if (fsg->state <= new_state) {
585                 fsg->state = new_state;
586                 if (fsg->thread_task)
587                         send_sig_info(SIGUSR1, SEND_SIG_FORCED,
588                                         fsg->thread_task);
589         }
590         spin_unlock_irqrestore(&fsg->lock, flags);
591 }
592
593
594 /*-------------------------------------------------------------------------*/
595
596 /* Bulk and interrupt endpoint completion handlers.
597  * These always run in_irq. */
598
599 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
600 {
601         struct fsg_dev          *fsg = ep->driver_data;
602         struct fsg_buffhd       *bh = req->context;
603
604         if (req->status || req->actual != req->length)
605                 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
606                                 req->status, req->actual, req->length);
607
608         /* Hold the lock while we update the request and buffer states */
609         smp_wmb();
610         spin_lock(&fsg->lock);
611         bh->inreq_busy = 0;
612         bh->state = BUF_STATE_EMPTY;
613         wakeup_thread(fsg);
614         spin_unlock(&fsg->lock);
615 }
616
617 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
618 {
619         struct fsg_dev          *fsg = ep->driver_data;
620         struct fsg_buffhd       *bh = req->context;
621
622         dump_msg(fsg, "bulk-out", req->buf, req->actual);
623         if (req->status || req->actual != bh->bulk_out_intended_length)
624                 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
625                                 req->status, req->actual,
626                                 bh->bulk_out_intended_length);
627
628         /* Hold the lock while we update the request and buffer states */
629         smp_wmb();
630         spin_lock(&fsg->lock);
631         bh->outreq_busy = 0;
632         bh->state = BUF_STATE_FULL;
633         wakeup_thread(fsg);
634         spin_unlock(&fsg->lock);
635 }
636
637 static int fsg_function_setup(struct usb_function *f,
638                                         const struct usb_ctrlrequest *ctrl)
639 {
640         struct fsg_dev  *fsg = func_to_dev(f);
641         struct usb_composite_dev *cdev = fsg->cdev;
642         int                     value = -EOPNOTSUPP;
643         u16                     w_index = le16_to_cpu(ctrl->wIndex);
644         u16                     w_value = le16_to_cpu(ctrl->wValue);
645         u16                     w_length = le16_to_cpu(ctrl->wLength);
646
647         DBG(fsg, "fsg_function_setup\n");
648         /* Handle Bulk-only class-specific requests */
649         if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
650         DBG(fsg, "USB_TYPE_CLASS\n");
651                 switch (ctrl->bRequest) {
652                 case USB_BULK_RESET_REQUEST:
653                         if (ctrl->bRequestType != (USB_DIR_OUT |
654                                         USB_TYPE_CLASS | USB_RECIP_INTERFACE))
655                                 break;
656                         if (w_index != 0 || w_value != 0) {
657                                 value = -EDOM;
658                                 break;
659                         }
660
661                         /* Raise an exception to stop the current operation
662                          * and reinitialize our state. */
663                         DBG(fsg, "bulk reset request\n");
664                         raise_exception(fsg, FSG_STATE_RESET);
665                         value = DELAYED_STATUS;
666                         break;
667
668                 case USB_BULK_GET_MAX_LUN_REQUEST:
669                         if (ctrl->bRequestType != (USB_DIR_IN |
670                                         USB_TYPE_CLASS | USB_RECIP_INTERFACE))
671                                 break;
672                         if (w_index != 0 || w_value != 0) {
673                                 value = -EDOM;
674                                 break;
675                         }
676                         VDBG(fsg, "get max LUN\n");
677                         *(u8 *)cdev->req->buf = fsg->nluns - 1;
678                         value = 1;
679                         break;
680                 }
681         }
682
683         if (value == -EOPNOTSUPP)
684                 VDBG(fsg,
685                         "unknown class-specific control req "
686                         "%02x.%02x v%04x i%04x l%u\n",
687                         ctrl->bRequestType, ctrl->bRequest,
688                         le16_to_cpu(ctrl->wValue), w_index, w_length);
689         return value;
690 }
691
692 /*-------------------------------------------------------------------------*/
693
694 /* All the following routines run in process context */
695
696
697 /* Use this for bulk or interrupt transfers, not ep0 */
698 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
699                 struct usb_request *req, int *pbusy,
700                 enum fsg_buffer_state *state)
701 {
702         int     rc;
703
704         DBG(fsg, "start_transfer req: %p, req->buf: %p\n", req, req->buf);
705         if (ep == fsg->bulk_in)
706                 dump_msg(fsg, "bulk-in", req->buf, req->length);
707
708         spin_lock_irq(&fsg->lock);
709         *pbusy = 1;
710         *state = BUF_STATE_BUSY;
711         spin_unlock_irq(&fsg->lock);
712         rc = usb_ep_queue(ep, req, GFP_KERNEL);
713         if (rc != 0) {
714                 *pbusy = 0;
715                 *state = BUF_STATE_EMPTY;
716
717                 /* We can't do much more than wait for a reset */
718
719                 /* Note: currently the net2280 driver fails zero-length
720                  * submissions if DMA is enabled. */
721                 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
722                                                 req->length == 0))
723                         WARN(fsg, "error in submission: %s --> %d\n",
724                                 (ep == fsg->bulk_in ? "bulk-in" : "bulk-out"),
725                                 rc);
726         }
727 }
728
729
730 static int sleep_thread(struct fsg_dev *fsg)
731 {
732         int     rc = 0;
733
734         /* Wait until a signal arrives or we are woken up */
735         for (;;) {
736                 try_to_freeze();
737                 set_current_state(TASK_INTERRUPTIBLE);
738                 if (signal_pending(current)) {
739                         rc = -EINTR;
740                         break;
741                 }
742                 if (fsg->thread_wakeup_needed)
743                         break;
744                 schedule();
745         }
746         __set_current_state(TASK_RUNNING);
747         fsg->thread_wakeup_needed = 0;
748         return rc;
749 }
750
751
752 /*-------------------------------------------------------------------------*/
753
754 static int do_read(struct fsg_dev *fsg)
755 {
756         struct lun              *curlun = fsg->curlun;
757         u32                     lba;
758         struct fsg_buffhd       *bh;
759         int                     rc;
760         u32                     amount_left;
761         loff_t                  file_offset, file_offset_tmp;
762         unsigned int            amount;
763         unsigned int            partial_page;
764         ssize_t                 nread;
765
766         /* Get the starting Logical Block Address and check that it's
767          * not too big */
768         if (fsg->cmnd[0] == SC_READ_6)
769                 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
770         else {
771                 lba = get_be32(&fsg->cmnd[2]);
772
773                 /* We allow DPO (Disable Page Out = don't save data in the
774                  * cache) and FUA (Force Unit Access = don't read from the
775                  * cache), but we don't implement them. */
776                 if ((fsg->cmnd[1] & ~0x18) != 0) {
777                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
778                         return -EINVAL;
779                 }
780         }
781         if (lba >= curlun->num_sectors) {
782                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
783                 return -EINVAL;
784         }
785         file_offset = ((loff_t) lba) << 9;
786
787         /* Carry out the file reads */
788         amount_left = fsg->data_size_from_cmnd;
789         if (unlikely(amount_left == 0))
790                 return -EIO;            /* No default reply */
791
792         for (;;) {
793
794                 /* Figure out how much we need to read:
795                  * Try to read the remaining amount.
796                  * But don't read more than the buffer size.
797                  * And don't try to read past the end of the file.
798                  * Finally, if we're not at a page boundary, don't read past
799                  *      the next page.
800                  * If this means reading 0 then we were asked to read past
801                  *      the end of file. */
802                 amount = min((unsigned int) amount_left,
803                                 (unsigned int)fsg->buf_size);
804                 amount = min((loff_t) amount,
805                                 curlun->file_length - file_offset);
806                 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
807                 if (partial_page > 0)
808                         amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
809                                         partial_page);
810
811                 /* Wait for the next buffer to become available */
812                 bh = fsg->next_buffhd_to_fill;
813                 while (bh->state != BUF_STATE_EMPTY) {
814                         rc = sleep_thread(fsg);
815                         if (rc)
816                                 return rc;
817                 }
818
819                 /* If we were asked to read past the end of file,
820                  * end with an empty buffer. */
821                 if (amount == 0) {
822                         curlun->sense_data =
823                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
824                         curlun->sense_data_info = file_offset >> 9;
825                         curlun->info_valid = 1;
826                         bh->inreq->length = 0;
827                         bh->state = BUF_STATE_FULL;
828                         break;
829                 }
830
831                 /* Perform the read */
832                 file_offset_tmp = file_offset;
833                 nread = vfs_read(curlun->filp,
834                                 (char __user *) bh->buf,
835                                 amount, &file_offset_tmp);
836                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
837                                 (unsigned long long) file_offset,
838                                 (int) nread);
839                 if (signal_pending(current))
840                         return -EINTR;
841
842                 if (nread < 0) {
843                         LDBG(curlun, "error in file read: %d\n",
844                                         (int) nread);
845                         nread = 0;
846                 } else if (nread < amount) {
847                         LDBG(curlun, "partial file read: %d/%u\n",
848                                         (int) nread, amount);
849                         nread -= (nread & 511); /* Round down to a block */
850                 }
851                 file_offset  += nread;
852                 amount_left  -= nread;
853                 fsg->residue -= nread;
854                 bh->inreq->length = nread;
855                 bh->state = BUF_STATE_FULL;
856
857                 /* If an error occurred, report it and its position */
858                 if (nread < amount) {
859                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
860                         curlun->sense_data_info = file_offset >> 9;
861                         curlun->info_valid = 1;
862                         break;
863                 }
864
865                 if (amount_left == 0)
866                         break;          /* No more left to read */
867
868                 /* Send this buffer and go read some more */
869                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
870                                 &bh->inreq_busy, &bh->state);
871                 fsg->next_buffhd_to_fill = bh->next;
872         }
873
874         return -EIO;            /* No default reply */
875 }
876
877
878 /*-------------------------------------------------------------------------*/
879
880 static int do_write(struct fsg_dev *fsg)
881 {
882         struct lun              *curlun = fsg->curlun;
883         u32                     lba;
884         struct fsg_buffhd       *bh;
885         int                     get_some_more;
886         u32                     amount_left_to_req, amount_left_to_write;
887         loff_t                  usb_offset, file_offset, file_offset_tmp;
888         unsigned int            amount;
889         unsigned int            partial_page;
890         ssize_t                 nwritten;
891         int                     rc;
892
893         if (curlun->ro) {
894                 curlun->sense_data = SS_WRITE_PROTECTED;
895                 return -EINVAL;
896         }
897         curlun->filp->f_flags &= ~O_SYNC;       /* Default is not to wait */
898
899         /* Get the starting Logical Block Address and check that it's
900          * not too big */
901         if (fsg->cmnd[0] == SC_WRITE_6)
902                 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
903         else {
904                 lba = get_be32(&fsg->cmnd[2]);
905
906                 /* We allow DPO (Disable Page Out = don't save data in the
907                  * cache) and FUA (Force Unit Access = write directly to the
908                  * medium).  We don't implement DPO; we implement FUA by
909                  * performing synchronous output. */
910                 if ((fsg->cmnd[1] & ~0x18) != 0) {
911                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
912                         return -EINVAL;
913                 }
914                 if (fsg->cmnd[1] & 0x08)        /* FUA */
915                         curlun->filp->f_flags |= O_SYNC;
916         }
917         if (lba >= curlun->num_sectors) {
918                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
919                 return -EINVAL;
920         }
921
922         /* Carry out the file writes */
923         get_some_more = 1;
924         file_offset = usb_offset = ((loff_t) lba) << 9;
925         amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
926
927         while (amount_left_to_write > 0) {
928
929                 /* Queue a request for more data from the host */
930                 bh = fsg->next_buffhd_to_fill;
931                 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
932
933                         /* Figure out how much we want to get:
934                          * Try to get the remaining amount.
935                          * But don't get more than the buffer size.
936                          * And don't try to go past the end of the file.
937                          * If we're not at a page boundary,
938                          *      don't go past the next page.
939                          * If this means getting 0, then we were asked
940                          *      to write past the end of file.
941                          * Finally, round down to a block boundary. */
942                         amount = min(amount_left_to_req, (u32)fsg->buf_size);
943                         amount = min((loff_t) amount, curlun->file_length -
944                                         usb_offset);
945                         partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
946                         if (partial_page > 0)
947                                 amount = min(amount,
948         (unsigned int) PAGE_CACHE_SIZE - partial_page);
949
950                         if (amount == 0) {
951                                 get_some_more = 0;
952                                 curlun->sense_data =
953                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
954                                 curlun->sense_data_info = usb_offset >> 9;
955                                 curlun->info_valid = 1;
956                                 continue;
957                         }
958                         amount -= (amount & 511);
959                         if (amount == 0) {
960
961                                 /* Why were we were asked to transfer a
962                                  * partial block? */
963                                 get_some_more = 0;
964                                 continue;
965                         }
966
967                         /* Get the next buffer */
968                         usb_offset += amount;
969                         fsg->usb_amount_left -= amount;
970                         amount_left_to_req -= amount;
971                         if (amount_left_to_req == 0)
972                                 get_some_more = 0;
973
974                         /* amount is always divisible by 512, hence by
975                          * the bulk-out maxpacket size */
976                         bh->outreq->length = bh->bulk_out_intended_length =
977                                         amount;
978                         start_transfer(fsg, fsg->bulk_out, bh->outreq,
979                                         &bh->outreq_busy, &bh->state);
980                         fsg->next_buffhd_to_fill = bh->next;
981                         continue;
982                 }
983
984                 /* Write the received data to the backing file */
985                 bh = fsg->next_buffhd_to_drain;
986                 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
987                         break;                  /* We stopped early */
988                 if (bh->state == BUF_STATE_FULL) {
989                         smp_rmb();
990                         fsg->next_buffhd_to_drain = bh->next;
991                         bh->state = BUF_STATE_EMPTY;
992
993                         /* Did something go wrong with the transfer? */
994                         if (bh->outreq->status != 0) {
995                                 curlun->sense_data = SS_COMMUNICATION_FAILURE;
996                                 curlun->sense_data_info = file_offset >> 9;
997                                 curlun->info_valid = 1;
998                                 break;
999                         }
1000
1001                         amount = bh->outreq->actual;
1002                         if (curlun->file_length - file_offset < amount) {
1003                                 LERROR(curlun,
1004         "write %u @ %llu beyond end %llu\n",
1005         amount, (unsigned long long) file_offset,
1006         (unsigned long long) curlun->file_length);
1007                                 amount = curlun->file_length - file_offset;
1008                         }
1009
1010                         /* Perform the write */
1011                         file_offset_tmp = file_offset;
1012                         nwritten = vfs_write(curlun->filp,
1013                                         (char __user *) bh->buf,
1014                                         amount, &file_offset_tmp);
1015                         VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1016                                         (unsigned long long) file_offset,
1017                                         (int) nwritten);
1018                         if (signal_pending(current))
1019                                 return -EINTR;          /* Interrupted! */
1020
1021                         if (nwritten < 0) {
1022                                 LDBG(curlun, "error in file write: %d\n",
1023                                                 (int) nwritten);
1024                                 nwritten = 0;
1025                         } else if (nwritten < amount) {
1026                                 LDBG(curlun, "partial file write: %d/%u\n",
1027                                                 (int) nwritten, amount);
1028                                 nwritten -= (nwritten & 511);
1029                                                 /* Round down to a block */
1030                         }
1031                         file_offset += nwritten;
1032                         amount_left_to_write -= nwritten;
1033                         fsg->residue -= nwritten;
1034
1035                         /* If an error occurred, report it and its position */
1036                         if (nwritten < amount) {
1037                                 curlun->sense_data = SS_WRITE_ERROR;
1038                                 curlun->sense_data_info = file_offset >> 9;
1039                                 curlun->info_valid = 1;
1040                                 break;
1041                         }
1042
1043                         /* Did the host decide to stop early? */
1044                         if (bh->outreq->actual != bh->outreq->length) {
1045                                 fsg->short_packet_received = 1;
1046                                 break;
1047                         }
1048                         continue;
1049                 }
1050
1051                 /* Wait for something to happen */
1052                 rc = sleep_thread(fsg);
1053                 if (rc)
1054                         return rc;
1055         }
1056
1057         return -EIO;            /* No default reply */
1058 }
1059
1060
1061 /*-------------------------------------------------------------------------*/
1062
1063 /* Sync the file data, don't bother with the metadata.
1064  * The caller must own fsg->filesem.
1065  * This code was copied from fs/buffer.c:sys_fdatasync(). */
1066 static int fsync_sub(struct lun *curlun)
1067 {
1068         struct file     *filp = curlun->filp;
1069         struct inode    *inode;
1070         int             rc, err;
1071
1072         if (curlun->ro || !filp)
1073                 return 0;
1074         if (!filp->f_op->fsync)
1075                 return -EINVAL;
1076
1077         inode = filp->f_path.dentry->d_inode;
1078         mutex_lock(&inode->i_mutex);
1079         rc = filemap_fdatawrite(inode->i_mapping);
1080         err = filp->f_op->fsync(filp, filp->f_path.dentry, 1);
1081         if (!rc)
1082                 rc = err;
1083         err = filemap_fdatawait(inode->i_mapping);
1084         if (!rc)
1085                 rc = err;
1086         mutex_unlock(&inode->i_mutex);
1087         VLDBG(curlun, "fdatasync -> %d\n", rc);
1088         return rc;
1089 }
1090
1091 static void fsync_all(struct fsg_dev *fsg)
1092 {
1093         int     i;
1094
1095         for (i = 0; i < fsg->nluns; ++i)
1096                 fsync_sub(&fsg->luns[i]);
1097 }
1098
1099 static int do_synchronize_cache(struct fsg_dev *fsg)
1100 {
1101         struct lun      *curlun = fsg->curlun;
1102         int             rc;
1103
1104         /* We ignore the requested LBA and write out all file's
1105          * dirty data buffers. */
1106         rc = fsync_sub(curlun);
1107         if (rc)
1108                 curlun->sense_data = SS_WRITE_ERROR;
1109         return 0;
1110 }
1111
1112
1113 /*-------------------------------------------------------------------------*/
1114
1115 static void invalidate_sub(struct lun *curlun)
1116 {
1117         struct file     *filp = curlun->filp;
1118         struct inode    *inode = filp->f_path.dentry->d_inode;
1119         unsigned long   rc;
1120
1121         rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1122         VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1123 }
1124
1125 static int do_verify(struct fsg_dev *fsg)
1126 {
1127         struct lun              *curlun = fsg->curlun;
1128         u32                     lba;
1129         u32                     verification_length;
1130         struct fsg_buffhd       *bh = fsg->next_buffhd_to_fill;
1131         loff_t                  file_offset, file_offset_tmp;
1132         u32                     amount_left;
1133         unsigned int            amount;
1134         ssize_t                 nread;
1135
1136         /* Get the starting Logical Block Address and check that it's
1137          * not too big */
1138         lba = get_be32(&fsg->cmnd[2]);
1139         if (lba >= curlun->num_sectors) {
1140                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1141                 return -EINVAL;
1142         }
1143
1144         /* We allow DPO (Disable Page Out = don't save data in the
1145          * cache) but we don't implement it. */
1146         if ((fsg->cmnd[1] & ~0x10) != 0) {
1147                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1148                 return -EINVAL;
1149         }
1150
1151         verification_length = get_be16(&fsg->cmnd[7]);
1152         if (unlikely(verification_length == 0))
1153                 return -EIO;            /* No default reply */
1154
1155         /* Prepare to carry out the file verify */
1156         amount_left = verification_length << 9;
1157         file_offset = ((loff_t) lba) << 9;
1158
1159         /* Write out all the dirty buffers before invalidating them */
1160         fsync_sub(curlun);
1161         if (signal_pending(current))
1162                 return -EINTR;
1163
1164         invalidate_sub(curlun);
1165         if (signal_pending(current))
1166                 return -EINTR;
1167
1168         /* Just try to read the requested blocks */
1169         while (amount_left > 0) {
1170
1171                 /* Figure out how much we need to read:
1172                  * Try to read the remaining amount, but not more than
1173                  * the buffer size.
1174                  * And don't try to read past the end of the file.
1175                  * If this means reading 0 then we were asked to read
1176                  * past the end of file. */
1177                 amount = min((unsigned int) amount_left,
1178                                 (unsigned int)fsg->buf_size);
1179                 amount = min((loff_t) amount,
1180                                 curlun->file_length - file_offset);
1181                 if (amount == 0) {
1182                         curlun->sense_data =
1183                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1184                         curlun->sense_data_info = file_offset >> 9;
1185                         curlun->info_valid = 1;
1186                         break;
1187                 }
1188
1189                 /* Perform the read */
1190                 file_offset_tmp = file_offset;
1191                 nread = vfs_read(curlun->filp,
1192                                 (char __user *) bh->buf,
1193                                 amount, &file_offset_tmp);
1194                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1195                                 (unsigned long long) file_offset,
1196                                 (int) nread);
1197                 if (signal_pending(current))
1198                         return -EINTR;
1199
1200                 if (nread < 0) {
1201                         LDBG(curlun, "error in file verify: %d\n",
1202                                         (int) nread);
1203                         nread = 0;
1204                 } else if (nread < amount) {
1205                         LDBG(curlun, "partial file verify: %d/%u\n",
1206                                         (int) nread, amount);
1207                         nread -= (nread & 511); /* Round down to a sector */
1208                 }
1209                 if (nread == 0) {
1210                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1211                         curlun->sense_data_info = file_offset >> 9;
1212                         curlun->info_valid = 1;
1213                         break;
1214                 }
1215                 file_offset += nread;
1216                 amount_left -= nread;
1217         }
1218         return 0;
1219 }
1220
1221
1222 /*-------------------------------------------------------------------------*/
1223
1224 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1225 {
1226         u8      *buf = (u8 *) bh->buf;
1227
1228         if (!fsg->curlun) {             /* Unsupported LUNs are okay */
1229                 fsg->bad_lun_okay = 1;
1230                 memset(buf, 0, 36);
1231                 buf[0] = 0x7f;          /* Unsupported, no device-type */
1232                 return 36;
1233         }
1234
1235         memset(buf, 0, 8);      /* Non-removable, direct-access device */
1236
1237         buf[1] = 0x80;  /* set removable bit */
1238         buf[2] = 2;             /* ANSI SCSI level 2 */
1239         buf[3] = 2;             /* SCSI-2 INQUIRY data format */
1240         buf[4] = 31;            /* Additional length */
1241                                 /* No special options */
1242         sprintf(buf + 8, "%-8s%-16s%04x", fsg->vendor,
1243                         fsg->product, fsg->release);
1244         return 36;
1245 }
1246
1247
1248 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1249 {
1250         struct lun      *curlun = fsg->curlun;
1251         u8              *buf = (u8 *) bh->buf;
1252         u32             sd, sdinfo;
1253         int             valid;
1254
1255         /*
1256          * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1257          *
1258          * If a REQUEST SENSE command is received from an initiator
1259          * with a pending unit attention condition (before the target
1260          * generates the contingent allegiance condition), then the
1261          * target shall either:
1262          *   a) report any pending sense data and preserve the unit
1263          *      attention condition on the logical unit, or,
1264          *   b) report the unit attention condition, may discard any
1265          *      pending sense data, and clear the unit attention
1266          *      condition on the logical unit for that initiator.
1267          *
1268          * FSG normally uses option a); enable this code to use option b).
1269          */
1270 #if 0
1271         if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1272                 curlun->sense_data = curlun->unit_attention_data;
1273                 curlun->unit_attention_data = SS_NO_SENSE;
1274         }
1275 #endif
1276
1277         if (!curlun) {          /* Unsupported LUNs are okay */
1278                 fsg->bad_lun_okay = 1;
1279                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1280                 sdinfo = 0;
1281                 valid = 0;
1282         } else {
1283                 sd = curlun->sense_data;
1284                 sdinfo = curlun->sense_data_info;
1285                 valid = curlun->info_valid << 7;
1286                 curlun->sense_data = SS_NO_SENSE;
1287                 curlun->sense_data_info = 0;
1288                 curlun->info_valid = 0;
1289         }
1290
1291         memset(buf, 0, 18);
1292         buf[0] = valid | 0x70;                  /* Valid, current error */
1293         buf[2] = SK(sd);
1294         put_be32(&buf[3], sdinfo);              /* Sense information */
1295         buf[7] = 18 - 8;                        /* Additional sense length */
1296         buf[12] = ASC(sd);
1297         buf[13] = ASCQ(sd);
1298         return 18;
1299 }
1300
1301
1302 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1303 {
1304         struct lun      *curlun = fsg->curlun;
1305         u32             lba = get_be32(&fsg->cmnd[2]);
1306         int             pmi = fsg->cmnd[8];
1307         u8              *buf = (u8 *) bh->buf;
1308
1309         /* Check the PMI and LBA fields */
1310         if (pmi > 1 || (pmi == 0 && lba != 0)) {
1311                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1312                 return -EINVAL;
1313         }
1314
1315         put_be32(&buf[0], curlun->num_sectors - 1);     /* Max logical block */
1316         put_be32(&buf[4], 512);                         /* Block length */
1317         return 8;
1318 }
1319
1320
1321 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1322 {
1323         struct lun      *curlun = fsg->curlun;
1324         int             mscmnd = fsg->cmnd[0];
1325         u8              *buf = (u8 *) bh->buf;
1326         u8              *buf0 = buf;
1327         int             pc, page_code;
1328         int             changeable_values, all_pages;
1329         int             valid_page = 0;
1330         int             len, limit;
1331
1332         if ((fsg->cmnd[1] & ~0x08) != 0) {              /* Mask away DBD */
1333                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1334                 return -EINVAL;
1335         }
1336         pc = fsg->cmnd[2] >> 6;
1337         page_code = fsg->cmnd[2] & 0x3f;
1338         if (pc == 3) {
1339                 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1340                 return -EINVAL;
1341         }
1342         changeable_values = (pc == 1);
1343         all_pages = (page_code == 0x3f);
1344
1345         /* Write the mode parameter header.  Fixed values are: default
1346          * medium type, no cache control (DPOFUA), and no block descriptors.
1347          * The only variable value is the WriteProtect bit.  We will fill in
1348          * the mode data length later. */
1349         memset(buf, 0, 8);
1350         if (mscmnd == SC_MODE_SENSE_6) {
1351                 buf[2] = (curlun->ro ? 0x80 : 0x00);            /* WP, DPOFUA */
1352                 buf += 4;
1353                 limit = 255;
1354         } else {                        /* SC_MODE_SENSE_10 */
1355                 buf[3] = (curlun->ro ? 0x80 : 0x00);            /* WP, DPOFUA */
1356                 buf += 8;
1357                 limit = 65535;
1358         }
1359
1360         /* No block descriptors */
1361
1362         /* Disabled to workaround USB reset problems with a Vista host.
1363          */
1364 #if 0
1365         /* The mode pages, in numerical order.  The only page we support
1366          * is the Caching page. */
1367         if (page_code == 0x08 || all_pages) {
1368                 valid_page = 1;
1369                 buf[0] = 0x08;          /* Page code */
1370                 buf[1] = 10;            /* Page length */
1371                 memset(buf+2, 0, 10);   /* None of the fields are changeable */
1372
1373                 if (!changeable_values) {
1374                         buf[2] = 0x04;  /* Write cache enable, */
1375                                         /* Read cache not disabled */
1376                                         /* No cache retention priorities */
1377                         put_be16(&buf[4], 0xffff);  /* Don't disable prefetch */
1378                                         /* Minimum prefetch = 0 */
1379                         put_be16(&buf[8], 0xffff);  /* Maximum prefetch */
1380                         /* Maximum prefetch ceiling */
1381                         put_be16(&buf[10], 0xffff);
1382                 }
1383                 buf += 12;
1384         }
1385 #else
1386         valid_page = 1;
1387 #endif
1388
1389         /* Check that a valid page was requested and the mode data length
1390          * isn't too long. */
1391         len = buf - buf0;
1392         if (!valid_page || len > limit) {
1393                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1394                 return -EINVAL;
1395         }
1396
1397         /*  Store the mode data length */
1398         if (mscmnd == SC_MODE_SENSE_6)
1399                 buf0[0] = len - 1;
1400         else
1401                 put_be16(buf0, len - 2);
1402         return len;
1403 }
1404
1405 static int do_start_stop(struct fsg_dev *fsg)
1406 {
1407         struct lun      *curlun = fsg->curlun;
1408         int             loej, start;
1409
1410         /* int immed = fsg->cmnd[1] & 0x01; */
1411         loej = fsg->cmnd[4] & 0x02;
1412         start = fsg->cmnd[4] & 0x01;
1413
1414         if (loej) {
1415                 /* eject request from the host */
1416                 if (backing_file_is_open(curlun)) {
1417                         close_backing_file(fsg, curlun);
1418                         curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
1419                 }
1420         }
1421
1422         return 0;
1423 }
1424
1425 static int do_prevent_allow(struct fsg_dev *fsg)
1426 {
1427         struct lun      *curlun = fsg->curlun;
1428         int             prevent;
1429
1430         prevent = fsg->cmnd[4] & 0x01;
1431         if ((fsg->cmnd[4] & ~0x01) != 0) {              /* Mask away Prevent */
1432                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1433                 return -EINVAL;
1434         }
1435
1436         if (curlun->prevent_medium_removal && !prevent)
1437                 fsync_sub(curlun);
1438         curlun->prevent_medium_removal = prevent;
1439         return 0;
1440 }
1441
1442
1443 static int do_read_format_capacities(struct fsg_dev *fsg,
1444                         struct fsg_buffhd *bh)
1445 {
1446         struct lun      *curlun = fsg->curlun;
1447         u8              *buf = (u8 *) bh->buf;
1448
1449         buf[0] = buf[1] = buf[2] = 0;
1450         buf[3] = 8;     /* Only the Current/Maximum Capacity Descriptor */
1451         buf += 4;
1452
1453         put_be32(&buf[0], curlun->num_sectors); /* Number of blocks */
1454         put_be32(&buf[4], 512);                         /* Block length */
1455         buf[4] = 0x02;                                  /* Current capacity */
1456         return 12;
1457 }
1458
1459
1460 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1461 {
1462         struct lun      *curlun = fsg->curlun;
1463
1464         /* We don't support MODE SELECT */
1465         curlun->sense_data = SS_INVALID_COMMAND;
1466         return -EINVAL;
1467 }
1468
1469
1470 /*-------------------------------------------------------------------------*/
1471 #if 0
1472 static int write_zero(struct fsg_dev *fsg)
1473 {
1474         struct fsg_buffhd       *bh;
1475         int                     rc;
1476
1477         DBG(fsg, "write_zero\n");
1478         /* Wait for the next buffer to become available */
1479         bh = fsg->next_buffhd_to_fill;
1480         while (bh->state != BUF_STATE_EMPTY) {
1481                 rc = sleep_thread(fsg);
1482                 if (rc)
1483                         return rc;
1484         }
1485
1486         bh->inreq->length = 0;
1487         start_transfer(fsg, fsg->bulk_in, bh->inreq,
1488                         &bh->inreq_busy, &bh->state);
1489
1490         fsg->next_buffhd_to_fill = bh->next;
1491         return 0;
1492 }
1493 #endif
1494
1495 static int throw_away_data(struct fsg_dev *fsg)
1496 {
1497         struct fsg_buffhd       *bh;
1498         u32                     amount;
1499         int                     rc;
1500
1501         DBG(fsg, "throw_away_data\n");
1502         while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1503                         fsg->usb_amount_left > 0) {
1504
1505                 /* Throw away the data in a filled buffer */
1506                 if (bh->state == BUF_STATE_FULL) {
1507                         smp_rmb();
1508                         bh->state = BUF_STATE_EMPTY;
1509                         fsg->next_buffhd_to_drain = bh->next;
1510
1511                         /* A short packet or an error ends everything */
1512                         if (bh->outreq->actual != bh->outreq->length ||
1513                                         bh->outreq->status != 0) {
1514                                 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1515                                 return -EINTR;
1516                         }
1517                         continue;
1518                 }
1519
1520                 /* Try to submit another request if we need one */
1521                 bh = fsg->next_buffhd_to_fill;
1522                 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1523                         amount = min(fsg->usb_amount_left, (u32) fsg->buf_size);
1524
1525                         /* amount is always divisible by 512, hence by
1526                          * the bulk-out maxpacket size */
1527                         bh->outreq->length = bh->bulk_out_intended_length =
1528                                         amount;
1529                         start_transfer(fsg, fsg->bulk_out, bh->outreq,
1530                                         &bh->outreq_busy, &bh->state);
1531                         fsg->next_buffhd_to_fill = bh->next;
1532                         fsg->usb_amount_left -= amount;
1533                         continue;
1534                 }
1535
1536                 /* Otherwise wait for something to happen */
1537                 rc = sleep_thread(fsg);
1538                 if (rc)
1539                         return rc;
1540         }
1541         return 0;
1542 }
1543
1544
1545 static int finish_reply(struct fsg_dev *fsg)
1546 {
1547         struct fsg_buffhd       *bh = fsg->next_buffhd_to_fill;
1548         int                     rc = 0;
1549
1550         switch (fsg->data_dir) {
1551         case DATA_DIR_NONE:
1552                 break;                  /* Nothing to send */
1553
1554         case DATA_DIR_UNKNOWN:
1555                 rc = -EINVAL;
1556                 break;
1557
1558         /* All but the last buffer of data must have already been sent */
1559         case DATA_DIR_TO_HOST:
1560                 if (fsg->data_size == 0)
1561                         ;               /* Nothing to send */
1562
1563                 /* If there's no residue, simply send the last buffer */
1564                 else if (fsg->residue == 0) {
1565                         start_transfer(fsg, fsg->bulk_in, bh->inreq,
1566                                         &bh->inreq_busy, &bh->state);
1567                         fsg->next_buffhd_to_fill = bh->next;
1568                 } else {
1569                         start_transfer(fsg, fsg->bulk_in, bh->inreq,
1570                                         &bh->inreq_busy, &bh->state);
1571                         fsg->next_buffhd_to_fill = bh->next;
1572 #if 0
1573                         /* this is unnecessary, and was causing problems with MacOS */
1574                         if (bh->inreq->length > 0)
1575                                 write_zero(fsg);
1576 #endif
1577                 }
1578                 break;
1579
1580         /* We have processed all we want from the data the host has sent.
1581          * There may still be outstanding bulk-out requests. */
1582         case DATA_DIR_FROM_HOST:
1583                 if (fsg->residue == 0)
1584                         ;               /* Nothing to receive */
1585
1586                 /* Did the host stop sending unexpectedly early? */
1587                 else if (fsg->short_packet_received) {
1588                         raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1589                         rc = -EINTR;
1590                 }
1591
1592                 /* We haven't processed all the incoming data.  Even though
1593                  * we may be allowed to stall, doing so would cause a race.
1594                  * The controller may already have ACK'ed all the remaining
1595                  * bulk-out packets, in which case the host wouldn't see a
1596                  * STALL.  Not realizing the endpoint was halted, it wouldn't
1597                  * clear the halt -- leading to problems later on. */
1598 #if 0
1599                 fsg_set_halt(fsg, fsg->bulk_out);
1600                 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1601                 rc = -EINTR;
1602 #endif
1603
1604                 /* We can't stall.  Read in the excess data and throw it
1605                  * all away. */
1606                 else
1607                         rc = throw_away_data(fsg);
1608                 break;
1609         }
1610         return rc;
1611 }
1612
1613
1614 static int send_status(struct fsg_dev *fsg)
1615 {
1616         struct lun              *curlun = fsg->curlun;
1617         struct fsg_buffhd       *bh;
1618         int                     rc;
1619         u8                      status = USB_STATUS_PASS;
1620         u32                     sd, sdinfo = 0;
1621         struct bulk_cs_wrap     *csw;
1622
1623         DBG(fsg, "send_status\n");
1624         /* Wait for the next buffer to become available */
1625         bh = fsg->next_buffhd_to_fill;
1626         while (bh->state != BUF_STATE_EMPTY) {
1627                 rc = sleep_thread(fsg);
1628                 if (rc)
1629                         return rc;
1630         }
1631
1632         if (curlun) {
1633                 sd = curlun->sense_data;
1634                 sdinfo = curlun->sense_data_info;
1635         } else if (fsg->bad_lun_okay)
1636                 sd = SS_NO_SENSE;
1637         else
1638                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1639
1640         if (fsg->phase_error) {
1641                 DBG(fsg, "sending phase-error status\n");
1642                 status = USB_STATUS_PHASE_ERROR;
1643                 sd = SS_INVALID_COMMAND;
1644         } else if (sd != SS_NO_SENSE) {
1645                 DBG(fsg, "sending command-failure status\n");
1646                 status = USB_STATUS_FAIL;
1647                 VDBG(fsg, "  sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1648                                 "  info x%x\n",
1649                                 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1650         }
1651
1652         csw = bh->buf;
1653
1654         /* Store and send the Bulk-only CSW */
1655         csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
1656         csw->Tag = fsg->tag;
1657         csw->Residue = cpu_to_le32(fsg->residue);
1658         csw->Status = status;
1659
1660         bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1661         start_transfer(fsg, fsg->bulk_in, bh->inreq,
1662                         &bh->inreq_busy, &bh->state);
1663
1664         fsg->next_buffhd_to_fill = bh->next;
1665         return 0;
1666 }
1667
1668
1669 /*-------------------------------------------------------------------------*/
1670
1671 /* Check whether the command is properly formed and whether its data size
1672  * and direction agree with the values we already have. */
1673 static int check_command(struct fsg_dev *fsg, int cmnd_size,
1674                 enum data_direction data_dir, unsigned int mask,
1675                 int needs_medium, const char *name)
1676 {
1677         int                     i;
1678         int                     lun = fsg->cmnd[1] >> 5;
1679         static const char       dirletter[4] = {'u', 'o', 'i', 'n'};
1680         char                    hdlen[20];
1681         struct lun              *curlun;
1682
1683         hdlen[0] = 0;
1684         if (fsg->data_dir != DATA_DIR_UNKNOWN)
1685                 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1686                                 fsg->data_size);
1687         VDBG(fsg, "SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
1688                         name, cmnd_size, dirletter[(int) data_dir],
1689                         fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
1690
1691         /* We can't reply at all until we know the correct data direction
1692          * and size. */
1693         if (fsg->data_size_from_cmnd == 0)
1694                 data_dir = DATA_DIR_NONE;
1695         if (fsg->data_dir == DATA_DIR_UNKNOWN) {        /* CB or CBI */
1696                 fsg->data_dir = data_dir;
1697                 fsg->data_size = fsg->data_size_from_cmnd;
1698
1699         } else {                                        /* Bulk-only */
1700                 if (fsg->data_size < fsg->data_size_from_cmnd) {
1701
1702                         /* Host data size < Device data size is a phase error.
1703                          * Carry out the command, but only transfer as much
1704                          * as we are allowed. */
1705                         DBG(fsg, "phase error 1\n");
1706                         fsg->data_size_from_cmnd = fsg->data_size;
1707                         fsg->phase_error = 1;
1708                 }
1709         }
1710         fsg->residue = fsg->usb_amount_left = fsg->data_size;
1711
1712         /* Conflicting data directions is a phase error */
1713         if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
1714                 fsg->phase_error = 1;
1715                 DBG(fsg, "phase error 2\n");
1716                 return -EINVAL;
1717         }
1718
1719         /* Verify the length of the command itself */
1720         if (cmnd_size != fsg->cmnd_size) {
1721
1722                 /* Special case workaround: MS-Windows issues REQUEST SENSE
1723                  * with cbw->Length == 12 (it should be 6). */
1724                 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
1725                         cmnd_size = fsg->cmnd_size;
1726                 else {
1727                         fsg->phase_error = 1;
1728                         return -EINVAL;
1729                 }
1730         }
1731
1732         /* Check that the LUN values are consistent */
1733         if (fsg->lun != lun)
1734                 DBG(fsg, "using LUN %d from CBW, "
1735                                 "not LUN %d from CDB\n",
1736                                 fsg->lun, lun);
1737
1738         /* Check the LUN */
1739         if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
1740                 fsg->curlun = curlun = &fsg->luns[fsg->lun];
1741                 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
1742                         curlun->sense_data = SS_NO_SENSE;
1743                         curlun->sense_data_info = 0;
1744                         curlun->info_valid = 0;
1745                 }
1746         } else {
1747                 fsg->curlun = curlun = NULL;
1748                 fsg->bad_lun_okay = 0;
1749
1750                 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1751                  * to use unsupported LUNs; all others may not. */
1752                 if (fsg->cmnd[0] != SC_INQUIRY &&
1753                                 fsg->cmnd[0] != SC_REQUEST_SENSE) {
1754                         DBG(fsg, "unsupported LUN %d\n", fsg->lun);
1755                         return -EINVAL;
1756                 }
1757         }
1758
1759         /* If a unit attention condition exists, only INQUIRY and
1760          * REQUEST SENSE commands are allowed; anything else must fail. */
1761         if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1762                         fsg->cmnd[0] != SC_INQUIRY &&
1763                         fsg->cmnd[0] != SC_REQUEST_SENSE) {
1764                 curlun->sense_data = curlun->unit_attention_data;
1765                 curlun->unit_attention_data = SS_NO_SENSE;
1766                 return -EINVAL;
1767         }
1768
1769         /* Check that only command bytes listed in the mask are non-zero */
1770         fsg->cmnd[1] &= 0x1f;                   /* Mask away the LUN */
1771         for (i = 1; i < cmnd_size; ++i) {
1772                 if (fsg->cmnd[i] && !(mask & (1 << i))) {
1773                         if (curlun)
1774                                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1775                         DBG(fsg, "SS_INVALID_FIELD_IN_CDB\n");
1776                         return -EINVAL;
1777                 }
1778         }
1779
1780         /* If the medium isn't mounted and the command needs to access
1781          * it, return an error. */
1782         if (curlun && !backing_file_is_open(curlun) && needs_medium) {
1783                 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1784                 DBG(fsg, "SS_MEDIUM_NOT_PRESENT\n");
1785                 return -EINVAL;
1786         }
1787
1788         return 0;
1789 }
1790
1791
1792 static int do_scsi_command(struct fsg_dev *fsg)
1793 {
1794         struct fsg_buffhd       *bh;
1795         int                     rc;
1796         int                     reply = -EINVAL;
1797         int                     i;
1798         static char             unknown[16];
1799
1800         dump_cdb(fsg);
1801
1802         /* Wait for the next buffer to become available for data or status */
1803         bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
1804         while (bh->state != BUF_STATE_EMPTY) {
1805                 rc = sleep_thread(fsg);
1806                 if (rc)
1807                         return rc;
1808         }
1809         fsg->phase_error = 0;
1810         fsg->short_packet_received = 0;
1811
1812         down_read(&fsg->filesem);       /* We're using the backing file */
1813         switch (fsg->cmnd[0]) {
1814
1815         case SC_INQUIRY:
1816                 fsg->data_size_from_cmnd = fsg->cmnd[4];
1817                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1818                                 (1<<4), 0,
1819                                 "INQUIRY")) == 0)
1820                         reply = do_inquiry(fsg, bh);
1821                 break;
1822
1823         case SC_MODE_SELECT_6:
1824                 fsg->data_size_from_cmnd = fsg->cmnd[4];
1825                 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
1826                                 (1<<1) | (1<<4), 0,
1827                                 "MODE SELECT(6)")) == 0)
1828                         reply = do_mode_select(fsg, bh);
1829                 break;
1830
1831         case SC_MODE_SELECT_10:
1832                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1833                 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
1834                                 (1<<1) | (3<<7), 0,
1835                                 "MODE SELECT(10)")) == 0)
1836                         reply = do_mode_select(fsg, bh);
1837                 break;
1838
1839         case SC_MODE_SENSE_6:
1840                 fsg->data_size_from_cmnd = fsg->cmnd[4];
1841                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1842                                 (1<<1) | (1<<2) | (1<<4), 0,
1843                                 "MODE SENSE(6)")) == 0)
1844                         reply = do_mode_sense(fsg, bh);
1845                 break;
1846
1847         case SC_MODE_SENSE_10:
1848                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1849                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1850                                 (1<<1) | (1<<2) | (3<<7), 0,
1851                                 "MODE SENSE(10)")) == 0)
1852                         reply = do_mode_sense(fsg, bh);
1853                 break;
1854
1855         case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1856                 fsg->data_size_from_cmnd = 0;
1857                 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
1858                                 (1<<4), 0,
1859                                 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
1860                         reply = do_prevent_allow(fsg);
1861                 break;
1862
1863         case SC_READ_6:
1864                 i = fsg->cmnd[4];
1865                 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1866                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1867                                 (7<<1) | (1<<4), 1,
1868                                 "READ(6)")) == 0)
1869                         reply = do_read(fsg);
1870                 break;
1871
1872         case SC_READ_10:
1873                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
1874                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1875                                 (1<<1) | (0xf<<2) | (3<<7), 1,
1876                                 "READ(10)")) == 0)
1877                         reply = do_read(fsg);
1878                 break;
1879
1880         case SC_READ_12:
1881                 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
1882                 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
1883                                 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1884                                 "READ(12)")) == 0)
1885                         reply = do_read(fsg);
1886                 break;
1887
1888         case SC_READ_CAPACITY:
1889                 fsg->data_size_from_cmnd = 8;
1890                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1891                                 (0xf<<2) | (1<<8), 1,
1892                                 "READ CAPACITY")) == 0)
1893                         reply = do_read_capacity(fsg, bh);
1894                 break;
1895
1896         case SC_READ_FORMAT_CAPACITIES:
1897                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1898                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1899                                 (3<<7), 1,
1900                                 "READ FORMAT CAPACITIES")) == 0)
1901                         reply = do_read_format_capacities(fsg, bh);
1902                 break;
1903
1904         case SC_REQUEST_SENSE:
1905                 fsg->data_size_from_cmnd = fsg->cmnd[4];
1906                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1907                                 (1<<4), 0,
1908                                 "REQUEST SENSE")) == 0)
1909                         reply = do_request_sense(fsg, bh);
1910                 break;
1911
1912         case SC_START_STOP_UNIT:
1913                 fsg->data_size_from_cmnd = 0;
1914                 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
1915                                 (1<<1) | (1<<4), 0,
1916                                 "START-STOP UNIT")) == 0)
1917                         reply = do_start_stop(fsg);
1918                 break;
1919
1920         case SC_SYNCHRONIZE_CACHE:
1921                 fsg->data_size_from_cmnd = 0;
1922                 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
1923                                 (0xf<<2) | (3<<7), 1,
1924                                 "SYNCHRONIZE CACHE")) == 0)
1925                         reply = do_synchronize_cache(fsg);
1926                 break;
1927
1928         case SC_TEST_UNIT_READY:
1929                 fsg->data_size_from_cmnd = 0;
1930                 reply = check_command(fsg, 6, DATA_DIR_NONE,
1931                                 0, 1,
1932                                 "TEST UNIT READY");
1933                 break;
1934
1935         /* Although optional, this command is used by MS-Windows.  We
1936          * support a minimal version: BytChk must be 0. */
1937         case SC_VERIFY:
1938                 fsg->data_size_from_cmnd = 0;
1939                 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
1940                                 (1<<1) | (0xf<<2) | (3<<7), 1,
1941                                 "VERIFY")) == 0)
1942                         reply = do_verify(fsg);
1943                 break;
1944
1945         case SC_WRITE_6:
1946                 i = fsg->cmnd[4];
1947                 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1948                 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
1949                                 (7<<1) | (1<<4), 1,
1950                                 "WRITE(6)")) == 0)
1951                         reply = do_write(fsg);
1952                 break;
1953
1954         case SC_WRITE_10:
1955                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
1956                 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
1957                                 (1<<1) | (0xf<<2) | (3<<7), 1,
1958                                 "WRITE(10)")) == 0)
1959                         reply = do_write(fsg);
1960                 break;
1961
1962         case SC_WRITE_12:
1963                 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
1964                 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
1965                                 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1966                                 "WRITE(12)")) == 0)
1967                         reply = do_write(fsg);
1968                 break;
1969
1970         /* Some mandatory commands that we recognize but don't implement.
1971          * They don't mean much in this setting.  It's left as an exercise
1972          * for anyone interested to implement RESERVE and RELEASE in terms
1973          * of Posix locks. */
1974         case SC_FORMAT_UNIT:
1975         case SC_RELEASE:
1976         case SC_RESERVE:
1977         case SC_SEND_DIAGNOSTIC:
1978                 /* Fall through */
1979
1980         default:
1981                 fsg->data_size_from_cmnd = 0;
1982                 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
1983                 if ((reply = check_command(fsg, fsg->cmnd_size,
1984                                 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
1985                         fsg->curlun->sense_data = SS_INVALID_COMMAND;
1986                         reply = -EINVAL;
1987                 }
1988                 break;
1989         }
1990         up_read(&fsg->filesem);
1991
1992         VDBG(fsg, "reply: %d, fsg->data_size_from_cmnd: %d\n",
1993                         reply, fsg->data_size_from_cmnd);
1994         if (reply == -EINTR || signal_pending(current))
1995                 return -EINTR;
1996
1997         /* Set up the single reply buffer for finish_reply() */
1998         if (reply == -EINVAL)
1999                 reply = 0;              /* Error reply length */
2000         if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2001                 reply = min((u32) reply, fsg->data_size_from_cmnd);
2002                 bh->inreq->length = reply;
2003                 bh->state = BUF_STATE_FULL;
2004                 fsg->residue -= reply;
2005         }                               /* Otherwise it's already set */
2006
2007         return 0;
2008 }
2009
2010
2011 /*-------------------------------------------------------------------------*/
2012
2013 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2014 {
2015         struct usb_request      *req = bh->outreq;
2016         struct bulk_cb_wrap     *cbw = req->buf;
2017
2018         /* Was this a real packet? */
2019         if (req->status)
2020                 return -EINVAL;
2021
2022         /* Is the CBW valid? */
2023         if (req->actual != USB_BULK_CB_WRAP_LEN ||
2024                         cbw->Signature != __constant_cpu_to_le32(
2025                                 USB_BULK_CB_SIG)) {
2026                 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2027                                 req->actual,
2028                                 le32_to_cpu(cbw->Signature));
2029                 return -EINVAL;
2030         }
2031
2032         /* Is the CBW meaningful? */
2033         if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2034                         cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2035                 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2036                                 "cmdlen %u\n",
2037                                 cbw->Lun, cbw->Flags, cbw->Length);
2038                 return -EINVAL;
2039         }
2040
2041         /* Save the command for later */
2042         fsg->cmnd_size = cbw->Length;
2043         memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2044         if (cbw->Flags & USB_BULK_IN_FLAG)
2045                 fsg->data_dir = DATA_DIR_TO_HOST;
2046         else
2047                 fsg->data_dir = DATA_DIR_FROM_HOST;
2048         fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2049         if (fsg->data_size == 0)
2050                 fsg->data_dir = DATA_DIR_NONE;
2051         fsg->lun = cbw->Lun;
2052         fsg->tag = cbw->Tag;
2053         return 0;
2054 }
2055
2056
2057 static int get_next_command(struct fsg_dev *fsg)
2058 {
2059         struct fsg_buffhd       *bh;
2060         int                     rc = 0;
2061
2062         /* Wait for the next buffer to become available */
2063         bh = fsg->next_buffhd_to_fill;
2064         while (bh->state != BUF_STATE_EMPTY) {
2065                 rc = sleep_thread(fsg);
2066                 if (rc)
2067                         return rc;
2068         }
2069
2070         /* Queue a request to read a Bulk-only CBW */
2071         set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2072         start_transfer(fsg, fsg->bulk_out, bh->outreq,
2073                         &bh->outreq_busy, &bh->state);
2074
2075         /* We will drain the buffer in software, which means we
2076          * can reuse it for the next filling.  No need to advance
2077          * next_buffhd_to_fill. */
2078
2079         /* Wait for the CBW to arrive */
2080         while (bh->state != BUF_STATE_FULL) {
2081                 rc = sleep_thread(fsg);
2082                 if (rc) {
2083                         usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2084                         bh->outreq_busy = 0;
2085                         bh->state = BUF_STATE_EMPTY;
2086                         return rc;
2087                 }
2088         }
2089         smp_rmb();
2090         rc = received_cbw(fsg, bh);
2091         bh->state = BUF_STATE_EMPTY;
2092
2093         return rc;
2094 }
2095
2096
2097 /*-------------------------------------------------------------------------*/
2098
2099 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2100                 const struct usb_endpoint_descriptor *d)
2101 {
2102         int     rc;
2103
2104         DBG(fsg, "usb_ep_enable %s\n", ep->name);
2105         ep->driver_data = fsg;
2106         rc = usb_ep_enable(ep, d);
2107         if (rc)
2108                 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2109         return rc;
2110 }
2111
2112 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2113                 struct usb_request **preq)
2114 {
2115         *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2116         if (*preq)
2117                 return 0;
2118         ERROR(fsg, "can't allocate request for %s\n", ep->name);
2119         return -ENOMEM;
2120 }
2121
2122 /*
2123  * Reset interface setting and re-init endpoint state (toggle etc).
2124  * Call with altsetting < 0 to disable the interface.  The only other
2125  * available altsetting is 0, which enables the interface.
2126  */
2127 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2128 {
2129         struct usb_composite_dev *cdev = fsg->cdev;
2130         int     rc = 0;
2131         int     i;
2132         const struct usb_endpoint_descriptor    *d;
2133
2134         if (fsg->running)
2135                 DBG(fsg, "reset interface\n");
2136 reset:
2137          /* Disable the endpoints */
2138         if (fsg->bulk_in_enabled) {
2139                 DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_in->name);
2140                 usb_ep_disable(fsg->bulk_in);
2141                 fsg->bulk_in_enabled = 0;
2142         }
2143         if (fsg->bulk_out_enabled) {
2144                 DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_out->name);
2145                 usb_ep_disable(fsg->bulk_out);
2146                 fsg->bulk_out_enabled = 0;
2147         }
2148
2149         /* Deallocate the requests */
2150         for (i = 0; i < NUM_BUFFERS; ++i) {
2151                 struct fsg_buffhd *bh = &fsg->buffhds[i];
2152                 if (bh->inreq) {
2153                         usb_ep_free_request(fsg->bulk_in, bh->inreq);
2154                         bh->inreq = NULL;
2155                 }
2156                 if (bh->outreq) {
2157                         usb_ep_free_request(fsg->bulk_out, bh->outreq);
2158                         bh->outreq = NULL;
2159                 }
2160         }
2161
2162
2163         fsg->running = 0;
2164         if (altsetting < 0 || rc != 0)
2165                 return rc;
2166
2167         DBG(fsg, "set interface %d\n", altsetting);
2168
2169         /* Enable the endpoints */
2170         d = ep_desc(cdev->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
2171         if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2172                 goto reset;
2173         fsg->bulk_in_enabled = 1;
2174
2175         d = ep_desc(cdev->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
2176         if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2177                 goto reset;
2178         fsg->bulk_out_enabled = 1;
2179         fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2180
2181         /* Allocate the requests */
2182         for (i = 0; i < NUM_BUFFERS; ++i) {
2183                 struct fsg_buffhd       *bh = &fsg->buffhds[i];
2184
2185                 rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq);
2186                 if (rc != 0)
2187                         goto reset;
2188                 rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq);
2189                 if (rc != 0)
2190                         goto reset;
2191                 bh->inreq->buf = bh->outreq->buf = bh->buf;
2192                 bh->inreq->context = bh->outreq->context = bh;
2193                 bh->inreq->complete = bulk_in_complete;
2194                 bh->outreq->complete = bulk_out_complete;
2195         }
2196
2197         fsg->running = 1;
2198         for (i = 0; i < fsg->nluns; ++i)
2199                 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2200
2201         return rc;
2202 }
2203
2204 static void adjust_wake_lock(struct fsg_dev *fsg)
2205 {
2206         int ums_active = 0;
2207         int i;
2208
2209         spin_lock_irq(&fsg->lock);
2210
2211         if (fsg->config) {
2212                 for (i = 0; i < fsg->nluns; ++i) {
2213                         if (backing_file_is_open(&fsg->luns[i]))
2214                                 ums_active = 1;
2215                 }
2216         }
2217
2218         if (ums_active)
2219                 wake_lock(&fsg->wake_lock);
2220         else
2221                 wake_unlock(&fsg->wake_lock);
2222
2223         spin_unlock_irq(&fsg->lock);
2224 }
2225
2226 /*
2227  * Change our operational configuration.  This code must agree with the code
2228  * that returns config descriptors, and with interface altsetting code.
2229  *
2230  * It's also responsible for power management interactions.  Some
2231  * configurations might not work with our current power sources.
2232  * For now we just assume the gadget is always self-powered.
2233  */
2234 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2235 {
2236         int     rc = 0;
2237
2238         if (new_config == fsg->config)
2239                 return rc;
2240
2241         /* Disable the single interface */
2242         if (fsg->config != 0) {
2243                 DBG(fsg, "reset config\n");
2244                 fsg->config = 0;
2245         }
2246
2247         /* Enable the interface */
2248         if (new_config != 0)
2249                 fsg->config = new_config;
2250
2251         switch_set_state(&fsg->sdev, new_config);
2252         adjust_wake_lock(fsg);
2253         return rc;
2254 }
2255
2256
2257 /*-------------------------------------------------------------------------*/
2258
2259 static void handle_exception(struct fsg_dev *fsg)
2260 {
2261         siginfo_t               info;
2262         int                     sig;
2263         int                     i;
2264         struct fsg_buffhd       *bh;
2265         enum fsg_state          old_state;
2266         u8                      new_config;
2267         struct lun              *curlun;
2268         int                     rc;
2269
2270         DBG(fsg, "handle_exception state: %d\n", (int)fsg->state);
2271         /* Clear the existing signals.  Anything but SIGUSR1 is converted
2272          * into a high-priority EXIT exception. */
2273         for (;;) {
2274                 sig = dequeue_signal_lock(current, &current->blocked, &info);
2275                 if (!sig)
2276                         break;
2277                 if (sig != SIGUSR1) {
2278                         if (fsg->state < FSG_STATE_EXIT)
2279                                 DBG(fsg, "Main thread exiting on signal\n");
2280                         raise_exception(fsg, FSG_STATE_EXIT);
2281                 }
2282         }
2283
2284         /* Clear out the controller's fifos */
2285         if (fsg->bulk_in_enabled)
2286                 usb_ep_fifo_flush(fsg->bulk_in);
2287         if (fsg->bulk_out_enabled)
2288                 usb_ep_fifo_flush(fsg->bulk_out);
2289
2290         /* Reset the I/O buffer states and pointers, the SCSI
2291          * state, and the exception.  Then invoke the handler. */
2292         spin_lock_irq(&fsg->lock);
2293
2294         for (i = 0; i < NUM_BUFFERS; ++i) {
2295                 bh = &fsg->buffhds[i];
2296                 bh->state = BUF_STATE_EMPTY;
2297         }
2298         fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2299                         &fsg->buffhds[0];
2300
2301         new_config = fsg->new_config;
2302         old_state = fsg->state;
2303
2304         if (old_state == FSG_STATE_ABORT_BULK_OUT)
2305                 fsg->state = FSG_STATE_STATUS_PHASE;
2306         else {
2307                 for (i = 0; i < fsg->nluns; ++i) {
2308                         curlun = &fsg->luns[i];
2309                         curlun->prevent_medium_removal = 0;
2310                         curlun->sense_data = curlun->unit_attention_data =
2311                                         SS_NO_SENSE;
2312                         curlun->sense_data_info = 0;
2313                         curlun->info_valid = 0;
2314                 }
2315                 fsg->state = FSG_STATE_IDLE;
2316         }
2317         spin_unlock_irq(&fsg->lock);
2318
2319         /* Carry out any extra actions required for the exception */
2320         switch (old_state) {
2321         default:
2322                 break;
2323
2324         case FSG_STATE_ABORT_BULK_OUT:
2325                 DBG(fsg, "FSG_STATE_ABORT_BULK_OUT\n");
2326                 spin_lock_irq(&fsg->lock);
2327                 if (fsg->state == FSG_STATE_STATUS_PHASE)
2328                         fsg->state = FSG_STATE_IDLE;
2329                 spin_unlock_irq(&fsg->lock);
2330                 break;
2331
2332         case FSG_STATE_RESET:
2333                 /* really not much to do here */
2334                 break;
2335
2336         case FSG_STATE_CONFIG_CHANGE:
2337                 rc = do_set_config(fsg, new_config);
2338                 if (new_config == 0) {
2339                         /* We're using the backing file */
2340                         down_read(&fsg->filesem);
2341                         fsync_all(fsg);
2342                         up_read(&fsg->filesem);
2343                 }
2344                 break;
2345
2346         case FSG_STATE_EXIT:
2347         case FSG_STATE_TERMINATED:
2348                 if (new_config)  {
2349                         fsg->new_config = 0;
2350                         do_set_interface(fsg, -1);
2351                 }
2352                 do_set_config(fsg, 0);                  /* Free resources */
2353                 spin_lock_irq(&fsg->lock);
2354                 fsg->state = FSG_STATE_TERMINATED;      /* Stop the thread */
2355                 spin_unlock_irq(&fsg->lock);
2356                 break;
2357         }
2358 }
2359
2360
2361 /*-------------------------------------------------------------------------*/
2362
2363 static int fsg_main_thread(void *fsg_)
2364 {
2365         struct fsg_dev          *fsg = fsg_;
2366
2367         /* Allow the thread to be killed by a signal, but set the signal mask
2368          * to block everything but INT, TERM, KILL, and USR1. */
2369         allow_signal(SIGINT);
2370         allow_signal(SIGTERM);
2371         allow_signal(SIGKILL);
2372         allow_signal(SIGUSR1);
2373
2374         /* Allow the thread to be frozen */
2375         set_freezable();
2376
2377         /* Arrange for userspace references to be interpreted as kernel
2378          * pointers.  That way we can pass a kernel pointer to a routine
2379          * that expects a __user pointer and it will work okay. */
2380         set_fs(get_ds());
2381
2382         /* The main loop */
2383         while (fsg->state != FSG_STATE_TERMINATED) {
2384                 if (exception_in_progress(fsg) || signal_pending(current)) {
2385                         handle_exception(fsg);
2386                         continue;
2387                 }
2388
2389                 if (!fsg->running) {
2390                         sleep_thread(fsg);
2391                         continue;
2392                 }
2393
2394                 if (get_next_command(fsg))
2395                         continue;
2396
2397                 spin_lock_irq(&fsg->lock);
2398                 if (!exception_in_progress(fsg))
2399                         fsg->state = FSG_STATE_DATA_PHASE;
2400                 spin_unlock_irq(&fsg->lock);
2401
2402                 if (do_scsi_command(fsg) || finish_reply(fsg))
2403                         continue;
2404
2405                 spin_lock_irq(&fsg->lock);
2406                 if (!exception_in_progress(fsg))
2407                         fsg->state = FSG_STATE_STATUS_PHASE;
2408                 spin_unlock_irq(&fsg->lock);
2409
2410                 if (send_status(fsg))
2411                         continue;
2412
2413                 spin_lock_irq(&fsg->lock);
2414                 if (!exception_in_progress(fsg))
2415                         fsg->state = FSG_STATE_IDLE;
2416                 spin_unlock_irq(&fsg->lock);
2417                 }
2418
2419         spin_lock_irq(&fsg->lock);
2420         fsg->thread_task = NULL;
2421         spin_unlock_irq(&fsg->lock);
2422
2423         /* In case we are exiting because of a signal, unregister the
2424          * gadget driver and close the backing file. */
2425         if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2426                 close_all_backing_files(fsg);
2427
2428         /* Let the unbind and cleanup routines know the thread has exited */
2429         complete_and_exit(&fsg->thread_notifier, 0);
2430 }
2431
2432
2433 /*-------------------------------------------------------------------------*/
2434
2435 /* If the next two routines are called while the gadget is registered,
2436  * the caller must own fsg->filesem for writing. */
2437
2438 static int open_backing_file(struct fsg_dev *fsg, struct lun *curlun,
2439         const char *filename)
2440 {
2441         int                             ro;
2442         struct file                     *filp = NULL;
2443         int                             rc = -EINVAL;
2444         struct inode                    *inode = NULL;
2445         loff_t                          size;
2446         loff_t                          num_sectors;
2447
2448         /* R/W if we can, R/O if we must */
2449         ro = curlun->ro;
2450         if (!ro) {
2451                 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
2452                 if (-EROFS == PTR_ERR(filp))
2453                         ro = 1;
2454         }
2455         if (ro)
2456                 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
2457         if (IS_ERR(filp)) {
2458                 LINFO(curlun, "unable to open backing file: %s\n", filename);
2459                 return PTR_ERR(filp);
2460         }
2461
2462         if (!(filp->f_mode & FMODE_WRITE))
2463                 ro = 1;
2464
2465         if (filp->f_path.dentry)
2466                 inode = filp->f_path.dentry->d_inode;
2467         if (inode && S_ISBLK(inode->i_mode)) {
2468                 if (bdev_read_only(inode->i_bdev))
2469                         ro = 1;
2470         } else if (!inode || !S_ISREG(inode->i_mode)) {
2471                 LINFO(curlun, "invalid file type: %s\n", filename);
2472                 goto out;
2473         }
2474
2475         /* If we can't read the file, it's no good.
2476          * If we can't write the file, use it read-only. */
2477         if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
2478                 LINFO(curlun, "file not readable: %s\n", filename);
2479                 goto out;
2480         }
2481         if (!(filp->f_op->write || filp->f_op->aio_write))
2482                 ro = 1;
2483
2484         size = i_size_read(inode->i_mapping->host);
2485         if (size < 0) {
2486                 LINFO(curlun, "unable to find file size: %s\n", filename);
2487                 rc = (int) size;
2488                 goto out;
2489         }
2490         num_sectors = size >> 9;        /* File size in 512-byte sectors */
2491         if (num_sectors == 0) {
2492                 LINFO(curlun, "file too small: %s\n", filename);
2493                 rc = -ETOOSMALL;
2494                 goto out;
2495         }
2496
2497         get_file(filp);
2498         curlun->ro = ro;
2499         curlun->filp = filp;
2500         curlun->file_length = size;
2501         curlun->num_sectors = num_sectors;
2502         LDBG(curlun, "open backing file: %s size: %lld num_sectors: %lld\n",
2503                         filename, size, num_sectors);
2504         rc = 0;
2505         adjust_wake_lock(fsg);
2506
2507 out:
2508         filp_close(filp, current->files);
2509         return rc;
2510 }
2511
2512
2513 static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun)
2514 {
2515         if (curlun->filp) {
2516                 int rc;
2517
2518                 /*
2519                  * XXX: San: Ugly hack here added to ensure that
2520                  * our pages get synced to disk.
2521                  * Also drop caches here just to be extra-safe
2522                  */
2523                 rc = vfs_fsync(curlun->filp, curlun->filp->f_path.dentry, 1);
2524                 if (rc < 0)
2525                         printk(KERN_ERR "ums: Error syncing data (%d)\n", rc);
2526                 /* drop_pagecache and drop_slab are no longer available */
2527                 /* drop_pagecache(); */
2528                 /* drop_slab(); */
2529
2530                 LDBG(curlun, "close backing file\n");
2531                 fput(curlun->filp);
2532                 curlun->filp = NULL;
2533                 adjust_wake_lock(fsg);
2534         }
2535 }
2536
2537 static void close_all_backing_files(struct fsg_dev *fsg)
2538 {
2539         int     i;
2540
2541         for (i = 0; i < fsg->nluns; ++i)
2542                 close_backing_file(fsg, &fsg->luns[i]);
2543 }
2544
2545 static ssize_t show_file(struct device *dev, struct device_attribute *attr,
2546                 char *buf)
2547 {
2548         struct lun      *curlun = dev_to_lun(dev);
2549         struct fsg_dev  *fsg = dev_get_drvdata(dev);
2550         char            *p;
2551         ssize_t         rc;
2552
2553         down_read(&fsg->filesem);
2554         if (backing_file_is_open(curlun)) {     /* Get the complete pathname */
2555                 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
2556                 if (IS_ERR(p))
2557                         rc = PTR_ERR(p);
2558                 else {
2559                         rc = strlen(p);
2560                         memmove(buf, p, rc);
2561                         buf[rc] = '\n';         /* Add a newline */
2562                         buf[++rc] = 0;
2563                 }
2564         } else {                                /* No file, return 0 bytes */
2565                 *buf = 0;
2566                 rc = 0;
2567         }
2568         up_read(&fsg->filesem);
2569         return rc;
2570 }
2571
2572 static ssize_t store_file(struct device *dev, struct device_attribute *attr,
2573                 const char *buf, size_t count)
2574 {
2575         struct lun      *curlun = dev_to_lun(dev);
2576         struct fsg_dev  *fsg = dev_get_drvdata(dev);
2577         int             rc = 0;
2578
2579         DBG(fsg, "store_file: \"%s\"\n", buf);
2580 #if 0
2581         /* disabled because we need to allow closing the backing file if the media was removed */
2582         if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
2583                 LDBG(curlun, "eject attempt prevented\n");
2584                 return -EBUSY;                          /* "Door is locked" */
2585         }
2586 #endif
2587
2588         /* Remove a trailing newline */
2589         if (count > 0 && buf[count-1] == '\n')
2590                 ((char *) buf)[count-1] = 0;
2591
2592         /* Eject current medium */
2593         down_write(&fsg->filesem);
2594         if (backing_file_is_open(curlun)) {
2595                 close_backing_file(fsg, curlun);
2596                 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2597         }
2598
2599         /* Load new medium */
2600         if (count > 0 && buf[0]) {
2601                 rc = open_backing_file(fsg, curlun, buf);
2602                 if (rc == 0)
2603                         curlun->unit_attention_data =
2604                                         SS_NOT_READY_TO_READY_TRANSITION;
2605         }
2606         up_write(&fsg->filesem);
2607         return (rc < 0 ? rc : count);
2608 }
2609
2610
2611 static DEVICE_ATTR(file, 0444, show_file, store_file);
2612
2613 /*-------------------------------------------------------------------------*/
2614
2615 static void fsg_release(struct kref *ref)
2616 {
2617         struct fsg_dev  *fsg = container_of(ref, struct fsg_dev, ref);
2618
2619         kfree(fsg->luns);
2620         kfree(fsg);
2621 }
2622
2623 static void lun_release(struct device *dev)
2624 {
2625         struct fsg_dev  *fsg = dev_get_drvdata(dev);
2626
2627         kref_put(&fsg->ref, fsg_release);
2628 }
2629
2630
2631 /*-------------------------------------------------------------------------*/
2632
2633 static int __init fsg_alloc(void)
2634 {
2635         struct fsg_dev          *fsg;
2636
2637         fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
2638         if (!fsg)
2639                 return -ENOMEM;
2640         spin_lock_init(&fsg->lock);
2641         init_rwsem(&fsg->filesem);
2642         kref_init(&fsg->ref);
2643         init_completion(&fsg->thread_notifier);
2644
2645         the_fsg = fsg;
2646         return 0;
2647 }
2648
2649 static ssize_t print_switch_name(struct switch_dev *sdev, char *buf)
2650 {
2651         return sprintf(buf, "%s\n", DRIVER_NAME);
2652 }
2653
2654 static ssize_t print_switch_state(struct switch_dev *sdev, char *buf)
2655 {
2656         struct fsg_dev  *fsg = container_of(sdev, struct fsg_dev, sdev);
2657         return sprintf(buf, "%s\n", (fsg->config ? "online" : "offline"));
2658 }
2659
2660 static void
2661 fsg_function_unbind(struct usb_configuration *c, struct usb_function *f)
2662 {
2663         struct fsg_dev  *fsg = func_to_dev(f);
2664         int                     i;
2665         struct lun              *curlun;
2666
2667         DBG(fsg, "fsg_function_unbind\n");
2668         clear_bit(REGISTERED, &fsg->atomic_bitflags);
2669
2670         /* Unregister the sysfs attribute files and the LUNs */
2671         for (i = 0; i < fsg->nluns; ++i) {
2672                 curlun = &fsg->luns[i];
2673                 if (curlun->registered) {
2674                         device_remove_file(&curlun->dev, &dev_attr_file);
2675                         device_unregister(&curlun->dev);
2676                         curlun->registered = 0;
2677                 }
2678         }
2679
2680         /* If the thread isn't already dead, tell it to exit now */
2681         if (fsg->state != FSG_STATE_TERMINATED) {
2682                 raise_exception(fsg, FSG_STATE_EXIT);
2683                 wait_for_completion(&fsg->thread_notifier);
2684
2685                 /* The cleanup routine waits for this completion also */
2686                 complete(&fsg->thread_notifier);
2687         }
2688
2689         /* Free the data buffers */
2690         for (i = 0; i < NUM_BUFFERS; ++i)
2691                 kfree(fsg->buffhds[i].buf);
2692         switch_dev_unregister(&fsg->sdev);
2693 }
2694
2695 static int __init
2696 fsg_function_bind(struct usb_configuration *c, struct usb_function *f)
2697 {
2698         struct usb_composite_dev *cdev = c->cdev;
2699         struct fsg_dev  *fsg = func_to_dev(f);
2700         int                     rc;
2701         int                     i;
2702         int                     id;
2703         struct lun              *curlun;
2704         struct usb_ep           *ep;
2705         char                    *pathbuf, *p;
2706
2707         fsg->cdev = cdev;
2708         DBG(fsg, "fsg_function_bind\n");
2709
2710         dev_attr_file.attr.mode = 0644;
2711
2712         /* Find out how many LUNs there should be */
2713         i = fsg->nluns;
2714         if (i == 0)
2715                 i = 1;
2716         if (i > MAX_LUNS) {
2717                 ERROR(fsg, "invalid number of LUNs: %d\n", i);
2718                 rc = -EINVAL;
2719                 goto out;
2720         }
2721
2722         /* Create the LUNs, open their backing files, and register the
2723          * LUN devices in sysfs. */
2724         fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL);
2725         if (!fsg->luns) {
2726                 rc = -ENOMEM;
2727                 goto out;
2728         }
2729         fsg->nluns = i;
2730
2731         for (i = 0; i < fsg->nluns; ++i) {
2732                 curlun = &fsg->luns[i];
2733                 curlun->ro = 0;
2734                 curlun->dev.release = lun_release;
2735                 /* use "usb_mass_storage" platform device as parent if available */
2736                 if (fsg->pdev)
2737                         curlun->dev.parent = &fsg->pdev->dev;
2738                 else
2739                         curlun->dev.parent = &cdev->gadget->dev;
2740                 dev_set_drvdata(&curlun->dev, fsg);
2741                 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
2742                                 "lun%d", i);
2743
2744                 rc = device_register(&curlun->dev);
2745                 if (rc != 0) {
2746                         INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
2747                         goto out;
2748                 }
2749                 rc = device_create_file(&curlun->dev, &dev_attr_file);
2750                 if (rc != 0) {
2751                         ERROR(fsg, "device_create_file failed: %d\n", rc);
2752                         device_unregister(&curlun->dev);
2753                         goto out;
2754                 }
2755                 curlun->registered = 1;
2756                 kref_get(&fsg->ref);
2757         }
2758
2759         /* allocate interface ID(s) */
2760         id = usb_interface_id(c, f);
2761         if (id < 0)
2762                 return id;
2763         intf_desc.bInterfaceNumber = id;
2764
2765         ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_in_desc);
2766         if (!ep)
2767                 goto autoconf_fail;
2768         ep->driver_data = fsg;          /* claim the endpoint */
2769         fsg->bulk_in = ep;
2770
2771         ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_out_desc);
2772         if (!ep)
2773                 goto autoconf_fail;
2774         ep->driver_data = fsg;          /* claim the endpoint */
2775         fsg->bulk_out = ep;
2776
2777         rc = -ENOMEM;
2778
2779         if (gadget_is_dualspeed(cdev->gadget)) {
2780                 /* Assume endpoint addresses are the same for both speeds */
2781                 hs_bulk_in_desc.bEndpointAddress =
2782                                 fs_bulk_in_desc.bEndpointAddress;
2783                 hs_bulk_out_desc.bEndpointAddress =
2784                                 fs_bulk_out_desc.bEndpointAddress;
2785
2786                 f->hs_descriptors = hs_function;
2787         }
2788
2789         /* Allocate the data buffers */
2790         for (i = 0; i < NUM_BUFFERS; ++i) {
2791                 struct fsg_buffhd       *bh = &fsg->buffhds[i];
2792
2793                 /* Allocate for the bulk-in endpoint.  We assume that
2794                  * the buffer will also work with the bulk-out (and
2795                  * interrupt-in) endpoint. */
2796                 bh->buf = kmalloc(fsg->buf_size, GFP_KERNEL);
2797                 if (!bh->buf)
2798                         goto out;
2799                 bh->next = bh + 1;
2800         }
2801         fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
2802
2803         fsg->thread_task = kthread_create(fsg_main_thread, fsg,
2804                         shortname);
2805         if (IS_ERR(fsg->thread_task)) {
2806                 rc = PTR_ERR(fsg->thread_task);
2807                 ERROR(fsg, "kthread_create failed: %d\n", rc);
2808                 goto out;
2809         }
2810
2811         INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
2812
2813         pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2814         for (i = 0; i < fsg->nluns; ++i) {
2815                 curlun = &fsg->luns[i];
2816                 if (backing_file_is_open(curlun)) {
2817                         p = NULL;
2818                         if (pathbuf) {
2819                                 p = d_path(&curlun->filp->f_path,
2820                                            pathbuf, PATH_MAX);
2821                                 if (IS_ERR(p))
2822                                         p = NULL;
2823                         }
2824                         LINFO(curlun, "ro=%d, file: %s\n",
2825                                         curlun->ro, (p ? p : "(error)"));
2826                 }
2827         }
2828         kfree(pathbuf);
2829
2830         set_bit(REGISTERED, &fsg->atomic_bitflags);
2831
2832         /* Tell the thread to start working */
2833         wake_up_process(fsg->thread_task);
2834         return 0;
2835
2836 autoconf_fail:
2837         ERROR(fsg, "unable to autoconfigure all endpoints\n");
2838         rc = -ENOTSUPP;
2839
2840 out:
2841         DBG(fsg, "fsg_function_bind failed: %d\n", rc);
2842         fsg->state = FSG_STATE_TERMINATED;      /* The thread is dead */
2843         fsg_function_unbind(c, f);
2844         close_all_backing_files(fsg);
2845         return rc;
2846 }
2847
2848 static int fsg_function_set_alt(struct usb_function *f,
2849                 unsigned intf, unsigned alt)
2850 {
2851         struct fsg_dev  *fsg = func_to_dev(f);
2852         DBG(fsg, "fsg_function_set_alt intf: %d alt: %d\n", intf, alt);
2853         fsg->new_config = 1;
2854         do_set_interface(fsg, 0);
2855         raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
2856         return 0;
2857 }
2858
2859 static void fsg_function_disable(struct usb_function *f)
2860 {
2861         struct fsg_dev  *fsg = func_to_dev(f);
2862         DBG(fsg, "fsg_function_disable\n");
2863         if (fsg->new_config)
2864                 do_set_interface(fsg, -1);
2865         fsg->new_config = 0;
2866         raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
2867 }
2868
2869 static int __init fsg_probe(struct platform_device *pdev)
2870 {
2871         struct usb_mass_storage_platform_data *pdata = pdev->dev.platform_data;
2872         struct fsg_dev *fsg = the_fsg;
2873
2874         fsg->pdev = pdev;
2875         printk(KERN_INFO "fsg_probe pdata: %p\n", pdata);
2876
2877         if (pdata) {
2878                 if (pdata->vendor)
2879                         fsg->vendor = pdata->vendor;
2880
2881                 if (pdata->product)
2882                         fsg->product = pdata->product;
2883
2884                 if (pdata->release)
2885                         fsg->release = pdata->release;
2886         }
2887
2888         return 0;
2889 }
2890
2891 static struct platform_driver fsg_platform_driver = {
2892         .driver = { .name = "usb_mass_storage", },
2893         .probe = fsg_probe,
2894 };
2895
2896 int __init mass_storage_function_add(struct usb_composite_dev *cdev,
2897         struct usb_configuration *c, int nluns)
2898 {
2899         int             rc;
2900         struct fsg_dev  *fsg;
2901
2902         printk(KERN_INFO "mass_storage_function_add\n");
2903         rc = fsg_alloc();
2904         if (rc)
2905                 return rc;
2906         fsg = the_fsg;
2907         fsg->nluns = nluns;
2908
2909         spin_lock_init(&fsg->lock);
2910         init_rwsem(&fsg->filesem);
2911         kref_init(&fsg->ref);
2912         init_completion(&fsg->thread_notifier);
2913
2914         the_fsg->buf_size = BULK_BUFFER_SIZE;
2915         the_fsg->sdev.name = DRIVER_NAME;
2916         the_fsg->sdev.print_name = print_switch_name;
2917         the_fsg->sdev.print_state = print_switch_state;
2918         rc = switch_dev_register(&the_fsg->sdev);
2919         if (rc < 0)
2920                 goto err_switch_dev_register;
2921
2922         rc = platform_driver_register(&fsg_platform_driver);
2923         if (rc != 0)
2924                 goto err_platform_driver_register;
2925
2926         wake_lock_init(&the_fsg->wake_lock, WAKE_LOCK_SUSPEND,
2927                        "usb_mass_storage");
2928
2929         fsg->cdev = cdev;
2930         fsg->function.name = shortname;
2931         fsg->function.descriptors = fs_function;
2932         fsg->function.bind = fsg_function_bind;
2933         fsg->function.unbind = fsg_function_unbind;
2934         fsg->function.setup = fsg_function_setup;
2935         fsg->function.set_alt = fsg_function_set_alt;
2936         fsg->function.disable = fsg_function_disable;
2937
2938         rc = usb_add_function(c, &fsg->function);
2939         if (rc != 0)
2940                 goto err_usb_add_function;
2941
2942
2943         return 0;
2944
2945 err_usb_add_function:
2946         platform_driver_unregister(&fsg_platform_driver);
2947 err_platform_driver_register:
2948         switch_dev_unregister(&the_fsg->sdev);
2949 err_switch_dev_register:
2950         kref_put(&the_fsg->ref, fsg_release);
2951
2952         return rc;
2953 }
2954
2955