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