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