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