VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[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->zero = rc < ctrl->wLength
1469                                 && (rc % gadget->ep0->maxpacket) == 0;
1470                 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1471                                 "ep0-in" : "ep0-out");
1472                 rc = ep0_queue(fsg);
1473         }
1474
1475         /* Device either stalls (rc < 0) or reports success */
1476         return rc;
1477 }
1478
1479
1480 /*-------------------------------------------------------------------------*/
1481
1482 /* All the following routines run in process context */
1483
1484
1485 /* Use this for bulk or interrupt transfers, not ep0 */
1486 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1487                 struct usb_request *req, volatile int *pbusy,
1488                 volatile enum fsg_buffer_state *state)
1489 {
1490         int     rc;
1491
1492         if (ep == fsg->bulk_in)
1493                 dump_msg(fsg, "bulk-in", req->buf, req->length);
1494         else if (ep == fsg->intr_in)
1495                 dump_msg(fsg, "intr-in", req->buf, req->length);
1496         *pbusy = 1;
1497         *state = BUF_STATE_BUSY;
1498         rc = usb_ep_queue(ep, req, GFP_KERNEL);
1499         if (rc != 0) {
1500                 *pbusy = 0;
1501                 *state = BUF_STATE_EMPTY;
1502
1503                 /* We can't do much more than wait for a reset */
1504
1505                 /* Note: currently the net2280 driver fails zero-length
1506                  * submissions if DMA is enabled. */
1507                 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1508                                                 req->length == 0))
1509                         WARN(fsg, "error in submission: %s --> %d\n",
1510                                         ep->name, rc);
1511         }
1512 }
1513
1514
1515 static int sleep_thread(struct fsg_dev *fsg)
1516 {
1517         int     rc;
1518
1519         /* Wait until a signal arrives or we are woken up */
1520         rc = wait_event_interruptible(fsg->thread_wqh,
1521                         fsg->thread_wakeup_needed);
1522         fsg->thread_wakeup_needed = 0;
1523         return (rc ? -EINTR : 0);
1524 }
1525
1526
1527 /*-------------------------------------------------------------------------*/
1528
1529 static int do_read(struct fsg_dev *fsg)
1530 {
1531         struct lun              *curlun = fsg->curlun;
1532         u32                     lba;
1533         struct fsg_buffhd       *bh;
1534         int                     rc;
1535         u32                     amount_left;
1536         loff_t                  file_offset, file_offset_tmp;
1537         unsigned int            amount;
1538         unsigned int            partial_page;
1539         ssize_t                 nread;
1540
1541         /* Get the starting Logical Block Address and check that it's
1542          * not too big */
1543         if (fsg->cmnd[0] == SC_READ_6)
1544                 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1545         else {
1546                 lba = get_be32(&fsg->cmnd[2]);
1547
1548                 /* We allow DPO (Disable Page Out = don't save data in the
1549                  * cache) and FUA (Force Unit Access = don't read from the
1550                  * cache), but we don't implement them. */
1551                 if ((fsg->cmnd[1] & ~0x18) != 0) {
1552                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1553                         return -EINVAL;
1554                 }
1555         }
1556         if (lba >= curlun->num_sectors) {
1557                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1558                 return -EINVAL;
1559         }
1560         file_offset = ((loff_t) lba) << 9;
1561
1562         /* Carry out the file reads */
1563         amount_left = fsg->data_size_from_cmnd;
1564         if (unlikely(amount_left == 0))
1565                 return -EIO;            // No default reply
1566
1567         for (;;) {
1568
1569                 /* Figure out how much we need to read:
1570                  * Try to read the remaining amount.
1571                  * But don't read more than the buffer size.
1572                  * And don't try to read past the end of the file.
1573                  * Finally, if we're not at a page boundary, don't read past
1574                  *      the next page.
1575                  * If this means reading 0 then we were asked to read past
1576                  *      the end of file. */
1577                 amount = min((unsigned int) amount_left, mod_data.buflen);
1578                 amount = min((loff_t) amount,
1579                                 curlun->file_length - file_offset);
1580                 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1581                 if (partial_page > 0)
1582                         amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1583                                         partial_page);
1584
1585                 /* Wait for the next buffer to become available */
1586                 bh = fsg->next_buffhd_to_fill;
1587                 while (bh->state != BUF_STATE_EMPTY) {
1588                         if ((rc = sleep_thread(fsg)) != 0)
1589                                 return rc;
1590                 }
1591
1592                 /* If we were asked to read past the end of file,
1593                  * end with an empty buffer. */
1594                 if (amount == 0) {
1595                         curlun->sense_data =
1596                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1597                         curlun->sense_data_info = file_offset >> 9;
1598                         bh->inreq->length = 0;
1599                         bh->state = BUF_STATE_FULL;
1600                         break;
1601                 }
1602
1603                 /* Perform the read */
1604                 file_offset_tmp = file_offset;
1605                 nread = vfs_read(curlun->filp,
1606                                 (char __user *) bh->buf,
1607                                 amount, &file_offset_tmp);
1608                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1609                                 (unsigned long long) file_offset,
1610                                 (int) nread);
1611                 if (signal_pending(current))
1612                         return -EINTR;
1613
1614                 if (nread < 0) {
1615                         LDBG(curlun, "error in file read: %d\n",
1616                                         (int) nread);
1617                         nread = 0;
1618                 } else if (nread < amount) {
1619                         LDBG(curlun, "partial file read: %d/%u\n",
1620                                         (int) nread, amount);
1621                         nread -= (nread & 511); // Round down to a block
1622                 }
1623                 file_offset  += nread;
1624                 amount_left  -= nread;
1625                 fsg->residue -= nread;
1626                 bh->inreq->length = nread;
1627                 bh->state = BUF_STATE_FULL;
1628
1629                 /* If an error occurred, report it and its position */
1630                 if (nread < amount) {
1631                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1632                         curlun->sense_data_info = file_offset >> 9;
1633                         break;
1634                 }
1635
1636                 if (amount_left == 0)
1637                         break;          // No more left to read
1638
1639                 /* Send this buffer and go read some more */
1640                 bh->inreq->zero = 0;
1641                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1642                                 &bh->inreq_busy, &bh->state);
1643                 fsg->next_buffhd_to_fill = bh->next;
1644         }
1645
1646         return -EIO;            // No default reply
1647 }
1648
1649
1650 /*-------------------------------------------------------------------------*/
1651
1652 static int do_write(struct fsg_dev *fsg)
1653 {
1654         struct lun              *curlun = fsg->curlun;
1655         u32                     lba;
1656         struct fsg_buffhd       *bh;
1657         int                     get_some_more;
1658         u32                     amount_left_to_req, amount_left_to_write;
1659         loff_t                  usb_offset, file_offset, file_offset_tmp;
1660         unsigned int            amount;
1661         unsigned int            partial_page;
1662         ssize_t                 nwritten;
1663         int                     rc;
1664
1665         if (curlun->ro) {
1666                 curlun->sense_data = SS_WRITE_PROTECTED;
1667                 return -EINVAL;
1668         }
1669         curlun->filp->f_flags &= ~O_SYNC;       // Default is not to wait
1670
1671         /* Get the starting Logical Block Address and check that it's
1672          * not too big */
1673         if (fsg->cmnd[0] == SC_WRITE_6)
1674                 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1675         else {
1676                 lba = get_be32(&fsg->cmnd[2]);
1677
1678                 /* We allow DPO (Disable Page Out = don't save data in the
1679                  * cache) and FUA (Force Unit Access = write directly to the
1680                  * medium).  We don't implement DPO; we implement FUA by
1681                  * performing synchronous output. */
1682                 if ((fsg->cmnd[1] & ~0x18) != 0) {
1683                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1684                         return -EINVAL;
1685                 }
1686                 if (fsg->cmnd[1] & 0x08)        // FUA
1687                         curlun->filp->f_flags |= O_SYNC;
1688         }
1689         if (lba >= curlun->num_sectors) {
1690                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1691                 return -EINVAL;
1692         }
1693
1694         /* Carry out the file writes */
1695         get_some_more = 1;
1696         file_offset = usb_offset = ((loff_t) lba) << 9;
1697         amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1698
1699         while (amount_left_to_write > 0) {
1700
1701                 /* Queue a request for more data from the host */
1702                 bh = fsg->next_buffhd_to_fill;
1703                 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1704
1705                         /* Figure out how much we want to get:
1706                          * Try to get the remaining amount.
1707                          * But don't get more than the buffer size.
1708                          * And don't try to go past the end of the file.
1709                          * If we're not at a page boundary,
1710                          *      don't go past the next page.
1711                          * If this means getting 0, then we were asked
1712                          *      to write past the end of file.
1713                          * Finally, round down to a block boundary. */
1714                         amount = min(amount_left_to_req, mod_data.buflen);
1715                         amount = min((loff_t) amount, curlun->file_length -
1716                                         usb_offset);
1717                         partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1718                         if (partial_page > 0)
1719                                 amount = min(amount,
1720         (unsigned int) PAGE_CACHE_SIZE - partial_page);
1721
1722                         if (amount == 0) {
1723                                 get_some_more = 0;
1724                                 curlun->sense_data =
1725                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1726                                 curlun->sense_data_info = usb_offset >> 9;
1727                                 continue;
1728                         }
1729                         amount -= (amount & 511);
1730                         if (amount == 0) {
1731
1732                                 /* Why were we were asked to transfer a
1733                                  * partial block? */
1734                                 get_some_more = 0;
1735                                 continue;
1736                         }
1737
1738                         /* Get the next buffer */
1739                         usb_offset += amount;
1740                         fsg->usb_amount_left -= amount;
1741                         amount_left_to_req -= amount;
1742                         if (amount_left_to_req == 0)
1743                                 get_some_more = 0;
1744
1745                         /* amount is always divisible by 512, hence by
1746                          * the bulk-out maxpacket size */
1747                         bh->outreq->length = bh->bulk_out_intended_length =
1748                                         amount;
1749                         start_transfer(fsg, fsg->bulk_out, bh->outreq,
1750                                         &bh->outreq_busy, &bh->state);
1751                         fsg->next_buffhd_to_fill = bh->next;
1752                         continue;
1753                 }
1754
1755                 /* Write the received data to the backing file */
1756                 bh = fsg->next_buffhd_to_drain;
1757                 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1758                         break;                  // We stopped early
1759                 if (bh->state == BUF_STATE_FULL) {
1760                         fsg->next_buffhd_to_drain = bh->next;
1761                         bh->state = BUF_STATE_EMPTY;
1762
1763                         /* Did something go wrong with the transfer? */
1764                         if (bh->outreq->status != 0) {
1765                                 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1766                                 curlun->sense_data_info = file_offset >> 9;
1767                                 break;
1768                         }
1769
1770                         amount = bh->outreq->actual;
1771                         if (curlun->file_length - file_offset < amount) {
1772                                 LERROR(curlun,
1773         "write %u @ %llu beyond end %llu\n",
1774         amount, (unsigned long long) file_offset,
1775         (unsigned long long) curlun->file_length);
1776                                 amount = curlun->file_length - file_offset;
1777                         }
1778
1779                         /* Perform the write */
1780                         file_offset_tmp = file_offset;
1781                         nwritten = vfs_write(curlun->filp,
1782                                         (char __user *) bh->buf,
1783                                         amount, &file_offset_tmp);
1784                         VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1785                                         (unsigned long long) file_offset,
1786                                         (int) nwritten);
1787                         if (signal_pending(current))
1788                                 return -EINTR;          // Interrupted!
1789
1790                         if (nwritten < 0) {
1791                                 LDBG(curlun, "error in file write: %d\n",
1792                                                 (int) nwritten);
1793                                 nwritten = 0;
1794                         } else if (nwritten < amount) {
1795                                 LDBG(curlun, "partial file write: %d/%u\n",
1796                                                 (int) nwritten, amount);
1797                                 nwritten -= (nwritten & 511);
1798                                                 // Round down to a block
1799                         }
1800                         file_offset += nwritten;
1801                         amount_left_to_write -= nwritten;
1802                         fsg->residue -= nwritten;
1803
1804                         /* If an error occurred, report it and its position */
1805                         if (nwritten < amount) {
1806                                 curlun->sense_data = SS_WRITE_ERROR;
1807                                 curlun->sense_data_info = file_offset >> 9;
1808                                 break;
1809                         }
1810
1811                         /* Did the host decide to stop early? */
1812                         if (bh->outreq->actual != bh->outreq->length) {
1813                                 fsg->short_packet_received = 1;
1814                                 break;
1815                         }
1816                         continue;
1817                 }
1818
1819                 /* Wait for something to happen */
1820                 if ((rc = sleep_thread(fsg)) != 0)
1821                         return rc;
1822         }
1823
1824         return -EIO;            // No default reply
1825 }
1826
1827
1828 /*-------------------------------------------------------------------------*/
1829
1830 /* Sync the file data, don't bother with the metadata.
1831  * This code was copied from fs/buffer.c:sys_fdatasync(). */
1832 static int fsync_sub(struct lun *curlun)
1833 {
1834         struct file     *filp = curlun->filp;
1835         struct inode    *inode;
1836         int             rc, err;
1837
1838         if (curlun->ro || !filp)
1839                 return 0;
1840         if (!filp->f_op->fsync)
1841                 return -EINVAL;
1842
1843         inode = filp->f_dentry->d_inode;
1844         down(&inode->i_sem);
1845         current->flags |= PF_SYNCWRITE;
1846         rc = filemap_fdatawrite(inode->i_mapping);
1847         err = filp->f_op->fsync(filp, filp->f_dentry, 1);
1848         if (!rc)
1849                 rc = err;
1850         err = filemap_fdatawait(inode->i_mapping);
1851         if (!rc)
1852                 rc = err;
1853         current->flags &= ~PF_SYNCWRITE;
1854         up(&inode->i_sem);
1855         VLDBG(curlun, "fdatasync -> %d\n", rc);
1856         return rc;
1857 }
1858
1859 static void fsync_all(struct fsg_dev *fsg)
1860 {
1861         int     i;
1862
1863         for (i = 0; i < fsg->nluns; ++i)
1864                 fsync_sub(&fsg->luns[i]);
1865 }
1866
1867 static int do_synchronize_cache(struct fsg_dev *fsg)
1868 {
1869         struct lun      *curlun = fsg->curlun;
1870         int             rc;
1871
1872         /* We ignore the requested LBA and write out all file's
1873          * dirty data buffers. */
1874         rc = fsync_sub(curlun);
1875         if (rc)
1876                 curlun->sense_data = SS_WRITE_ERROR;
1877         return 0;
1878 }
1879
1880
1881 /*-------------------------------------------------------------------------*/
1882
1883 static void invalidate_sub(struct lun *curlun)
1884 {
1885         struct file     *filp = curlun->filp;
1886         struct inode    *inode = filp->f_dentry->d_inode;
1887         unsigned long   rc;
1888
1889         rc = invalidate_inode_pages(inode->i_mapping);
1890         VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1891 }
1892
1893 static int do_verify(struct fsg_dev *fsg)
1894 {
1895         struct lun              *curlun = fsg->curlun;
1896         u32                     lba;
1897         u32                     verification_length;
1898         struct fsg_buffhd       *bh = fsg->next_buffhd_to_fill;
1899         loff_t                  file_offset, file_offset_tmp;
1900         u32                     amount_left;
1901         unsigned int            amount;
1902         ssize_t                 nread;
1903
1904         /* Get the starting Logical Block Address and check that it's
1905          * not too big */
1906         lba = get_be32(&fsg->cmnd[2]);
1907         if (lba >= curlun->num_sectors) {
1908                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1909                 return -EINVAL;
1910         }
1911
1912         /* We allow DPO (Disable Page Out = don't save data in the
1913          * cache) but we don't implement it. */
1914         if ((fsg->cmnd[1] & ~0x10) != 0) {
1915                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1916                 return -EINVAL;
1917         }
1918
1919         verification_length = get_be16(&fsg->cmnd[7]);
1920         if (unlikely(verification_length == 0))
1921                 return -EIO;            // No default reply
1922
1923         /* Prepare to carry out the file verify */
1924         amount_left = verification_length << 9;
1925         file_offset = ((loff_t) lba) << 9;
1926
1927         /* Write out all the dirty buffers before invalidating them */
1928         fsync_sub(curlun);
1929         if (signal_pending(current))
1930                 return -EINTR;
1931
1932         invalidate_sub(curlun);
1933         if (signal_pending(current))
1934                 return -EINTR;
1935
1936         /* Just try to read the requested blocks */
1937         while (amount_left > 0) {
1938
1939                 /* Figure out how much we need to read:
1940                  * Try to read the remaining amount, but not more than
1941                  * the buffer size.
1942                  * And don't try to read past the end of the file.
1943                  * If this means reading 0 then we were asked to read
1944                  * past the end of file. */
1945                 amount = min((unsigned int) amount_left, mod_data.buflen);
1946                 amount = min((loff_t) amount,
1947                                 curlun->file_length - file_offset);
1948                 if (amount == 0) {
1949                         curlun->sense_data =
1950                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1951                         curlun->sense_data_info = file_offset >> 9;
1952                         break;
1953                 }
1954
1955                 /* Perform the read */
1956                 file_offset_tmp = file_offset;
1957                 nread = vfs_read(curlun->filp,
1958                                 (char __user *) bh->buf,
1959                                 amount, &file_offset_tmp);
1960                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1961                                 (unsigned long long) file_offset,
1962                                 (int) nread);
1963                 if (signal_pending(current))
1964                         return -EINTR;
1965
1966                 if (nread < 0) {
1967                         LDBG(curlun, "error in file verify: %d\n",
1968                                         (int) nread);
1969                         nread = 0;
1970                 } else if (nread < amount) {
1971                         LDBG(curlun, "partial file verify: %d/%u\n",
1972                                         (int) nread, amount);
1973                         nread -= (nread & 511); // Round down to a sector
1974                 }
1975                 if (nread == 0) {
1976                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1977                         curlun->sense_data_info = file_offset >> 9;
1978                         break;
1979                 }
1980                 file_offset += nread;
1981                 amount_left -= nread;
1982         }
1983         return 0;
1984 }
1985
1986
1987 /*-------------------------------------------------------------------------*/
1988
1989 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1990 {
1991         u8      *buf = (u8 *) bh->buf;
1992
1993         static char vendor_id[] = "Linux   ";
1994         static char product_id[] = "File-Stor Gadget";
1995
1996         if (!fsg->curlun) {             // Unsupported LUNs are okay
1997                 fsg->bad_lun_okay = 1;
1998                 memset(buf, 0, 36);
1999                 buf[0] = 0x7f;          // Unsupported, no device-type
2000                 return 36;
2001         }
2002
2003         memset(buf, 0, 8);      // Non-removable, direct-access device
2004         if (mod_data.removable)
2005                 buf[1] = 0x80;
2006         buf[2] = 2;             // ANSI SCSI level 2
2007         buf[3] = 2;             // SCSI-2 INQUIRY data format
2008         buf[4] = 31;            // Additional length
2009                                 // No special options
2010         sprintf(buf + 8, "%-8s%-16s%04x", vendor_id, product_id,
2011                         mod_data.release);
2012         return 36;
2013 }
2014
2015
2016 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2017 {
2018         struct lun      *curlun = fsg->curlun;
2019         u8              *buf = (u8 *) bh->buf;
2020         u32             sd, sdinfo;
2021
2022         /*
2023          * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2024          *
2025          * If a REQUEST SENSE command is received from an initiator
2026          * with a pending unit attention condition (before the target
2027          * generates the contingent allegiance condition), then the
2028          * target shall either:
2029          *   a) report any pending sense data and preserve the unit
2030          *      attention condition on the logical unit, or,
2031          *   b) report the unit attention condition, may discard any
2032          *      pending sense data, and clear the unit attention
2033          *      condition on the logical unit for that initiator.
2034          *
2035          * FSG normally uses option a); enable this code to use option b).
2036          */
2037 #if 0
2038         if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2039                 curlun->sense_data = curlun->unit_attention_data;
2040                 curlun->unit_attention_data = SS_NO_SENSE;
2041         }
2042 #endif
2043
2044         if (!curlun) {          // Unsupported LUNs are okay
2045                 fsg->bad_lun_okay = 1;
2046                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2047                 sdinfo = 0;
2048         } else {
2049                 sd = curlun->sense_data;
2050                 sdinfo = curlun->sense_data_info;
2051                 curlun->sense_data = SS_NO_SENSE;
2052                 curlun->sense_data_info = 0;
2053         }
2054
2055         memset(buf, 0, 18);
2056         buf[0] = 0x80 | 0x70;                   // Valid, current error
2057         buf[2] = SK(sd);
2058         put_be32(&buf[3], sdinfo);              // Sense information
2059         buf[7] = 18 - 8;                        // Additional sense length
2060         buf[12] = ASC(sd);
2061         buf[13] = ASCQ(sd);
2062         return 18;
2063 }
2064
2065
2066 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2067 {
2068         struct lun      *curlun = fsg->curlun;
2069         u32             lba = get_be32(&fsg->cmnd[2]);
2070         int             pmi = fsg->cmnd[8];
2071         u8              *buf = (u8 *) bh->buf;
2072
2073         /* Check the PMI and LBA fields */
2074         if (pmi > 1 || (pmi == 0 && lba != 0)) {
2075                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2076                 return -EINVAL;
2077         }
2078
2079         put_be32(&buf[0], curlun->num_sectors - 1);     // Max logical block
2080         put_be32(&buf[4], 512);                         // Block length
2081         return 8;
2082 }
2083
2084
2085 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2086 {
2087         struct lun      *curlun = fsg->curlun;
2088         int             mscmnd = fsg->cmnd[0];
2089         u8              *buf = (u8 *) bh->buf;
2090         u8              *buf0 = buf;
2091         int             pc, page_code;
2092         int             changeable_values, all_pages;
2093         int             valid_page = 0;
2094         int             len, limit;
2095
2096         if ((fsg->cmnd[1] & ~0x08) != 0) {              // Mask away DBD
2097                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2098                 return -EINVAL;
2099         }
2100         pc = fsg->cmnd[2] >> 6;
2101         page_code = fsg->cmnd[2] & 0x3f;
2102         if (pc == 3) {
2103                 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2104                 return -EINVAL;
2105         }
2106         changeable_values = (pc == 1);
2107         all_pages = (page_code == 0x3f);
2108
2109         /* Write the mode parameter header.  Fixed values are: default
2110          * medium type, no cache control (DPOFUA), and no block descriptors.
2111          * The only variable value is the WriteProtect bit.  We will fill in
2112          * the mode data length later. */
2113         memset(buf, 0, 8);
2114         if (mscmnd == SC_MODE_SENSE_6) {
2115                 buf[2] = (curlun->ro ? 0x80 : 0x00);            // WP, DPOFUA
2116                 buf += 4;
2117                 limit = 255;
2118         } else {                        // SC_MODE_SENSE_10
2119                 buf[3] = (curlun->ro ? 0x80 : 0x00);            // WP, DPOFUA
2120                 buf += 8;
2121                 limit = 65535;          // Should really be mod_data.buflen
2122         }
2123
2124         /* No block descriptors */
2125
2126         /* The mode pages, in numerical order.  The only page we support
2127          * is the Caching page. */
2128         if (page_code == 0x08 || all_pages) {
2129                 valid_page = 1;
2130                 buf[0] = 0x08;          // Page code
2131                 buf[1] = 10;            // Page length
2132                 memset(buf+2, 0, 10);   // None of the fields are changeable
2133
2134                 if (!changeable_values) {
2135                         buf[2] = 0x04;  // Write cache enable,
2136                                         // Read cache not disabled
2137                                         // No cache retention priorities
2138                         put_be16(&buf[4], 0xffff);  // Don't disable prefetch
2139                                         // Minimum prefetch = 0
2140                         put_be16(&buf[8], 0xffff);  // Maximum prefetch
2141                         put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2142                 }
2143                 buf += 12;
2144         }
2145
2146         /* Check that a valid page was requested and the mode data length
2147          * isn't too long. */
2148         len = buf - buf0;
2149         if (!valid_page || len > limit) {
2150                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2151                 return -EINVAL;
2152         }
2153
2154         /*  Store the mode data length */
2155         if (mscmnd == SC_MODE_SENSE_6)
2156                 buf0[0] = len - 1;
2157         else
2158                 put_be16(buf0, len - 2);
2159         return len;
2160 }
2161
2162
2163 static int do_start_stop(struct fsg_dev *fsg)
2164 {
2165         struct lun      *curlun = fsg->curlun;
2166         int             loej, start;
2167
2168         if (!mod_data.removable) {
2169                 curlun->sense_data = SS_INVALID_COMMAND;
2170                 return -EINVAL;
2171         }
2172
2173         // int immed = fsg->cmnd[1] & 0x01;
2174         loej = fsg->cmnd[4] & 0x02;
2175         start = fsg->cmnd[4] & 0x01;
2176
2177 #ifdef CONFIG_USB_FILE_STORAGE_TEST
2178         if ((fsg->cmnd[1] & ~0x01) != 0 ||              // Mask away Immed
2179                         (fsg->cmnd[4] & ~0x03) != 0) {  // Mask LoEj, Start
2180                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2181                 return -EINVAL;
2182         }
2183
2184         if (!start) {
2185
2186                 /* Are we allowed to unload the media? */
2187                 if (curlun->prevent_medium_removal) {
2188                         LDBG(curlun, "unload attempt prevented\n");
2189                         curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2190                         return -EINVAL;
2191                 }
2192                 if (loej) {             // Simulate an unload/eject
2193                         up_read(&fsg->filesem);
2194                         down_write(&fsg->filesem);
2195                         close_backing_file(curlun);
2196                         up_write(&fsg->filesem);
2197                         down_read(&fsg->filesem);
2198                 }
2199         } else {
2200
2201                 /* Our emulation doesn't support mounting; the medium is
2202                  * available for use as soon as it is loaded. */
2203                 if (!backing_file_is_open(curlun)) {
2204                         curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2205                         return -EINVAL;
2206                 }
2207         }
2208 #endif
2209         return 0;
2210 }
2211
2212
2213 static int do_prevent_allow(struct fsg_dev *fsg)
2214 {
2215         struct lun      *curlun = fsg->curlun;
2216         int             prevent;
2217
2218         if (!mod_data.removable) {
2219                 curlun->sense_data = SS_INVALID_COMMAND;
2220                 return -EINVAL;
2221         }
2222
2223         prevent = fsg->cmnd[4] & 0x01;
2224         if ((fsg->cmnd[4] & ~0x01) != 0) {              // Mask away Prevent
2225                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2226                 return -EINVAL;
2227         }
2228
2229         if (curlun->prevent_medium_removal && !prevent)
2230                 fsync_sub(curlun);
2231         curlun->prevent_medium_removal = prevent;
2232         return 0;
2233 }
2234
2235
2236 static int do_read_format_capacities(struct fsg_dev *fsg,
2237                         struct fsg_buffhd *bh)
2238 {
2239         struct lun      *curlun = fsg->curlun;
2240         u8              *buf = (u8 *) bh->buf;
2241
2242         buf[0] = buf[1] = buf[2] = 0;
2243         buf[3] = 8;             // Only the Current/Maximum Capacity Descriptor
2244         buf += 4;
2245
2246         put_be32(&buf[0], curlun->num_sectors);         // Number of blocks
2247         put_be32(&buf[4], 512);                         // Block length
2248         buf[4] = 0x02;                                  // Current capacity
2249         return 12;
2250 }
2251
2252
2253 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2254 {
2255         struct lun      *curlun = fsg->curlun;
2256
2257         /* We don't support MODE SELECT */
2258         curlun->sense_data = SS_INVALID_COMMAND;
2259         return -EINVAL;
2260 }
2261
2262
2263 /*-------------------------------------------------------------------------*/
2264
2265 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2266 {
2267         int     rc;
2268
2269         rc = fsg_set_halt(fsg, fsg->bulk_in);
2270         if (rc == -EAGAIN)
2271                 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2272         while (rc != 0) {
2273                 if (rc != -EAGAIN) {
2274                         WARN(fsg, "usb_ep_set_halt -> %d\n", rc);
2275                         rc = 0;
2276                         break;
2277                 }
2278
2279                 /* Wait for a short time and then try again */
2280                 set_current_state(TASK_INTERRUPTIBLE);
2281                 if (schedule_timeout(HZ / 10) != 0)
2282                         return -EINTR;
2283                 rc = usb_ep_set_halt(fsg->bulk_in);
2284         }
2285         return rc;
2286 }
2287
2288 static int pad_with_zeros(struct fsg_dev *fsg)
2289 {
2290         struct fsg_buffhd       *bh = fsg->next_buffhd_to_fill;
2291         u32                     nkeep = bh->inreq->length;
2292         u32                     nsend;
2293         int                     rc;
2294
2295         bh->state = BUF_STATE_EMPTY;            // For the first iteration
2296         fsg->usb_amount_left = nkeep + fsg->residue;
2297         while (fsg->usb_amount_left > 0) {
2298
2299                 /* Wait for the next buffer to be free */
2300                 while (bh->state != BUF_STATE_EMPTY) {
2301                         if ((rc = sleep_thread(fsg)) != 0)
2302                                 return rc;
2303                 }
2304
2305                 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2306                 memset(bh->buf + nkeep, 0, nsend - nkeep);
2307                 bh->inreq->length = nsend;
2308                 bh->inreq->zero = 0;
2309                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2310                                 &bh->inreq_busy, &bh->state);
2311                 bh = fsg->next_buffhd_to_fill = bh->next;
2312                 fsg->usb_amount_left -= nsend;
2313                 nkeep = 0;
2314         }
2315         return 0;
2316 }
2317
2318 static int throw_away_data(struct fsg_dev *fsg)
2319 {
2320         struct fsg_buffhd       *bh;
2321         u32                     amount;
2322         int                     rc;
2323
2324         while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2325                         fsg->usb_amount_left > 0) {
2326
2327                 /* Throw away the data in a filled buffer */
2328                 if (bh->state == BUF_STATE_FULL) {
2329                         bh->state = BUF_STATE_EMPTY;
2330                         fsg->next_buffhd_to_drain = bh->next;
2331
2332                         /* A short packet or an error ends everything */
2333                         if (bh->outreq->actual != bh->outreq->length ||
2334                                         bh->outreq->status != 0) {
2335                                 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2336                                 return -EINTR;
2337                         }
2338                         continue;
2339                 }
2340
2341                 /* Try to submit another request if we need one */
2342                 bh = fsg->next_buffhd_to_fill;
2343                 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2344                         amount = min(fsg->usb_amount_left,
2345                                         (u32) mod_data.buflen);
2346
2347                         /* amount is always divisible by 512, hence by
2348                          * the bulk-out maxpacket size */
2349                         bh->outreq->length = bh->bulk_out_intended_length =
2350                                         amount;
2351                         start_transfer(fsg, fsg->bulk_out, bh->outreq,
2352                                         &bh->outreq_busy, &bh->state);
2353                         fsg->next_buffhd_to_fill = bh->next;
2354                         fsg->usb_amount_left -= amount;
2355                         continue;
2356                 }
2357
2358                 /* Otherwise wait for something to happen */
2359                 if ((rc = sleep_thread(fsg)) != 0)
2360                         return rc;
2361         }
2362         return 0;
2363 }
2364
2365
2366 static int finish_reply(struct fsg_dev *fsg)
2367 {
2368         struct fsg_buffhd       *bh = fsg->next_buffhd_to_fill;
2369         int                     rc = 0;
2370
2371         switch (fsg->data_dir) {
2372         case DATA_DIR_NONE:
2373                 break;                  // Nothing to send
2374
2375         /* If we don't know whether the host wants to read or write,
2376          * this must be CB or CBI with an unknown command.  We mustn't
2377          * try to send or receive any data.  So stall both bulk pipes
2378          * if we can and wait for a reset. */
2379         case DATA_DIR_UNKNOWN:
2380                 if (mod_data.can_stall) {
2381                         fsg_set_halt(fsg, fsg->bulk_out);
2382                         rc = halt_bulk_in_endpoint(fsg);
2383                 }
2384                 break;
2385
2386         /* All but the last buffer of data must have already been sent */
2387         case DATA_DIR_TO_HOST:
2388                 if (fsg->data_size == 0)
2389                         ;               // Nothing to send
2390
2391                 /* If there's no residue, simply send the last buffer */
2392                 else if (fsg->residue == 0) {
2393                         bh->inreq->zero = 0;
2394                         start_transfer(fsg, fsg->bulk_in, bh->inreq,
2395                                         &bh->inreq_busy, &bh->state);
2396                         fsg->next_buffhd_to_fill = bh->next;
2397                 }
2398
2399                 /* There is a residue.  For CB and CBI, simply mark the end
2400                  * of the data with a short packet.  However, if we are
2401                  * allowed to stall, there was no data at all (residue ==
2402                  * data_size), and the command failed (invalid LUN or
2403                  * sense data is set), then halt the bulk-in endpoint
2404                  * instead. */
2405                 else if (!transport_is_bbb()) {
2406                         if (mod_data.can_stall &&
2407                                         fsg->residue == fsg->data_size &&
2408         (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2409                                 bh->state = BUF_STATE_EMPTY;
2410                                 rc = halt_bulk_in_endpoint(fsg);
2411                         } else {
2412                                 bh->inreq->zero = 1;
2413                                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2414                                                 &bh->inreq_busy, &bh->state);
2415                                 fsg->next_buffhd_to_fill = bh->next;
2416                         }
2417                 }
2418
2419                 /* For Bulk-only, if we're allowed to stall then send the
2420                  * short packet and halt the bulk-in endpoint.  If we can't
2421                  * stall, pad out the remaining data with 0's. */
2422                 else {
2423                         if (mod_data.can_stall) {
2424                                 bh->inreq->zero = 1;
2425                                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2426                                                 &bh->inreq_busy, &bh->state);
2427                                 fsg->next_buffhd_to_fill = bh->next;
2428                                 rc = halt_bulk_in_endpoint(fsg);
2429                         } else
2430                                 rc = pad_with_zeros(fsg);
2431                 }
2432                 break;
2433
2434         /* We have processed all we want from the data the host has sent.
2435          * There may still be outstanding bulk-out requests. */
2436         case DATA_DIR_FROM_HOST:
2437                 if (fsg->residue == 0)
2438                         ;               // Nothing to receive
2439
2440                 /* Did the host stop sending unexpectedly early? */
2441                 else if (fsg->short_packet_received) {
2442                         raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2443                         rc = -EINTR;
2444                 }
2445
2446                 /* We haven't processed all the incoming data.  If we are
2447                  * allowed to stall, halt the bulk-out endpoint and cancel
2448                  * any outstanding requests. */
2449                 else if (mod_data.can_stall) {
2450                         fsg_set_halt(fsg, fsg->bulk_out);
2451                         raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2452                         rc = -EINTR;
2453                 }
2454
2455                 /* We can't stall.  Read in the excess data and throw it
2456                  * all away. */
2457                 else
2458                         rc = throw_away_data(fsg);
2459                 break;
2460         }
2461         return rc;
2462 }
2463
2464
2465 static int send_status(struct fsg_dev *fsg)
2466 {
2467         struct lun              *curlun = fsg->curlun;
2468         struct fsg_buffhd       *bh;
2469         int                     rc;
2470         u8                      status = USB_STATUS_PASS;
2471         u32                     sd, sdinfo = 0;
2472
2473         /* Wait for the next buffer to become available */
2474         bh = fsg->next_buffhd_to_fill;
2475         while (bh->state != BUF_STATE_EMPTY) {
2476                 if ((rc = sleep_thread(fsg)) != 0)
2477                         return rc;
2478         }
2479
2480         if (curlun) {
2481                 sd = curlun->sense_data;
2482                 sdinfo = curlun->sense_data_info;
2483         } else if (fsg->bad_lun_okay)
2484                 sd = SS_NO_SENSE;
2485         else
2486                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2487
2488         if (fsg->phase_error) {
2489                 DBG(fsg, "sending phase-error status\n");
2490                 status = USB_STATUS_PHASE_ERROR;
2491                 sd = SS_INVALID_COMMAND;
2492         } else if (sd != SS_NO_SENSE) {
2493                 DBG(fsg, "sending command-failure status\n");
2494                 status = USB_STATUS_FAIL;
2495                 VDBG(fsg, "  sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2496                                 "  info x%x\n",
2497                                 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2498         }
2499
2500         if (transport_is_bbb()) {
2501                 struct bulk_cs_wrap     *csw = (struct bulk_cs_wrap *) bh->buf;
2502
2503                 /* Store and send the Bulk-only CSW */
2504                 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
2505                 csw->Tag = fsg->tag;
2506                 csw->Residue = cpu_to_le32(fsg->residue);
2507                 csw->Status = status;
2508
2509                 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2510                 bh->inreq->zero = 0;
2511                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2512                                 &bh->inreq_busy, &bh->state);
2513
2514         } else if (mod_data.transport_type == USB_PR_CB) {
2515
2516                 /* Control-Bulk transport has no status stage! */
2517                 return 0;
2518
2519         } else {                        // USB_PR_CBI
2520                 struct interrupt_data   *buf = (struct interrupt_data *)
2521                                                 bh->buf;
2522
2523                 /* Store and send the Interrupt data.  UFI sends the ASC
2524                  * and ASCQ bytes.  Everything else sends a Type (which
2525                  * is always 0) and the status Value. */
2526                 if (mod_data.protocol_type == USB_SC_UFI) {
2527                         buf->bType = ASC(sd);
2528                         buf->bValue = ASCQ(sd);
2529                 } else {
2530                         buf->bType = 0;
2531                         buf->bValue = status;
2532                 }
2533                 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2534
2535                 fsg->intr_buffhd = bh;          // Point to the right buffhd
2536                 fsg->intreq->buf = bh->inreq->buf;
2537                 fsg->intreq->dma = bh->inreq->dma;
2538                 fsg->intreq->context = bh;
2539                 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2540                                 &fsg->intreq_busy, &bh->state);
2541         }
2542
2543         fsg->next_buffhd_to_fill = bh->next;
2544         return 0;
2545 }
2546
2547
2548 /*-------------------------------------------------------------------------*/
2549
2550 /* Check whether the command is properly formed and whether its data size
2551  * and direction agree with the values we already have. */
2552 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2553                 enum data_direction data_dir, unsigned int mask,
2554                 int needs_medium, const char *name)
2555 {
2556         int                     i;
2557         int                     lun = fsg->cmnd[1] >> 5;
2558         static const char       dirletter[4] = {'u', 'o', 'i', 'n'};
2559         char                    hdlen[20];
2560         struct lun              *curlun;
2561
2562         /* Adjust the expected cmnd_size for protocol encapsulation padding.
2563          * Transparent SCSI doesn't pad. */
2564         if (protocol_is_scsi())
2565                 ;
2566
2567         /* There's some disagreement as to whether RBC pads commands or not.
2568          * We'll play it safe and accept either form. */
2569         else if (mod_data.protocol_type == USB_SC_RBC) {
2570                 if (fsg->cmnd_size == 12)
2571                         cmnd_size = 12;
2572
2573         /* All the other protocols pad to 12 bytes */
2574         } else
2575                 cmnd_size = 12;
2576
2577         hdlen[0] = 0;
2578         if (fsg->data_dir != DATA_DIR_UNKNOWN)
2579                 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2580                                 fsg->data_size);
2581         VDBG(fsg, "SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
2582                         name, cmnd_size, dirletter[(int) data_dir],
2583                         fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2584
2585         /* We can't reply at all until we know the correct data direction
2586          * and size. */
2587         if (fsg->data_size_from_cmnd == 0)
2588                 data_dir = DATA_DIR_NONE;
2589         if (fsg->data_dir == DATA_DIR_UNKNOWN) {        // CB or CBI
2590                 fsg->data_dir = data_dir;
2591                 fsg->data_size = fsg->data_size_from_cmnd;
2592
2593         } else {                                        // Bulk-only
2594                 if (fsg->data_size < fsg->data_size_from_cmnd) {
2595
2596                         /* Host data size < Device data size is a phase error.
2597                          * Carry out the command, but only transfer as much
2598                          * as we are allowed. */
2599                         fsg->data_size_from_cmnd = fsg->data_size;
2600                         fsg->phase_error = 1;
2601                 }
2602         }
2603         fsg->residue = fsg->usb_amount_left = fsg->data_size;
2604
2605         /* Conflicting data directions is a phase error */
2606         if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0)
2607                 goto phase_error;
2608
2609         /* Verify the length of the command itself */
2610         if (cmnd_size != fsg->cmnd_size) {
2611
2612                 /* Special case workaround: MS-Windows issues REQUEST SENSE
2613                  * with cbw->Length == 12 (it should be 6). */
2614                 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
2615                         cmnd_size = fsg->cmnd_size;
2616                 else
2617                         goto phase_error;
2618         }
2619
2620         /* Check that the LUN values are oonsistent */
2621         if (transport_is_bbb()) {
2622                 if (fsg->lun != lun)
2623                         DBG(fsg, "using LUN %d from CBW, "
2624                                         "not LUN %d from CDB\n",
2625                                         fsg->lun, lun);
2626         } else
2627                 fsg->lun = lun;         // Use LUN from the command
2628
2629         /* Check the LUN */
2630         if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2631                 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2632                 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2633                         curlun->sense_data = SS_NO_SENSE;
2634                         curlun->sense_data_info = 0;
2635                 }
2636         } else {
2637                 fsg->curlun = curlun = NULL;
2638                 fsg->bad_lun_okay = 0;
2639
2640                 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2641                  * to use unsupported LUNs; all others may not. */
2642                 if (fsg->cmnd[0] != SC_INQUIRY &&
2643                                 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2644                         DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2645                         return -EINVAL;
2646                 }
2647         }
2648
2649         /* If a unit attention condition exists, only INQUIRY and
2650          * REQUEST SENSE commands are allowed; anything else must fail. */
2651         if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2652                         fsg->cmnd[0] != SC_INQUIRY &&
2653                         fsg->cmnd[0] != SC_REQUEST_SENSE) {
2654                 curlun->sense_data = curlun->unit_attention_data;
2655                 curlun->unit_attention_data = SS_NO_SENSE;
2656                 return -EINVAL;
2657         }
2658
2659         /* Check that only command bytes listed in the mask are non-zero */
2660         fsg->cmnd[1] &= 0x1f;                   // Mask away the LUN
2661         for (i = 1; i < cmnd_size; ++i) {
2662                 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2663                         if (curlun)
2664                                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2665                         return -EINVAL;
2666                 }
2667         }
2668
2669         /* If the medium isn't mounted and the command needs to access
2670          * it, return an error. */
2671         if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2672                 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2673                 return -EINVAL;
2674         }
2675
2676         return 0;
2677
2678 phase_error:
2679         fsg->phase_error = 1;
2680         return -EINVAL;
2681 }
2682
2683
2684 static int do_scsi_command(struct fsg_dev *fsg)
2685 {
2686         struct fsg_buffhd       *bh;
2687         int                     rc;
2688         int                     reply = -EINVAL;
2689         int                     i;
2690         static char             unknown[16];
2691
2692         dump_cdb(fsg);
2693
2694         /* Wait for the next buffer to become available for data or status */
2695         bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2696         while (bh->state != BUF_STATE_EMPTY) {
2697                 if ((rc = sleep_thread(fsg)) != 0)
2698                         return rc;
2699                 }
2700         fsg->phase_error = 0;
2701         fsg->short_packet_received = 0;
2702
2703         down_read(&fsg->filesem);       // We're using the backing file
2704         switch (fsg->cmnd[0]) {
2705
2706         case SC_INQUIRY:
2707                 fsg->data_size_from_cmnd = fsg->cmnd[4];
2708                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2709                                 (1<<4), 0,
2710                                 "INQUIRY")) == 0)
2711                         reply = do_inquiry(fsg, bh);
2712                 break;
2713
2714         case SC_MODE_SELECT_6:
2715                 fsg->data_size_from_cmnd = fsg->cmnd[4];
2716                 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2717                                 (1<<1) | (1<<4), 0,
2718                                 "MODE SELECT(6)")) == 0)
2719                         reply = do_mode_select(fsg, bh);
2720                 break;
2721
2722         case SC_MODE_SELECT_10:
2723                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2724                 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2725                                 (1<<1) | (3<<7), 0,
2726                                 "MODE SELECT(10)")) == 0)
2727                         reply = do_mode_select(fsg, bh);
2728                 break;
2729
2730         case SC_MODE_SENSE_6:
2731                 fsg->data_size_from_cmnd = fsg->cmnd[4];
2732                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2733                                 (1<<1) | (1<<2) | (1<<4), 0,
2734                                 "MODE SENSE(6)")) == 0)
2735                         reply = do_mode_sense(fsg, bh);
2736                 break;
2737
2738         case SC_MODE_SENSE_10:
2739                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2740                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2741                                 (1<<1) | (1<<2) | (3<<7), 0,
2742                                 "MODE SENSE(10)")) == 0)
2743                         reply = do_mode_sense(fsg, bh);
2744                 break;
2745
2746         case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2747                 fsg->data_size_from_cmnd = 0;
2748                 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2749                                 (1<<4), 0,
2750                                 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2751                         reply = do_prevent_allow(fsg);
2752                 break;
2753
2754         case SC_READ_6:
2755                 i = fsg->cmnd[4];
2756                 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2757                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2758                                 (7<<1) | (1<<4), 1,
2759                                 "READ(6)")) == 0)
2760                         reply = do_read(fsg);
2761                 break;
2762
2763         case SC_READ_10:
2764                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2765                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2766                                 (1<<1) | (0xf<<2) | (3<<7), 1,
2767                                 "READ(10)")) == 0)
2768                         reply = do_read(fsg);
2769                 break;
2770
2771         case SC_READ_12:
2772                 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2773                 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2774                                 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2775                                 "READ(12)")) == 0)
2776                         reply = do_read(fsg);
2777                 break;
2778
2779         case SC_READ_CAPACITY:
2780                 fsg->data_size_from_cmnd = 8;
2781                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2782                                 (0xf<<2) | (1<<8), 1,
2783                                 "READ CAPACITY")) == 0)
2784                         reply = do_read_capacity(fsg, bh);
2785                 break;
2786
2787         case SC_READ_FORMAT_CAPACITIES:
2788                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2789                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2790                                 (3<<7), 1,
2791                                 "READ FORMAT CAPACITIES")) == 0)
2792                         reply = do_read_format_capacities(fsg, bh);
2793                 break;
2794
2795         case SC_REQUEST_SENSE:
2796                 fsg->data_size_from_cmnd = fsg->cmnd[4];
2797                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2798                                 (1<<4), 0,
2799                                 "REQUEST SENSE")) == 0)
2800                         reply = do_request_sense(fsg, bh);
2801                 break;
2802
2803         case SC_START_STOP_UNIT:
2804                 fsg->data_size_from_cmnd = 0;
2805                 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2806                                 (1<<1) | (1<<4), 0,
2807                                 "START-STOP UNIT")) == 0)
2808                         reply = do_start_stop(fsg);
2809                 break;
2810
2811         case SC_SYNCHRONIZE_CACHE:
2812                 fsg->data_size_from_cmnd = 0;
2813                 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2814                                 (0xf<<2) | (3<<7), 1,
2815                                 "SYNCHRONIZE CACHE")) == 0)
2816                         reply = do_synchronize_cache(fsg);
2817                 break;
2818
2819         case SC_TEST_UNIT_READY:
2820                 fsg->data_size_from_cmnd = 0;
2821                 reply = check_command(fsg, 6, DATA_DIR_NONE,
2822                                 0, 1,
2823                                 "TEST UNIT READY");
2824                 break;
2825
2826         /* Although optional, this command is used by MS-Windows.  We
2827          * support a minimal version: BytChk must be 0. */
2828         case SC_VERIFY:
2829                 fsg->data_size_from_cmnd = 0;
2830                 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2831                                 (1<<1) | (0xf<<2) | (3<<7), 1,
2832                                 "VERIFY")) == 0)
2833                         reply = do_verify(fsg);
2834                 break;
2835
2836         case SC_WRITE_6:
2837                 i = fsg->cmnd[4];
2838                 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2839                 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2840                                 (7<<1) | (1<<4), 1,
2841                                 "WRITE(6)")) == 0)
2842                         reply = do_write(fsg);
2843                 break;
2844
2845         case SC_WRITE_10:
2846                 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2847                 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2848                                 (1<<1) | (0xf<<2) | (3<<7), 1,
2849                                 "WRITE(10)")) == 0)
2850                         reply = do_write(fsg);
2851                 break;
2852
2853         case SC_WRITE_12:
2854                 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2855                 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2856                                 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2857                                 "WRITE(12)")) == 0)
2858                         reply = do_write(fsg);
2859                 break;
2860
2861         /* Some mandatory commands that we recognize but don't implement.
2862          * They don't mean much in this setting.  It's left as an exercise
2863          * for anyone interested to implement RESERVE and RELEASE in terms
2864          * of Posix locks. */
2865         case SC_FORMAT_UNIT:
2866         case SC_RELEASE:
2867         case SC_RESERVE:
2868         case SC_SEND_DIAGNOSTIC:
2869                 // Fall through
2870
2871         default:
2872                 fsg->data_size_from_cmnd = 0;
2873                 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2874                 if ((reply = check_command(fsg, fsg->cmnd_size,
2875                                 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2876                         fsg->curlun->sense_data = SS_INVALID_COMMAND;
2877                         reply = -EINVAL;
2878                 }
2879                 break;
2880         }
2881         up_read(&fsg->filesem);
2882
2883         if (reply == -EINTR || signal_pending(current))
2884                 return -EINTR;
2885
2886         /* Set up the single reply buffer for finish_reply() */
2887         if (reply == -EINVAL)
2888                 reply = 0;              // Error reply length
2889         if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2890                 reply = min((u32) reply, fsg->data_size_from_cmnd);
2891                 bh->inreq->length = reply;
2892                 bh->state = BUF_STATE_FULL;
2893                 fsg->residue -= reply;
2894         }                               // Otherwise it's already set
2895
2896         return 0;
2897 }
2898
2899
2900 /*-------------------------------------------------------------------------*/
2901
2902 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2903 {
2904         struct usb_request      *req = bh->outreq;
2905         struct bulk_cb_wrap     *cbw = (struct bulk_cb_wrap *) req->buf;
2906
2907         /* Was this a real packet? */
2908         if (req->status)
2909                 return -EINVAL;
2910
2911         /* Is the CBW valid? */
2912         if (req->actual != USB_BULK_CB_WRAP_LEN ||
2913                         cbw->Signature != __constant_cpu_to_le32(
2914                                 USB_BULK_CB_SIG)) {
2915                 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2916                                 req->actual,
2917                                 le32_to_cpu(cbw->Signature));
2918
2919                 /* The Bulk-only spec says we MUST stall the bulk pipes!
2920                  * If we want to avoid stalls, set a flag so that we will
2921                  * clear the endpoint halts at the next reset. */
2922                 if (!mod_data.can_stall)
2923                         set_bit(CLEAR_BULK_HALTS, &fsg->atomic_bitflags);
2924                 fsg_set_halt(fsg, fsg->bulk_out);
2925                 halt_bulk_in_endpoint(fsg);
2926                 return -EINVAL;
2927         }
2928
2929         /* Is the CBW meaningful? */
2930         if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2931                         cbw->Length < 6 || cbw->Length > MAX_COMMAND_SIZE) {
2932                 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2933                                 "cmdlen %u\n",
2934                                 cbw->Lun, cbw->Flags, cbw->Length);
2935
2936                 /* We can do anything we want here, so let's stall the
2937                  * bulk pipes if we are allowed to. */
2938                 if (mod_data.can_stall) {
2939                         fsg_set_halt(fsg, fsg->bulk_out);
2940                         halt_bulk_in_endpoint(fsg);
2941                 }
2942                 return -EINVAL;
2943         }
2944
2945         /* Save the command for later */
2946         fsg->cmnd_size = cbw->Length;
2947         memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2948         if (cbw->Flags & USB_BULK_IN_FLAG)
2949                 fsg->data_dir = DATA_DIR_TO_HOST;
2950         else
2951                 fsg->data_dir = DATA_DIR_FROM_HOST;
2952         fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2953         if (fsg->data_size == 0)
2954                 fsg->data_dir = DATA_DIR_NONE;
2955         fsg->lun = cbw->Lun;
2956         fsg->tag = cbw->Tag;
2957         return 0;
2958 }
2959
2960
2961 static int get_next_command(struct fsg_dev *fsg)
2962 {
2963         struct fsg_buffhd       *bh;
2964         int                     rc = 0;
2965
2966         if (transport_is_bbb()) {
2967
2968                 /* Wait for the next buffer to become available */
2969                 bh = fsg->next_buffhd_to_fill;
2970                 while (bh->state != BUF_STATE_EMPTY) {
2971                         if ((rc = sleep_thread(fsg)) != 0)
2972                                 return rc;
2973                         }
2974
2975                 /* Queue a request to read a Bulk-only CBW */
2976                 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2977                 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2978                                 &bh->outreq_busy, &bh->state);
2979
2980                 /* We will drain the buffer in software, which means we
2981                  * can reuse it for the next filling.  No need to advance
2982                  * next_buffhd_to_fill. */
2983
2984                 /* Wait for the CBW to arrive */
2985                 while (bh->state != BUF_STATE_FULL) {
2986                         if ((rc = sleep_thread(fsg)) != 0)
2987                                 return rc;
2988                         }
2989                 rc = received_cbw(fsg, bh);
2990                 bh->state = BUF_STATE_EMPTY;
2991
2992         } else {                // USB_PR_CB or USB_PR_CBI
2993
2994                 /* Wait for the next command to arrive */
2995                 while (fsg->cbbuf_cmnd_size == 0) {
2996                         if ((rc = sleep_thread(fsg)) != 0)
2997                                 return rc;
2998                         }
2999
3000                 /* Is the previous status interrupt request still busy?
3001                  * The host is allowed to skip reading the status,
3002                  * so we must cancel it. */
3003                 if (fsg->intreq_busy)
3004                         usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3005
3006                 /* Copy the command and mark the buffer empty */
3007                 fsg->data_dir = DATA_DIR_UNKNOWN;
3008                 spin_lock_irq(&fsg->lock);
3009                 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3010                 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3011                 fsg->cbbuf_cmnd_size = 0;
3012                 spin_unlock_irq(&fsg->lock);
3013         }
3014         return rc;
3015 }
3016
3017
3018 /*-------------------------------------------------------------------------*/
3019
3020 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3021                 const struct usb_endpoint_descriptor *d)
3022 {
3023         int     rc;
3024
3025         ep->driver_data = fsg;
3026         rc = usb_ep_enable(ep, d);
3027         if (rc)
3028                 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3029         return rc;
3030 }
3031
3032 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3033                 struct usb_request **preq)
3034 {
3035         *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3036         if (*preq)
3037                 return 0;
3038         ERROR(fsg, "can't allocate request for %s\n", ep->name);
3039         return -ENOMEM;
3040 }
3041
3042 /*
3043  * Reset interface setting and re-init endpoint state (toggle etc).
3044  * Call with altsetting < 0 to disable the interface.  The only other
3045  * available altsetting is 0, which enables the interface.
3046  */
3047 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3048 {
3049         int     rc = 0;
3050         int     i;
3051         const struct usb_endpoint_descriptor    *d;
3052
3053         if (fsg->running)
3054                 DBG(fsg, "reset interface\n");
3055
3056 reset:
3057         /* Deallocate the requests */
3058         for (i = 0; i < NUM_BUFFERS; ++i) {
3059                 struct fsg_buffhd *bh = &fsg->buffhds[i];
3060
3061                 if (bh->inreq) {
3062                         usb_ep_free_request(fsg->bulk_in, bh->inreq);
3063                         bh->inreq = NULL;
3064                 }
3065                 if (bh->outreq) {
3066                         usb_ep_free_request(fsg->bulk_out, bh->outreq);
3067                         bh->outreq = NULL;
3068                 }
3069         }
3070         if (fsg->intreq) {
3071                 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3072                 fsg->intreq = NULL;
3073         }
3074
3075         /* Disable the endpoints */
3076         if (fsg->bulk_in_enabled) {
3077                 usb_ep_disable(fsg->bulk_in);
3078                 fsg->bulk_in_enabled = 0;
3079         }
3080         if (fsg->bulk_out_enabled) {
3081                 usb_ep_disable(fsg->bulk_out);
3082                 fsg->bulk_out_enabled = 0;
3083         }
3084         if (fsg->intr_in_enabled) {
3085                 usb_ep_disable(fsg->intr_in);
3086                 fsg->intr_in_enabled = 0;
3087         }
3088
3089         fsg->running = 0;
3090         if (altsetting < 0 || rc != 0)
3091                 return rc;
3092
3093         DBG(fsg, "set interface %d\n", altsetting);
3094
3095         /* Enable the endpoints */
3096         d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3097         if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3098                 goto reset;
3099         fsg->bulk_in_enabled = 1;
3100
3101         d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3102         if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3103                 goto reset;
3104         fsg->bulk_out_enabled = 1;
3105         fsg->bulk_out_maxpacket = d->wMaxPacketSize;
3106
3107         if (transport_is_cbi()) {
3108                 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3109                 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3110                         goto reset;
3111                 fsg->intr_in_enabled = 1;
3112         }
3113
3114         /* Allocate the requests */
3115         for (i = 0; i < NUM_BUFFERS; ++i) {
3116                 struct fsg_buffhd       *bh = &fsg->buffhds[i];
3117
3118                 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3119                         goto reset;
3120                 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3121                         goto reset;
3122                 bh->inreq->buf = bh->outreq->buf = bh->buf;
3123                 bh->inreq->dma = bh->outreq->dma = bh->dma;
3124                 bh->inreq->context = bh->outreq->context = bh;
3125                 bh->inreq->complete = bulk_in_complete;
3126                 bh->outreq->complete = bulk_out_complete;
3127         }
3128         if (transport_is_cbi()) {
3129                 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3130                         goto reset;
3131                 fsg->intreq->complete = intr_in_complete;
3132         }
3133
3134         fsg->running = 1;
3135         for (i = 0; i < fsg->nluns; ++i)
3136                 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3137         return rc;
3138 }
3139
3140
3141 /*
3142  * Change our operational configuration.  This code must agree with the code
3143  * that returns config descriptors, and with interface altsetting code.
3144  *
3145  * It's also responsible for power management interactions.  Some
3146  * configurations might not work with our current power sources.
3147  * For now we just assume the gadget is always self-powered.
3148  */
3149 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3150 {
3151         int     rc = 0;
3152
3153         /* Disable the single interface */
3154         if (fsg->config != 0) {
3155                 DBG(fsg, "reset config\n");
3156                 fsg->config = 0;
3157                 rc = do_set_interface(fsg, -1);
3158         }
3159
3160         /* Enable the interface */
3161         if (new_config != 0) {
3162                 fsg->config = new_config;
3163                 if ((rc = do_set_interface(fsg, 0)) != 0)
3164                         fsg->config = 0;        // Reset on errors
3165                 else {
3166                         char *speed;
3167
3168                         switch (fsg->gadget->speed) {
3169                         case USB_SPEED_LOW:     speed = "low";  break;
3170                         case USB_SPEED_FULL:    speed = "full"; break;
3171                         case USB_SPEED_HIGH:    speed = "high"; break;
3172                         default:                speed = "?";    break;
3173                         }
3174                         INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3175                 }
3176         }
3177         return rc;
3178 }
3179
3180
3181 /*-------------------------------------------------------------------------*/
3182
3183 static void handle_exception(struct fsg_dev *fsg)
3184 {
3185         siginfo_t               info;
3186         int                     sig;
3187         int                     i;
3188         int                     num_active;
3189         struct fsg_buffhd       *bh;
3190         enum fsg_state          old_state;
3191         u8                      new_config;
3192         struct lun              *curlun;
3193         unsigned int            exception_req_tag;
3194         int                     rc;
3195
3196         /* Clear the existing signals.  Anything but SIGUSR1 is converted
3197          * into a high-priority EXIT exception. */
3198         for (;;) {
3199                 sig = dequeue_signal_lock(current, &fsg->thread_signal_mask,
3200                                 &info);
3201                 if (!sig)
3202                         break;
3203                 if (sig != SIGUSR1) {
3204                         if (fsg->state < FSG_STATE_EXIT)
3205                                 DBG(fsg, "Main thread exiting on signal\n");
3206                         raise_exception(fsg, FSG_STATE_EXIT);
3207                 }
3208         }
3209
3210         /* Cancel all the pending transfers */
3211         if (fsg->intreq_busy)
3212                 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3213         for (i = 0; i < NUM_BUFFERS; ++i) {
3214                 bh = &fsg->buffhds[i];
3215                 if (bh->inreq_busy)
3216                         usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3217                 if (bh->outreq_busy)
3218                         usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3219         }
3220
3221         /* Wait until everything is idle */
3222         for (;;) {
3223                 num_active = fsg->intreq_busy;
3224                 for (i = 0; i < NUM_BUFFERS; ++i) {
3225                         bh = &fsg->buffhds[i];
3226                         num_active += bh->inreq_busy + bh->outreq_busy;
3227                 }
3228                 if (num_active == 0)
3229                         break;
3230                 if (sleep_thread(fsg))
3231                         return;
3232         }
3233
3234         /* Clear out the controller's fifos */
3235         if (fsg->bulk_in_enabled)
3236                 usb_ep_fifo_flush(fsg->bulk_in);
3237         if (fsg->bulk_out_enabled)
3238                 usb_ep_fifo_flush(fsg->bulk_out);
3239         if (fsg->intr_in_enabled)
3240                 usb_ep_fifo_flush(fsg->intr_in);
3241
3242         /* Reset the I/O buffer states and pointers, the SCSI
3243          * state, and the exception.  Then invoke the handler. */
3244         spin_lock_irq(&fsg->lock);
3245
3246         for (i = 0; i < NUM_BUFFERS; ++i) {
3247                 bh = &fsg->buffhds[i];
3248                 bh->state = BUF_STATE_EMPTY;
3249         }
3250         fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3251                         &fsg->buffhds[0];
3252
3253         exception_req_tag = fsg->exception_req_tag;
3254         new_config = fsg->new_config;
3255         old_state = fsg->state;
3256
3257         if (old_state == FSG_STATE_ABORT_BULK_OUT)
3258                 fsg->state = FSG_STATE_STATUS_PHASE;
3259         else {
3260                 for (i = 0; i < fsg->nluns; ++i) {
3261                         curlun = &fsg->luns[i];
3262                         curlun->prevent_medium_removal = 0;
3263                         curlun->sense_data = curlun->unit_attention_data =
3264                                         SS_NO_SENSE;
3265                         curlun->sense_data_info = 0;
3266                 }
3267                 fsg->state = FSG_STATE_IDLE;
3268         }
3269         spin_unlock_irq(&fsg->lock);
3270
3271         /* Carry out any extra actions required for the exception */
3272         switch (old_state) {
3273         default:
3274                 break;
3275
3276         case FSG_STATE_ABORT_BULK_OUT:
3277                 send_status(fsg);
3278                 spin_lock_irq(&fsg->lock);
3279                 if (fsg->state == FSG_STATE_STATUS_PHASE)
3280                         fsg->state = FSG_STATE_IDLE;
3281                 spin_unlock_irq(&fsg->lock);
3282                 break;
3283
3284         case FSG_STATE_RESET:
3285                 /* In case we were forced against our will to halt a
3286                  * bulk endpoint, clear the halt now.  (The SuperH UDC
3287                  * requires this.) */
3288                 if (test_and_clear_bit(CLEAR_BULK_HALTS,
3289                                 &fsg->atomic_bitflags)) {
3290                         usb_ep_clear_halt(fsg->bulk_in);
3291                         usb_ep_clear_halt(fsg->bulk_out);
3292                 }
3293
3294                 if (transport_is_bbb()) {
3295                         if (fsg->ep0_req_tag == exception_req_tag)
3296                                 ep0_queue(fsg); // Complete the status stage
3297
3298                 } else if (transport_is_cbi())
3299                         send_status(fsg);       // Status by interrupt pipe
3300
3301                 /* Technically this should go here, but it would only be
3302                  * a waste of time.  Ditto for the INTERFACE_CHANGE and
3303                  * CONFIG_CHANGE cases. */
3304                 // for (i = 0; i < fsg->nluns; ++i)
3305                 //      fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3306                 break;
3307
3308         case FSG_STATE_INTERFACE_CHANGE:
3309                 rc = do_set_interface(fsg, 0);
3310                 if (fsg->ep0_req_tag != exception_req_tag)
3311                         break;
3312                 if (rc != 0)                    // STALL on errors
3313                         fsg_set_halt(fsg, fsg->ep0);
3314                 else                            // Complete the status stage
3315                         ep0_queue(fsg);
3316                 break;
3317
3318         case FSG_STATE_CONFIG_CHANGE:
3319                 rc = do_set_config(fsg, new_config);
3320                 if (fsg->ep0_req_tag != exception_req_tag)
3321                         break;
3322                 if (rc != 0)                    // STALL on errors
3323                         fsg_set_halt(fsg, fsg->ep0);
3324                 else                            // Complete the status stage
3325                         ep0_queue(fsg);
3326                 break;
3327
3328         case FSG_STATE_DISCONNECT:
3329                 fsync_all(fsg);
3330                 do_set_config(fsg, 0);          // Unconfigured state
3331                 break;
3332
3333         case FSG_STATE_EXIT:
3334         case FSG_STATE_TERMINATED:
3335                 do_set_config(fsg, 0);                  // Free resources
3336                 spin_lock_irq(&fsg->lock);
3337                 fsg->state = FSG_STATE_TERMINATED;      // Stop the thread
3338                 spin_unlock_irq(&fsg->lock);
3339                 break;
3340         }
3341 }
3342
3343
3344 /*-------------------------------------------------------------------------*/
3345
3346 static int fsg_main_thread(void *fsg_)
3347 {
3348         struct fsg_dev          *fsg = (struct fsg_dev *) fsg_;
3349
3350         fsg->thread_task = current;
3351
3352         /* Release all our userspace resources */
3353         daemonize("file-storage-gadget");
3354
3355         /* Allow the thread to be killed by a signal, but set the signal mask
3356          * to block everything but INT, TERM, KILL, and USR1. */
3357         siginitsetinv(&fsg->thread_signal_mask, sigmask(SIGINT) |
3358                         sigmask(SIGTERM) | sigmask(SIGKILL) |
3359                         sigmask(SIGUSR1));
3360         sigprocmask(SIG_SETMASK, &fsg->thread_signal_mask, NULL);
3361
3362         /* Arrange for userspace references to be interpreted as kernel
3363          * pointers.  That way we can pass a kernel pointer to a routine
3364          * that expects a __user pointer and it will work okay. */
3365         set_fs(get_ds());
3366
3367         /* Wait for the gadget registration to finish up */
3368         wait_for_completion(&fsg->thread_notifier);
3369
3370         /* The main loop */
3371         while (fsg->state != FSG_STATE_TERMINATED) {
3372                 if (exception_in_progress(fsg) || signal_pending(current)) {
3373                         handle_exception(fsg);
3374                         continue;
3375                 }
3376
3377                 if (!fsg->running) {
3378                         sleep_thread(fsg);
3379                         continue;
3380                 }
3381
3382                 if (get_next_command(fsg))
3383                         continue;
3384
3385                 spin_lock_irq(&fsg->lock);
3386                 if (!exception_in_progress(fsg))
3387                         fsg->state = FSG_STATE_DATA_PHASE;
3388                 spin_unlock_irq(&fsg->lock);
3389
3390                 if (do_scsi_command(fsg) || finish_reply(fsg))
3391                         continue;
3392
3393                 spin_lock_irq(&fsg->lock);
3394                 if (!exception_in_progress(fsg))
3395                         fsg->state = FSG_STATE_STATUS_PHASE;
3396                 spin_unlock_irq(&fsg->lock);
3397
3398                 if (send_status(fsg))
3399                         continue;
3400
3401                 spin_lock_irq(&fsg->lock);
3402                 if (!exception_in_progress(fsg))
3403                         fsg->state = FSG_STATE_IDLE;
3404                 spin_unlock_irq(&fsg->lock);
3405                 }
3406
3407         fsg->thread_task = NULL;
3408         flush_signals(current);
3409
3410         /* In case we are exiting because of a signal, unregister the
3411          * gadget driver and close the backing file. */
3412         if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) {
3413                 usb_gadget_unregister_driver(&fsg_driver);
3414                 close_all_backing_files(fsg);
3415         }
3416
3417         /* Let the unbind and cleanup routines know the thread has exited */
3418         complete_and_exit(&fsg->thread_notifier, 0);
3419 }
3420
3421
3422 /*-------------------------------------------------------------------------*/
3423
3424 /* If the next two routines are called while the gadget is registered,
3425  * the caller must own fsg->filesem for writing. */
3426
3427 static int NORMALLY_INIT open_backing_file(struct lun *curlun,
3428                 const char *filename)
3429 {
3430         int                             ro;
3431         struct file                     *filp = NULL;
3432         int                             rc = -EINVAL;
3433         struct inode                    *inode = NULL;
3434         loff_t                          size;
3435         loff_t                          num_sectors;
3436
3437         /* R/W if we can, R/O if we must */
3438         ro = curlun->ro;
3439         if (!ro) {
3440                 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3441                 if (-EROFS == PTR_ERR(filp))
3442                         ro = 1;
3443         }
3444         if (ro)
3445                 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3446         if (IS_ERR(filp)) {
3447                 LINFO(curlun, "unable to open backing file: %s\n", filename);
3448                 return PTR_ERR(filp);
3449         }
3450
3451         if (!(filp->f_mode & FMODE_WRITE))
3452                 ro = 1;
3453
3454         if (filp->f_dentry)
3455                 inode = filp->f_dentry->d_inode;
3456         if (inode && S_ISBLK(inode->i_mode)) {
3457                 if (bdev_read_only(inode->i_bdev))
3458                         ro = 1;
3459         } else if (!inode || !S_ISREG(inode->i_mode)) {
3460                 LINFO(curlun, "invalid file type: %s\n", filename);
3461                 goto out;
3462         }
3463
3464         /* If we can't read the file, it's no good.
3465          * If we can't write the file, use it read-only. */
3466         if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3467                 LINFO(curlun, "file not readable: %s\n", filename);
3468                 goto out;
3469         }
3470         if (!(filp->f_op->write || filp->f_op->aio_write))
3471                 ro = 1;
3472
3473         size = i_size_read(inode->i_mapping->host);
3474         if (size < 0) {
3475                 LINFO(curlun, "unable to find file size: %s\n", filename);
3476                 rc = (int) size;
3477                 goto out;
3478         }
3479         num_sectors = size >> 9;        // File size in 512-byte sectors
3480         if (num_sectors == 0) {
3481                 LINFO(curlun, "file too small: %s\n", filename);
3482                 rc = -ETOOSMALL;
3483                 goto out;
3484         }
3485
3486         get_file(filp);
3487         curlun->ro = ro;
3488         curlun->filp = filp;
3489         curlun->file_length = size;
3490         curlun->num_sectors = num_sectors;
3491         LDBG(curlun, "open backing file: %s\n", filename);
3492         rc = 0;
3493
3494 out:
3495         filp_close(filp, current->files);
3496         return rc;
3497 }
3498
3499
3500 static void close_backing_file(struct lun *curlun)
3501 {
3502         if (curlun->filp) {
3503                 LDBG(curlun, "close backing file\n");
3504                 fput(curlun->filp);
3505                 curlun->filp = NULL;
3506         }
3507 }
3508
3509 static void close_all_backing_files(struct fsg_dev *fsg)
3510 {
3511         int     i;
3512
3513         for (i = 0; i < fsg->nluns; ++i)
3514                 close_backing_file(&fsg->luns[i]);
3515 }
3516
3517
3518 static ssize_t show_ro(struct device *dev, char *buf)
3519 {
3520         struct lun      *curlun = dev_to_lun(dev);
3521
3522         return sprintf(buf, "%d\n", curlun->ro);
3523 }
3524
3525 static ssize_t show_file(struct device *dev, char *buf)
3526 {
3527         struct lun      *curlun = dev_to_lun(dev);
3528         struct fsg_dev  *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3529         char            *p;
3530         ssize_t         rc;
3531
3532         down_read(&fsg->filesem);
3533         if (backing_file_is_open(curlun)) {     // Get the complete pathname
3534                 p = d_path(curlun->filp->f_dentry, curlun->filp->f_vfsmnt,
3535                                 buf, PAGE_SIZE - 1);
3536                 if (IS_ERR(p))
3537                         rc = PTR_ERR(p);
3538                 else {
3539                         rc = strlen(p);
3540                         memmove(buf, p, rc);
3541                         buf[rc] = '\n';         // Add a newline
3542                         buf[++rc] = 0;
3543                 }
3544         } else {                                // No file, return 0 bytes
3545                 *buf = 0;
3546                 rc = 0;
3547         }
3548         up_read(&fsg->filesem);
3549         return rc;
3550 }
3551
3552
3553 ssize_t NORMALLY_INIT store_ro(struct device *dev, const char *buf,
3554                 size_t count)
3555 {
3556         ssize_t         rc = count;
3557         struct lun      *curlun = dev_to_lun(dev);
3558         struct fsg_dev  *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3559         int             i;
3560
3561         if (sscanf(buf, "%d", &i) != 1)
3562                 return -EINVAL;
3563
3564         /* Allow the write-enable status to change only while the backing file
3565          * is closed. */
3566         down_read(&fsg->filesem);
3567         if (backing_file_is_open(curlun)) {
3568                 LDBG(curlun, "read-only status change prevented\n");
3569                 rc = -EBUSY;
3570         } else {
3571                 curlun->ro = !!i;
3572                 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3573         }
3574         up_read(&fsg->filesem);
3575         return rc;
3576 }
3577
3578 ssize_t NORMALLY_INIT store_file(struct device *dev, const char *buf,
3579                 size_t count)
3580 {
3581         struct lun      *curlun = dev_to_lun(dev);
3582         struct fsg_dev  *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3583         int             rc = 0;
3584
3585         if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3586                 LDBG(curlun, "eject attempt prevented\n");
3587                 return -EBUSY;                          // "Door is locked"
3588         }
3589
3590         /* Remove a trailing newline */
3591         if (count > 0 && buf[count-1] == '\n')
3592                 ((char *) buf)[count-1] = 0;            // Ugh!
3593
3594         /* Eject current medium */
3595         down_write(&fsg->filesem);
3596         if (backing_file_is_open(curlun)) {
3597                 close_backing_file(curlun);
3598                 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3599         }
3600
3601         /* Load new medium */
3602         if (count > 0 && buf[0]) {
3603                 rc = open_backing_file(curlun, buf);
3604                 if (rc == 0)
3605                         curlun->unit_attention_data =
3606                                         SS_NOT_READY_TO_READY_TRANSITION;
3607         }
3608         up_write(&fsg->filesem);
3609         return (rc < 0 ? rc : count);
3610 }
3611
3612
3613 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3614 static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3615 static DEVICE_ATTR(file, 0444, show_file, NULL);
3616
3617
3618 /*-------------------------------------------------------------------------*/
3619
3620 static void lun_release(struct device *dev)
3621 {
3622         struct fsg_dev  *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3623
3624         complete(&fsg->lun_released);
3625 }
3626
3627 static void fsg_unbind(struct usb_gadget *gadget)
3628 {
3629         struct fsg_dev          *fsg = get_gadget_data(gadget);
3630         int                     i;
3631         struct lun              *curlun;
3632         struct usb_request      *req = fsg->ep0req;
3633
3634         DBG(fsg, "unbind\n");
3635         clear_bit(REGISTERED, &fsg->atomic_bitflags);
3636
3637         /* Unregister the sysfs attribute files and the LUNs */
3638         init_completion(&fsg->lun_released);
3639         for (i = 0; i < fsg->nluns; ++i) {
3640                 curlun = &fsg->luns[i];
3641                 if (curlun->registered) {
3642                         device_remove_file(&curlun->dev, &dev_attr_ro);
3643                         device_remove_file(&curlun->dev, &dev_attr_file);
3644                         device_unregister(&curlun->dev);
3645                         wait_for_completion(&fsg->lun_released);
3646                         curlun->registered = 0;
3647                 }
3648         }
3649
3650         /* If the thread isn't already dead, tell it to exit now */
3651         if (fsg->state != FSG_STATE_TERMINATED) {
3652                 raise_exception(fsg, FSG_STATE_EXIT);
3653                 wait_for_completion(&fsg->thread_notifier);
3654
3655                 /* The cleanup routine waits for this completion also */
3656                 complete(&fsg->thread_notifier);
3657         }
3658
3659         /* Free the data buffers */
3660         for (i = 0; i < NUM_BUFFERS; ++i) {
3661                 struct fsg_buffhd       *bh = &fsg->buffhds[i];
3662
3663                 if (bh->buf)
3664                         usb_ep_free_buffer(fsg->bulk_in, bh->buf, bh->dma,
3665                                         mod_data.buflen);
3666         }
3667
3668         /* Free the request and buffer for endpoint 0 */
3669         if (req) {
3670                 if (req->buf)
3671                         usb_ep_free_buffer(fsg->ep0, req->buf,
3672                                         req->dma, EP0_BUFSIZE);
3673                 usb_ep_free_request(fsg->ep0, req);
3674         }
3675
3676         set_gadget_data(gadget, NULL);
3677 }
3678
3679
3680 static int __init check_parameters(struct fsg_dev *fsg)
3681 {
3682         int     prot;
3683
3684         /* Store the default values */
3685         mod_data.transport_type = USB_PR_BULK;
3686         mod_data.transport_name = "Bulk-only";
3687         mod_data.protocol_type = USB_SC_SCSI;
3688         mod_data.protocol_name = "Transparent SCSI";
3689
3690         if (gadget_is_sh(fsg->gadget))
3691                 mod_data.can_stall = 0;
3692
3693         if (mod_data.release == 0xffff) {       // Parameter wasn't set
3694                 if (gadget_is_net2280(fsg->gadget))
3695                         mod_data.release = __constant_cpu_to_le16(0x0301);
3696                 else if (gadget_is_dummy(fsg->gadget))
3697                         mod_data.release = __constant_cpu_to_le16(0x0302);
3698                 else if (gadget_is_pxa(fsg->gadget))
3699                         mod_data.release = __constant_cpu_to_le16(0x0303);
3700                 else if (gadget_is_sh(fsg->gadget))
3701                         mod_data.release = __constant_cpu_to_le16(0x0304);
3702
3703                 /* The sa1100 controller is not supported */
3704
3705                 else if (gadget_is_goku(fsg->gadget))
3706                         mod_data.release = __constant_cpu_to_le16(0x0306);
3707                 else if (gadget_is_mq11xx(fsg->gadget))
3708                         mod_data.release = __constant_cpu_to_le16(0x0307);
3709                 else if (gadget_is_omap(fsg->gadget))
3710                         mod_data.release = __constant_cpu_to_le16(0x0308);
3711                 else {
3712                         WARN(fsg, "controller '%s' not recognized\n",
3713                                 fsg->gadget->name);
3714                         mod_data.release = __constant_cpu_to_le16(0x0399);
3715                 }
3716         }
3717
3718         prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3719
3720 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3721         if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3722                 ;               // Use default setting
3723         } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3724                 mod_data.transport_type = USB_PR_CB;
3725                 mod_data.transport_name = "Control-Bulk";
3726         } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3727                 mod_data.transport_type = USB_PR_CBI;
3728                 mod_data.transport_name = "Control-Bulk-Interrupt";
3729         } else {
3730                 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3731                 return -EINVAL;
3732         }
3733
3734         if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3735                         prot == USB_SC_SCSI) {
3736                 ;               // Use default setting
3737         } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3738                         prot == USB_SC_RBC) {
3739                 mod_data.protocol_type = USB_SC_RBC;
3740                 mod_data.protocol_name = "RBC";
3741         } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3742                         strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3743                         prot == USB_SC_8020) {
3744                 mod_data.protocol_type = USB_SC_8020;
3745                 mod_data.protocol_name = "8020i (ATAPI)";
3746         } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3747                         prot == USB_SC_QIC) {
3748                 mod_data.protocol_type = USB_SC_QIC;
3749                 mod_data.protocol_name = "QIC-157";
3750         } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3751                         prot == USB_SC_UFI) {
3752                 mod_data.protocol_type = USB_SC_UFI;
3753                 mod_data.protocol_name = "UFI";
3754         } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3755                         prot == USB_SC_8070) {
3756                 mod_data.protocol_type = USB_SC_8070;
3757                 mod_data.protocol_name = "8070i";
3758         } else {
3759                 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3760                 return -EINVAL;
3761         }
3762
3763         mod_data.buflen &= PAGE_CACHE_MASK;
3764         if (mod_data.buflen <= 0) {
3765                 ERROR(fsg, "invalid buflen\n");
3766                 return -ETOOSMALL;
3767         }
3768 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3769
3770         return 0;
3771 }
3772
3773
3774 static int __init fsg_bind(struct usb_gadget *gadget)
3775 {
3776         struct fsg_dev          *fsg = the_fsg;
3777         int                     rc;
3778         int                     i;
3779         struct lun              *curlun;
3780         struct usb_ep           *ep;
3781         struct usb_request      *req;
3782         char                    *pathbuf, *p;
3783
3784         fsg->gadget = gadget;
3785         set_gadget_data(gadget, fsg);
3786         fsg->ep0 = gadget->ep0;
3787         fsg->ep0->driver_data = fsg;
3788
3789         if ((rc = check_parameters(fsg)) != 0)
3790                 goto out;
3791
3792         if (mod_data.removable) {       // Enable the store_xxx attributes
3793                 dev_attr_ro.attr.mode = dev_attr_file.attr.mode = 0644;
3794                 dev_attr_ro.store = store_ro;
3795                 dev_attr_file.store = store_file;
3796         }
3797
3798         /* Find out how many LUNs there should be */
3799         i = mod_data.nluns;
3800         if (i == 0)
3801                 i = max(mod_data.num_filenames, 1);
3802         if (i > MAX_LUNS) {
3803                 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3804                 rc = -EINVAL;
3805                 goto out;
3806         }
3807
3808         /* Create the LUNs and open their backing files.  We can't register
3809          * the LUN devices until the gadget itself is registered, which
3810          * doesn't happen until after fsg_bind() returns. */
3811         fsg->luns = kmalloc(i * sizeof(struct lun), GFP_KERNEL);
3812         if (!fsg->luns) {
3813                 rc = -ENOMEM;
3814                 goto out;
3815         }
3816         memset(fsg->luns, 0, i * sizeof(struct lun));
3817         fsg->nluns = i;
3818
3819         for (i = 0; i < fsg->nluns; ++i) {
3820                 curlun = &fsg->luns[i];
3821                 curlun->ro = ro[i];
3822                 curlun->dev.parent = &gadget->dev;
3823                 curlun->dev.driver = &fsg_driver.driver;
3824                 dev_set_drvdata(&curlun->dev, fsg);
3825                 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
3826                                 "%s-lun%d", gadget->dev.bus_id, i);
3827
3828                 if (file[i] && *file[i]) {
3829                         if ((rc = open_backing_file(curlun, file[i])) != 0)
3830                                 goto out;
3831                 } else if (!mod_data.removable) {
3832                         ERROR(fsg, "no file given for LUN%d\n", i);
3833                         rc = -EINVAL;
3834                         goto out;
3835                 }
3836         }
3837
3838         /* Find all the endpoints we will use */
3839         usb_ep_autoconfig_reset(gadget);
3840         ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
3841         if (!ep)
3842                 goto autoconf_fail;
3843         ep->driver_data = fsg;          // claim the endpoint
3844         fsg->bulk_in = ep;
3845
3846         ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
3847         if (!ep)
3848                 goto autoconf_fail;
3849         ep->driver_data = fsg;          // claim the endpoint
3850         fsg->bulk_out = ep;
3851
3852         if (transport_is_cbi()) {
3853                 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
3854                 if (!ep)
3855                         goto autoconf_fail;
3856                 ep->driver_data = fsg;          // claim the endpoint
3857                 fsg->intr_in = ep;
3858         }
3859
3860         /* Fix up the descriptors */
3861         device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3862         device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3863         device_desc.idProduct = cpu_to_le16(mod_data.product);
3864         device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3865
3866         i = (transport_is_cbi() ? 3 : 2);       // Number of endpoints
3867         intf_desc.bNumEndpoints = i;
3868         intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3869         intf_desc.bInterfaceProtocol = mod_data.transport_type;
3870         fs_function[i+1] = NULL;
3871
3872 #ifdef CONFIG_USB_GADGET_DUALSPEED
3873         hs_function[i+1] = NULL;
3874
3875         /* Assume ep0 uses the same maxpacket value for both speeds */
3876         dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3877
3878         /* Assume that all endpoint addresses are the same for both speeds */
3879         hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress;
3880         hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress;
3881         hs_intr_in_desc.bEndpointAddress = fs_intr_in_desc.bEndpointAddress;
3882 #endif
3883
3884         rc = -ENOMEM;
3885
3886         /* Allocate the request and buffer for endpoint 0 */
3887         fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3888         if (!req)
3889                 goto out;
3890         req->buf = usb_ep_alloc_buffer(fsg->ep0, EP0_BUFSIZE,
3891                         &req->dma, GFP_KERNEL);
3892         if (!req->buf)
3893                 goto out;
3894         req->complete = ep0_complete;
3895
3896         /* Allocate the data buffers */
3897         for (i = 0; i < NUM_BUFFERS; ++i) {
3898                 struct fsg_buffhd       *bh = &fsg->buffhds[i];
3899
3900                 bh->buf = usb_ep_alloc_buffer(fsg->bulk_in, mod_data.buflen,
3901                                 &bh->dma, GFP_KERNEL);
3902                 if (!bh->buf)
3903                         goto out;
3904                 bh->next = bh + 1;
3905         }
3906         fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3907
3908         /* This should reflect the actual gadget power source */
3909         usb_gadget_set_selfpowered(gadget);
3910
3911         snprintf(manufacturer, sizeof manufacturer,
3912                         UTS_SYSNAME " " UTS_RELEASE " with %s",
3913                         gadget->name);
3914
3915         /* On a real device, serial[] would be loaded from permanent
3916          * storage.  We just encode it from the driver version string. */
3917         for (i = 0; i < sizeof(serial) - 2; i += 2) {
3918                 unsigned char           c = DRIVER_VERSION[i / 2];
3919
3920                 if (!c)
3921                         break;
3922                 sprintf(&serial[i], "%02X", c);
3923         }
3924
3925         if ((rc = kernel_thread(fsg_main_thread, fsg, (CLONE_VM | CLONE_FS |
3926                         CLONE_FILES))) < 0)
3927                 goto out;
3928         fsg->thread_pid = rc;
3929
3930         INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3931         INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3932
3933         pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3934         for (i = 0; i < fsg->nluns; ++i) {
3935                 curlun = &fsg->luns[i];
3936                 if (backing_file_is_open(curlun)) {
3937                         p = NULL;
3938                         if (pathbuf) {
3939                                 p = d_path(curlun->filp->f_dentry,
3940                                         curlun->filp->f_vfsmnt,
3941                                         pathbuf, PATH_MAX);
3942                                 if (IS_ERR(p))
3943                                         p = NULL;
3944                         }
3945                         LINFO(curlun, "ro=%d, file: %s\n",
3946                                         curlun->ro, (p ? p : "(error)"));
3947                 }
3948         }
3949         kfree(pathbuf);
3950
3951         DBG(fsg, "transport=%s (x%02x)\n",
3952                         mod_data.transport_name, mod_data.transport_type);
3953         DBG(fsg, "protocol=%s (x%02x)\n",
3954                         mod_data.protocol_name, mod_data.protocol_type);
3955         DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3956                         mod_data.vendor, mod_data.product, mod_data.release);
3957         DBG(fsg, "removable=%d, stall=%d, buflen=%u\n",
3958                         mod_data.removable, mod_data.can_stall,
3959                         mod_data.buflen);
3960         DBG(fsg, "I/O thread pid: %d\n", fsg->thread_pid);
3961         return 0;
3962
3963 autoconf_fail:
3964         ERROR(fsg, "unable to autoconfigure all endpoints\n");
3965         rc = -ENOTSUPP;
3966
3967 out:
3968         fsg->state = FSG_STATE_TERMINATED;      // The thread is dead
3969         fsg_unbind(gadget);
3970         close_all_backing_files(fsg);
3971         return rc;
3972 }
3973
3974
3975 /*-------------------------------------------------------------------------*/
3976
3977 static struct usb_gadget_driver         fsg_driver = {
3978 #ifdef CONFIG_USB_GADGET_DUALSPEED
3979         .speed          = USB_SPEED_HIGH,
3980 #else
3981         .speed          = USB_SPEED_FULL,
3982 #endif
3983         .function       = (char *) longname,
3984         .bind           = fsg_bind,
3985         .unbind         = fsg_unbind,
3986         .disconnect     = fsg_disconnect,
3987         .setup          = fsg_setup,
3988
3989         .driver         = {
3990                 .name           = (char *) shortname,
3991                 // .release = ...
3992                 // .suspend = ...
3993                 // .resume = ...
3994         },
3995 };
3996
3997
3998 static int __init fsg_alloc(void)
3999 {
4000         struct fsg_dev          *fsg;
4001
4002         fsg = kmalloc(sizeof *fsg, GFP_KERNEL);
4003         if (!fsg)
4004                 return -ENOMEM;
4005         memset(fsg, 0, sizeof *fsg);
4006         spin_lock_init(&fsg->lock);
4007         init_rwsem(&fsg->filesem);
4008         init_waitqueue_head(&fsg->thread_wqh);
4009         init_completion(&fsg->thread_notifier);
4010
4011         the_fsg = fsg;
4012         return 0;
4013 }
4014
4015
4016 static void fsg_free(struct fsg_dev *fsg)
4017 {
4018         kfree(fsg->luns);
4019         kfree(fsg);
4020 }
4021
4022
4023 static int __init fsg_init(void)
4024 {
4025         int             rc;
4026         struct fsg_dev  *fsg;
4027         int             i;
4028         struct lun      *curlun;
4029
4030         if ((rc = fsg_alloc()) != 0)
4031                 return rc;
4032         fsg = the_fsg;
4033         if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0) {
4034                 fsg_free(fsg);
4035                 return rc;
4036         }
4037         set_bit(REGISTERED, &fsg->atomic_bitflags);
4038
4039         /* Register the LUN devices and their attribute files */
4040         for (i = 0; i < fsg->nluns; ++i) {
4041                 curlun = &fsg->luns[i];
4042                 if ((rc = device_register(&curlun->dev)) != 0)
4043                         INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
4044                 else {
4045                         curlun->registered = 1;
4046                         curlun->dev.release = lun_release;
4047                         device_create_file(&curlun->dev, &dev_attr_ro);
4048                         device_create_file(&curlun->dev, &dev_attr_file);
4049                 }
4050         }
4051
4052         /* Tell the thread to start working */
4053         complete(&fsg->thread_notifier);
4054         return 0;
4055 }
4056 module_init(fsg_init);
4057
4058
4059 static void __exit fsg_cleanup(void)
4060 {
4061         struct fsg_dev  *fsg = the_fsg;
4062
4063         /* Unregister the driver iff the thread hasn't already done so */
4064         if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4065                 usb_gadget_unregister_driver(&fsg_driver);
4066
4067         /* Wait for the thread to finish up */
4068         wait_for_completion(&fsg->thread_notifier);
4069
4070         close_all_backing_files(fsg);
4071         fsg_free(fsg);
4072 }
4073 module_exit(fsg_cleanup);