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