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