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