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