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