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