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