Merge remote-tracking branch 'kernel-2.6.32/develop' into develop-2.6.36
[firefly-linux-kernel-4.4.55.git] / drivers / usb / gadget / f_mass_storage.c
1 /*
2  * f_mass_storage.c -- Mass Storage USB Composite Function
3  *
4  * Copyright (C) 2003-2008 Alan Stern
5  * Copyright (C) 2009 Samsung Electronics
6  *                    Author: Michal Nazarewicz <m.nazarewicz@samsung.com>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. The names of the above-listed copyright holders may not be used
19  *    to endorse or promote products derived from this software without
20  *    specific prior written permission.
21  *
22  * ALTERNATIVELY, this software may be distributed under the terms of the
23  * GNU General Public License ("GPL") as published by the Free Software
24  * Foundation, either version 2 of that License or (at your option) any
25  * later version.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
28  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
31  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
33  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
34  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
35  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
36  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
37  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39
40
41 /*
42  * The Mass Storage Function acts as a USB Mass Storage device,
43  * appearing to the host as a disk drive or as a CD-ROM drive.  In
44  * addition to providing an example of a genuinely useful composite
45  * function for a USB device, it also illustrates a technique of
46  * double-buffering for increased throughput.
47  *
48  * Function supports multiple logical units (LUNs).  Backing storage
49  * for each LUN is provided by a regular file or a block device.
50  * Access for each LUN can be limited to read-only.  Moreover, the
51  * function can indicate that LUN is removable and/or CD-ROM.  (The
52  * later implies read-only access.)
53  *
54  * MSF is configured by specifying a fsg_config structure.  It has the
55  * following fields:
56  *
57  *      nluns           Number of LUNs function have (anywhere from 1
58  *                              to FSG_MAX_LUNS which is 8).
59  *      luns            An array of LUN configuration values.  This
60  *                              should be filled for each LUN that
61  *                              function will include (ie. for "nluns"
62  *                              LUNs).  Each element of the array has
63  *                              the following fields:
64  *      ->filename      The path to the backing file for the LUN.
65  *                              Required if LUN is not marked as
66  *                              removable.
67  *      ->ro            Flag specifying access to the LUN shall be
68  *                              read-only.  This is implied if CD-ROM
69  *                              emulation is enabled as well as when
70  *                              it was impossible to open "filename"
71  *                              in R/W mode.
72  *      ->removable     Flag specifying that LUN shall be indicated as
73  *                              being removable.
74  *      ->cdrom         Flag specifying that LUN shall be reported as
75  *                              being a CD-ROM.
76  *
77  *      lun_name_format A printf-like format for names of the LUN
78  *                              devices.  This determines how the
79  *                              directory in sysfs will be named.
80  *                              Unless you are using several MSFs in
81  *                              a single gadget (as opposed to single
82  *                              MSF in many configurations) you may
83  *                              leave it as NULL (in which case
84  *                              "lun%d" will be used).  In the format
85  *                              you can use "%d" to index LUNs for
86  *                              MSF's with more than one LUN.  (Beware
87  *                              that there is only one integer given
88  *                              as an argument for the format and
89  *                              specifying invalid format may cause
90  *                              unspecified behaviour.)
91  *      thread_name     Name of the kernel thread process used by the
92  *                              MSF.  You can safely set it to NULL
93  *                              (in which case default "file-storage"
94  *                              will be used).
95  *
96  *      vendor_name
97  *      product_name
98  *      release         Information used as a reply to INQUIRY
99  *                              request.  To use default set to NULL,
100  *                              NULL, 0xffff respectively.  The first
101  *                              field should be 8 and the second 16
102  *                              characters or less.
103  *
104  *      can_stall       Set to permit function to halt bulk endpoints.
105  *                              Disabled on some USB devices known not
106  *                              to work correctly.  You should set it
107  *                              to true.
108  *
109  * If "removable" is not set for a LUN then a backing file must be
110  * specified.  If it is set, then NULL filename means the LUN's medium
111  * is not loaded (an empty string as "filename" in the fsg_config
112  * structure causes error).  The CD-ROM emulation includes a single
113  * data track and no audio tracks; hence there need be only one
114  * backing file per LUN.  Note also that the CD-ROM block length is
115  * set to 512 rather than the more common value 2048.
116  *
117  *
118  * MSF includes support for module parameters.  If gadget using it
119  * decides to use it, the following module parameters will be
120  * available:
121  *
122  *      file=filename[,filename...]
123  *                      Names of the files or block devices used for
124  *                              backing storage.
125  *      ro=b[,b...]     Default false, boolean for read-only access.
126  *      removable=b[,b...]
127  *                      Default true, boolean for removable media.
128  *      cdrom=b[,b...]  Default false, boolean for whether to emulate
129  *                              a CD-ROM drive.
130  *      luns=N          Default N = number of filenames, number of
131  *                              LUNs to support.
132  *      stall           Default determined according to the type of
133  *                              USB device controller (usually true),
134  *                              boolean to permit the driver to halt
135  *                              bulk endpoints.
136  *
137  * The module parameters may be prefixed with some string.  You need
138  * to consult gadget's documentation or source to verify whether it is
139  * using those module parameters and if it does what are the prefixes
140  * (look for FSG_MODULE_PARAMETERS() macro usage, what's inside it is
141  * the prefix).
142  *
143  *
144  * Requirements are modest; only a bulk-in and a bulk-out endpoint are
145  * needed.  The memory requirement amounts to two 16K buffers, size
146  * configurable by a parameter.  Support is included for both
147  * full-speed and high-speed operation.
148  *
149  * Note that the driver is slightly non-portable in that it assumes a
150  * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
151  * interrupt-in endpoints.  With most device controllers this isn't an
152  * issue, but there may be some with hardware restrictions that prevent
153  * a buffer from being used by more than one endpoint.
154  *
155  *
156  * The pathnames of the backing files and the ro settings are
157  * available in the attribute files "file" and "ro" in the lun<n> (or
158  * to be more precise in a directory which name comes from
159  * "lun_name_format" option!) subdirectory of the gadget's sysfs
160  * directory.  If the "removable" option is set, writing to these
161  * files will simulate ejecting/loading the medium (writing an empty
162  * line means eject) and adjusting a write-enable tab.  Changes to the
163  * ro setting are not allowed when the medium is loaded or if CD-ROM
164  * emulation is being used.
165  *
166  * When a LUN receive an "eject" SCSI request (Start/Stop Unit),
167  * if the LUN is removable, the backing file is released to simulate
168  * ejection.
169  *
170  *
171  * This function is heavily based on "File-backed Storage Gadget" by
172  * Alan Stern which in turn is heavily based on "Gadget Zero" by David
173  * Brownell.  The driver's SCSI command interface was based on the
174  * "Information technology - Small Computer System Interface - 2"
175  * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
176  * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
177  * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
178  * was based on the "Universal Serial Bus Mass Storage Class UFI
179  * Command Specification" document, Revision 1.0, December 14, 1998,
180  * available at
181  * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
182  */
183
184
185 /*
186  *                              Driver Design
187  *
188  * The MSF is fairly straightforward.  There is a main kernel
189  * thread that handles most of the work.  Interrupt routines field
190  * callbacks from the controller driver: bulk- and interrupt-request
191  * completion notifications, endpoint-0 events, and disconnect events.
192  * Completion events are passed to the main thread by wakeup calls.  Many
193  * ep0 requests are handled at interrupt time, but SetInterface,
194  * SetConfiguration, and device reset requests are forwarded to the
195  * thread in the form of "exceptions" using SIGUSR1 signals (since they
196  * should interrupt any ongoing file I/O operations).
197  *
198  * The thread's main routine implements the standard command/data/status
199  * parts of a SCSI interaction.  It and its subroutines are full of tests
200  * for pending signals/exceptions -- all this polling is necessary since
201  * the kernel has no setjmp/longjmp equivalents.  (Maybe this is an
202  * indication that the driver really wants to be running in userspace.)
203  * An important point is that so long as the thread is alive it keeps an
204  * open reference to the backing file.  This will prevent unmounting
205  * the backing file's underlying filesystem and could cause problems
206  * during system shutdown, for example.  To prevent such problems, the
207  * thread catches INT, TERM, and KILL signals and converts them into
208  * an EXIT exception.
209  *
210  * In normal operation the main thread is started during the gadget's
211  * fsg_bind() callback and stopped during fsg_unbind().  But it can
212  * also exit when it receives a signal, and there's no point leaving
213  * the gadget running when the thread is dead.  At of this moment, MSF
214  * provides no way to deregister the gadget when thread dies -- maybe
215  * a callback functions is needed.
216  *
217  * To provide maximum throughput, the driver uses a circular pipeline of
218  * buffer heads (struct fsg_buffhd).  In principle the pipeline can be
219  * arbitrarily long; in practice the benefits don't justify having more
220  * than 2 stages (i.e., double buffering).  But it helps to think of the
221  * pipeline as being a long one.  Each buffer head contains a bulk-in and
222  * a bulk-out request pointer (since the buffer can be used for both
223  * output and input -- directions always are given from the host's
224  * point of view) as well as a pointer to the buffer and various state
225  * variables.
226  *
227  * Use of the pipeline follows a simple protocol.  There is a variable
228  * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
229  * At any time that buffer head may still be in use from an earlier
230  * request, so each buffer head has a state variable indicating whether
231  * it is EMPTY, FULL, or BUSY.  Typical use involves waiting for the
232  * buffer head to be EMPTY, filling the buffer either by file I/O or by
233  * USB I/O (during which the buffer head is BUSY), and marking the buffer
234  * head FULL when the I/O is complete.  Then the buffer will be emptied
235  * (again possibly by USB I/O, during which it is marked BUSY) and
236  * finally marked EMPTY again (possibly by a completion routine).
237  *
238  * A module parameter tells the driver to avoid stalling the bulk
239  * endpoints wherever the transport specification allows.  This is
240  * necessary for some UDCs like the SuperH, which cannot reliably clear a
241  * halt on a bulk endpoint.  However, under certain circumstances the
242  * Bulk-only specification requires a stall.  In such cases the driver
243  * will halt the endpoint and set a flag indicating that it should clear
244  * the halt in software during the next device reset.  Hopefully this
245  * will permit everything to work correctly.  Furthermore, although the
246  * specification allows the bulk-out endpoint to halt when the host sends
247  * too much data, implementing this would cause an unavoidable race.
248  * The driver will always use the "no-stall" approach for OUT transfers.
249  *
250  * One subtle point concerns sending status-stage responses for ep0
251  * requests.  Some of these requests, such as device reset, can involve
252  * interrupting an ongoing file I/O operation, which might take an
253  * arbitrarily long time.  During that delay the host might give up on
254  * the original ep0 request and issue a new one.  When that happens the
255  * driver should not notify the host about completion of the original
256  * request, as the host will no longer be waiting for it.  So the driver
257  * assigns to each ep0 request a unique tag, and it keeps track of the
258  * tag value of the request associated with a long-running exception
259  * (device-reset, interface-change, or configuration-change).  When the
260  * exception handler is finished, the status-stage response is submitted
261  * only if the current ep0 request tag is equal to the exception request
262  * tag.  Thus only the most recently received ep0 request will get a
263  * status-stage response.
264  *
265  * Warning: This driver source file is too long.  It ought to be split up
266  * into a header file plus about 3 separate .c files, to handle the details
267  * of the Gadget, USB Mass Storage, and SCSI protocols.
268  */
269
270
271 /* #define VERBOSE_DEBUG */
272 /* #define DUMP_MSGS */
273
274
275 #include <linux/blkdev.h>
276 #include <linux/completion.h>
277 #include <linux/dcache.h>
278 #include <linux/delay.h>
279 #include <linux/device.h>
280 #include <linux/fcntl.h>
281 #include <linux/file.h>
282 #include <linux/fs.h>
283 #include <linux/kref.h>
284 #include <linux/kthread.h>
285 #include <linux/limits.h>
286 #include <linux/rwsem.h>
287 #include <linux/slab.h>
288 #include <linux/spinlock.h>
289 #include <linux/string.h>
290 #include <linux/freezer.h>
291 #include <linux/utsname.h>
292
293 #include <linux/usb/ch9.h>
294 #include <linux/usb/gadget.h>
295
296 #include "gadget_chips.h"
297
298 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
299 #include <linux/usb/android_composite.h>
300 #include <linux/platform_device.h>
301
302 #define FUNCTION_NAME           "usb_mass_storage"
303 #endif
304
305 #ifdef CONFIG_ARCH_RK29
306 #include <linux/power_supply.h>
307 #include <linux/reboot.h>
308 #include <linux/syscalls.h>
309
310 static int usb_msc_connected;   /*usb charge status*/
311
312 static void set_msc_connect_flag( int connected )
313 {
314         printk("%s status = %d 20101216\n" , __func__, connected);
315         if( usb_msc_connected == connected )
316                 return;
317         usb_msc_connected = connected;//usb mass storage is ok
318 }
319
320 int get_msc_connect_flag( void )
321 {
322         return usb_msc_connected;
323 }
324 EXPORT_SYMBOL(get_msc_connect_flag);
325 #endif
326
327 /*------------------------------------------------------------------------*/
328
329 #define FSG_DRIVER_DESC         "Mass Storage Function"
330 #define FSG_DRIVER_VERSION      "2009/09/11"
331
332 static const char fsg_string_interface[] = "Mass Storage";
333
334
335 #define FSG_NO_INTR_EP 1
336 #define FSG_NO_DEVICE_STRINGS    1
337 #define FSG_NO_OTG               1
338 #define FSG_NO_INTR_EP           1
339
340 #include "storage_common.c"
341
342
343 /*-------------------------------------------------------------------------*/
344
345 struct fsg_dev;
346 struct fsg_common;
347
348 /* FSF callback functions */
349 struct fsg_operations {
350         /* Callback function to call when thread exits.  If no
351          * callback is set or it returns value lower then zero MSF
352          * will force eject all LUNs it operates on (including those
353          * marked as non-removable or with prevent_medium_removal flag
354          * set). */
355         int (*thread_exits)(struct fsg_common *common);
356
357         /* Called prior to ejection.  Negative return means error,
358          * zero means to continue with ejection, positive means not to
359          * eject. */
360         int (*pre_eject)(struct fsg_common *common,
361                          struct fsg_lun *lun, int num);
362         /* Called after ejection.  Negative return means error, zero
363          * or positive is just a success. */
364         int (*post_eject)(struct fsg_common *common,
365                           struct fsg_lun *lun, int num);
366 };
367
368
369 /* Data shared by all the FSG instances. */
370 struct fsg_common {
371         struct usb_gadget       *gadget;
372         struct fsg_dev          *fsg, *new_fsg;
373         wait_queue_head_t       fsg_wait;
374
375         /* filesem protects: backing files in use */
376         struct rw_semaphore     filesem;
377
378         /* lock protects: state, all the req_busy's */
379         spinlock_t              lock;
380
381         struct usb_ep           *ep0;           /* Copy of gadget->ep0 */
382         struct usb_request      *ep0req;        /* Copy of cdev->req */
383         unsigned int            ep0_req_tag;
384
385         struct fsg_buffhd       *next_buffhd_to_fill;
386         struct fsg_buffhd       *next_buffhd_to_drain;
387         struct fsg_buffhd       buffhds[FSG_NUM_BUFFERS];
388
389         int                     cmnd_size;
390         u8                      cmnd[MAX_COMMAND_SIZE];
391
392         unsigned int            nluns;
393         unsigned int            lun;
394         struct fsg_lun          *luns;
395         struct fsg_lun          *curlun;
396
397         unsigned int            bulk_out_maxpacket;
398         enum fsg_state          state;          /* For exception handling */
399         unsigned int            exception_req_tag;
400
401         enum data_direction     data_dir;
402         u32                     data_size;
403         u32                     data_size_from_cmnd;
404         u32                     tag;
405         u32                     residue;
406         u32                     usb_amount_left;
407
408         unsigned int            can_stall:1;
409         unsigned int            free_storage_on_release:1;
410         unsigned int            phase_error:1;
411         unsigned int            short_packet_received:1;
412         unsigned int            bad_lun_okay:1;
413         unsigned int            running:1;
414
415         int                     thread_wakeup_needed;
416         struct completion       thread_notifier;
417         struct task_struct      *thread_task;
418
419         /* Callback functions. */
420         const struct fsg_operations     *ops;
421         /* Gadget's private data. */
422         void                    *private_data;
423
424         /* Vendor (8 chars), product (16 chars), release (4
425          * hexadecimal digits) and NUL byte */
426         char inquiry_string[8 + 16 + 4 + 1];
427
428         struct kref             ref;
429 };
430
431
432 struct fsg_config {
433         unsigned nluns;
434         struct fsg_lun_config {
435                 const char *filename;
436                 char ro;
437                 char removable;
438                 char cdrom;
439         } luns[FSG_MAX_LUNS];
440
441         const char              *lun_name_format;
442         const char              *thread_name;
443
444         /* Callback functions. */
445         const struct fsg_operations     *ops;
446         /* Gadget's private data. */
447         void                    *private_data;
448
449         const char *vendor_name;                /*  8 characters or less */
450         const char *product_name;               /* 16 characters or less */
451         u16 release;
452
453         char                    can_stall;
454
455 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
456         struct platform_device *pdev;
457 #endif
458 };
459
460
461 struct fsg_dev {
462         struct usb_function     function;
463         struct usb_gadget       *gadget;        /* Copy of cdev->gadget */
464         struct fsg_common       *common;
465
466         u16                     interface_number;
467
468         unsigned int            bulk_in_enabled:1;
469         unsigned int            bulk_out_enabled:1;
470
471         unsigned long           atomic_bitflags;
472 #define IGNORE_BULK_OUT         0
473
474         struct usb_ep           *bulk_in;
475         struct usb_ep           *bulk_out;
476 };
477
478
479 static inline int __fsg_is_set(struct fsg_common *common,
480                                const char *func, unsigned line)
481 {
482         if (common->fsg)
483                 return 1;
484         ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
485         WARN_ON(1);
486         return 0;
487 }
488
489 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
490
491
492 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
493 {
494         return container_of(f, struct fsg_dev, function);
495 }
496
497
498 typedef void (*fsg_routine_t)(struct fsg_dev *);
499
500 static int exception_in_progress(struct fsg_common *common)
501 {
502         return common->state > FSG_STATE_IDLE;
503 }
504
505 /* Make bulk-out requests be divisible by the maxpacket size */
506 static void set_bulk_out_req_length(struct fsg_common *common,
507                 struct fsg_buffhd *bh, unsigned int length)
508 {
509         unsigned int    rem;
510
511         bh->bulk_out_intended_length = length;
512         rem = length % common->bulk_out_maxpacket;
513         if (rem > 0)
514                 length += common->bulk_out_maxpacket - rem;
515         bh->outreq->length = length;
516 }
517
518 /*-------------------------------------------------------------------------*/
519
520 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
521 {
522         const char      *name;
523
524         if (ep == fsg->bulk_in)
525                 name = "bulk-in";
526         else if (ep == fsg->bulk_out)
527                 name = "bulk-out";
528         else
529                 name = ep->name;
530         DBG(fsg, "%s set halt\n", name);
531         return usb_ep_set_halt(ep);
532 }
533
534
535 /*-------------------------------------------------------------------------*/
536
537 /* These routines may be called in process context or in_irq */
538
539 /* Caller must hold fsg->lock */
540 static void wakeup_thread(struct fsg_common *common)
541 {
542         /* Tell the main thread that something has happened */
543         common->thread_wakeup_needed = 1;
544         if (common->thread_task)
545                 wake_up_process(common->thread_task);
546 }
547
548
549 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
550 {
551         unsigned long           flags;
552
553         /* Do nothing if a higher-priority exception is already in progress.
554          * If a lower-or-equal priority exception is in progress, preempt it
555          * and notify the main thread by sending it a signal. */
556         spin_lock_irqsave(&common->lock, flags);
557         if (common->state <= new_state) {
558                 common->exception_req_tag = common->ep0_req_tag;
559                 common->state = new_state;
560                 if (common->thread_task)
561                         send_sig_info(SIGUSR1, SEND_SIG_FORCED,
562                                       common->thread_task);
563         }
564         spin_unlock_irqrestore(&common->lock, flags);
565 }
566
567
568 /*-------------------------------------------------------------------------*/
569
570 static int ep0_queue(struct fsg_common *common)
571 {
572         int     rc;
573
574         rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
575         common->ep0->driver_data = common;
576         if (rc != 0 && rc != -ESHUTDOWN) {
577                 /* We can't do much more than wait for a reset */
578                 WARNING(common, "error in submission: %s --> %d\n",
579                         common->ep0->name, rc);
580         }
581         return rc;
582 }
583
584 /*-------------------------------------------------------------------------*/
585
586 /* Bulk and interrupt endpoint completion handlers.
587  * These always run in_irq. */
588
589 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
590 {
591         struct fsg_common       *common = ep->driver_data;
592         struct fsg_buffhd       *bh = req->context;
593
594         if (req->status || req->actual != req->length)
595                 DBG(common, "%s --> %d, %u/%u\n", __func__,
596                                 req->status, req->actual, req->length);
597         if (req->status == -ECONNRESET)         /* Request was cancelled */
598                 usb_ep_fifo_flush(ep);
599
600         /* Hold the lock while we update the request and buffer states */
601         smp_wmb();
602         spin_lock(&common->lock);
603         bh->inreq_busy = 0;
604         bh->state = BUF_STATE_EMPTY;
605         wakeup_thread(common);
606         spin_unlock(&common->lock);
607 }
608
609 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
610 {
611         struct fsg_common       *common = ep->driver_data;
612         struct fsg_buffhd       *bh = req->context;
613
614         dump_msg(common, "bulk-out", req->buf, req->actual);
615         if (req->status || req->actual != bh->bulk_out_intended_length)
616                 DBG(common, "%s --> %d, %u/%u\n", __func__,
617                                 req->status, req->actual,
618                                 bh->bulk_out_intended_length);
619         if (req->status == -ECONNRESET)         /* Request was cancelled */
620                 usb_ep_fifo_flush(ep);
621
622         /* Hold the lock while we update the request and buffer states */
623         smp_wmb();
624         spin_lock(&common->lock);
625         bh->outreq_busy = 0;
626         bh->state = BUF_STATE_FULL;
627         wakeup_thread(common);
628         spin_unlock(&common->lock);
629 }
630
631
632 /*-------------------------------------------------------------------------*/
633
634 /* Ep0 class-specific handlers.  These always run in_irq. */
635
636 static int fsg_setup(struct usb_function *f,
637                 const struct usb_ctrlrequest *ctrl)
638 {
639         struct fsg_dev          *fsg = fsg_from_func(f);
640         struct usb_request      *req = fsg->common->ep0req;
641         u16                     w_index = le16_to_cpu(ctrl->wIndex);
642         u16                     w_value = le16_to_cpu(ctrl->wValue);
643         u16                     w_length = le16_to_cpu(ctrl->wLength);
644
645         if (!fsg_is_set(fsg->common))
646                 return -EOPNOTSUPP;
647
648         switch (ctrl->bRequest) {
649
650         case USB_BULK_RESET_REQUEST:
651                 if (ctrl->bRequestType !=
652                     (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
653                         break;
654                 if (w_index != fsg->interface_number || w_value != 0)
655                         return -EDOM;
656
657                 /* Raise an exception to stop the current operation
658                  * and reinitialize our state. */
659                 DBG(fsg, "bulk reset request\n");
660                 raise_exception(fsg->common, FSG_STATE_RESET);
661                 return DELAYED_STATUS;
662
663         case USB_BULK_GET_MAX_LUN_REQUEST:
664                 if (ctrl->bRequestType !=
665                     (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
666                         break;
667                 if (w_index != fsg->interface_number || w_value != 0)
668                         return -EDOM;
669                 VDBG(fsg, "get max LUN\n");
670                 *(u8 *) req->buf = fsg->common->nluns - 1;
671
672                 /* Respond with data/status */
673                 req->length = min((u16)1, w_length);
674                 return ep0_queue(fsg->common);
675         }
676
677         VDBG(fsg,
678              "unknown class-specific control req "
679              "%02x.%02x v%04x i%04x l%u\n",
680              ctrl->bRequestType, ctrl->bRequest,
681              le16_to_cpu(ctrl->wValue), w_index, w_length);
682         return -EOPNOTSUPP;
683 }
684
685
686 /*-------------------------------------------------------------------------*/
687
688 /* All the following routines run in process context */
689
690
691 /* Use this for bulk or interrupt transfers, not ep0 */
692 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
693                 struct usb_request *req, int *pbusy,
694                 enum fsg_buffer_state *state)
695 {
696         int     rc;
697
698         if (ep == fsg->bulk_in)
699                 dump_msg(fsg, "bulk-in", req->buf, req->length);
700
701         spin_lock_irq(&fsg->common->lock);
702         *pbusy = 1;
703         *state = BUF_STATE_BUSY;
704         spin_unlock_irq(&fsg->common->lock);
705         rc = usb_ep_queue(ep, req, GFP_KERNEL);
706         if (rc != 0) {
707                 *pbusy = 0;
708                 *state = BUF_STATE_EMPTY;
709
710                 /* We can't do much more than wait for a reset */
711
712                 /* Note: currently the net2280 driver fails zero-length
713                  * submissions if DMA is enabled. */
714                 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
715                                                 req->length == 0))
716                         WARNING(fsg, "error in submission: %s --> %d\n",
717                                         ep->name, rc);
718         }
719 }
720
721 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state)           \
722         if (fsg_is_set(common))                                         \
723                 start_transfer((common)->fsg, (common)->fsg->ep_name,   \
724                                req, pbusy, state);                      \
725         else
726
727 #define START_TRANSFER(common, ep_name, req, pbusy, state)              \
728         START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
729
730
731
732 static int sleep_thread(struct fsg_common *common)
733 {
734         int     rc = 0;
735
736         /* Wait until a signal arrives or we are woken up */
737         for (;;) {
738                 try_to_freeze();
739                 set_current_state(TASK_INTERRUPTIBLE);
740                 if (signal_pending(current)) {
741                         rc = -EINTR;
742                         break;
743                 }
744                 if (common->thread_wakeup_needed)
745                         break;
746                 schedule();
747         }
748         __set_current_state(TASK_RUNNING);
749         common->thread_wakeup_needed = 0;
750         return rc;
751 }
752
753
754 /*-------------------------------------------------------------------------*/
755
756 static int do_read(struct fsg_common *common)
757 {
758         struct fsg_lun          *curlun = common->curlun;
759         u32                     lba;
760         struct fsg_buffhd       *bh;
761         int                     rc;
762         u32                     amount_left;
763         loff_t                  file_offset, file_offset_tmp;
764         unsigned int            amount;
765         unsigned int            partial_page;
766         ssize_t                 nread;
767
768         /* Get the starting Logical Block Address and check that it's
769          * not too big */
770         if (common->cmnd[0] == SC_READ_6)
771                 lba = get_unaligned_be24(&common->cmnd[1]);
772         else {
773                 lba = get_unaligned_be32(&common->cmnd[2]);
774
775                 /* We allow DPO (Disable Page Out = don't save data in the
776                  * cache) and FUA (Force Unit Access = don't read from the
777                  * cache), but we don't implement them. */
778                 if ((common->cmnd[1] & ~0x18) != 0) {
779                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
780                         return -EINVAL;
781                 }
782         }
783         if (lba >= curlun->num_sectors) {
784                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
785                 return -EINVAL;
786         }
787         file_offset = ((loff_t) lba) << 9;
788
789         /* Carry out the file reads */
790         amount_left = common->data_size_from_cmnd;
791         if (unlikely(amount_left == 0))
792                 return -EIO;            /* No default reply */
793
794         for (;;) {
795
796                 /* Figure out how much we need to read:
797                  * Try to read the remaining amount.
798                  * But don't read more than the buffer size.
799                  * And don't try to read past the end of the file.
800                  * Finally, if we're not at a page boundary, don't read past
801                  *      the next page.
802                  * If this means reading 0 then we were asked to read past
803                  *      the end of file. */
804                 amount = min(amount_left, FSG_BUFLEN);
805                 amount = min((loff_t) amount,
806                                 curlun->file_length - file_offset);
807                 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
808                 if (partial_page > 0)
809                         amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
810                                         partial_page);
811
812                 /* kever@rk
813                  * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
814                  * because of the DOEPTSIZ.PKTCNT has only 10 bits
815                  */
816                 if((common->gadget->speed != USB_SPEED_HIGH)&&(amount >0x8000))
817                     amount = 0x8000;
818
819                 /* Wait for the next buffer to become available */
820                 bh = common->next_buffhd_to_fill;
821                 while (bh->state != BUF_STATE_EMPTY) {
822                         rc = sleep_thread(common);
823                         if (rc)
824                                 return rc;
825                 }
826
827                 /* If we were asked to read past the end of file,
828                  * end with an empty buffer. */
829                 if (amount == 0) {
830                         curlun->sense_data =
831                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
832                         curlun->sense_data_info = file_offset >> 9;
833                         curlun->info_valid = 1;
834                         bh->inreq->length = 0;
835                         bh->state = BUF_STATE_FULL;
836                         break;
837                 }
838
839                 /* Perform the read */
840                 file_offset_tmp = file_offset;
841                 nread = vfs_read(curlun->filp,
842                                 (char __user *) bh->buf,
843                                 amount, &file_offset_tmp);
844                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
845                                 (unsigned long long) file_offset,
846                                 (int) nread);
847                 if (signal_pending(current))
848                         return -EINTR;
849
850                 if (nread < 0) {
851                         LDBG(curlun, "error in file read: %d\n",
852                                         (int) nread);
853                         nread = 0;
854                 } else if (nread < amount) {
855                         LDBG(curlun, "partial file read: %d/%u\n",
856                                         (int) nread, amount);
857                         nread -= (nread & 511); /* Round down to a block */
858                 }
859                 file_offset  += nread;
860                 amount_left  -= nread;
861                 common->residue -= nread;
862                 bh->inreq->length = nread;
863                 bh->state = BUF_STATE_FULL;
864
865                 /* If an error occurred, report it and its position */
866                 if (nread < amount) {
867                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
868                         curlun->sense_data_info = file_offset >> 9;
869                         curlun->info_valid = 1;
870                         break;
871                 }
872
873                 if (amount_left == 0)
874                         break;          /* No more left to read */
875
876                 /* Send this buffer and go read some more */
877                 bh->inreq->zero = 0;
878                 START_TRANSFER_OR(common, bulk_in, bh->inreq,
879                                &bh->inreq_busy, &bh->state)
880                         /* Don't know what to do if
881                          * common->fsg is NULL */
882                         return -EIO;
883                 common->next_buffhd_to_fill = bh->next;
884         }
885
886         return -EIO;            /* No default reply */
887 }
888
889
890 /*-------------------------------------------------------------------------*/
891
892 static int do_write(struct fsg_common *common)
893 {
894         struct fsg_lun          *curlun = common->curlun;
895         u32                     lba;
896         struct fsg_buffhd       *bh;
897         int                     get_some_more;
898         u32                     amount_left_to_req, amount_left_to_write;
899         loff_t                  usb_offset, file_offset, file_offset_tmp;
900         unsigned int            amount;
901         unsigned int            partial_page;
902         ssize_t                 nwritten;
903         int                     rc;
904
905         if (curlun->ro) {
906                 curlun->sense_data = SS_WRITE_PROTECTED;
907                 return -EINVAL;
908         }
909         spin_lock(&curlun->filp->f_lock);
910         curlun->filp->f_flags &= ~O_SYNC;       /* Default is not to wait */
911         spin_unlock(&curlun->filp->f_lock);
912
913         /* Get the starting Logical Block Address and check that it's
914          * not too big */
915         if (common->cmnd[0] == SC_WRITE_6)
916                 lba = get_unaligned_be24(&common->cmnd[1]);
917         else {
918                 lba = get_unaligned_be32(&common->cmnd[2]);
919
920                 /* We allow DPO (Disable Page Out = don't save data in the
921                  * cache) and FUA (Force Unit Access = write directly to the
922                  * medium).  We don't implement DPO; we implement FUA by
923                  * performing synchronous output. */
924                 if (common->cmnd[1] & ~0x18) {
925                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
926                         return -EINVAL;
927                 }
928                 if (common->cmnd[1] & 0x08) {   /* FUA */
929                         spin_lock(&curlun->filp->f_lock);
930                         curlun->filp->f_flags |= O_SYNC;
931                         spin_unlock(&curlun->filp->f_lock);
932                 }
933         }
934         if (lba >= curlun->num_sectors) {
935                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
936                 return -EINVAL;
937         }
938
939         /* Carry out the file writes */
940         get_some_more = 1;
941         file_offset = usb_offset = ((loff_t) lba) << 9;
942         amount_left_to_req = common->data_size_from_cmnd;
943         amount_left_to_write = common->data_size_from_cmnd;
944
945         while (amount_left_to_write > 0) {
946
947                 /* Queue a request for more data from the host */
948                 bh = common->next_buffhd_to_fill;
949                 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
950
951                         /* Figure out how much we want to get:
952                          * Try to get the remaining amount.
953                          * But don't get more than the buffer size.
954                          * And don't try to go past the end of the file.
955                          * If we're not at a page boundary,
956                          *      don't go past the next page.
957                          * If this means getting 0, then we were asked
958                          *      to write past the end of file.
959                          * Finally, round down to a block boundary. */
960                         amount = min(amount_left_to_req, FSG_BUFLEN);
961                         amount = min((loff_t) amount, curlun->file_length -
962                                         usb_offset);
963                         partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
964                         if (partial_page > 0)
965                                 amount = min(amount,
966         (unsigned int) PAGE_CACHE_SIZE - partial_page);
967
968                         if (amount == 0) {
969                                 get_some_more = 0;
970                                 curlun->sense_data =
971                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
972                                 curlun->sense_data_info = usb_offset >> 9;
973                                 curlun->info_valid = 1;
974                                 continue;
975                         }
976                         amount -= (amount & 511);
977                         if (amount == 0) {
978
979                                 /* Why were we were asked to transfer a
980                                  * partial block? */
981                                 get_some_more = 0;
982                                 continue;
983                         }
984
985                         /* Get the next buffer */
986                         usb_offset += amount;
987                         common->usb_amount_left -= amount;
988                         amount_left_to_req -= amount;
989                         if (amount_left_to_req == 0)
990                                 get_some_more = 0;
991                                 
992                         /* kever@rk
993                          * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
994                          * because of the DOEPTSIZ.PKTCNT has only 10 bits
995                          */
996                         if((common->gadget->speed != USB_SPEED_HIGH)&&(amount >0x8000))
997                             amount = 0x8000;
998
999                         /* amount is always divisible by 512, hence by
1000                          * the bulk-out maxpacket size */
1001                         bh->outreq->length = amount;
1002                         bh->bulk_out_intended_length = amount;
1003                         bh->outreq->short_not_ok = 1;
1004                         START_TRANSFER_OR(common, bulk_out, bh->outreq,
1005                                           &bh->outreq_busy, &bh->state)
1006                                 /* Don't know what to do if
1007                                  * common->fsg is NULL */
1008                                 return -EIO;
1009                         common->next_buffhd_to_fill = bh->next;
1010                         continue;
1011                 }
1012
1013                 /* Write the received data to the backing file */
1014                 bh = common->next_buffhd_to_drain;
1015                 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1016                         break;                  /* We stopped early */
1017                 if (bh->state == BUF_STATE_FULL) {
1018                         smp_rmb();
1019                         common->next_buffhd_to_drain = bh->next;
1020                         bh->state = BUF_STATE_EMPTY;
1021
1022                         /* Did something go wrong with the transfer? */
1023                         if (bh->outreq->status != 0) {
1024                                 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1025                                 curlun->sense_data_info = file_offset >> 9;
1026                                 curlun->info_valid = 1;
1027                                 break;
1028                         }
1029
1030                         amount = bh->outreq->actual;
1031                         if (curlun->file_length - file_offset < amount) {
1032                                 LERROR(curlun,
1033         "write %u @ %llu beyond end %llu\n",
1034         amount, (unsigned long long) file_offset,
1035         (unsigned long long) curlun->file_length);
1036                                 amount = curlun->file_length - file_offset;
1037                         }
1038
1039                         /* Perform the write */
1040                         file_offset_tmp = file_offset;
1041                         nwritten = vfs_write(curlun->filp,
1042                                         (char __user *) bh->buf,
1043                                         amount, &file_offset_tmp);
1044                         VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1045                                         (unsigned long long) file_offset,
1046                                         (int) nwritten);
1047                         if (signal_pending(current))
1048                                 return -EINTR;          /* Interrupted! */
1049
1050                         if (nwritten < 0) {
1051                                 LDBG(curlun, "error in file write: %d\n",
1052                                                 (int) nwritten);
1053                                 nwritten = 0;
1054                         } else if (nwritten < amount) {
1055                                 LDBG(curlun, "partial file write: %d/%u\n",
1056                                                 (int) nwritten, amount);
1057                                 nwritten -= (nwritten & 511);
1058                                 /* Round down to a block */
1059                         }
1060                         file_offset += nwritten;
1061                         amount_left_to_write -= nwritten;
1062                         common->residue -= nwritten;
1063
1064                         /* If an error occurred, report it and its position */
1065                         if (nwritten < amount) {
1066                                 curlun->sense_data = SS_WRITE_ERROR;
1067                                 curlun->sense_data_info = file_offset >> 9;
1068                                 curlun->info_valid = 1;
1069                                 break;
1070                         }
1071
1072                         /* Did the host decide to stop early? */
1073                         if (bh->outreq->actual != bh->outreq->length) {
1074                                 common->short_packet_received = 1;
1075                                 break;
1076                         }
1077                         continue;
1078                 }
1079
1080                 /* Wait for something to happen */
1081                 rc = sleep_thread(common);
1082                 if (rc)
1083                         return rc;
1084         }
1085
1086         return -EIO;            /* No default reply */
1087 }
1088
1089
1090 /*-------------------------------------------------------------------------*/
1091
1092 static int do_synchronize_cache(struct fsg_common *common)
1093 {
1094         struct fsg_lun  *curlun = common->curlun;
1095         int             rc;
1096
1097         /* We ignore the requested LBA and write out all file's
1098          * dirty data buffers. */
1099         rc = fsg_lun_fsync_sub(curlun);
1100         if (rc)
1101                 curlun->sense_data = SS_WRITE_ERROR;
1102         return 0;
1103 }
1104
1105
1106 /*-------------------------------------------------------------------------*/
1107
1108 static void invalidate_sub(struct fsg_lun *curlun)
1109 {
1110         struct file     *filp = curlun->filp;
1111         struct inode    *inode = filp->f_path.dentry->d_inode;
1112         unsigned long   rc;
1113
1114         rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1115         VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1116 }
1117
1118 static int do_verify(struct fsg_common *common)
1119 {
1120         struct fsg_lun          *curlun = common->curlun;
1121         u32                     lba;
1122         u32                     verification_length;
1123         struct fsg_buffhd       *bh = common->next_buffhd_to_fill;
1124         loff_t                  file_offset, file_offset_tmp;
1125         u32                     amount_left;
1126         unsigned int            amount;
1127         ssize_t                 nread;
1128
1129         /* Get the starting Logical Block Address and check that it's
1130          * not too big */
1131         lba = get_unaligned_be32(&common->cmnd[2]);
1132         if (lba >= curlun->num_sectors) {
1133                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1134                 return -EINVAL;
1135         }
1136
1137         /* We allow DPO (Disable Page Out = don't save data in the
1138          * cache) but we don't implement it. */
1139         if (common->cmnd[1] & ~0x10) {
1140                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1141                 return -EINVAL;
1142         }
1143
1144         verification_length = get_unaligned_be16(&common->cmnd[7]);
1145         if (unlikely(verification_length == 0))
1146                 return -EIO;            /* No default reply */
1147
1148         /* Prepare to carry out the file verify */
1149         amount_left = verification_length << 9;
1150         file_offset = ((loff_t) lba) << 9;
1151
1152         /* Write out all the dirty buffers before invalidating them */
1153         fsg_lun_fsync_sub(curlun);
1154         if (signal_pending(current))
1155                 return -EINTR;
1156
1157         invalidate_sub(curlun);
1158         if (signal_pending(current))
1159                 return -EINTR;
1160
1161         /* Just try to read the requested blocks */
1162         while (amount_left > 0) {
1163
1164                 /* Figure out how much we need to read:
1165                  * Try to read the remaining amount, but not more than
1166                  * the buffer size.
1167                  * And don't try to read past the end of the file.
1168                  * If this means reading 0 then we were asked to read
1169                  * past the end of file. */
1170                 amount = min(amount_left, FSG_BUFLEN);
1171                 amount = min((loff_t) amount,
1172                                 curlun->file_length - file_offset);
1173                 if (amount == 0) {
1174                         curlun->sense_data =
1175                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1176                         curlun->sense_data_info = file_offset >> 9;
1177                         curlun->info_valid = 1;
1178                         break;
1179                 }
1180
1181                 /* Perform the read */
1182                 file_offset_tmp = file_offset;
1183                 nread = vfs_read(curlun->filp,
1184                                 (char __user *) bh->buf,
1185                                 amount, &file_offset_tmp);
1186                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1187                                 (unsigned long long) file_offset,
1188                                 (int) nread);
1189                 if (signal_pending(current))
1190                         return -EINTR;
1191
1192                 if (nread < 0) {
1193                         LDBG(curlun, "error in file verify: %d\n",
1194                                         (int) nread);
1195                         nread = 0;
1196                 } else if (nread < amount) {
1197                         LDBG(curlun, "partial file verify: %d/%u\n",
1198                                         (int) nread, amount);
1199                         nread -= (nread & 511); /* Round down to a sector */
1200                 }
1201                 if (nread == 0) {
1202                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1203                         curlun->sense_data_info = file_offset >> 9;
1204                         curlun->info_valid = 1;
1205                         break;
1206                 }
1207                 file_offset += nread;
1208                 amount_left -= nread;
1209         }
1210         return 0;
1211 }
1212
1213
1214 /*-------------------------------------------------------------------------*/
1215
1216 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1217 {
1218         struct fsg_lun *curlun = common->curlun;
1219         u8      *buf = (u8 *) bh->buf;
1220
1221         if (!curlun) {          /* Unsupported LUNs are okay */
1222                 common->bad_lun_okay = 1;
1223                 memset(buf, 0, 36);
1224                 buf[0] = 0x7f;          /* Unsupported, no device-type */
1225                 buf[4] = 31;            /* Additional length */
1226                 return 36;
1227         }
1228
1229         buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1230         buf[1] = curlun->removable ? 0x80 : 0;
1231         buf[2] = 2;             /* ANSI SCSI level 2 */
1232         buf[3] = 2;             /* SCSI-2 INQUIRY data format */
1233         buf[4] = 31;            /* Additional length */
1234         buf[5] = 0;             /* No special options */
1235         buf[6] = 0;
1236         buf[7] = 0;
1237         memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1238         return 36;
1239 }
1240
1241
1242 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1243 {
1244         struct fsg_lun  *curlun = common->curlun;
1245         u8              *buf = (u8 *) bh->buf;
1246         u32             sd, sdinfo;
1247         int             valid;
1248
1249         /*
1250          * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1251          *
1252          * If a REQUEST SENSE command is received from an initiator
1253          * with a pending unit attention condition (before the target
1254          * generates the contingent allegiance condition), then the
1255          * target shall either:
1256          *   a) report any pending sense data and preserve the unit
1257          *      attention condition on the logical unit, or,
1258          *   b) report the unit attention condition, may discard any
1259          *      pending sense data, and clear the unit attention
1260          *      condition on the logical unit for that initiator.
1261          *
1262          * FSG normally uses option a); enable this code to use option b).
1263          */
1264 #if 0
1265         if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1266                 curlun->sense_data = curlun->unit_attention_data;
1267                 curlun->unit_attention_data = SS_NO_SENSE;
1268         }
1269 #endif
1270
1271         if (!curlun) {          /* Unsupported LUNs are okay */
1272                 common->bad_lun_okay = 1;
1273                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1274                 sdinfo = 0;
1275                 valid = 0;
1276         } else {
1277                 sd = curlun->sense_data;
1278                 sdinfo = curlun->sense_data_info;
1279                 valid = curlun->info_valid << 7;
1280                 curlun->sense_data = SS_NO_SENSE;
1281                 curlun->sense_data_info = 0;
1282                 curlun->info_valid = 0;
1283         }
1284
1285         memset(buf, 0, 18);
1286         buf[0] = valid | 0x70;                  /* Valid, current error */
1287         buf[2] = SK(sd);
1288         put_unaligned_be32(sdinfo, &buf[3]);    /* Sense information */
1289         buf[7] = 18 - 8;                        /* Additional sense length */
1290         buf[12] = ASC(sd);
1291         buf[13] = ASCQ(sd);
1292         return 18;
1293 }
1294
1295
1296 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1297 {
1298         struct fsg_lun  *curlun = common->curlun;
1299         u32             lba = get_unaligned_be32(&common->cmnd[2]);
1300         int             pmi = common->cmnd[8];
1301         u8              *buf = (u8 *) bh->buf;
1302
1303         /* Check the PMI and LBA fields */
1304         if (pmi > 1 || (pmi == 0 && lba != 0)) {
1305                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1306                 return -EINVAL;
1307         }
1308
1309         put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1310                                                 /* Max logical block */
1311         put_unaligned_be32(512, &buf[4]);       /* Block length */
1312         return 8;
1313 }
1314
1315
1316 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1317 {
1318         struct fsg_lun  *curlun = common->curlun;
1319         int             msf = common->cmnd[1] & 0x02;
1320         u32             lba = get_unaligned_be32(&common->cmnd[2]);
1321         u8              *buf = (u8 *) bh->buf;
1322
1323         if (common->cmnd[1] & ~0x02) {          /* Mask away MSF */
1324                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1325                 return -EINVAL;
1326         }
1327         if (lba >= curlun->num_sectors) {
1328                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1329                 return -EINVAL;
1330         }
1331
1332         memset(buf, 0, 8);
1333         buf[0] = 0x01;          /* 2048 bytes of user data, rest is EC */
1334         store_cdrom_address(&buf[4], msf, lba);
1335         return 8;
1336 }
1337
1338
1339 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1340 {
1341         struct fsg_lun  *curlun = common->curlun;
1342         int             msf = common->cmnd[1] & 0x02;
1343         int             start_track = common->cmnd[6];
1344         u8              *buf = (u8 *) bh->buf;
1345
1346         if ((common->cmnd[1] & ~0x02) != 0 ||   /* Mask away MSF */
1347                         start_track > 1) {
1348                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1349                 return -EINVAL;
1350         }
1351
1352         memset(buf, 0, 20);
1353         buf[1] = (20-2);                /* TOC data length */
1354         buf[2] = 1;                     /* First track number */
1355         buf[3] = 1;                     /* Last track number */
1356         buf[5] = 0x16;                  /* Data track, copying allowed */
1357         buf[6] = 0x01;                  /* Only track is number 1 */
1358         store_cdrom_address(&buf[8], msf, 0);
1359
1360         buf[13] = 0x16;                 /* Lead-out track is data */
1361         buf[14] = 0xAA;                 /* Lead-out track number */
1362         store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1363         return 20;
1364 }
1365
1366
1367 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1368 {
1369         struct fsg_lun  *curlun = common->curlun;
1370         int             mscmnd = common->cmnd[0];
1371         u8              *buf = (u8 *) bh->buf;
1372         u8              *buf0 = buf;
1373         int             pc, page_code;
1374         int             changeable_values, all_pages;
1375         int             valid_page = 0;
1376         int             len, limit;
1377
1378         if ((common->cmnd[1] & ~0x08) != 0) {   /* Mask away DBD */
1379                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1380                 return -EINVAL;
1381         }
1382         pc = common->cmnd[2] >> 6;
1383         page_code = common->cmnd[2] & 0x3f;
1384         if (pc == 3) {
1385                 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1386                 return -EINVAL;
1387         }
1388         changeable_values = (pc == 1);
1389         all_pages = (page_code == 0x3f);
1390
1391         /* Write the mode parameter header.  Fixed values are: default
1392          * medium type, no cache control (DPOFUA), and no block descriptors.
1393          * The only variable value is the WriteProtect bit.  We will fill in
1394          * the mode data length later. */
1395         memset(buf, 0, 8);
1396         if (mscmnd == SC_MODE_SENSE_6) {
1397                 buf[2] = (curlun->ro ? 0x80 : 0x00);            /* WP, DPOFUA */
1398                 buf += 4;
1399                 limit = 255;
1400         } else {                        /* SC_MODE_SENSE_10 */
1401                 buf[3] = (curlun->ro ? 0x80 : 0x00);            /* WP, DPOFUA */
1402                 buf += 8;
1403                 limit = 65535;          /* Should really be FSG_BUFLEN */
1404         }
1405
1406         /* No block descriptors */
1407
1408         /* The mode pages, in numerical order.  The only page we support
1409          * is the Caching page. */
1410         if (page_code == 0x08 || all_pages) {
1411                 valid_page = 1;
1412                 buf[0] = 0x08;          /* Page code */
1413                 buf[1] = 10;            /* Page length */
1414                 memset(buf+2, 0, 10);   /* None of the fields are changeable */
1415
1416                 if (!changeable_values) {
1417                         buf[2] = 0x04;  /* Write cache enable, */
1418                                         /* Read cache not disabled */
1419                                         /* No cache retention priorities */
1420                         put_unaligned_be16(0xffff, &buf[4]);
1421                                         /* Don't disable prefetch */
1422                                         /* Minimum prefetch = 0 */
1423                         put_unaligned_be16(0xffff, &buf[8]);
1424                                         /* Maximum prefetch */
1425                         put_unaligned_be16(0xffff, &buf[10]);
1426                                         /* Maximum prefetch ceiling */
1427                 }
1428                 buf += 12;
1429         }
1430
1431         /* Check that a valid page was requested and the mode data length
1432          * isn't too long. */
1433         len = buf - buf0;
1434         if (!valid_page || len > limit) {
1435                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1436                 return -EINVAL;
1437         }
1438
1439         /*  Store the mode data length */
1440         if (mscmnd == SC_MODE_SENSE_6)
1441                 buf0[0] = len - 1;
1442         else
1443                 put_unaligned_be16(len - 2, buf0);
1444         return len;
1445 }
1446
1447
1448 static int do_start_stop(struct fsg_common *common)
1449 {
1450         struct fsg_lun  *curlun = common->curlun;
1451         int             loej, start;
1452
1453         if (!curlun) {
1454                 return -EINVAL;
1455         } else if (!curlun->removable) {
1456                 curlun->sense_data = SS_INVALID_COMMAND;
1457                 return -EINVAL;
1458         } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1459                    (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1460                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1461                 return -EINVAL;
1462         }
1463
1464         loej  = common->cmnd[4] & 0x02;
1465         start = common->cmnd[4] & 0x01;
1466
1467         /* Our emulation doesn't support mounting; the medium is
1468          * available for use as soon as it is loaded. */
1469         if (start) {
1470                 if (!fsg_lun_is_open(curlun)) {
1471                         curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1472                         return -EINVAL;
1473                 }
1474                 return 0;
1475         }
1476
1477         /* Are we allowed to unload the media? */
1478         if (curlun->prevent_medium_removal) {
1479                 LDBG(curlun, "unload attempt prevented\n");
1480                 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1481                 return -EINVAL;
1482         }
1483
1484         if (!loej)
1485                 return 0;
1486
1487         /* Simulate an unload/eject */
1488         if (common->ops && common->ops->pre_eject) {
1489                 int r = common->ops->pre_eject(common, curlun,
1490                                                curlun - common->luns);
1491                 if (unlikely(r < 0))
1492                         return r;
1493                 else if (r)
1494                         return 0;
1495         }
1496
1497         up_read(&common->filesem);
1498         down_write(&common->filesem);
1499         fsg_lun_close(curlun);
1500         up_write(&common->filesem);
1501         down_read(&common->filesem);
1502
1503         return common->ops && common->ops->post_eject
1504                 ? min(0, common->ops->post_eject(common, curlun,
1505                                                  curlun - common->luns))
1506                 : 0;
1507 }
1508
1509
1510 static int do_prevent_allow(struct fsg_common *common)
1511 {
1512         struct fsg_lun  *curlun = common->curlun;
1513         int             prevent;
1514
1515         if (!common->curlun) {
1516                 return -EINVAL;
1517         } else if (!common->curlun->removable) {
1518                 common->curlun->sense_data = SS_INVALID_COMMAND;
1519                 return -EINVAL;
1520         }
1521
1522         prevent = common->cmnd[4] & 0x01;
1523         if ((common->cmnd[4] & ~0x01) != 0) {   /* Mask away Prevent */
1524                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1525                 return -EINVAL;
1526         }
1527
1528         if (curlun->prevent_medium_removal && !prevent)
1529                 fsg_lun_fsync_sub(curlun);
1530         curlun->prevent_medium_removal = prevent;
1531         return 0;
1532 }
1533
1534
1535 static int do_read_format_capacities(struct fsg_common *common,
1536                         struct fsg_buffhd *bh)
1537 {
1538         struct fsg_lun  *curlun = common->curlun;
1539         u8              *buf = (u8 *) bh->buf;
1540
1541         buf[0] = buf[1] = buf[2] = 0;
1542         buf[3] = 8;     /* Only the Current/Maximum Capacity Descriptor */
1543         buf += 4;
1544
1545         put_unaligned_be32(curlun->num_sectors, &buf[0]);
1546                                                 /* Number of blocks */
1547         put_unaligned_be32(512, &buf[4]);       /* Block length */
1548         buf[4] = 0x02;                          /* Current capacity */
1549         return 12;
1550 }
1551
1552
1553 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1554 {
1555         struct fsg_lun  *curlun = common->curlun;
1556
1557         /* We don't support MODE SELECT */
1558         if (curlun)
1559                 curlun->sense_data = SS_INVALID_COMMAND;
1560         return -EINVAL;
1561 }
1562
1563
1564 /*-------------------------------------------------------------------------*/
1565
1566 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1567 {
1568         int     rc;
1569
1570         rc = fsg_set_halt(fsg, fsg->bulk_in);
1571         if (rc == -EAGAIN)
1572                 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1573         while (rc != 0) {
1574                 if (rc != -EAGAIN) {
1575                         WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1576                         rc = 0;
1577                         break;
1578                 }
1579
1580                 /* Wait for a short time and then try again */
1581                 if (msleep_interruptible(100) != 0)
1582                         return -EINTR;
1583                 rc = usb_ep_set_halt(fsg->bulk_in);
1584         }
1585         return rc;
1586 }
1587
1588 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1589 {
1590         int     rc;
1591
1592         DBG(fsg, "bulk-in set wedge\n");
1593         rc = usb_ep_set_wedge(fsg->bulk_in);
1594         if (rc == -EAGAIN)
1595                 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1596         while (rc != 0) {
1597                 if (rc != -EAGAIN) {
1598                         WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1599                         rc = 0;
1600                         break;
1601                 }
1602
1603                 /* Wait for a short time and then try again */
1604                 if (msleep_interruptible(100) != 0)
1605                         return -EINTR;
1606                 rc = usb_ep_set_wedge(fsg->bulk_in);
1607         }
1608         return rc;
1609 }
1610
1611 static int pad_with_zeros(struct fsg_dev *fsg)
1612 {
1613         struct fsg_buffhd       *bh = fsg->common->next_buffhd_to_fill;
1614         u32                     nkeep = bh->inreq->length;
1615         u32                     nsend;
1616         int                     rc;
1617
1618         bh->state = BUF_STATE_EMPTY;            /* For the first iteration */
1619         fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1620         while (fsg->common->usb_amount_left > 0) {
1621
1622                 /* Wait for the next buffer to be free */
1623                 while (bh->state != BUF_STATE_EMPTY) {
1624                         rc = sleep_thread(fsg->common);
1625                         if (rc)
1626                                 return rc;
1627                 }
1628
1629                 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1630                 memset(bh->buf + nkeep, 0, nsend - nkeep);
1631                 bh->inreq->length = nsend;
1632                 bh->inreq->zero = 0;
1633                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1634                                 &bh->inreq_busy, &bh->state);
1635                 bh = fsg->common->next_buffhd_to_fill = bh->next;
1636                 fsg->common->usb_amount_left -= nsend;
1637                 nkeep = 0;
1638         }
1639         return 0;
1640 }
1641
1642 static int throw_away_data(struct fsg_common *common)
1643 {
1644         struct fsg_buffhd       *bh;
1645         u32                     amount;
1646         int                     rc;
1647
1648         for (bh = common->next_buffhd_to_drain;
1649              bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1650              bh = common->next_buffhd_to_drain) {
1651
1652                 /* Throw away the data in a filled buffer */
1653                 if (bh->state == BUF_STATE_FULL) {
1654                         smp_rmb();
1655                         bh->state = BUF_STATE_EMPTY;
1656                         common->next_buffhd_to_drain = bh->next;
1657
1658                         /* A short packet or an error ends everything */
1659                         if (bh->outreq->actual != bh->outreq->length ||
1660                                         bh->outreq->status != 0) {
1661                                 raise_exception(common,
1662                                                 FSG_STATE_ABORT_BULK_OUT);
1663                                 return -EINTR;
1664                         }
1665                         continue;
1666                 }
1667
1668                 /* Try to submit another request if we need one */
1669                 bh = common->next_buffhd_to_fill;
1670                 if (bh->state == BUF_STATE_EMPTY
1671                  && common->usb_amount_left > 0) {
1672                         amount = min(common->usb_amount_left, FSG_BUFLEN);
1673
1674                         /* amount is always divisible by 512, hence by
1675                          * the bulk-out maxpacket size */
1676                         bh->outreq->length = amount;
1677                         bh->bulk_out_intended_length = amount;
1678                         bh->outreq->short_not_ok = 1;
1679                         START_TRANSFER_OR(common, bulk_out, bh->outreq,
1680                                           &bh->outreq_busy, &bh->state)
1681                                 /* Don't know what to do if
1682                                  * common->fsg is NULL */
1683                                 return -EIO;
1684                         common->next_buffhd_to_fill = bh->next;
1685                         common->usb_amount_left -= amount;
1686                         continue;
1687                 }
1688
1689                 /* Otherwise wait for something to happen */
1690                 rc = sleep_thread(common);
1691                 if (rc)
1692                         return rc;
1693         }
1694         return 0;
1695 }
1696
1697
1698 static int finish_reply(struct fsg_common *common)
1699 {
1700         struct fsg_buffhd       *bh = common->next_buffhd_to_fill;
1701         int                     rc = 0;
1702
1703         switch (common->data_dir) {
1704         case DATA_DIR_NONE:
1705                 break;                  /* Nothing to send */
1706
1707         /* If we don't know whether the host wants to read or write,
1708          * this must be CB or CBI with an unknown command.  We mustn't
1709          * try to send or receive any data.  So stall both bulk pipes
1710          * if we can and wait for a reset. */
1711         case DATA_DIR_UNKNOWN:
1712                 if (!common->can_stall) {
1713                         /* Nothing */
1714                 } else if (fsg_is_set(common)) {
1715                         fsg_set_halt(common->fsg, common->fsg->bulk_out);
1716                         rc = halt_bulk_in_endpoint(common->fsg);
1717                 } else {
1718                         /* Don't know what to do if common->fsg is NULL */
1719                         rc = -EIO;
1720                 }
1721                 break;
1722
1723         /* All but the last buffer of data must have already been sent */
1724         case DATA_DIR_TO_HOST:
1725                 if (common->data_size == 0) {
1726                         /* Nothing to send */
1727
1728                 /* If there's no residue, simply send the last buffer */
1729                 } else if (common->residue == 0) {
1730                         bh->inreq->zero = 0;
1731                         START_TRANSFER_OR(common, bulk_in, bh->inreq,
1732                                           &bh->inreq_busy, &bh->state)
1733                                 return -EIO;
1734                         common->next_buffhd_to_fill = bh->next;
1735
1736                 /* For Bulk-only, if we're allowed to stall then send the
1737                  * short packet and halt the bulk-in endpoint.  If we can't
1738                  * stall, pad out the remaining data with 0's. */
1739                 } else if (common->can_stall) {
1740                         bh->inreq->zero = 1;
1741                         START_TRANSFER_OR(common, bulk_in, bh->inreq,
1742                                           &bh->inreq_busy, &bh->state)
1743                                 /* Don't know what to do if
1744                                  * common->fsg is NULL */
1745                                 rc = -EIO;
1746                         common->next_buffhd_to_fill = bh->next;
1747                         if (common->fsg)
1748                                 rc = halt_bulk_in_endpoint(common->fsg);
1749                 } else if (fsg_is_set(common)) {
1750                         rc = pad_with_zeros(common->fsg);
1751                 } else {
1752                         /* Don't know what to do if common->fsg is NULL */
1753                         rc = -EIO;
1754                 }
1755                 break;
1756
1757         /* We have processed all we want from the data the host has sent.
1758          * There may still be outstanding bulk-out requests. */
1759         case DATA_DIR_FROM_HOST:
1760                 if (common->residue == 0) {
1761                         /* Nothing to receive */
1762
1763                 /* Did the host stop sending unexpectedly early? */
1764                 } else if (common->short_packet_received) {
1765                         raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1766                         rc = -EINTR;
1767
1768                 /* We haven't processed all the incoming data.  Even though
1769                  * we may be allowed to stall, doing so would cause a race.
1770                  * The controller may already have ACK'ed all the remaining
1771                  * bulk-out packets, in which case the host wouldn't see a
1772                  * STALL.  Not realizing the endpoint was halted, it wouldn't
1773                  * clear the halt -- leading to problems later on. */
1774 #if 0
1775                 } else if (common->can_stall) {
1776                         if (fsg_is_set(common))
1777                                 fsg_set_halt(common->fsg,
1778                                              common->fsg->bulk_out);
1779                         raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1780                         rc = -EINTR;
1781 #endif
1782
1783                 /* We can't stall.  Read in the excess data and throw it
1784                  * all away. */
1785                 } else {
1786                         rc = throw_away_data(common);
1787                 }
1788                 break;
1789         }
1790         return rc;
1791 }
1792
1793
1794 static int send_status(struct fsg_common *common)
1795 {
1796         struct fsg_lun          *curlun = common->curlun;
1797         struct fsg_buffhd       *bh;
1798         struct bulk_cs_wrap     *csw;
1799         int                     rc;
1800         u8                      status = USB_STATUS_PASS;
1801         u32                     sd, sdinfo = 0;
1802
1803         /* Wait for the next buffer to become available */
1804         bh = common->next_buffhd_to_fill;
1805         while (bh->state != BUF_STATE_EMPTY) {
1806                 rc = sleep_thread(common);
1807                 if (rc)
1808                         return rc;
1809         }
1810
1811         if (curlun) {
1812                 sd = curlun->sense_data;
1813                 sdinfo = curlun->sense_data_info;
1814         } else if (common->bad_lun_okay)
1815                 sd = SS_NO_SENSE;
1816         else
1817                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1818
1819         if (common->phase_error) {
1820                 DBG(common, "sending phase-error status\n");
1821                 status = USB_STATUS_PHASE_ERROR;
1822                 sd = SS_INVALID_COMMAND;
1823         } else if (sd != SS_NO_SENSE) {
1824                 DBG(common, "sending command-failure status\n");
1825                 status = USB_STATUS_FAIL;
1826                 VDBG(common, "  sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1827                                 "  info x%x\n",
1828                                 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1829         }
1830
1831         /* Store and send the Bulk-only CSW */
1832         csw = (void *)bh->buf;
1833
1834         csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1835         csw->Tag = common->tag;
1836         csw->Residue = cpu_to_le32(common->residue);
1837         csw->Status = status;
1838
1839         bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1840         bh->inreq->zero = 0;
1841         START_TRANSFER_OR(common, bulk_in, bh->inreq,
1842                           &bh->inreq_busy, &bh->state)
1843                 /* Don't know what to do if common->fsg is NULL */
1844                 return -EIO;
1845
1846         common->next_buffhd_to_fill = bh->next;
1847         return 0;
1848 }
1849
1850
1851 /*-------------------------------------------------------------------------*/
1852
1853 /* Check whether the command is properly formed and whether its data size
1854  * and direction agree with the values we already have. */
1855 static int check_command(struct fsg_common *common, int cmnd_size,
1856                 enum data_direction data_dir, unsigned int mask,
1857                 int needs_medium, const char *name)
1858 {
1859         int                     i;
1860         int                     lun = common->cmnd[1] >> 5;
1861         static const char       dirletter[4] = {'u', 'o', 'i', 'n'};
1862         char                    hdlen[20];
1863         struct fsg_lun          *curlun;
1864
1865         hdlen[0] = 0;
1866         if (common->data_dir != DATA_DIR_UNKNOWN)
1867                 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1868                                 common->data_size);
1869         VDBG(common, "SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
1870              name, cmnd_size, dirletter[(int) data_dir],
1871              common->data_size_from_cmnd, common->cmnd_size, hdlen);
1872
1873         /* We can't reply at all until we know the correct data direction
1874          * and size. */
1875         if (common->data_size_from_cmnd == 0)
1876                 data_dir = DATA_DIR_NONE;
1877         if (common->data_size < common->data_size_from_cmnd) {
1878                 /* Host data size < Device data size is a phase error.
1879                  * Carry out the command, but only transfer as much as
1880                  * we are allowed. */
1881                 common->data_size_from_cmnd = common->data_size;
1882                 common->phase_error = 1;
1883         }
1884         common->residue = common->data_size;
1885         common->usb_amount_left = common->data_size;
1886
1887         /* Conflicting data directions is a phase error */
1888         if (common->data_dir != data_dir
1889          && common->data_size_from_cmnd > 0) {
1890                 common->phase_error = 1;
1891                 return -EINVAL;
1892         }
1893
1894         /* Verify the length of the command itself */
1895         if (cmnd_size != common->cmnd_size) {
1896
1897                 /* Special case workaround: There are plenty of buggy SCSI
1898                  * implementations. Many have issues with cbw->Length
1899                  * field passing a wrong command size. For those cases we
1900                  * always try to work around the problem by using the length
1901                  * sent by the host side provided it is at least as large
1902                  * as the correct command length.
1903                  * Examples of such cases would be MS-Windows, which issues
1904                  * REQUEST SENSE with cbw->Length == 12 where it should
1905                  * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1906                  * REQUEST SENSE with cbw->Length == 10 where it should
1907                  * be 6 as well.
1908                  */
1909                 if (cmnd_size <= common->cmnd_size) {
1910                         DBG(common, "%s is buggy! Expected length %d "
1911                             "but we got %d\n", name,
1912                             cmnd_size, common->cmnd_size);
1913                         cmnd_size = common->cmnd_size;
1914                 } else {
1915                         common->phase_error = 1;
1916                         return -EINVAL;
1917                 }
1918         }
1919
1920         /* Check that the LUN values are consistent */
1921         if (common->lun != lun)
1922                 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1923                     common->lun, lun);
1924
1925         /* Check the LUN */
1926         if (common->lun >= 0 && common->lun < common->nluns) {
1927                 curlun = &common->luns[common->lun];
1928                 common->curlun = curlun;
1929                 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1930                         curlun->sense_data = SS_NO_SENSE;
1931                         curlun->sense_data_info = 0;
1932                         curlun->info_valid = 0;
1933                 }
1934         } else {
1935                 common->curlun = NULL;
1936                 curlun = NULL;
1937                 common->bad_lun_okay = 0;
1938
1939                 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1940                  * to use unsupported LUNs; all others may not. */
1941                 if (common->cmnd[0] != SC_INQUIRY &&
1942                     common->cmnd[0] != SC_REQUEST_SENSE) {
1943                         DBG(common, "unsupported LUN %d\n", common->lun);
1944                         return -EINVAL;
1945                 }
1946         }
1947
1948         /* If a unit attention condition exists, only INQUIRY and
1949          * REQUEST SENSE commands are allowed; anything else must fail. */
1950         if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1951                         common->cmnd[0] != SC_INQUIRY &&
1952                         common->cmnd[0] != SC_REQUEST_SENSE) {
1953                 curlun->sense_data = curlun->unit_attention_data;
1954                 curlun->unit_attention_data = SS_NO_SENSE;
1955                 return -EINVAL;
1956         }
1957
1958         /* Check that only command bytes listed in the mask are non-zero */
1959         common->cmnd[1] &= 0x1f;                        /* Mask away the LUN */
1960         for (i = 1; i < cmnd_size; ++i) {
1961                 if (common->cmnd[i] && !(mask & (1 << i))) {
1962                         if (curlun)
1963                                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1964                         return -EINVAL;
1965                 }
1966         }
1967
1968         /* If the medium isn't mounted and the command needs to access
1969          * it, return an error. */
1970         if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1971                 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1972                 return -EINVAL;
1973         }
1974
1975         return 0;
1976 }
1977
1978
1979 #ifdef CONFIG_ARCH_RK29
1980 static void deferred_restart(struct work_struct *dummy)
1981 {
1982         sys_sync();
1983         kernel_restart("loader");
1984 }
1985 static DECLARE_WORK(restart_work, deferred_restart);
1986
1987 typedef struct tagLoaderParam
1988 {
1989         int     tag;
1990         int     length;
1991         char    parameter[1];
1992         int     crc;
1993 } PARM_INFO;
1994 #define PARM_TAG                        0x4D524150
1995 #define MSC_EXT_DBG                     1
1996 extern int  GetParamterInfo(char * pbuf , int len);
1997
1998 /* the buf is bh->buf,it is large enough. */
1999 static char * get_param_tag( char* buf , const char* tag )
2000 {
2001         PARM_INFO       *pi;
2002         int             i;
2003         char            *pp = buf+256;
2004         char            *spp;
2005         i = GetParamterInfo( pp , 1024 );
2006         pi = (PARM_INFO*)pp;
2007         if( pi->tag != PARM_TAG ){
2008 error_out:      
2009                 printk("paramter error,tag=0x%x\n" , pi->tag );
2010                 return NULL;
2011         }
2012         if( pi->length+sizeof(PARM_INFO) > i ) {
2013                 GetParamterInfo( pp , pi->length+sizeof(PARM_INFO)  + 511 );
2014         }
2015         pp = strstr( pi->parameter , tag );
2016         if( !pp ) goto error_out;
2017         pp += strlen(tag); // sizeof "MACHINE_MODEL:"
2018         while( *pp == ' ' || *pp == '\t' ) {
2019                 if(pp - pi->parameter >= pi->length)
2020                   break;        
2021                 pp++;
2022         }
2023         spp = pp;
2024         while( *pp != 0x0d && *pp != 0x0a ) {
2025                 if(pp - pi->parameter >= pi->length)
2026                   break;
2027                 pp++;
2028         }
2029         *pp = 0;
2030         if( spp == pp ) return NULL;
2031         return spp;
2032 }
2033
2034 static int do_get_product_name(int ret ,char *buf)
2035 {
2036         char            *tag = "MACHINE_MODEL:";
2037         char            *pname;
2038         #if MSC_EXT_DBG
2039         char            tbuf[1300];
2040         if( buf == NULL )   buf = tbuf;
2041         #endif
2042         memset( buf , 0 , ret );
2043         pname = get_param_tag( buf , tag );
2044         if( pname ){
2045                 strcpy( buf , pname);
2046         } 
2047         #if MSC_EXT_DBG
2048         printk("%s%s\n" , tag , buf );
2049         #endif
2050         return ret;
2051 }
2052
2053 static int do_get_versions( int ret ,char* buf )
2054 {
2055         /* get boot version and fireware version from cmdline
2056         * bootver=2010-07-08#4.02 firmware_ver=1.0.0 // Firmware Ver:16.01.0000
2057         * return format: 0x02 0x04 0x00 0x00 0x00 0x01 
2058         * RK29: bootver=2011-07-18#2.05 firmware_ver=0.2.3 (==00.02.0003)
2059         * for the old loader,the firmware_ver may be empty,so get the fw ver from paramter.
2060         */
2061 #define ASC_BCD0( c )  (((c-'0'))&0xf)
2062 #define ASC_BCD1( c )  (((c-'0')<<4)&0xf0)
2063
2064         char *ver = buf;
2065         char *p_l , *p_f;
2066         char            *l_tag = "bootver=";
2067         char            *fw_tag = "FIRMWARE_VER:";
2068         
2069         #if MSC_EXT_DBG
2070         char            tbuf[1300];
2071         if( ver == NULL )   ver = tbuf;
2072         #endif
2073         
2074         memset( ver , 0x00 , ret );
2075         p_l = strstr( saved_command_line , l_tag );
2076         if( !p_l ) {
2077                 return ret;
2078         } 
2079         p_l+=strlen( l_tag );
2080         if( (p_l = strchr( p_l,'#')) ) {
2081                 p_l++;
2082                 if( p_l[1] == '.' ) {
2083                         ver[1] = ASC_BCD0(p_l[0]);
2084                         p_l+=2;
2085                 } else {
2086                         ver[1] = ASC_BCD1(p_l[0])|ASC_BCD0(p_l[1]);
2087                         p_l+=3;
2088                 }
2089                 ver[0] = ASC_BCD1(p_l[0])|ASC_BCD0(p_l[1]);
2090         }
2091         
2092         p_f = get_param_tag( ver , fw_tag );
2093         if( !p_f ) return ret;
2094         
2095         if( p_f[1] == '.' ) {
2096                 ver[5] = ASC_BCD0(p_f[0]);
2097                 p_f+=2;
2098         } else {
2099                 ver[5] = ASC_BCD1(p_f[0])|ASC_BCD0(p_f[1]);
2100                 p_f+=3;
2101         } 
2102         if( p_f[1] == '.' ) {
2103                 ver[4] = ASC_BCD0(p_f[0]);
2104                 p_f+=2;
2105         } else {
2106                 ver[4] = ASC_BCD1(p_f[0])|ASC_BCD0(p_f[1]);
2107                 p_f+=3;
2108         } 
2109         ver[2] = ASC_BCD0(p_f[0]);
2110         p_f++;
2111         if( p_f[0] != ' ' ){
2112                 ver[2] |= ASC_BCD1(p_f[0]);
2113                 p_f++;
2114         }
2115         // only support 2 byte version.
2116         ver[3] = 0;
2117
2118         #if MSC_EXT_DBG
2119         printk("VERSION:%02x %02x %02x %02x %02x %02x\n" , 
2120                 ver[0],ver[1],ver[2],ver[3],ver[4],ver[5]);
2121         #endif
2122         return ret;
2123 }
2124 #endif
2125
2126 static int do_scsi_command(struct fsg_common *common)
2127 {
2128         struct fsg_buffhd       *bh;
2129         int                     rc;
2130         int                     reply = -EINVAL;
2131         int                     i;
2132         static char             unknown[16];
2133 #ifdef CONFIG_ARCH_RK29
2134         struct fsg_common       *fsg = common;
2135 #endif
2136
2137         dump_cdb(common);
2138
2139         /* Wait for the next buffer to become available for data or status */
2140         bh = common->next_buffhd_to_fill;
2141         common->next_buffhd_to_drain = bh;
2142         while (bh->state != BUF_STATE_EMPTY) {
2143                 rc = sleep_thread(common);
2144                 if (rc)
2145                         return rc;
2146         }
2147         common->phase_error = 0;
2148         common->short_packet_received = 0;
2149
2150         down_read(&common->filesem);    /* We're using the backing file */
2151         switch (common->cmnd[0]) {
2152
2153         case SC_INQUIRY:
2154                 common->data_size_from_cmnd = common->cmnd[4];
2155                 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2156                                       (1<<4), 0,
2157                                       "INQUIRY");
2158                 if (reply == 0)
2159                         reply = do_inquiry(common, bh);
2160                 break;
2161
2162         case SC_MODE_SELECT_6:
2163                 common->data_size_from_cmnd = common->cmnd[4];
2164                 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2165                                       (1<<1) | (1<<4), 0,
2166                                       "MODE SELECT(6)");
2167                 if (reply == 0)
2168                         reply = do_mode_select(common, bh);
2169                 break;
2170
2171         case SC_MODE_SELECT_10:
2172                 common->data_size_from_cmnd =
2173                         get_unaligned_be16(&common->cmnd[7]);
2174                 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2175                                       (1<<1) | (3<<7), 0,
2176                                       "MODE SELECT(10)");
2177                 if (reply == 0)
2178                         reply = do_mode_select(common, bh);
2179                 break;
2180
2181         case SC_MODE_SENSE_6:
2182                 common->data_size_from_cmnd = common->cmnd[4];
2183                 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2184                                       (1<<1) | (1<<2) | (1<<4), 0,
2185                                       "MODE SENSE(6)");
2186                 if (reply == 0)
2187                         reply = do_mode_sense(common, bh);
2188                 break;
2189
2190         case SC_MODE_SENSE_10:
2191                 common->data_size_from_cmnd =
2192                         get_unaligned_be16(&common->cmnd[7]);
2193                 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2194                                       (1<<1) | (1<<2) | (3<<7), 0,
2195                                       "MODE SENSE(10)");
2196                 if (reply == 0)
2197                         reply = do_mode_sense(common, bh);
2198                 break;
2199
2200         case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2201                 common->data_size_from_cmnd = 0;
2202                 reply = check_command(common, 6, DATA_DIR_NONE,
2203                                       (1<<4), 0,
2204                                       "PREVENT-ALLOW MEDIUM REMOVAL");
2205                 if (reply == 0)
2206                         reply = do_prevent_allow(common);
2207                 break;
2208
2209         case SC_READ_6:
2210                 i = common->cmnd[4];
2211                 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2212                 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2213                                       (7<<1) | (1<<4), 1,
2214                                       "READ(6)");
2215                 if (reply == 0)
2216                         reply = do_read(common);
2217                 break;
2218
2219         case SC_READ_10:
2220                 common->data_size_from_cmnd =
2221                                 get_unaligned_be16(&common->cmnd[7]) << 9;
2222                 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2223                                       (1<<1) | (0xf<<2) | (3<<7), 1,
2224                                       "READ(10)");
2225                 if (reply == 0)
2226                         reply = do_read(common);
2227                 break;
2228
2229         case SC_READ_12:
2230                 common->data_size_from_cmnd =
2231                                 get_unaligned_be32(&common->cmnd[6]) << 9;
2232                 reply = check_command(common, 12, DATA_DIR_TO_HOST,
2233                                       (1<<1) | (0xf<<2) | (0xf<<6), 1,
2234                                       "READ(12)");
2235                 if (reply == 0)
2236                         reply = do_read(common);
2237                 break;
2238
2239         case SC_READ_CAPACITY:
2240                 common->data_size_from_cmnd = 8;
2241                 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2242                                       (0xf<<2) | (1<<8), 1,
2243                                       "READ CAPACITY");
2244                 if (reply == 0)
2245                         reply = do_read_capacity(common, bh);
2246                 break;
2247
2248         case SC_READ_HEADER:
2249                 if (!common->curlun || !common->curlun->cdrom)
2250                         goto unknown_cmnd;
2251                 common->data_size_from_cmnd =
2252                         get_unaligned_be16(&common->cmnd[7]);
2253                 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2254                                       (3<<7) | (0x1f<<1), 1,
2255                                       "READ HEADER");
2256                 if (reply == 0)
2257                         reply = do_read_header(common, bh);
2258                 break;
2259
2260         case SC_READ_TOC:
2261                 if (!common->curlun || !common->curlun->cdrom)
2262                         goto unknown_cmnd;
2263                 common->data_size_from_cmnd =
2264                         get_unaligned_be16(&common->cmnd[7]);
2265                 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2266                                       (7<<6) | (1<<1), 1,
2267                                       "READ TOC");
2268                 if (reply == 0)
2269                         reply = do_read_toc(common, bh);
2270                 break;
2271
2272         case SC_READ_FORMAT_CAPACITIES:
2273                 common->data_size_from_cmnd =
2274                         get_unaligned_be16(&common->cmnd[7]);
2275                 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2276                                       (3<<7), 1,
2277                                       "READ FORMAT CAPACITIES");
2278                 if (reply == 0)
2279                         reply = do_read_format_capacities(common, bh);
2280                 break;
2281
2282         case SC_REQUEST_SENSE:
2283                 common->data_size_from_cmnd = common->cmnd[4];
2284                 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2285                                       (1<<4), 0,
2286                                       "REQUEST SENSE");
2287                 if (reply == 0)
2288                         reply = do_request_sense(common, bh);
2289                 break;
2290
2291         case SC_START_STOP_UNIT:
2292                 common->data_size_from_cmnd = 0;
2293                 reply = check_command(common, 6, DATA_DIR_NONE,
2294                                       (1<<1) | (1<<4), 0,
2295                                       "START-STOP UNIT");
2296                 if (reply == 0)
2297                         reply = do_start_stop(common);
2298                 break;
2299
2300         case SC_SYNCHRONIZE_CACHE:
2301                 common->data_size_from_cmnd = 0;
2302                 reply = check_command(common, 10, DATA_DIR_NONE,
2303                                       (0xf<<2) | (3<<7), 1,
2304                                       "SYNCHRONIZE CACHE");
2305                 if (reply == 0)
2306                         reply = do_synchronize_cache(common);
2307                 break;
2308
2309         case SC_TEST_UNIT_READY:
2310                 common->data_size_from_cmnd = 0;
2311                 reply = check_command(common, 6, DATA_DIR_NONE,
2312                                 0, 1,
2313                                 "TEST UNIT READY");
2314                 break;
2315
2316         /* Although optional, this command is used by MS-Windows.  We
2317          * support a minimal version: BytChk must be 0. */
2318         case SC_VERIFY:
2319                 common->data_size_from_cmnd = 0;
2320                 reply = check_command(common, 10, DATA_DIR_NONE,
2321                                       (1<<1) | (0xf<<2) | (3<<7), 1,
2322                                       "VERIFY");
2323                 if (reply == 0)
2324 #ifdef CONFIG_ARCH_RK29
2325                         reply = 0; //zyf 20100302
2326 #else
2327                         reply = do_verify(common);
2328 #endif
2329                 break;
2330
2331         case SC_WRITE_6:
2332                 i = common->cmnd[4];
2333                 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2334                 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2335                                       (7<<1) | (1<<4), 1,
2336                                       "WRITE(6)");
2337                 if (reply == 0)
2338                         reply = do_write(common);
2339                 break;
2340
2341         case SC_WRITE_10:
2342                 common->data_size_from_cmnd =
2343                                 get_unaligned_be16(&common->cmnd[7]) << 9;
2344                 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2345                                       (1<<1) | (0xf<<2) | (3<<7), 1,
2346                                       "WRITE(10)");
2347                 if (reply == 0)
2348                         reply = do_write(common);
2349                 break;
2350
2351         case SC_WRITE_12:
2352                 common->data_size_from_cmnd =
2353                                 get_unaligned_be32(&common->cmnd[6]) << 9;
2354                 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2355                                       (1<<1) | (0xf<<2) | (0xf<<6), 1,
2356                                       "WRITE(12)");
2357                 if (reply == 0)
2358                         reply = do_write(common);
2359                 break;
2360
2361         /* Some mandatory commands that we recognize but don't implement.
2362          * They don't mean much in this setting.  It's left as an exercise
2363          * for anyone interested to implement RESERVE and RELEASE in terms
2364          * of Posix locks. */
2365         case SC_FORMAT_UNIT:
2366         case SC_RELEASE:
2367         case SC_RESERVE:
2368         case SC_SEND_DIAGNOSTIC:
2369                 /* Fall through */
2370
2371         default:
2372 unknown_cmnd:
2373                 common->data_size_from_cmnd = 0;
2374                 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2375                 reply = check_command(common, common->cmnd_size,
2376                                       DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2377                 if (reply == 0) {
2378                         common->curlun->sense_data = SS_INVALID_COMMAND;
2379                         reply = -EINVAL;
2380                 }
2381                 break;
2382 #ifdef CONFIG_ARCH_RK29
2383         case 0xff:
2384                 if( fsg->cmnd[1] != 0xe0 ||
2385                     fsg->cmnd[2] != 0xff || fsg->cmnd[3] != 0xff ||
2386                     fsg->cmnd[4] != 0xff )
2387                     break;
2388                 if (fsg->cmnd_size >= 6 && fsg->cmnd[5] == 0xfe) {
2389                         schedule_work(&restart_work);
2390                 }
2391                 else if ( fsg->cmnd[5] == 0xf3 ) {
2392                         fsg->data_size_from_cmnd = fsg->data_size;
2393                 /* get product name from parameter section */
2394                         reply = do_get_product_name( fsg->data_size,bh->buf );
2395                 }
2396                 else if ( fsg->cmnd[5] == 0xff ){
2397                         fsg->data_size_from_cmnd = fsg->data_size;
2398                         reply = do_get_versions( fsg->data_size,bh->buf ); 
2399                 }
2400                 break;
2401 #endif
2402         }
2403         up_read(&common->filesem);
2404
2405         if (reply == -EINTR || signal_pending(current))
2406                 return -EINTR;
2407
2408         /* Set up the single reply buffer for finish_reply() */
2409         if (reply == -EINVAL)
2410                 reply = 0;              /* Error reply length */
2411         if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2412                 reply = min((u32) reply, common->data_size_from_cmnd);
2413                 bh->inreq->length = reply;
2414                 bh->state = BUF_STATE_FULL;
2415                 common->residue -= reply;
2416         }                               /* Otherwise it's already set */
2417
2418         return 0;
2419 }
2420
2421
2422 /*-------------------------------------------------------------------------*/
2423
2424 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2425 {
2426         struct usb_request      *req = bh->outreq;
2427         struct fsg_bulk_cb_wrap *cbw = req->buf;
2428         struct fsg_common       *common = fsg->common;
2429
2430         /* Was this a real packet?  Should it be ignored? */
2431         if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2432                 return -EINVAL;
2433
2434         /* Is the CBW valid? */
2435         if (req->actual != USB_BULK_CB_WRAP_LEN ||
2436                         cbw->Signature != cpu_to_le32(
2437                                 USB_BULK_CB_SIG)) {
2438                 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2439                                 req->actual,
2440                                 le32_to_cpu(cbw->Signature));
2441
2442                 /* The Bulk-only spec says we MUST stall the IN endpoint
2443                  * (6.6.1), so it's unavoidable.  It also says we must
2444                  * retain this state until the next reset, but there's
2445                  * no way to tell the controller driver it should ignore
2446                  * Clear-Feature(HALT) requests.
2447                  *
2448                  * We aren't required to halt the OUT endpoint; instead
2449                  * we can simply accept and discard any data received
2450                  * until the next reset. */
2451                 wedge_bulk_in_endpoint(fsg);
2452                 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2453                 return -EINVAL;
2454         }
2455
2456         /* Is the CBW meaningful? */
2457         if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2458                         cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2459                 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2460                                 "cmdlen %u\n",
2461                                 cbw->Lun, cbw->Flags, cbw->Length);
2462
2463                 /* We can do anything we want here, so let's stall the
2464                  * bulk pipes if we are allowed to. */
2465                 if (common->can_stall) {
2466                         fsg_set_halt(fsg, fsg->bulk_out);
2467                         halt_bulk_in_endpoint(fsg);
2468                 }
2469                 return -EINVAL;
2470         }
2471
2472         /* Save the command for later */
2473         common->cmnd_size = cbw->Length;
2474         memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2475         if (cbw->Flags & USB_BULK_IN_FLAG)
2476                 common->data_dir = DATA_DIR_TO_HOST;
2477         else
2478                 common->data_dir = DATA_DIR_FROM_HOST;
2479         common->data_size = le32_to_cpu(cbw->DataTransferLength);
2480         if (common->data_size == 0)
2481                 common->data_dir = DATA_DIR_NONE;
2482         common->lun = cbw->Lun;
2483         common->tag = cbw->Tag;
2484         return 0;
2485 }
2486
2487
2488 static int get_next_command(struct fsg_common *common)
2489 {
2490         struct fsg_buffhd       *bh;
2491         int                     rc = 0;
2492
2493         /* Wait for the next buffer to become available */
2494         bh = common->next_buffhd_to_fill;
2495         while (bh->state != BUF_STATE_EMPTY) {
2496                 rc = sleep_thread(common);
2497                 if (rc)
2498                         return rc;
2499         }
2500
2501         /* Queue a request to read a Bulk-only CBW */
2502         set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2503         bh->outreq->short_not_ok = 1;
2504         START_TRANSFER_OR(common, bulk_out, bh->outreq,
2505                           &bh->outreq_busy, &bh->state)
2506                 /* Don't know what to do if common->fsg is NULL */
2507                 return -EIO;
2508
2509         /* We will drain the buffer in software, which means we
2510          * can reuse it for the next filling.  No need to advance
2511          * next_buffhd_to_fill. */
2512
2513         /* Wait for the CBW to arrive */
2514         while (bh->state != BUF_STATE_FULL) {
2515                 rc = sleep_thread(common);
2516                 if (rc)
2517                         return rc;
2518         }
2519         smp_rmb();
2520         rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2521         bh->state = BUF_STATE_EMPTY;
2522
2523         return rc;
2524 }
2525
2526
2527 /*-------------------------------------------------------------------------*/
2528
2529 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2530                 const struct usb_endpoint_descriptor *d)
2531 {
2532         int     rc;
2533
2534         ep->driver_data = common;
2535         rc = usb_ep_enable(ep, d);
2536         if (rc)
2537                 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2538         return rc;
2539 }
2540
2541 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2542                 struct usb_request **preq)
2543 {
2544         *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2545         if (*preq)
2546                 return 0;
2547         ERROR(common, "can't allocate request for %s\n", ep->name);
2548         return -ENOMEM;
2549 }
2550
2551 /* Reset interface setting and re-init endpoint state (toggle etc). */
2552 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2553 {
2554         const struct usb_endpoint_descriptor *d;
2555         struct fsg_dev *fsg;
2556         int i, rc = 0;
2557
2558         if (common->running)
2559                 DBG(common, "reset interface\n");
2560
2561 reset:
2562         /* Deallocate the requests */
2563         if (common->fsg) {
2564                 fsg = common->fsg;
2565
2566                 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2567                         struct fsg_buffhd *bh = &common->buffhds[i];
2568
2569                         if (bh->inreq) {
2570                                 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2571                                 bh->inreq = NULL;
2572                         }
2573                         if (bh->outreq) {
2574                                 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2575                                 bh->outreq = NULL;
2576                         }
2577                 }
2578
2579                 /* Disable the endpoints */
2580                 if (fsg->bulk_in_enabled) {
2581                         usb_ep_disable(fsg->bulk_in);
2582                         fsg->bulk_in_enabled = 0;
2583                 }
2584                 if (fsg->bulk_out_enabled) {
2585                         usb_ep_disable(fsg->bulk_out);
2586                         fsg->bulk_out_enabled = 0;
2587                 }
2588
2589                 common->fsg = NULL;
2590                 wake_up(&common->fsg_wait);
2591         }
2592
2593         common->running = 0;
2594         if (!new_fsg || rc)
2595                 return rc;
2596
2597         common->fsg = new_fsg;
2598         fsg = common->fsg;
2599
2600         /* Enable the endpoints */
2601         d = fsg_ep_desc(common->gadget,
2602                         &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2603         rc = enable_endpoint(common, fsg->bulk_in, d);
2604         if (rc)
2605                 goto reset;
2606         fsg->bulk_in_enabled = 1;
2607
2608         d = fsg_ep_desc(common->gadget,
2609                         &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2610         rc = enable_endpoint(common, fsg->bulk_out, d);
2611         if (rc)
2612                 goto reset;
2613         fsg->bulk_out_enabled = 1;
2614         common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2615         clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2616
2617         /* Allocate the requests */
2618         for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2619                 struct fsg_buffhd       *bh = &common->buffhds[i];
2620
2621                 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2622                 if (rc)
2623                         goto reset;
2624                 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2625                 if (rc)
2626                         goto reset;
2627                 bh->inreq->buf = bh->outreq->buf = bh->buf;
2628                 bh->inreq->context = bh->outreq->context = bh;
2629                 bh->inreq->complete = bulk_in_complete;
2630                 bh->outreq->complete = bulk_out_complete;
2631         }
2632
2633         common->running = 1;
2634         for (i = 0; i < common->nluns; ++i)
2635                 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2636         return rc;
2637 }
2638
2639
2640 /****************************** ALT CONFIGS ******************************/
2641
2642
2643 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2644 {
2645         struct fsg_dev *fsg = fsg_from_func(f);
2646         fsg->common->new_fsg = fsg;
2647         raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2648         return 0;
2649 }
2650
2651 static void fsg_disable(struct usb_function *f)
2652 {
2653         struct fsg_dev *fsg = fsg_from_func(f);
2654         fsg->common->new_fsg = NULL;
2655         raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2656         // yk 201009
2657         set_msc_connect_flag(0);
2658 }
2659
2660
2661 /*-------------------------------------------------------------------------*/
2662
2663 static void handle_exception(struct fsg_common *common)
2664 {
2665         siginfo_t               info;
2666         int                     i;
2667         struct fsg_buffhd       *bh;
2668         enum fsg_state          old_state;
2669         struct fsg_lun          *curlun;
2670         unsigned int            exception_req_tag;
2671
2672         /* Clear the existing signals.  Anything but SIGUSR1 is converted
2673          * into a high-priority EXIT exception. */
2674         for (;;) {
2675                 int sig =
2676                         dequeue_signal_lock(current, &current->blocked, &info);
2677                 if (!sig)
2678                         break;
2679                 if (sig != SIGUSR1) {
2680                         if (common->state < FSG_STATE_EXIT)
2681                                 DBG(common, "Main thread exiting on signal\n");
2682                         raise_exception(common, FSG_STATE_EXIT);
2683                 }
2684         }
2685
2686         /* Cancel all the pending transfers */
2687         if (likely(common->fsg)) {
2688                 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2689                         bh = &common->buffhds[i];
2690                         if (bh->inreq_busy)
2691                                 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2692                         if (bh->outreq_busy)
2693                                 usb_ep_dequeue(common->fsg->bulk_out,
2694                                                bh->outreq);
2695                 }
2696
2697                 /* Wait until everything is idle */
2698                 for (;;) {
2699                         int num_active = 0;
2700                         for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2701                                 bh = &common->buffhds[i];
2702                                 num_active += bh->inreq_busy + bh->outreq_busy;
2703                         }
2704                         if (num_active == 0)
2705                                 break;
2706                         if (sleep_thread(common))
2707                                 return;
2708                 }
2709
2710                 /* Clear out the controller's fifos */
2711                 if (common->fsg->bulk_in_enabled)
2712                         usb_ep_fifo_flush(common->fsg->bulk_in);
2713                 if (common->fsg->bulk_out_enabled)
2714                         usb_ep_fifo_flush(common->fsg->bulk_out);
2715         }
2716
2717         /* Reset the I/O buffer states and pointers, the SCSI
2718          * state, and the exception.  Then invoke the handler. */
2719         spin_lock_irq(&common->lock);
2720
2721         for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2722                 bh = &common->buffhds[i];
2723                 bh->state = BUF_STATE_EMPTY;
2724         }
2725         common->next_buffhd_to_fill = &common->buffhds[0];
2726         common->next_buffhd_to_drain = &common->buffhds[0];
2727         exception_req_tag = common->exception_req_tag;
2728         old_state = common->state;
2729
2730         if (old_state == FSG_STATE_ABORT_BULK_OUT)
2731                 common->state = FSG_STATE_STATUS_PHASE;
2732         else {
2733                 for (i = 0; i < common->nluns; ++i) {
2734                         curlun = &common->luns[i];
2735                         curlun->prevent_medium_removal = 0;
2736                         curlun->sense_data = SS_NO_SENSE;
2737                         curlun->unit_attention_data = SS_NO_SENSE;
2738                         curlun->sense_data_info = 0;
2739                         curlun->info_valid = 0;
2740                 }
2741                 common->state = FSG_STATE_IDLE;
2742         }
2743         spin_unlock_irq(&common->lock);
2744
2745         /* Carry out any extra actions required for the exception */
2746         switch (old_state) {
2747         case FSG_STATE_ABORT_BULK_OUT:
2748                 send_status(common);
2749                 spin_lock_irq(&common->lock);
2750                 if (common->state == FSG_STATE_STATUS_PHASE)
2751                         common->state = FSG_STATE_IDLE;
2752                 spin_unlock_irq(&common->lock);
2753                 break;
2754
2755         case FSG_STATE_RESET:
2756                 /* In case we were forced against our will to halt a
2757                  * bulk endpoint, clear the halt now.  (The SuperH UDC
2758                  * requires this.) */
2759                 if (!fsg_is_set(common))
2760                         break;
2761                 if (test_and_clear_bit(IGNORE_BULK_OUT,
2762                                        &common->fsg->atomic_bitflags))
2763                         usb_ep_clear_halt(common->fsg->bulk_in);
2764
2765                 if (common->ep0_req_tag == exception_req_tag)
2766                         ep0_queue(common);      /* Complete the status stage */
2767
2768                 /* Technically this should go here, but it would only be
2769                  * a waste of time.  Ditto for the INTERFACE_CHANGE and
2770                  * CONFIG_CHANGE cases. */
2771                 /* for (i = 0; i < common->nluns; ++i) */
2772                 /*      common->luns[i].unit_attention_data = */
2773                 /*              SS_RESET_OCCURRED;  */
2774                 break;
2775
2776         case FSG_STATE_CONFIG_CHANGE:
2777                 do_set_interface(common, common->new_fsg);
2778                 break;
2779
2780         case FSG_STATE_EXIT:
2781         case FSG_STATE_TERMINATED:
2782                 do_set_interface(common, NULL);         /* Free resources */
2783                 spin_lock_irq(&common->lock);
2784                 common->state = FSG_STATE_TERMINATED;   /* Stop the thread */
2785                 spin_unlock_irq(&common->lock);
2786                 break;
2787
2788         case FSG_STATE_INTERFACE_CHANGE:
2789         case FSG_STATE_DISCONNECT:
2790         case FSG_STATE_COMMAND_PHASE:
2791         case FSG_STATE_DATA_PHASE:
2792         case FSG_STATE_STATUS_PHASE:
2793         case FSG_STATE_IDLE:
2794                 break;
2795         }
2796 }
2797
2798
2799 /*-------------------------------------------------------------------------*/
2800
2801 static int fsg_main_thread(void *common_)
2802 {
2803         struct fsg_common       *common = common_;
2804
2805         /* Allow the thread to be killed by a signal, but set the signal mask
2806          * to block everything but INT, TERM, KILL, and USR1. */
2807         allow_signal(SIGINT);
2808         allow_signal(SIGTERM);
2809         allow_signal(SIGKILL);
2810         allow_signal(SIGUSR1);
2811
2812         /* Allow the thread to be frozen */
2813         set_freezable();
2814
2815         /* Arrange for userspace references to be interpreted as kernel
2816          * pointers.  That way we can pass a kernel pointer to a routine
2817          * that expects a __user pointer and it will work okay. */
2818         set_fs(get_ds());
2819
2820         /* The main loop */
2821         while (common->state != FSG_STATE_TERMINATED) {
2822                 if (exception_in_progress(common) || signal_pending(current)) {
2823                         handle_exception(common);
2824                         continue;
2825                 }
2826
2827                 if (!common->running) {
2828                         sleep_thread(common);
2829                         continue;
2830                 }
2831
2832                 if (get_next_command(common))
2833                         continue;
2834
2835                 spin_lock_irq(&common->lock);
2836                 if (!exception_in_progress(common))
2837                         common->state = FSG_STATE_DATA_PHASE;
2838                 spin_unlock_irq(&common->lock);
2839
2840                 if (do_scsi_command(common) || finish_reply(common))
2841                         continue;
2842
2843                 spin_lock_irq(&common->lock);
2844                 if (!exception_in_progress(common))
2845                         common->state = FSG_STATE_STATUS_PHASE;
2846                 spin_unlock_irq(&common->lock);
2847
2848                 if (send_status(common))
2849                         continue;
2850
2851                 spin_lock_irq(&common->lock);
2852                 if (!exception_in_progress(common))
2853                         common->state = FSG_STATE_IDLE;
2854                 spin_unlock_irq(&common->lock);
2855         }
2856
2857         spin_lock_irq(&common->lock);
2858         common->thread_task = NULL;
2859         spin_unlock_irq(&common->lock);
2860
2861         if (!common->ops || !common->ops->thread_exits
2862          || common->ops->thread_exits(common) < 0) {
2863                 struct fsg_lun *curlun = common->luns;
2864                 unsigned i = common->nluns;
2865
2866                 down_write(&common->filesem);
2867                 for (; i--; ++curlun) {
2868                         if (!fsg_lun_is_open(curlun))
2869                                 continue;
2870
2871                         fsg_lun_close(curlun);
2872                         curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2873                 }
2874                 up_write(&common->filesem);
2875         }
2876
2877         /* Let the unbind and cleanup routines know the thread has exited */
2878         complete_and_exit(&common->thread_notifier, 0);
2879 }
2880
2881
2882 /*************************** DEVICE ATTRIBUTES ***************************/
2883
2884 /* Write permission is checked per LUN in store_*() functions. */
2885 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2886 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2887
2888
2889 /****************************** FSG COMMON ******************************/
2890
2891 static void fsg_common_release(struct kref *ref);
2892
2893 static void fsg_lun_release(struct device *dev)
2894 {
2895         /* Nothing needs to be done */
2896 }
2897
2898 static inline void fsg_common_get(struct fsg_common *common)
2899 {
2900         kref_get(&common->ref);
2901 }
2902
2903 static inline void fsg_common_put(struct fsg_common *common)
2904 {
2905         kref_put(&common->ref, fsg_common_release);
2906 }
2907
2908
2909 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2910                                           struct usb_composite_dev *cdev,
2911                                           struct fsg_config *cfg)
2912 {
2913         struct usb_gadget *gadget = cdev->gadget;
2914         struct fsg_buffhd *bh;
2915         struct fsg_lun *curlun;
2916         struct fsg_lun_config *lcfg;
2917         int nluns, i, rc;
2918         char *pathbuf;
2919
2920         /* Find out how many LUNs there should be */
2921         nluns = cfg->nluns;
2922         if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2923                 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2924                 return ERR_PTR(-EINVAL);
2925         }
2926
2927         /* Allocate? */
2928         if (!common) {
2929                 common = kzalloc(sizeof *common, GFP_KERNEL);
2930                 if (!common)
2931                         return ERR_PTR(-ENOMEM);
2932                 common->free_storage_on_release = 1;
2933         } else {
2934                 memset(common, 0, sizeof common);
2935                 common->free_storage_on_release = 0;
2936         }
2937
2938         common->ops = cfg->ops;
2939         common->private_data = cfg->private_data;
2940
2941         common->gadget = gadget;
2942         common->ep0 = gadget->ep0;
2943         common->ep0req = cdev->req;
2944
2945         /* Maybe allocate device-global string IDs, and patch descriptors */
2946         if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2947                 rc = usb_string_id(cdev);
2948                 if (unlikely(rc < 0))
2949                         goto error_release;
2950                 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2951                 fsg_intf_desc.iInterface = rc;
2952         }
2953
2954         /* Create the LUNs, open their backing files, and register the
2955          * LUN devices in sysfs. */
2956         curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2957         if (unlikely(!curlun)) {
2958                 rc = -ENOMEM;
2959                 goto error_release;
2960         }
2961         common->luns = curlun;
2962
2963         init_rwsem(&common->filesem);
2964
2965         for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2966                 curlun->cdrom = !!lcfg->cdrom;
2967                 curlun->ro = lcfg->cdrom || lcfg->ro;
2968                 curlun->removable = lcfg->removable;
2969                 curlun->dev.release = fsg_lun_release;
2970
2971 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
2972                 /* use "usb_mass_storage" platform device as parent */
2973                 curlun->dev.parent = &cfg->pdev->dev;
2974 #else
2975                 curlun->dev.parent = &gadget->dev;
2976 #endif
2977                 /* curlun->dev.driver = &fsg_driver.driver; XXX */
2978                 dev_set_drvdata(&curlun->dev, &common->filesem);
2979                 dev_set_name(&curlun->dev,
2980                              cfg->lun_name_format
2981                            ? cfg->lun_name_format
2982                            : "lun%d",
2983                              i);
2984
2985                 rc = device_register(&curlun->dev);
2986                 if (rc) {
2987                         INFO(common, "failed to register LUN%d: %d\n", i, rc);
2988                         common->nluns = i;
2989                         goto error_release;
2990                 }
2991
2992                 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2993                 if (rc)
2994                         goto error_luns;
2995                 rc = device_create_file(&curlun->dev, &dev_attr_file);
2996                 if (rc)
2997                         goto error_luns;
2998
2999                 if (lcfg->filename) {
3000                         rc = fsg_lun_open(curlun, lcfg->filename);
3001                         if (rc)
3002                                 goto error_luns;
3003                 } else if (!curlun->removable) {
3004                         ERROR(common, "no file given for LUN%d\n", i);
3005                         rc = -EINVAL;
3006                         goto error_luns;
3007                 }
3008         }
3009         common->nluns = nluns;
3010
3011
3012         /* Data buffers cyclic list */
3013         bh = common->buffhds;
3014         i = FSG_NUM_BUFFERS;
3015         goto buffhds_first_it;
3016         do {
3017                 bh->next = bh + 1;
3018                 ++bh;
3019 buffhds_first_it:
3020                 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
3021                 if (unlikely(!bh->buf)) {
3022                         rc = -ENOMEM;
3023                         goto error_release;
3024                 }
3025         } while (--i);
3026         bh->next = common->buffhds;
3027
3028
3029         /* Prepare inquiryString */
3030         if (cfg->release != 0xffff) {
3031                 i = cfg->release;
3032         } else {
3033                 i = usb_gadget_controller_number(gadget);
3034                 if (i >= 0) {
3035                         i = 0x0300 + i;
3036                 } else {
3037                         WARNING(common, "controller '%s' not recognized\n",
3038                                 gadget->name);
3039                         i = 0x0399;
3040                 }
3041         }
3042 #define OR(x, y) ((x) ? (x) : (y))
3043         snprintf(common->inquiry_string, sizeof common->inquiry_string,
3044                  "%-8s%-16s%04x",
3045                  OR(cfg->vendor_name, "Linux   "),
3046                  /* Assume product name dependent on the first LUN */
3047                  OR(cfg->product_name, common->luns->cdrom
3048                                      ? "File-Stor Gadget"
3049                                      : "File-CD Gadget  "),
3050                  i);
3051
3052
3053         /* Some peripheral controllers are known not to be able to
3054          * halt bulk endpoints correctly.  If one of them is present,
3055          * disable stalls.
3056          */
3057         common->can_stall = cfg->can_stall &&
3058                 !(gadget_is_at91(common->gadget));
3059
3060
3061         spin_lock_init(&common->lock);
3062         kref_init(&common->ref);
3063
3064
3065         /* Tell the thread to start working */
3066         common->thread_task =
3067                 kthread_create(fsg_main_thread, common,
3068                                OR(cfg->thread_name, "file-storage"));
3069         if (IS_ERR(common->thread_task)) {
3070                 rc = PTR_ERR(common->thread_task);
3071                 goto error_release;
3072         }
3073         init_completion(&common->thread_notifier);
3074         init_waitqueue_head(&common->fsg_wait);
3075 #undef OR
3076
3077
3078         /* Information */
3079         INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
3080         INFO(common, "Number of LUNs=%d\n", common->nluns);
3081
3082         pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3083         for (i = 0, nluns = common->nluns, curlun = common->luns;
3084              i < nluns;
3085              ++curlun, ++i) {
3086                 char *p = "(no medium)";
3087                 if (fsg_lun_is_open(curlun)) {
3088                         p = "(error)";
3089                         if (pathbuf) {
3090                                 p = d_path(&curlun->filp->f_path,
3091                                            pathbuf, PATH_MAX);
3092                                 if (IS_ERR(p))
3093                                         p = "(error)";
3094                         }
3095                 }
3096                 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
3097                       curlun->removable ? "removable " : "",
3098                       curlun->ro ? "read only " : "",
3099                       curlun->cdrom ? "CD-ROM " : "",
3100                       p);
3101         }
3102         kfree(pathbuf);
3103
3104         DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
3105
3106         wake_up_process(common->thread_task);
3107
3108         return common;
3109
3110
3111 error_luns:
3112         common->nluns = i + 1;
3113 error_release:
3114         common->state = FSG_STATE_TERMINATED;   /* The thread is dead */
3115         /* Call fsg_common_release() directly, ref might be not
3116          * initialised */
3117         fsg_common_release(&common->ref);
3118         return ERR_PTR(rc);
3119 }
3120
3121
3122 static void fsg_common_release(struct kref *ref)
3123 {
3124         struct fsg_common *common = container_of(ref, struct fsg_common, ref);
3125
3126         /* If the thread isn't already dead, tell it to exit now */
3127         if (common->state != FSG_STATE_TERMINATED) {
3128                 raise_exception(common, FSG_STATE_EXIT);
3129                 wait_for_completion(&common->thread_notifier);
3130
3131                 /* The cleanup routine waits for this completion also */
3132                 complete(&common->thread_notifier);
3133         }
3134
3135         if (likely(common->luns)) {
3136                 struct fsg_lun *lun = common->luns;
3137                 unsigned i = common->nluns;
3138
3139                 /* In error recovery common->nluns may be zero. */
3140                 for (; i; --i, ++lun) {
3141                         device_remove_file(&lun->dev, &dev_attr_ro);
3142                         device_remove_file(&lun->dev, &dev_attr_file);
3143                         fsg_lun_close(lun);
3144                         device_unregister(&lun->dev);
3145                 }
3146
3147                 kfree(common->luns);
3148         }
3149
3150         {
3151                 struct fsg_buffhd *bh = common->buffhds;
3152                 unsigned i = FSG_NUM_BUFFERS;
3153                 do {
3154                         kfree(bh->buf);
3155                 } while (++bh, --i);
3156         }
3157
3158         if (common->free_storage_on_release)
3159                 kfree(common);
3160 }
3161
3162
3163 /*-------------------------------------------------------------------------*/
3164
3165
3166 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
3167 {
3168         struct fsg_dev          *fsg = fsg_from_func(f);
3169         struct fsg_common       *common = fsg->common;
3170
3171         DBG(fsg, "unbind\n");
3172         if (fsg->common->fsg == fsg) {
3173                 fsg->common->new_fsg = NULL;
3174                 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
3175                 /* FIXME: make interruptible or killable somehow? */
3176                 wait_event(common->fsg_wait, common->fsg != fsg);
3177         }
3178
3179         fsg_common_put(common);
3180         usb_free_descriptors(fsg->function.descriptors);
3181         usb_free_descriptors(fsg->function.hs_descriptors);
3182         kfree(fsg);
3183 }
3184
3185
3186 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
3187 {
3188         struct fsg_dev          *fsg = fsg_from_func(f);
3189         struct usb_gadget       *gadget = c->cdev->gadget;
3190         int                     i;
3191         struct usb_ep           *ep;
3192
3193         fsg->gadget = gadget;
3194
3195         /* New interface */
3196         i = usb_interface_id(c, f);
3197         if (i < 0)
3198                 return i;
3199         fsg_intf_desc.bInterfaceNumber = i;
3200         fsg->interface_number = i;
3201
3202         /* Find all the endpoints we will use */
3203         ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3204         if (!ep)
3205                 goto autoconf_fail;
3206         ep->driver_data = fsg->common;  /* claim the endpoint */
3207         fsg->bulk_in = ep;
3208
3209         ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3210         if (!ep)
3211                 goto autoconf_fail;
3212         ep->driver_data = fsg->common;  /* claim the endpoint */
3213         fsg->bulk_out = ep;
3214
3215         /* Copy descriptors */
3216         f->descriptors = usb_copy_descriptors(fsg_fs_function);
3217         if (unlikely(!f->descriptors))
3218                 return -ENOMEM;
3219
3220         if (gadget_is_dualspeed(gadget)) {
3221                 /* Assume endpoint addresses are the same for both speeds */
3222                 fsg_hs_bulk_in_desc.bEndpointAddress =
3223                         fsg_fs_bulk_in_desc.bEndpointAddress;
3224                 fsg_hs_bulk_out_desc.bEndpointAddress =
3225                         fsg_fs_bulk_out_desc.bEndpointAddress;
3226                 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
3227                 if (unlikely(!f->hs_descriptors)) {
3228                         usb_free_descriptors(f->descriptors);
3229                         return -ENOMEM;
3230                 }
3231         }
3232
3233         return 0;
3234
3235 autoconf_fail:
3236         ERROR(fsg, "unable to autoconfigure all endpoints\n");
3237         return -ENOTSUPP;
3238 }
3239
3240
3241 /****************************** ADD FUNCTION ******************************/
3242
3243 static struct usb_gadget_strings *fsg_strings_array[] = {
3244         &fsg_stringtab,
3245         NULL,
3246 };
3247
3248 static int fsg_bind_config(struct usb_composite_dev *cdev,
3249                            struct usb_configuration *c,
3250                            struct fsg_common *common)
3251 {
3252         struct fsg_dev *fsg;
3253         int rc;
3254
3255         fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3256         if (unlikely(!fsg))
3257                 return -ENOMEM;
3258
3259 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
3260         fsg->function.name        = FUNCTION_NAME;
3261 #else
3262         fsg->function.name        = FSG_DRIVER_DESC;
3263 #endif
3264         fsg->function.strings     = fsg_strings_array;
3265         fsg->function.bind        = fsg_bind;
3266         fsg->function.unbind      = fsg_unbind;
3267         fsg->function.setup       = fsg_setup;
3268         fsg->function.set_alt     = fsg_set_alt;
3269         fsg->function.disable     = fsg_disable;
3270
3271         fsg->common               = common;
3272         /* Our caller holds a reference to common structure so we
3273          * don't have to be worry about it being freed until we return
3274          * from this function.  So instead of incrementing counter now
3275          * and decrement in error recovery we increment it only when
3276          * call to usb_add_function() was successful. */
3277
3278         rc = usb_add_function(c, &fsg->function);
3279         if (unlikely(rc))
3280                 kfree(fsg);
3281         else
3282                 fsg_common_get(fsg->common);
3283         return rc;
3284 }
3285
3286 static inline int __deprecated __maybe_unused
3287 fsg_add(struct usb_composite_dev *cdev,
3288         struct usb_configuration *c,
3289         struct fsg_common *common)
3290 {
3291         return fsg_bind_config(cdev, c, common);
3292 }
3293
3294
3295 /************************* Module parameters *************************/
3296
3297
3298 struct fsg_module_parameters {
3299         char            *file[FSG_MAX_LUNS];
3300         int             ro[FSG_MAX_LUNS];
3301         int             removable[FSG_MAX_LUNS];
3302         int             cdrom[FSG_MAX_LUNS];
3303
3304         unsigned int    file_count, ro_count, removable_count, cdrom_count;
3305         unsigned int    luns;   /* nluns */
3306         int             stall;  /* can_stall */
3307 };
3308
3309
3310 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc)       \
3311         module_param_array_named(prefix ## name, params.name, type,     \
3312                                  &prefix ## params.name ## _count,      \
3313                                  S_IRUGO);                              \
3314         MODULE_PARM_DESC(prefix ## name, desc)
3315
3316 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc)             \
3317         module_param_named(prefix ## name, params.name, type,           \
3318                            S_IRUGO);                                    \
3319         MODULE_PARM_DESC(prefix ## name, desc)
3320
3321 #define FSG_MODULE_PARAMETERS(prefix, params)                           \
3322         _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp,            \
3323                                 "names of backing files or devices");   \
3324         _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool,               \
3325                                 "true to force read-only");             \
3326         _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool,        \
3327                                 "true to simulate removable media");    \
3328         _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool,            \
3329                                 "true to simulate CD-ROM instead of disk"); \
3330         _FSG_MODULE_PARAM(prefix, params, luns, uint,                   \
3331                           "number of LUNs");                            \
3332         _FSG_MODULE_PARAM(prefix, params, stall, bool,                  \
3333                           "false to prevent bulk stalls")
3334
3335
3336 static void
3337 fsg_config_from_params(struct fsg_config *cfg,
3338                        const struct fsg_module_parameters *params)
3339 {
3340         struct fsg_lun_config *lun;
3341         unsigned i;
3342
3343         /* Configure LUNs */
3344         cfg->nluns =
3345                 min(params->luns ?: (params->file_count ?: 1u),
3346                     (unsigned)FSG_MAX_LUNS);
3347         for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3348                 lun->ro = !!params->ro[i];
3349                 lun->cdrom = !!params->cdrom[i];
3350                 lun->removable = /* Removable by default */
3351                         params->removable_count <= i || params->removable[i];
3352                 lun->filename =
3353                         params->file_count > i && params->file[i][0]
3354                         ? params->file[i]
3355                         : 0;
3356         }
3357
3358         /* Let MSF use defaults */
3359         cfg->lun_name_format = 0;
3360         cfg->thread_name = 0;
3361         cfg->vendor_name = 0;
3362         cfg->product_name = 0;
3363         cfg->release = 0xffff;
3364
3365         cfg->ops = NULL;
3366         cfg->private_data = NULL;
3367
3368         /* Finalise */
3369         cfg->can_stall = params->stall;
3370 }
3371
3372 static inline struct fsg_common *
3373 fsg_common_from_params(struct fsg_common *common,
3374                        struct usb_composite_dev *cdev,
3375                        const struct fsg_module_parameters *params)
3376         __attribute__((unused));
3377 static inline struct fsg_common *
3378 fsg_common_from_params(struct fsg_common *common,
3379                        struct usb_composite_dev *cdev,
3380                        const struct fsg_module_parameters *params)
3381 {
3382         struct fsg_config cfg;
3383         fsg_config_from_params(&cfg, params);
3384         return fsg_common_init(common, cdev, &cfg);
3385 }
3386
3387 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
3388
3389 #ifdef CONFIG_ARCH_RK29
3390 static enum power_supply_property usb_props[] = {
3391 //      POWER_SUPPLY_PROP_STATUS,
3392         POWER_SUPPLY_PROP_ONLINE,
3393 };
3394
3395 static int usb_get_property(struct power_supply *psy,
3396                                 enum power_supply_property psp,
3397                                         union power_supply_propval *val)
3398 {
3399         int ret = 0;
3400
3401         switch (psp) {
3402         case POWER_SUPPLY_PROP_ONLINE:
3403 #ifndef CONFIG_DWC_OTG_HOST_ONLY
3404                 val->intval = get_msc_connect_flag();
3405 #else
3406                 val->intval = 0;
3407 #endif
3408                 break;
3409         default:
3410                 return -EINVAL;
3411         }
3412
3413         return ret;
3414 }
3415
3416 static int usb_power_supply_register(struct device* parent)
3417 {
3418         struct power_supply *ps;
3419         int retval = 0;
3420
3421         ps = kzalloc(sizeof(*ps), GFP_KERNEL);
3422         if (!ps) {
3423                 dev_err(parent, "failed to allocate power supply data\n");
3424                 retval = -ENOMEM;
3425                 goto out;
3426         }
3427         ps->name = "usb";
3428         ps->type = POWER_SUPPLY_TYPE_USB;
3429         ps->properties = usb_props;
3430         ps->num_properties = ARRAY_SIZE(usb_props);
3431         ps->get_property = usb_get_property;
3432         ps->external_power_changed = NULL;
3433         retval = power_supply_register(parent, ps);
3434         if (retval) {
3435                 dev_err(parent, "failed to register battery\n");
3436                 goto out;
3437         }
3438 out:
3439         return retval;
3440 }
3441 #endif
3442
3443 static struct fsg_config fsg_cfg;
3444
3445 static int fsg_probe(struct platform_device *pdev)
3446 {
3447         struct usb_mass_storage_platform_data *pdata = pdev->dev.platform_data;
3448         int i, nluns;
3449
3450         printk(KERN_INFO "fsg_probe pdev: %p, pdata: %p\n", pdev, pdata);
3451         if (!pdata)
3452                 return -1;
3453
3454         nluns = pdata->nluns;
3455         if (nluns > FSG_MAX_LUNS)
3456                 nluns = FSG_MAX_LUNS;
3457         fsg_cfg.nluns = nluns;
3458         for (i = 0; i < nluns; i++)
3459                 fsg_cfg.luns[i].removable = 1;
3460
3461         fsg_cfg.vendor_name = pdata->vendor;
3462         fsg_cfg.product_name = pdata->product;
3463         fsg_cfg.release = pdata->release;
3464         fsg_cfg.can_stall = 0;
3465         fsg_cfg.pdev = pdev;
3466
3467 #ifdef CONFIG_ARCH_RK29
3468 {
3469         /*
3470          * Initialize usb power supply
3471          */
3472         int retval = usb_power_supply_register(&pdev->dev);
3473         if (retval != 0) {
3474                 dev_err(&pdev->dev, "usb_power_supply_register failed\n");
3475         }
3476
3477         return retval;
3478 }
3479 #else
3480         return 0;
3481 #endif
3482 }
3483
3484 static struct platform_driver fsg_platform_driver = {
3485         .driver = { .name = FUNCTION_NAME, },
3486         .probe = fsg_probe,
3487 };
3488
3489 int mass_storage_bind_config(struct usb_configuration *c)
3490 {
3491         struct fsg_common *common = fsg_common_init(NULL, c->cdev, &fsg_cfg);
3492         if (IS_ERR(common))
3493                 return -1;
3494         return fsg_add(c->cdev, c, common);
3495 }
3496
3497 static struct android_usb_function mass_storage_function = {
3498         .name = FUNCTION_NAME,
3499         .bind_config = mass_storage_bind_config,
3500 };
3501
3502 static int __init init(void)
3503 {
3504         int             rc;
3505         printk(KERN_INFO "f_mass_storage init\n");
3506         rc = platform_driver_register(&fsg_platform_driver);
3507         if (rc != 0)
3508                 return rc;
3509         android_register_function(&mass_storage_function);
3510         return 0;
3511 }module_init(init);
3512
3513 #endif /* CONFIG_USB_ANDROID_MASS_STORAGE */
3514