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