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