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