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