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