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