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