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