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