USB: g_mass_storage: constant length buffers used
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / usb / gadget / f_mass_storage.c
1 /*
2  * file_storage.c -- File-backed USB Storage Gadget, for USB development
3  *
4  * Copyright (C) 2003-2008 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 or as a CD-ROM drive.  In addition
42  * to providing an example of a genuinely useful gadget driver for a USB
43  * device, it also illustrates a technique of double-buffering for increased
44  * throughput.  Last but not least, it gives an easy way to probe the
45  * behavior of the 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.  (For CD-ROM emulation,
50  * access is always read-only.)  The gadget will indicate that it has
51  * removable media if the optional "removable" module parameter is set.
52  *
53  * There is support for multiple logical units (LUNs), each of which has
54  * its own backing file.  The number of LUNs can be set using the optional
55  * "luns" module parameter (anywhere from 1 to 8), and the corresponding
56  * files are specified using comma-separated lists for "file" and "ro".
57  * The default number of LUNs is taken from the number of "file" elements;
58  * it is 1 if "file" is not given.  If "removable" is not set then a backing
59  * file must be specified for each LUN.  If it is set, then an unspecified
60  * or empty backing filename means the LUN's medium is not loaded.  Ideally
61  * each LUN would be settable independently as a disk drive or a CD-ROM
62  * drive, but currently all LUNs have to be the same type.  The CD-ROM
63  * emulation includes a single data track and no audio tracks; hence there
64  * need be only one backing file per LUN.  Note also that the CD-ROM block
65  * length is set to 512 rather than the more common value 2048.
66  *
67  * Requirements are modest; only a bulk-in and a bulk-out endpoint are
68  * needed (an interrupt-out endpoint is also needed for CBI).  The memory
69  * requirement amounts to two 16K buffers, size configurable by a parameter.
70  * Support is included for both full-speed and high-speed operation.
71  *
72  * Note that the driver is slightly non-portable in that it assumes a
73  * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
74  * interrupt-in endpoints.  With most device controllers this isn't an
75  * issue, but there may be some with hardware restrictions that prevent
76  * a buffer from being used by more than one endpoint.
77  *
78  * Module options:
79  *
80  *      file=filename[,filename...]
81  *                              Required if "removable" is not set, names of
82  *                                      the files or block devices used for
83  *                                      backing storage
84  *      ro=b[,b...]             Default false, booleans for read-only access
85  *      removable               Default false, boolean for removable media
86  *      luns=N                  Default N = number of filenames, number of
87  *                                      LUNs to support
88  *      stall                   Default determined according to the type of
89  *                                      USB device controller (usually true),
90  *                                      boolean to permit the driver to halt
91  *                                      bulk endpoints
92  *      cdrom                   Default false, boolean for whether to emulate
93  *                                      a CD-ROM drive
94  *
95  * The pathnames of the backing files and the ro settings are available in
96  * the attribute files "file" and "ro" in the lun<n> subdirectory of the
97  * gadget's sysfs directory.  If the "removable" option is set, writing to
98  * these files will simulate ejecting/loading the medium (writing an empty
99  * line means eject) and adjusting a write-enable tab.  Changes to the ro
100  * setting are not allowed when the medium is loaded or if CD-ROM emulation
101  * is being used.
102  *
103  * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
104  * The driver's SCSI command interface was based on the "Information
105  * technology - Small Computer System Interface - 2" document from
106  * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
107  * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.  The single exception
108  * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
109  * "Universal Serial Bus Mass Storage Class UFI Command Specification"
110  * document, Revision 1.0, December 14, 1998, available at
111  * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
112  */
113
114
115 /*
116  *                              Driver Design
117  *
118  * The FSG driver is fairly straightforward.  There is a main kernel
119  * thread that handles most of the work.  Interrupt routines field
120  * callbacks from the controller driver: bulk- and interrupt-request
121  * completion notifications, endpoint-0 events, and disconnect events.
122  * Completion events are passed to the main thread by wakeup calls.  Many
123  * ep0 requests are handled at interrupt time, but SetInterface,
124  * SetConfiguration, and device reset requests are forwarded to the
125  * thread in the form of "exceptions" using SIGUSR1 signals (since they
126  * should interrupt any ongoing file I/O operations).
127  *
128  * The thread's main routine implements the standard command/data/status
129  * parts of a SCSI interaction.  It and its subroutines are full of tests
130  * for pending signals/exceptions -- all this polling is necessary since
131  * the kernel has no setjmp/longjmp equivalents.  (Maybe this is an
132  * indication that the driver really wants to be running in userspace.)
133  * An important point is that so long as the thread is alive it keeps an
134  * open reference to the backing file.  This will prevent unmounting
135  * the backing file's underlying filesystem and could cause problems
136  * during system shutdown, for example.  To prevent such problems, the
137  * thread catches INT, TERM, and KILL signals and converts them into
138  * an EXIT exception.
139  *
140  * In normal operation the main thread is started during the gadget's
141  * fsg_bind() callback and stopped during fsg_unbind().  But it can also
142  * exit when it receives a signal, and there's no point leaving the
143  * gadget running when the thread is dead.  So just before the thread
144  * exits, it deregisters the gadget driver.  This makes things a little
145  * tricky: The driver is deregistered at two places, and the exiting
146  * thread can indirectly call fsg_unbind() which in turn can tell the
147  * thread to exit.  The first problem is resolved through the use of the
148  * REGISTERED atomic bitflag; the driver will only be deregistered once.
149  * The second problem is resolved by having fsg_unbind() check
150  * fsg->state; it won't try to stop the thread if the state is already
151  * FSG_STATE_TERMINATED.
152  *
153  * To provide maximum throughput, the driver uses a circular pipeline of
154  * buffer heads (struct fsg_buffhd).  In principle the pipeline can be
155  * arbitrarily long; in practice the benefits don't justify having more
156  * than 2 stages (i.e., double buffering).  But it helps to think of the
157  * pipeline as being a long one.  Each buffer head contains a bulk-in and
158  * a bulk-out request pointer (since the buffer can be used for both
159  * output and input -- directions always are given from the host's
160  * point of view) as well as a pointer to the buffer and various state
161  * variables.
162  *
163  * Use of the pipeline follows a simple protocol.  There is a variable
164  * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
165  * At any time that buffer head may still be in use from an earlier
166  * request, so each buffer head has a state variable indicating whether
167  * it is EMPTY, FULL, or BUSY.  Typical use involves waiting for the
168  * buffer head to be EMPTY, filling the buffer either by file I/O or by
169  * USB I/O (during which the buffer head is BUSY), and marking the buffer
170  * head FULL when the I/O is complete.  Then the buffer will be emptied
171  * (again possibly by USB I/O, during which it is marked BUSY) and
172  * finally marked EMPTY again (possibly by a completion routine).
173  *
174  * A module parameter tells the driver to avoid stalling the bulk
175  * endpoints wherever the transport specification allows.  This is
176  * necessary for some UDCs like the SuperH, which cannot reliably clear a
177  * halt on a bulk endpoint.  However, under certain circumstances the
178  * Bulk-only specification requires a stall.  In such cases the driver
179  * will halt the endpoint and set a flag indicating that it should clear
180  * the halt in software during the next device reset.  Hopefully this
181  * will permit everything to work correctly.  Furthermore, although the
182  * specification allows the bulk-out endpoint to halt when the host sends
183  * too much data, implementing this would cause an unavoidable race.
184  * The driver will always use the "no-stall" approach for OUT transfers.
185  *
186  * One subtle point concerns sending status-stage responses for ep0
187  * requests.  Some of these requests, such as device reset, can involve
188  * interrupting an ongoing file I/O operation, which might take an
189  * arbitrarily long time.  During that delay the host might give up on
190  * the original ep0 request and issue a new one.  When that happens the
191  * driver should not notify the host about completion of the original
192  * request, as the host will no longer be waiting for it.  So the driver
193  * assigns to each ep0 request a unique tag, and it keeps track of the
194  * tag value of the request associated with a long-running exception
195  * (device-reset, interface-change, or configuration-change).  When the
196  * exception handler is finished, the status-stage response is submitted
197  * only if the current ep0 request tag is equal to the exception request
198  * tag.  Thus only the most recently received ep0 request will get a
199  * status-stage response.
200  *
201  * Warning: This driver source file is too long.  It ought to be split up
202  * into a header file plus about 3 separate .c files, to handle the details
203  * of the Gadget, USB Mass Storage, and SCSI protocols.
204  */
205
206
207 /* #define VERBOSE_DEBUG */
208 /* #define DUMP_MSGS */
209
210
211 #include <linux/blkdev.h>
212 #include <linux/completion.h>
213 #include <linux/dcache.h>
214 #include <linux/delay.h>
215 #include <linux/device.h>
216 #include <linux/fcntl.h>
217 #include <linux/file.h>
218 #include <linux/fs.h>
219 #include <linux/kref.h>
220 #include <linux/kthread.h>
221 #include <linux/limits.h>
222 #include <linux/rwsem.h>
223 #include <linux/slab.h>
224 #include <linux/spinlock.h>
225 #include <linux/string.h>
226 #include <linux/freezer.h>
227 #include <linux/utsname.h>
228
229 #include <linux/usb/ch9.h>
230 #include <linux/usb/gadget.h>
231
232 #include "gadget_chips.h"
233
234
235
236 /*
237  * Kbuild is not very cooperative with respect to linking separately
238  * compiled library objects into one module.  So for now we won't use
239  * separate compilation ... ensuring init/exit sections work to shrink
240  * the runtime footprint, and giving us at least some parts of what
241  * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
242  */
243 #include "usbstring.c"
244 #include "config.c"
245 #include "epautoconf.c"
246
247 /*-------------------------------------------------------------------------*/
248
249 #define DRIVER_DESC             "File-backed Storage Gadget"
250 #define DRIVER_NAME             "g_file_storage"
251 #define DRIVER_VERSION          "20 November 2008"
252
253 static       char fsg_string_manufacturer[64];
254 static const char fsg_string_product[] = DRIVER_DESC;
255 static       char fsg_string_serial[13];
256 static const char fsg_string_config[] = "Self-powered";
257 static const char fsg_string_interface[] = "Mass Storage";
258
259
260 #define FSG_NO_INTR_EP 1
261 #define FSG_BUFFHD_STATIC_BUFFER 1
262
263 #include "storage_common.c"
264
265
266 MODULE_DESCRIPTION(DRIVER_DESC);
267 MODULE_AUTHOR("Alan Stern");
268 MODULE_LICENSE("Dual BSD/GPL");
269
270 /*
271  * This driver assumes self-powered hardware and has no way for users to
272  * trigger remote wakeup.  It uses autoconfiguration to select endpoints
273  * and endpoint addresses.
274  */
275
276
277 /*-------------------------------------------------------------------------*/
278
279
280 /* Encapsulate the module parameter settings */
281
282 static struct {
283         char            *file[FSG_MAX_LUNS];
284         int             ro[FSG_MAX_LUNS];
285         unsigned int    num_filenames;
286         unsigned int    num_ros;
287         unsigned int    nluns;
288
289         int             removable;
290         int             can_stall;
291         int             cdrom;
292
293         unsigned short  release;
294 } mod_data = {                                  // Default values
295         .removable              = 0,
296         .can_stall              = 1,
297         .cdrom                  = 0,
298         };
299
300
301 module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
302                 S_IRUGO);
303 MODULE_PARM_DESC(file, "names of backing files or devices");
304
305 module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
306 MODULE_PARM_DESC(ro, "true to force read-only");
307
308 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
309 MODULE_PARM_DESC(luns, "number of LUNs");
310
311 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
312 MODULE_PARM_DESC(removable, "true to simulate removable media");
313
314 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
315 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
316
317 module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
318 MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
319
320
321 /*-------------------------------------------------------------------------*/
322
323
324 /* Data shared by all the FSG instances. */
325 struct fsg_common {
326         /* filesem protects: backing files in use */
327         struct rw_semaphore     filesem;
328
329         struct fsg_buffhd       *next_buffhd_to_fill;
330         struct fsg_buffhd       *next_buffhd_to_drain;
331         struct fsg_buffhd       buffhds[FSG_NUM_BUFFERS];
332
333         int                     cmnd_size;
334         u8                      cmnd[MAX_COMMAND_SIZE];
335
336         unsigned int            nluns;
337         unsigned int            lun;
338         struct fsg_lun          *luns;
339         struct fsg_lun          *curlun;
340 };
341
342
343 struct fsg_dev {
344         struct fsg_common       *common;
345
346         /* lock protects: state, all the req_busy's */
347         spinlock_t              lock;
348         struct usb_gadget       *gadget;
349
350         /* reference counting: wait until all LUNs are released */
351         struct kref             ref;
352
353         struct usb_ep           *ep0;           // Handy copy of gadget->ep0
354         struct usb_request      *ep0req;        // For control responses
355         unsigned int            ep0_req_tag;
356         const char              *ep0req_name;
357
358         unsigned int            bulk_out_maxpacket;
359         enum fsg_state          state;          // For exception handling
360         unsigned int            exception_req_tag;
361
362         u8                      config, new_config;
363
364         unsigned int            running : 1;
365         unsigned int            bulk_in_enabled : 1;
366         unsigned int            bulk_out_enabled : 1;
367         unsigned int            phase_error : 1;
368         unsigned int            short_packet_received : 1;
369         unsigned int            bad_lun_okay : 1;
370
371         unsigned long           atomic_bitflags;
372 #define REGISTERED              0
373 #define IGNORE_BULK_OUT         1
374
375         struct usb_ep           *bulk_in;
376         struct usb_ep           *bulk_out;
377
378         int                     thread_wakeup_needed;
379         struct completion       thread_notifier;
380         struct task_struct      *thread_task;
381
382         enum data_direction     data_dir;
383         u32                     data_size;
384         u32                     data_size_from_cmnd;
385         u32                     tag;
386         u32                     residue;
387         u32                     usb_amount_left;
388 };
389
390 typedef void (*fsg_routine_t)(struct fsg_dev *);
391
392 static int exception_in_progress(struct fsg_dev *fsg)
393 {
394         return (fsg->state > FSG_STATE_IDLE);
395 }
396
397 /* Make bulk-out requests be divisible by the maxpacket size */
398 static void set_bulk_out_req_length(struct fsg_dev *fsg,
399                 struct fsg_buffhd *bh, unsigned int length)
400 {
401         unsigned int    rem;
402
403         bh->bulk_out_intended_length = length;
404         rem = length % fsg->bulk_out_maxpacket;
405         if (rem > 0)
406                 length += fsg->bulk_out_maxpacket - rem;
407         bh->outreq->length = length;
408 }
409
410 static struct fsg_dev                   *the_fsg;
411 static struct usb_gadget_driver         fsg_driver;
412
413
414 /*-------------------------------------------------------------------------*/
415
416 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
417 {
418         const char      *name;
419
420         if (ep == fsg->bulk_in)
421                 name = "bulk-in";
422         else if (ep == fsg->bulk_out)
423                 name = "bulk-out";
424         else
425                 name = ep->name;
426         DBG(fsg, "%s set halt\n", name);
427         return usb_ep_set_halt(ep);
428 }
429
430
431 /*-------------------------------------------------------------------------*/
432
433 /*
434  * DESCRIPTORS ... most are static, but strings and (full) configuration
435  * descriptors are built on demand.  Also the (static) config and interface
436  * descriptors are adjusted during fsg_bind().
437  */
438
439 /* There is only one configuration. */
440 #define CONFIG_VALUE            1
441
442 static struct usb_device_descriptor
443 device_desc = {
444         .bLength =              sizeof device_desc,
445         .bDescriptorType =      USB_DT_DEVICE,
446
447         .bcdUSB =               cpu_to_le16(0x0200),
448         .bDeviceClass =         USB_CLASS_PER_INTERFACE,
449
450         /* The next three values can be overridden by module parameters */
451         .idVendor =             cpu_to_le16(FSG_VENDOR_ID),
452         .idProduct =            cpu_to_le16(FSG_PRODUCT_ID),
453         .bcdDevice =            cpu_to_le16(0xffff),
454
455         .iManufacturer =        FSG_STRING_MANUFACTURER,
456         .iProduct =             FSG_STRING_PRODUCT,
457         .iSerialNumber =        FSG_STRING_SERIAL,
458         .bNumConfigurations =   1,
459 };
460
461 static struct usb_config_descriptor
462 config_desc = {
463         .bLength =              sizeof config_desc,
464         .bDescriptorType =      USB_DT_CONFIG,
465
466         /* wTotalLength computed by usb_gadget_config_buf() */
467         .bNumInterfaces =       1,
468         .bConfigurationValue =  CONFIG_VALUE,
469         .iConfiguration =       FSG_STRING_CONFIG,
470         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
471         .bMaxPower =            CONFIG_USB_GADGET_VBUS_DRAW / 2,
472 };
473
474
475 static struct usb_qualifier_descriptor
476 dev_qualifier = {
477         .bLength =              sizeof dev_qualifier,
478         .bDescriptorType =      USB_DT_DEVICE_QUALIFIER,
479
480         .bcdUSB =               cpu_to_le16(0x0200),
481         .bDeviceClass =         USB_CLASS_PER_INTERFACE,
482
483         .bNumConfigurations =   1,
484 };
485
486
487
488 /*
489  * Config descriptors must agree with the code that sets configurations
490  * and with code managing interfaces and their altsettings.  They must
491  * also handle different speeds and other-speed requests.
492  */
493 static int populate_config_buf(struct usb_gadget *gadget,
494                 u8 *buf, u8 type, unsigned index)
495 {
496         enum usb_device_speed                   speed = gadget->speed;
497         int                                     len;
498         const struct usb_descriptor_header      **function;
499
500         if (index > 0)
501                 return -EINVAL;
502
503         if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
504                 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
505         if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
506                 function = fsg_hs_function;
507         else
508                 function = fsg_fs_function;
509
510         /* for now, don't advertise srp-only devices */
511         if (!gadget_is_otg(gadget))
512                 function++;
513
514         len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
515         ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
516         return len;
517 }
518
519
520 /*-------------------------------------------------------------------------*/
521
522 /* These routines may be called in process context or in_irq */
523
524 /* Caller must hold fsg->lock */
525 static void wakeup_thread(struct fsg_dev *fsg)
526 {
527         /* Tell the main thread that something has happened */
528         fsg->thread_wakeup_needed = 1;
529         if (fsg->thread_task)
530                 wake_up_process(fsg->thread_task);
531 }
532
533
534 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
535 {
536         unsigned long           flags;
537
538         /* Do nothing if a higher-priority exception is already in progress.
539          * If a lower-or-equal priority exception is in progress, preempt it
540          * and notify the main thread by sending it a signal. */
541         spin_lock_irqsave(&fsg->lock, flags);
542         if (fsg->state <= new_state) {
543                 fsg->exception_req_tag = fsg->ep0_req_tag;
544                 fsg->state = new_state;
545                 if (fsg->thread_task)
546                         send_sig_info(SIGUSR1, SEND_SIG_FORCED,
547                                         fsg->thread_task);
548         }
549         spin_unlock_irqrestore(&fsg->lock, flags);
550 }
551
552
553 /*-------------------------------------------------------------------------*/
554
555 /* The disconnect callback and ep0 routines.  These always run in_irq,
556  * except that ep0_queue() is called in the main thread to acknowledge
557  * completion of various requests: set config, set interface, and
558  * Bulk-only device reset. */
559
560 static void fsg_disconnect(struct usb_gadget *gadget)
561 {
562         struct fsg_dev          *fsg = get_gadget_data(gadget);
563
564         DBG(fsg, "disconnect or port reset\n");
565         raise_exception(fsg, FSG_STATE_DISCONNECT);
566 }
567
568
569 static int ep0_queue(struct fsg_dev *fsg)
570 {
571         int     rc;
572
573         rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
574         if (rc != 0 && rc != -ESHUTDOWN) {
575
576                 /* We can't do much more than wait for a reset */
577                 WARNING(fsg, "error in submission: %s --> %d\n",
578                                 fsg->ep0->name, rc);
579         }
580         return rc;
581 }
582
583 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
584 {
585         struct fsg_dev          *fsg = ep->driver_data;
586
587         if (req->actual > 0)
588                 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
589         if (req->status || req->actual != req->length)
590                 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
591                                 req->status, req->actual, req->length);
592         if (req->status == -ECONNRESET)         // Request was cancelled
593                 usb_ep_fifo_flush(ep);
594
595         if (req->status == 0 && req->context)
596                 ((fsg_routine_t) (req->context))(fsg);
597 }
598
599
600 /*-------------------------------------------------------------------------*/
601
602 /* Bulk and interrupt endpoint completion handlers.
603  * These always run in_irq. */
604
605 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
606 {
607         struct fsg_dev          *fsg = ep->driver_data;
608         struct fsg_buffhd       *bh = req->context;
609
610         if (req->status || req->actual != req->length)
611                 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
612                                 req->status, req->actual, req->length);
613         if (req->status == -ECONNRESET)         // Request was cancelled
614                 usb_ep_fifo_flush(ep);
615
616         /* Hold the lock while we update the request and buffer states */
617         smp_wmb();
618         spin_lock(&fsg->lock);
619         bh->inreq_busy = 0;
620         bh->state = BUF_STATE_EMPTY;
621         wakeup_thread(fsg);
622         spin_unlock(&fsg->lock);
623 }
624
625 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
626 {
627         struct fsg_dev          *fsg = ep->driver_data;
628         struct fsg_buffhd       *bh = req->context;
629
630         dump_msg(fsg, "bulk-out", req->buf, req->actual);
631         if (req->status || req->actual != bh->bulk_out_intended_length)
632                 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
633                                 req->status, req->actual,
634                                 bh->bulk_out_intended_length);
635         if (req->status == -ECONNRESET)         // Request was cancelled
636                 usb_ep_fifo_flush(ep);
637
638         /* Hold the lock while we update the request and buffer states */
639         smp_wmb();
640         spin_lock(&fsg->lock);
641         bh->outreq_busy = 0;
642         bh->state = BUF_STATE_FULL;
643         wakeup_thread(fsg);
644         spin_unlock(&fsg->lock);
645 }
646
647
648 /*-------------------------------------------------------------------------*/
649
650 /* Ep0 class-specific handlers.  These always run in_irq. */
651
652 static int class_setup_req(struct fsg_dev *fsg,
653                 const struct usb_ctrlrequest *ctrl)
654 {
655         struct usb_request      *req = fsg->ep0req;
656         u16                     w_index = le16_to_cpu(ctrl->wIndex);
657         u16                     w_value = le16_to_cpu(ctrl->wValue);
658         u16                     w_length = le16_to_cpu(ctrl->wLength);
659
660         if (!fsg->config)
661                 return -EOPNOTSUPP;
662
663         switch (ctrl->bRequest) {
664
665         case USB_BULK_RESET_REQUEST:
666                 if (ctrl->bRequestType !=
667                     (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
668                         break;
669                 if (w_index != 0 || w_value != 0)
670                         return -EDOM;
671
672                 /* Raise an exception to stop the current operation
673                  * and reinitialize our state. */
674                 DBG(fsg, "bulk reset request\n");
675                 raise_exception(fsg, FSG_STATE_RESET);
676                 return DELAYED_STATUS;
677
678         case USB_BULK_GET_MAX_LUN_REQUEST:
679                 if (ctrl->bRequestType !=
680                     (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
681                         break;
682                 if (w_index != 0 || w_value != 0)
683                         return -EDOM;
684                 VDBG(fsg, "get max LUN\n");
685                 *(u8 *) req->buf = fsg->common->nluns - 1;
686                 return 1;
687         }
688
689         VDBG(fsg,
690              "unknown class-specific control req "
691              "%02x.%02x v%04x i%04x l%u\n",
692              ctrl->bRequestType, ctrl->bRequest,
693              le16_to_cpu(ctrl->wValue), w_index, w_length);
694         return -EOPNOTSUPP;
695 }
696
697
698 /*-------------------------------------------------------------------------*/
699
700 /* Ep0 standard request handlers.  These always run in_irq. */
701
702 static int standard_setup_req(struct fsg_dev *fsg,
703                 const struct usb_ctrlrequest *ctrl)
704 {
705         struct usb_request      *req = fsg->ep0req;
706         int                     value = -EOPNOTSUPP;
707         u16                     w_index = le16_to_cpu(ctrl->wIndex);
708         u16                     w_value = le16_to_cpu(ctrl->wValue);
709
710         /* Usually this just stores reply data in the pre-allocated ep0 buffer,
711          * but config change events will also reconfigure hardware. */
712         switch (ctrl->bRequest) {
713
714         case USB_REQ_GET_DESCRIPTOR:
715                 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
716                                 USB_RECIP_DEVICE))
717                         break;
718                 switch (w_value >> 8) {
719
720                 case USB_DT_DEVICE:
721                         VDBG(fsg, "get device descriptor\n");
722                         value = sizeof device_desc;
723                         memcpy(req->buf, &device_desc, value);
724                         break;
725                 case USB_DT_DEVICE_QUALIFIER:
726                         VDBG(fsg, "get device qualifier\n");
727                         if (!gadget_is_dualspeed(fsg->gadget))
728                                 break;
729                         value = sizeof dev_qualifier;
730                         memcpy(req->buf, &dev_qualifier, value);
731                         break;
732
733                 case USB_DT_OTHER_SPEED_CONFIG:
734                         VDBG(fsg, "get other-speed config descriptor\n");
735                         if (!gadget_is_dualspeed(fsg->gadget))
736                                 break;
737                         goto get_config;
738                 case USB_DT_CONFIG:
739                         VDBG(fsg, "get configuration descriptor\n");
740 get_config:
741                         value = populate_config_buf(fsg->gadget,
742                                         req->buf,
743                                         w_value >> 8,
744                                         w_value & 0xff);
745                         break;
746
747                 case USB_DT_STRING:
748                         VDBG(fsg, "get string descriptor\n");
749
750                         /* wIndex == language code */
751                         value = usb_gadget_get_string(&fsg_stringtab,
752                                         w_value & 0xff, req->buf);
753                         break;
754                 }
755                 break;
756
757         /* One config, two speeds */
758         case USB_REQ_SET_CONFIGURATION:
759                 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
760                                 USB_RECIP_DEVICE))
761                         break;
762                 VDBG(fsg, "set configuration\n");
763                 if (w_value == CONFIG_VALUE || w_value == 0) {
764                         fsg->new_config = w_value;
765
766                         /* Raise an exception to wipe out previous transaction
767                          * state (queued bufs, etc) and set the new config. */
768                         raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
769                         value = DELAYED_STATUS;
770                 }
771                 break;
772         case USB_REQ_GET_CONFIGURATION:
773                 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
774                                 USB_RECIP_DEVICE))
775                         break;
776                 VDBG(fsg, "get configuration\n");
777                 *(u8 *) req->buf = fsg->config;
778                 value = 1;
779                 break;
780
781         case USB_REQ_SET_INTERFACE:
782                 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
783                                 USB_RECIP_INTERFACE))
784                         break;
785                 if (fsg->config && w_index == 0) {
786
787                         /* Raise an exception to wipe out previous transaction
788                          * state (queued bufs, etc) and install the new
789                          * interface altsetting. */
790                         raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
791                         value = DELAYED_STATUS;
792                 }
793                 break;
794         case USB_REQ_GET_INTERFACE:
795                 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
796                                 USB_RECIP_INTERFACE))
797                         break;
798                 if (!fsg->config)
799                         break;
800                 if (w_index != 0) {
801                         value = -EDOM;
802                         break;
803                 }
804                 VDBG(fsg, "get interface\n");
805                 *(u8 *) req->buf = 0;
806                 value = 1;
807                 break;
808
809         default:
810                 VDBG(fsg,
811                         "unknown control req %02x.%02x v%04x i%04x l%u\n",
812                         ctrl->bRequestType, ctrl->bRequest,
813                         w_value, w_index, le16_to_cpu(ctrl->wLength));
814         }
815
816         return value;
817 }
818
819
820 static int fsg_setup(struct usb_gadget *gadget,
821                 const struct usb_ctrlrequest *ctrl)
822 {
823         struct fsg_dev          *fsg = get_gadget_data(gadget);
824         int                     rc;
825         int                     w_length = le16_to_cpu(ctrl->wLength);
826
827         ++fsg->ep0_req_tag;             // Record arrival of a new request
828         fsg->ep0req->context = NULL;
829         fsg->ep0req->length = 0;
830         dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
831
832         if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
833                 rc = class_setup_req(fsg, ctrl);
834         else
835                 rc = standard_setup_req(fsg, ctrl);
836
837         /* Respond with data/status or defer until later? */
838         if (rc >= 0 && rc != DELAYED_STATUS) {
839                 rc = min(rc, w_length);
840                 fsg->ep0req->length = rc;
841                 fsg->ep0req->zero = rc < w_length;
842                 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
843                                 "ep0-in" : "ep0-out");
844                 rc = ep0_queue(fsg);
845         }
846
847         /* Device either stalls (rc < 0) or reports success */
848         return rc;
849 }
850
851
852 /*-------------------------------------------------------------------------*/
853
854 /* All the following routines run in process context */
855
856
857 /* Use this for bulk or interrupt transfers, not ep0 */
858 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
859                 struct usb_request *req, int *pbusy,
860                 enum fsg_buffer_state *state)
861 {
862         int     rc;
863
864         if (ep == fsg->bulk_in)
865                 dump_msg(fsg, "bulk-in", req->buf, req->length);
866
867         spin_lock_irq(&fsg->lock);
868         *pbusy = 1;
869         *state = BUF_STATE_BUSY;
870         spin_unlock_irq(&fsg->lock);
871         rc = usb_ep_queue(ep, req, GFP_KERNEL);
872         if (rc != 0) {
873                 *pbusy = 0;
874                 *state = BUF_STATE_EMPTY;
875
876                 /* We can't do much more than wait for a reset */
877
878                 /* Note: currently the net2280 driver fails zero-length
879                  * submissions if DMA is enabled. */
880                 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
881                                                 req->length == 0))
882                         WARNING(fsg, "error in submission: %s --> %d\n",
883                                         ep->name, rc);
884         }
885 }
886
887
888 static int sleep_thread(struct fsg_dev *fsg)
889 {
890         int     rc = 0;
891
892         /* Wait until a signal arrives or we are woken up */
893         for (;;) {
894                 try_to_freeze();
895                 set_current_state(TASK_INTERRUPTIBLE);
896                 if (signal_pending(current)) {
897                         rc = -EINTR;
898                         break;
899                 }
900                 if (fsg->thread_wakeup_needed)
901                         break;
902                 schedule();
903         }
904         __set_current_state(TASK_RUNNING);
905         fsg->thread_wakeup_needed = 0;
906         return rc;
907 }
908
909
910 /*-------------------------------------------------------------------------*/
911
912 static int do_read(struct fsg_dev *fsg)
913 {
914         struct fsg_lun          *curlun = fsg->common->curlun;
915         u32                     lba;
916         struct fsg_buffhd       *bh;
917         int                     rc;
918         u32                     amount_left;
919         loff_t                  file_offset, file_offset_tmp;
920         unsigned int            amount;
921         unsigned int            partial_page;
922         ssize_t                 nread;
923
924         /* Get the starting Logical Block Address and check that it's
925          * not too big */
926         if (fsg->common->cmnd[0] == SC_READ_6)
927                 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
928         else {
929                 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
930
931                 /* We allow DPO (Disable Page Out = don't save data in the
932                  * cache) and FUA (Force Unit Access = don't read from the
933                  * cache), but we don't implement them. */
934                 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
935                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
936                         return -EINVAL;
937                 }
938         }
939         if (lba >= curlun->num_sectors) {
940                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
941                 return -EINVAL;
942         }
943         file_offset = ((loff_t) lba) << 9;
944
945         /* Carry out the file reads */
946         amount_left = fsg->data_size_from_cmnd;
947         if (unlikely(amount_left == 0))
948                 return -EIO;            // No default reply
949
950         for (;;) {
951
952                 /* Figure out how much we need to read:
953                  * Try to read the remaining amount.
954                  * But don't read more than the buffer size.
955                  * And don't try to read past the end of the file.
956                  * Finally, if we're not at a page boundary, don't read past
957                  *      the next page.
958                  * If this means reading 0 then we were asked to read past
959                  *      the end of file. */
960                 amount = min(amount_left, FSG_BUFLEN);
961                 amount = min((loff_t) amount,
962                                 curlun->file_length - file_offset);
963                 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
964                 if (partial_page > 0)
965                         amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
966                                         partial_page);
967
968                 /* Wait for the next buffer to become available */
969                 bh = fsg->common->next_buffhd_to_fill;
970                 while (bh->state != BUF_STATE_EMPTY) {
971                         rc = sleep_thread(fsg);
972                         if (rc)
973                                 return rc;
974                 }
975
976                 /* If we were asked to read past the end of file,
977                  * end with an empty buffer. */
978                 if (amount == 0) {
979                         curlun->sense_data =
980                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
981                         curlun->sense_data_info = file_offset >> 9;
982                         curlun->info_valid = 1;
983                         bh->inreq->length = 0;
984                         bh->state = BUF_STATE_FULL;
985                         break;
986                 }
987
988                 /* Perform the read */
989                 file_offset_tmp = file_offset;
990                 nread = vfs_read(curlun->filp,
991                                 (char __user *) bh->buf,
992                                 amount, &file_offset_tmp);
993                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
994                                 (unsigned long long) file_offset,
995                                 (int) nread);
996                 if (signal_pending(current))
997                         return -EINTR;
998
999                 if (nread < 0) {
1000                         LDBG(curlun, "error in file read: %d\n",
1001                                         (int) nread);
1002                         nread = 0;
1003                 } else if (nread < amount) {
1004                         LDBG(curlun, "partial file read: %d/%u\n",
1005                                         (int) nread, amount);
1006                         nread -= (nread & 511); // Round down to a block
1007                 }
1008                 file_offset  += nread;
1009                 amount_left  -= nread;
1010                 fsg->residue -= nread;
1011                 bh->inreq->length = nread;
1012                 bh->state = BUF_STATE_FULL;
1013
1014                 /* If an error occurred, report it and its position */
1015                 if (nread < amount) {
1016                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1017                         curlun->sense_data_info = file_offset >> 9;
1018                         curlun->info_valid = 1;
1019                         break;
1020                 }
1021
1022                 if (amount_left == 0)
1023                         break;          // No more left to read
1024
1025                 /* Send this buffer and go read some more */
1026                 bh->inreq->zero = 0;
1027                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1028                                 &bh->inreq_busy, &bh->state);
1029                 fsg->common->next_buffhd_to_fill = bh->next;
1030         }
1031
1032         return -EIO;            // No default reply
1033 }
1034
1035
1036 /*-------------------------------------------------------------------------*/
1037
1038 static int do_write(struct fsg_dev *fsg)
1039 {
1040         struct fsg_lun          *curlun = fsg->common->curlun;
1041         u32                     lba;
1042         struct fsg_buffhd       *bh;
1043         int                     get_some_more;
1044         u32                     amount_left_to_req, amount_left_to_write;
1045         loff_t                  usb_offset, file_offset, file_offset_tmp;
1046         unsigned int            amount;
1047         unsigned int            partial_page;
1048         ssize_t                 nwritten;
1049         int                     rc;
1050
1051         if (curlun->ro) {
1052                 curlun->sense_data = SS_WRITE_PROTECTED;
1053                 return -EINVAL;
1054         }
1055         spin_lock(&curlun->filp->f_lock);
1056         curlun->filp->f_flags &= ~O_SYNC;       // Default is not to wait
1057         spin_unlock(&curlun->filp->f_lock);
1058
1059         /* Get the starting Logical Block Address and check that it's
1060          * not too big */
1061         if (fsg->common->cmnd[0] == SC_WRITE_6)
1062                 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
1063         else {
1064                 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1065
1066                 /* We allow DPO (Disable Page Out = don't save data in the
1067                  * cache) and FUA (Force Unit Access = write directly to the
1068                  * medium).  We don't implement DPO; we implement FUA by
1069                  * performing synchronous output. */
1070                 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
1071                         curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1072                         return -EINVAL;
1073                 }
1074                 if (fsg->common->cmnd[1] & 0x08) {      // FUA
1075                         spin_lock(&curlun->filp->f_lock);
1076                         curlun->filp->f_flags |= O_SYNC;
1077                         spin_unlock(&curlun->filp->f_lock);
1078                 }
1079         }
1080         if (lba >= curlun->num_sectors) {
1081                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1082                 return -EINVAL;
1083         }
1084
1085         /* Carry out the file writes */
1086         get_some_more = 1;
1087         file_offset = usb_offset = ((loff_t) lba) << 9;
1088         amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1089
1090         while (amount_left_to_write > 0) {
1091
1092                 /* Queue a request for more data from the host */
1093                 bh = fsg->common->next_buffhd_to_fill;
1094                 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1095
1096                         /* Figure out how much we want to get:
1097                          * Try to get the remaining amount.
1098                          * But don't get more than the buffer size.
1099                          * And don't try to go past the end of the file.
1100                          * If we're not at a page boundary,
1101                          *      don't go past the next page.
1102                          * If this means getting 0, then we were asked
1103                          *      to write past the end of file.
1104                          * Finally, round down to a block boundary. */
1105                         amount = min(amount_left_to_req, FSG_BUFLEN);
1106                         amount = min((loff_t) amount, curlun->file_length -
1107                                         usb_offset);
1108                         partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1109                         if (partial_page > 0)
1110                                 amount = min(amount,
1111         (unsigned int) PAGE_CACHE_SIZE - partial_page);
1112
1113                         if (amount == 0) {
1114                                 get_some_more = 0;
1115                                 curlun->sense_data =
1116                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1117                                 curlun->sense_data_info = usb_offset >> 9;
1118                                 curlun->info_valid = 1;
1119                                 continue;
1120                         }
1121                         amount -= (amount & 511);
1122                         if (amount == 0) {
1123
1124                                 /* Why were we were asked to transfer a
1125                                  * partial block? */
1126                                 get_some_more = 0;
1127                                 continue;
1128                         }
1129
1130                         /* Get the next buffer */
1131                         usb_offset += amount;
1132                         fsg->usb_amount_left -= amount;
1133                         amount_left_to_req -= amount;
1134                         if (amount_left_to_req == 0)
1135                                 get_some_more = 0;
1136
1137                         /* amount is always divisible by 512, hence by
1138                          * the bulk-out maxpacket size */
1139                         bh->outreq->length = bh->bulk_out_intended_length =
1140                                         amount;
1141                         bh->outreq->short_not_ok = 1;
1142                         start_transfer(fsg, fsg->bulk_out, bh->outreq,
1143                                         &bh->outreq_busy, &bh->state);
1144                         fsg->common->next_buffhd_to_fill = bh->next;
1145                         continue;
1146                 }
1147
1148                 /* Write the received data to the backing file */
1149                 bh = fsg->common->next_buffhd_to_drain;
1150                 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1151                         break;                  // We stopped early
1152                 if (bh->state == BUF_STATE_FULL) {
1153                         smp_rmb();
1154                         fsg->common->next_buffhd_to_drain = bh->next;
1155                         bh->state = BUF_STATE_EMPTY;
1156
1157                         /* Did something go wrong with the transfer? */
1158                         if (bh->outreq->status != 0) {
1159                                 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1160                                 curlun->sense_data_info = file_offset >> 9;
1161                                 curlun->info_valid = 1;
1162                                 break;
1163                         }
1164
1165                         amount = bh->outreq->actual;
1166                         if (curlun->file_length - file_offset < amount) {
1167                                 LERROR(curlun,
1168         "write %u @ %llu beyond end %llu\n",
1169         amount, (unsigned long long) file_offset,
1170         (unsigned long long) curlun->file_length);
1171                                 amount = curlun->file_length - file_offset;
1172                         }
1173
1174                         /* Perform the write */
1175                         file_offset_tmp = file_offset;
1176                         nwritten = vfs_write(curlun->filp,
1177                                         (char __user *) bh->buf,
1178                                         amount, &file_offset_tmp);
1179                         VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1180                                         (unsigned long long) file_offset,
1181                                         (int) nwritten);
1182                         if (signal_pending(current))
1183                                 return -EINTR;          // Interrupted!
1184
1185                         if (nwritten < 0) {
1186                                 LDBG(curlun, "error in file write: %d\n",
1187                                                 (int) nwritten);
1188                                 nwritten = 0;
1189                         } else if (nwritten < amount) {
1190                                 LDBG(curlun, "partial file write: %d/%u\n",
1191                                                 (int) nwritten, amount);
1192                                 nwritten -= (nwritten & 511);
1193                                                 // Round down to a block
1194                         }
1195                         file_offset += nwritten;
1196                         amount_left_to_write -= nwritten;
1197                         fsg->residue -= nwritten;
1198
1199                         /* If an error occurred, report it and its position */
1200                         if (nwritten < amount) {
1201                                 curlun->sense_data = SS_WRITE_ERROR;
1202                                 curlun->sense_data_info = file_offset >> 9;
1203                                 curlun->info_valid = 1;
1204                                 break;
1205                         }
1206
1207                         /* Did the host decide to stop early? */
1208                         if (bh->outreq->actual != bh->outreq->length) {
1209                                 fsg->short_packet_received = 1;
1210                                 break;
1211                         }
1212                         continue;
1213                 }
1214
1215                 /* Wait for something to happen */
1216                 rc = sleep_thread(fsg);
1217                 if (rc)
1218                         return rc;
1219         }
1220
1221         return -EIO;            // No default reply
1222 }
1223
1224
1225 /*-------------------------------------------------------------------------*/
1226
1227 static int do_synchronize_cache(struct fsg_dev *fsg)
1228 {
1229         struct fsg_lun  *curlun = fsg->common->curlun;
1230         int             rc;
1231
1232         /* We ignore the requested LBA and write out all file's
1233          * dirty data buffers. */
1234         rc = fsg_lun_fsync_sub(curlun);
1235         if (rc)
1236                 curlun->sense_data = SS_WRITE_ERROR;
1237         return 0;
1238 }
1239
1240
1241 /*-------------------------------------------------------------------------*/
1242
1243 static void invalidate_sub(struct fsg_lun *curlun)
1244 {
1245         struct file     *filp = curlun->filp;
1246         struct inode    *inode = filp->f_path.dentry->d_inode;
1247         unsigned long   rc;
1248
1249         rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1250         VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1251 }
1252
1253 static int do_verify(struct fsg_dev *fsg)
1254 {
1255         struct fsg_lun          *curlun = fsg->common->curlun;
1256         u32                     lba;
1257         u32                     verification_length;
1258         struct fsg_buffhd       *bh = fsg->common->next_buffhd_to_fill;
1259         loff_t                  file_offset, file_offset_tmp;
1260         u32                     amount_left;
1261         unsigned int            amount;
1262         ssize_t                 nread;
1263
1264         /* Get the starting Logical Block Address and check that it's
1265          * not too big */
1266         lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1267         if (lba >= curlun->num_sectors) {
1268                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1269                 return -EINVAL;
1270         }
1271
1272         /* We allow DPO (Disable Page Out = don't save data in the
1273          * cache) but we don't implement it. */
1274         if ((fsg->common->cmnd[1] & ~0x10) != 0) {
1275                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1276                 return -EINVAL;
1277         }
1278
1279         verification_length = get_unaligned_be16(&fsg->common->cmnd[7]);
1280         if (unlikely(verification_length == 0))
1281                 return -EIO;            // No default reply
1282
1283         /* Prepare to carry out the file verify */
1284         amount_left = verification_length << 9;
1285         file_offset = ((loff_t) lba) << 9;
1286
1287         /* Write out all the dirty buffers before invalidating them */
1288         fsg_lun_fsync_sub(curlun);
1289         if (signal_pending(current))
1290                 return -EINTR;
1291
1292         invalidate_sub(curlun);
1293         if (signal_pending(current))
1294                 return -EINTR;
1295
1296         /* Just try to read the requested blocks */
1297         while (amount_left > 0) {
1298
1299                 /* Figure out how much we need to read:
1300                  * Try to read the remaining amount, but not more than
1301                  * the buffer size.
1302                  * And don't try to read past the end of the file.
1303                  * If this means reading 0 then we were asked to read
1304                  * past the end of file. */
1305                 amount = min(amount_left, FSG_BUFLEN);
1306                 amount = min((loff_t) amount,
1307                                 curlun->file_length - file_offset);
1308                 if (amount == 0) {
1309                         curlun->sense_data =
1310                                         SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1311                         curlun->sense_data_info = file_offset >> 9;
1312                         curlun->info_valid = 1;
1313                         break;
1314                 }
1315
1316                 /* Perform the read */
1317                 file_offset_tmp = file_offset;
1318                 nread = vfs_read(curlun->filp,
1319                                 (char __user *) bh->buf,
1320                                 amount, &file_offset_tmp);
1321                 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1322                                 (unsigned long long) file_offset,
1323                                 (int) nread);
1324                 if (signal_pending(current))
1325                         return -EINTR;
1326
1327                 if (nread < 0) {
1328                         LDBG(curlun, "error in file verify: %d\n",
1329                                         (int) nread);
1330                         nread = 0;
1331                 } else if (nread < amount) {
1332                         LDBG(curlun, "partial file verify: %d/%u\n",
1333                                         (int) nread, amount);
1334                         nread -= (nread & 511); // Round down to a sector
1335                 }
1336                 if (nread == 0) {
1337                         curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1338                         curlun->sense_data_info = file_offset >> 9;
1339                         curlun->info_valid = 1;
1340                         break;
1341                 }
1342                 file_offset += nread;
1343                 amount_left -= nread;
1344         }
1345         return 0;
1346 }
1347
1348
1349 /*-------------------------------------------------------------------------*/
1350
1351 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1352 {
1353         u8      *buf = (u8 *) bh->buf;
1354
1355         static char vendor_id[] = "Linux   ";
1356         static char product_disk_id[] = "File-Stor Gadget";
1357         static char product_cdrom_id[] = "File-CD Gadget  ";
1358
1359         if (!fsg->common->curlun) {             // Unsupported LUNs are okay
1360                 fsg->bad_lun_okay = 1;
1361                 memset(buf, 0, 36);
1362                 buf[0] = 0x7f;          // Unsupported, no device-type
1363                 buf[4] = 31;            // Additional length
1364                 return 36;
1365         }
1366
1367         memset(buf, 0, 8);
1368         buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
1369         if (mod_data.removable)
1370                 buf[1] = 0x80;
1371         buf[2] = 2;             // ANSI SCSI level 2
1372         buf[3] = 2;             // SCSI-2 INQUIRY data format
1373         buf[4] = 31;            // Additional length
1374                                 // No special options
1375         sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1376                         (mod_data.cdrom ? product_cdrom_id :
1377                                 product_disk_id),
1378                         mod_data.release);
1379         return 36;
1380 }
1381
1382
1383 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1384 {
1385         struct fsg_lun  *curlun = fsg->common->curlun;
1386         u8              *buf = (u8 *) bh->buf;
1387         u32             sd, sdinfo;
1388         int             valid;
1389
1390         /*
1391          * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1392          *
1393          * If a REQUEST SENSE command is received from an initiator
1394          * with a pending unit attention condition (before the target
1395          * generates the contingent allegiance condition), then the
1396          * target shall either:
1397          *   a) report any pending sense data and preserve the unit
1398          *      attention condition on the logical unit, or,
1399          *   b) report the unit attention condition, may discard any
1400          *      pending sense data, and clear the unit attention
1401          *      condition on the logical unit for that initiator.
1402          *
1403          * FSG normally uses option a); enable this code to use option b).
1404          */
1405 #if 0
1406         if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1407                 curlun->sense_data = curlun->unit_attention_data;
1408                 curlun->unit_attention_data = SS_NO_SENSE;
1409         }
1410 #endif
1411
1412         if (!curlun) {          // Unsupported LUNs are okay
1413                 fsg->bad_lun_okay = 1;
1414                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1415                 sdinfo = 0;
1416                 valid = 0;
1417         } else {
1418                 sd = curlun->sense_data;
1419                 sdinfo = curlun->sense_data_info;
1420                 valid = curlun->info_valid << 7;
1421                 curlun->sense_data = SS_NO_SENSE;
1422                 curlun->sense_data_info = 0;
1423                 curlun->info_valid = 0;
1424         }
1425
1426         memset(buf, 0, 18);
1427         buf[0] = valid | 0x70;                  // Valid, current error
1428         buf[2] = SK(sd);
1429         put_unaligned_be32(sdinfo, &buf[3]);    /* Sense information */
1430         buf[7] = 18 - 8;                        // Additional sense length
1431         buf[12] = ASC(sd);
1432         buf[13] = ASCQ(sd);
1433         return 18;
1434 }
1435
1436
1437 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1438 {
1439         struct fsg_lun  *curlun = fsg->common->curlun;
1440         u32             lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1441         int             pmi = fsg->common->cmnd[8];
1442         u8              *buf = (u8 *) bh->buf;
1443
1444         /* Check the PMI and LBA fields */
1445         if (pmi > 1 || (pmi == 0 && lba != 0)) {
1446                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1447                 return -EINVAL;
1448         }
1449
1450         put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1451                                                 /* Max logical block */
1452         put_unaligned_be32(512, &buf[4]);       /* Block length */
1453         return 8;
1454 }
1455
1456
1457 static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1458 {
1459         struct fsg_lun  *curlun = fsg->common->curlun;
1460         int             msf = fsg->common->cmnd[1] & 0x02;
1461         u32             lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1462         u8              *buf = (u8 *) bh->buf;
1463
1464         if ((fsg->common->cmnd[1] & ~0x02) != 0) {      /* Mask away MSF */
1465                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1466                 return -EINVAL;
1467         }
1468         if (lba >= curlun->num_sectors) {
1469                 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1470                 return -EINVAL;
1471         }
1472
1473         memset(buf, 0, 8);
1474         buf[0] = 0x01;          /* 2048 bytes of user data, rest is EC */
1475         store_cdrom_address(&buf[4], msf, lba);
1476         return 8;
1477 }
1478
1479
1480 static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1481 {
1482         struct fsg_lun  *curlun = fsg->common->curlun;
1483         int             msf = fsg->common->cmnd[1] & 0x02;
1484         int             start_track = fsg->common->cmnd[6];
1485         u8              *buf = (u8 *) bh->buf;
1486
1487         if ((fsg->common->cmnd[1] & ~0x02) != 0 ||      /* Mask away MSF */
1488                         start_track > 1) {
1489                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1490                 return -EINVAL;
1491         }
1492
1493         memset(buf, 0, 20);
1494         buf[1] = (20-2);                /* TOC data length */
1495         buf[2] = 1;                     /* First track number */
1496         buf[3] = 1;                     /* Last track number */
1497         buf[5] = 0x16;                  /* Data track, copying allowed */
1498         buf[6] = 0x01;                  /* Only track is number 1 */
1499         store_cdrom_address(&buf[8], msf, 0);
1500
1501         buf[13] = 0x16;                 /* Lead-out track is data */
1502         buf[14] = 0xAA;                 /* Lead-out track number */
1503         store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1504         return 20;
1505 }
1506
1507
1508 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1509 {
1510         struct fsg_lun  *curlun = fsg->common->curlun;
1511         int             mscmnd = fsg->common->cmnd[0];
1512         u8              *buf = (u8 *) bh->buf;
1513         u8              *buf0 = buf;
1514         int             pc, page_code;
1515         int             changeable_values, all_pages;
1516         int             valid_page = 0;
1517         int             len, limit;
1518
1519         if ((fsg->common->cmnd[1] & ~0x08) != 0) {      // Mask away DBD
1520                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1521                 return -EINVAL;
1522         }
1523         pc = fsg->common->cmnd[2] >> 6;
1524         page_code = fsg->common->cmnd[2] & 0x3f;
1525         if (pc == 3) {
1526                 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1527                 return -EINVAL;
1528         }
1529         changeable_values = (pc == 1);
1530         all_pages = (page_code == 0x3f);
1531
1532         /* Write the mode parameter header.  Fixed values are: default
1533          * medium type, no cache control (DPOFUA), and no block descriptors.
1534          * The only variable value is the WriteProtect bit.  We will fill in
1535          * the mode data length later. */
1536         memset(buf, 0, 8);
1537         if (mscmnd == SC_MODE_SENSE_6) {
1538                 buf[2] = (curlun->ro ? 0x80 : 0x00);            // WP, DPOFUA
1539                 buf += 4;
1540                 limit = 255;
1541         } else {                        // SC_MODE_SENSE_10
1542                 buf[3] = (curlun->ro ? 0x80 : 0x00);            // WP, DPOFUA
1543                 buf += 8;
1544                 limit = 65535;          // Should really be FSG_BUFLEN
1545         }
1546
1547         /* No block descriptors */
1548
1549         /* The mode pages, in numerical order.  The only page we support
1550          * is the Caching page. */
1551         if (page_code == 0x08 || all_pages) {
1552                 valid_page = 1;
1553                 buf[0] = 0x08;          // Page code
1554                 buf[1] = 10;            // Page length
1555                 memset(buf+2, 0, 10);   // None of the fields are changeable
1556
1557                 if (!changeable_values) {
1558                         buf[2] = 0x04;  // Write cache enable,
1559                                         // Read cache not disabled
1560                                         // No cache retention priorities
1561                         put_unaligned_be16(0xffff, &buf[4]);
1562                                         /* Don't disable prefetch */
1563                                         /* Minimum prefetch = 0 */
1564                         put_unaligned_be16(0xffff, &buf[8]);
1565                                         /* Maximum prefetch */
1566                         put_unaligned_be16(0xffff, &buf[10]);
1567                                         /* Maximum prefetch ceiling */
1568                 }
1569                 buf += 12;
1570         }
1571
1572         /* Check that a valid page was requested and the mode data length
1573          * isn't too long. */
1574         len = buf - buf0;
1575         if (!valid_page || len > limit) {
1576                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1577                 return -EINVAL;
1578         }
1579
1580         /*  Store the mode data length */
1581         if (mscmnd == SC_MODE_SENSE_6)
1582                 buf0[0] = len - 1;
1583         else
1584                 put_unaligned_be16(len - 2, buf0);
1585         return len;
1586 }
1587
1588
1589 static int do_start_stop(struct fsg_dev *fsg)
1590 {
1591         if (!mod_data.removable) {
1592                 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
1593                 return -EINVAL;
1594         }
1595         return 0;
1596 }
1597
1598
1599 static int do_prevent_allow(struct fsg_dev *fsg)
1600 {
1601         struct fsg_lun  *curlun = fsg->common->curlun;
1602         int             prevent;
1603
1604         if (!mod_data.removable) {
1605                 curlun->sense_data = SS_INVALID_COMMAND;
1606                 return -EINVAL;
1607         }
1608
1609         prevent = fsg->common->cmnd[4] & 0x01;
1610         if ((fsg->common->cmnd[4] & ~0x01) != 0) {      // Mask away Prevent
1611                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1612                 return -EINVAL;
1613         }
1614
1615         if (curlun->prevent_medium_removal && !prevent)
1616                 fsg_lun_fsync_sub(curlun);
1617         curlun->prevent_medium_removal = prevent;
1618         return 0;
1619 }
1620
1621
1622 static int do_read_format_capacities(struct fsg_dev *fsg,
1623                         struct fsg_buffhd *bh)
1624 {
1625         struct fsg_lun  *curlun = fsg->common->curlun;
1626         u8              *buf = (u8 *) bh->buf;
1627
1628         buf[0] = buf[1] = buf[2] = 0;
1629         buf[3] = 8;             // Only the Current/Maximum Capacity Descriptor
1630         buf += 4;
1631
1632         put_unaligned_be32(curlun->num_sectors, &buf[0]);
1633                                                 /* Number of blocks */
1634         put_unaligned_be32(512, &buf[4]);       /* Block length */
1635         buf[4] = 0x02;                          /* Current capacity */
1636         return 12;
1637 }
1638
1639
1640 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1641 {
1642         struct fsg_lun  *curlun = fsg->common->curlun;
1643
1644         /* We don't support MODE SELECT */
1645         curlun->sense_data = SS_INVALID_COMMAND;
1646         return -EINVAL;
1647 }
1648
1649
1650 /*-------------------------------------------------------------------------*/
1651
1652 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1653 {
1654         int     rc;
1655
1656         rc = fsg_set_halt(fsg, fsg->bulk_in);
1657         if (rc == -EAGAIN)
1658                 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1659         while (rc != 0) {
1660                 if (rc != -EAGAIN) {
1661                         WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1662                         rc = 0;
1663                         break;
1664                 }
1665
1666                 /* Wait for a short time and then try again */
1667                 if (msleep_interruptible(100) != 0)
1668                         return -EINTR;
1669                 rc = usb_ep_set_halt(fsg->bulk_in);
1670         }
1671         return rc;
1672 }
1673
1674 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1675 {
1676         int     rc;
1677
1678         DBG(fsg, "bulk-in set wedge\n");
1679         rc = usb_ep_set_wedge(fsg->bulk_in);
1680         if (rc == -EAGAIN)
1681                 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1682         while (rc != 0) {
1683                 if (rc != -EAGAIN) {
1684                         WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1685                         rc = 0;
1686                         break;
1687                 }
1688
1689                 /* Wait for a short time and then try again */
1690                 if (msleep_interruptible(100) != 0)
1691                         return -EINTR;
1692                 rc = usb_ep_set_wedge(fsg->bulk_in);
1693         }
1694         return rc;
1695 }
1696
1697 static int pad_with_zeros(struct fsg_dev *fsg)
1698 {
1699         struct fsg_buffhd       *bh = fsg->common->next_buffhd_to_fill;
1700         u32                     nkeep = bh->inreq->length;
1701         u32                     nsend;
1702         int                     rc;
1703
1704         bh->state = BUF_STATE_EMPTY;            // For the first iteration
1705         fsg->usb_amount_left = nkeep + fsg->residue;
1706         while (fsg->usb_amount_left > 0) {
1707
1708                 /* Wait for the next buffer to be free */
1709                 while (bh->state != BUF_STATE_EMPTY) {
1710                         rc = sleep_thread(fsg);
1711                         if (rc)
1712                                 return rc;
1713                 }
1714
1715                 nsend = min(fsg->usb_amount_left, FSG_BUFLEN);
1716                 memset(bh->buf + nkeep, 0, nsend - nkeep);
1717                 bh->inreq->length = nsend;
1718                 bh->inreq->zero = 0;
1719                 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1720                                 &bh->inreq_busy, &bh->state);
1721                 bh = fsg->common->next_buffhd_to_fill = bh->next;
1722                 fsg->usb_amount_left -= nsend;
1723                 nkeep = 0;
1724         }
1725         return 0;
1726 }
1727
1728 static int throw_away_data(struct fsg_dev *fsg)
1729 {
1730         struct fsg_buffhd       *bh;
1731         u32                     amount;
1732         int                     rc;
1733
1734         for (bh = fsg->common->next_buffhd_to_drain;
1735              bh->state != BUF_STATE_EMPTY || fsg->usb_amount_left > 0;
1736              bh = fsg->common->next_buffhd_to_drain) {
1737
1738                 /* Throw away the data in a filled buffer */
1739                 if (bh->state == BUF_STATE_FULL) {
1740                         smp_rmb();
1741                         bh->state = BUF_STATE_EMPTY;
1742                         fsg->common->next_buffhd_to_drain = bh->next;
1743
1744                         /* A short packet or an error ends everything */
1745                         if (bh->outreq->actual != bh->outreq->length ||
1746                                         bh->outreq->status != 0) {
1747                                 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1748                                 return -EINTR;
1749                         }
1750                         continue;
1751                 }
1752
1753                 /* Try to submit another request if we need one */
1754                 bh = fsg->common->next_buffhd_to_fill;
1755                 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1756                         amount = min(fsg->usb_amount_left, FSG_BUFLEN);
1757
1758                         /* amount is always divisible by 512, hence by
1759                          * the bulk-out maxpacket size */
1760                         bh->outreq->length = bh->bulk_out_intended_length =
1761                                         amount;
1762                         bh->outreq->short_not_ok = 1;
1763                         start_transfer(fsg, fsg->bulk_out, bh->outreq,
1764                                         &bh->outreq_busy, &bh->state);
1765                         fsg->common->next_buffhd_to_fill = bh->next;
1766                         fsg->usb_amount_left -= amount;
1767                         continue;
1768                 }
1769
1770                 /* Otherwise wait for something to happen */
1771                 rc = sleep_thread(fsg);
1772                 if (rc)
1773                         return rc;
1774         }
1775         return 0;
1776 }
1777
1778
1779 static int finish_reply(struct fsg_dev *fsg)
1780 {
1781         struct fsg_buffhd       *bh = fsg->common->next_buffhd_to_fill;
1782         int                     rc = 0;
1783
1784         switch (fsg->data_dir) {
1785         case DATA_DIR_NONE:
1786                 break;                  // Nothing to send
1787
1788         /* If we don't know whether the host wants to read or write,
1789          * this must be CB or CBI with an unknown command.  We mustn't
1790          * try to send or receive any data.  So stall both bulk pipes
1791          * if we can and wait for a reset. */
1792         case DATA_DIR_UNKNOWN:
1793                 if (mod_data.can_stall) {
1794                         fsg_set_halt(fsg, fsg->bulk_out);
1795                         rc = halt_bulk_in_endpoint(fsg);
1796                 }
1797                 break;
1798
1799         /* All but the last buffer of data must have already been sent */
1800         case DATA_DIR_TO_HOST:
1801                 if (fsg->data_size == 0) {
1802                         /* Nothing to send */
1803
1804                 /* If there's no residue, simply send the last buffer */
1805                 } else if (fsg->residue == 0) {
1806                         bh->inreq->zero = 0;
1807                         start_transfer(fsg, fsg->bulk_in, bh->inreq,
1808                                         &bh->inreq_busy, &bh->state);
1809                         fsg->common->next_buffhd_to_fill = bh->next;
1810
1811                 /* For Bulk-only, if we're allowed to stall then send the
1812                  * short packet and halt the bulk-in endpoint.  If we can't
1813                  * stall, pad out the remaining data with 0's. */
1814                 } else if (mod_data.can_stall) {
1815                         bh->inreq->zero = 1;
1816                         start_transfer(fsg, fsg->bulk_in, bh->inreq,
1817                                        &bh->inreq_busy, &bh->state);
1818                         fsg->common->next_buffhd_to_fill = bh->next;
1819                         rc = halt_bulk_in_endpoint(fsg);
1820                 } else {
1821                         rc = pad_with_zeros(fsg);
1822                 }
1823                 break;
1824
1825         /* We have processed all we want from the data the host has sent.
1826          * There may still be outstanding bulk-out requests. */
1827         case DATA_DIR_FROM_HOST:
1828                 if (fsg->residue == 0)
1829                         ;               // Nothing to receive
1830
1831                 /* Did the host stop sending unexpectedly early? */
1832                 else if (fsg->short_packet_received) {
1833                         raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1834                         rc = -EINTR;
1835                 }
1836
1837                 /* We haven't processed all the incoming data.  Even though
1838                  * we may be allowed to stall, doing so would cause a race.
1839                  * The controller may already have ACK'ed all the remaining
1840                  * bulk-out packets, in which case the host wouldn't see a
1841                  * STALL.  Not realizing the endpoint was halted, it wouldn't
1842                  * clear the halt -- leading to problems later on. */
1843 #if 0
1844                 else if (mod_data.can_stall) {
1845                         fsg_set_halt(fsg, fsg->bulk_out);
1846                         raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1847                         rc = -EINTR;
1848                 }
1849 #endif
1850
1851                 /* We can't stall.  Read in the excess data and throw it
1852                  * all away. */
1853                 else
1854                         rc = throw_away_data(fsg);
1855                 break;
1856         }
1857         return rc;
1858 }
1859
1860
1861 static int send_status(struct fsg_dev *fsg)
1862 {
1863         struct fsg_lun          *curlun = fsg->common->curlun;
1864         struct fsg_buffhd       *bh;
1865         struct bulk_cs_wrap     *csw;
1866         int                     rc;
1867         u8                      status = USB_STATUS_PASS;
1868         u32                     sd, sdinfo = 0;
1869
1870         /* Wait for the next buffer to become available */
1871         bh = fsg->common->next_buffhd_to_fill;
1872         while (bh->state != BUF_STATE_EMPTY) {
1873                 rc = sleep_thread(fsg);
1874                 if (rc)
1875                         return rc;
1876         }
1877
1878         if (curlun) {
1879                 sd = curlun->sense_data;
1880                 sdinfo = curlun->sense_data_info;
1881         } else if (fsg->bad_lun_okay)
1882                 sd = SS_NO_SENSE;
1883         else
1884                 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1885
1886         if (fsg->phase_error) {
1887                 DBG(fsg, "sending phase-error status\n");
1888                 status = USB_STATUS_PHASE_ERROR;
1889                 sd = SS_INVALID_COMMAND;
1890         } else if (sd != SS_NO_SENSE) {
1891                 DBG(fsg, "sending command-failure status\n");
1892                 status = USB_STATUS_FAIL;
1893                 VDBG(fsg, "  sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1894                                 "  info x%x\n",
1895                                 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1896         }
1897
1898         /* Store and send the Bulk-only CSW */
1899         csw = (void*)bh->buf;
1900
1901         csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1902         csw->Tag = fsg->tag;
1903         csw->Residue = cpu_to_le32(fsg->residue);
1904         csw->Status = status;
1905
1906         bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1907         bh->inreq->zero = 0;
1908         start_transfer(fsg, fsg->bulk_in, bh->inreq,
1909                        &bh->inreq_busy, &bh->state);
1910
1911         fsg->common->next_buffhd_to_fill = bh->next;
1912         return 0;
1913 }
1914
1915
1916 /*-------------------------------------------------------------------------*/
1917
1918 /* Check whether the command is properly formed and whether its data size
1919  * and direction agree with the values we already have. */
1920 static int check_command(struct fsg_dev *fsg, int cmnd_size,
1921                 enum data_direction data_dir, unsigned int mask,
1922                 int needs_medium, const char *name)
1923 {
1924         int                     i;
1925         int                     lun = fsg->common->cmnd[1] >> 5;
1926         static const char       dirletter[4] = {'u', 'o', 'i', 'n'};
1927         char                    hdlen[20];
1928         struct fsg_lun          *curlun;
1929
1930         hdlen[0] = 0;
1931         if (fsg->data_dir != DATA_DIR_UNKNOWN)
1932                 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1933                                 fsg->data_size);
1934         VDBG(fsg, "SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
1935                         name, cmnd_size, dirletter[(int) data_dir],
1936                         fsg->data_size_from_cmnd, fsg->common->cmnd_size, hdlen);
1937
1938         /* We can't reply at all until we know the correct data direction
1939          * and size. */
1940         if (fsg->data_size_from_cmnd == 0)
1941                 data_dir = DATA_DIR_NONE;
1942         if (fsg->data_dir == DATA_DIR_UNKNOWN) {        // CB or CBI
1943                 fsg->data_dir = data_dir;
1944                 fsg->data_size = fsg->data_size_from_cmnd;
1945
1946         } else {                                        // Bulk-only
1947                 if (fsg->data_size < fsg->data_size_from_cmnd) {
1948
1949                         /* Host data size < Device data size is a phase error.
1950                          * Carry out the command, but only transfer as much
1951                          * as we are allowed. */
1952                         fsg->data_size_from_cmnd = fsg->data_size;
1953                         fsg->phase_error = 1;
1954                 }
1955         }
1956         fsg->residue = fsg->usb_amount_left = fsg->data_size;
1957
1958         /* Conflicting data directions is a phase error */
1959         if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
1960                 fsg->phase_error = 1;
1961                 return -EINVAL;
1962         }
1963
1964         /* Verify the length of the command itself */
1965         if (cmnd_size != fsg->common->cmnd_size) {
1966
1967                 /* Special case workaround: There are plenty of buggy SCSI
1968                  * implementations. Many have issues with cbw->Length
1969                  * field passing a wrong command size. For those cases we
1970                  * always try to work around the problem by using the length
1971                  * sent by the host side provided it is at least as large
1972                  * as the correct command length.
1973                  * Examples of such cases would be MS-Windows, which issues
1974                  * REQUEST SENSE with cbw->Length == 12 where it should
1975                  * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1976                  * REQUEST SENSE with cbw->Length == 10 where it should
1977                  * be 6 as well.
1978                  */
1979                 if (cmnd_size <= fsg->common->cmnd_size) {
1980                         DBG(fsg, "%s is buggy! Expected length %d "
1981                             "but we got %d\n", name,
1982                             cmnd_size, fsg->common->cmnd_size);
1983                         cmnd_size = fsg->common->cmnd_size;
1984                 } else {
1985                         fsg->phase_error = 1;
1986                         return -EINVAL;
1987                 }
1988         }
1989
1990         /* Check that the LUN values are consistent */
1991         if (fsg->common->lun != lun)
1992                 DBG(fsg, "using LUN %d from CBW, not LUN %d from CDB\n",
1993                     fsg->common->lun, lun);
1994
1995         /* Check the LUN */
1996         if (fsg->common->lun >= 0 && fsg->common->lun < fsg->common->nluns) {
1997                 fsg->common->curlun = curlun = &fsg->common->luns[fsg->common->lun];
1998                 if (fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
1999                         curlun->sense_data = SS_NO_SENSE;
2000                         curlun->sense_data_info = 0;
2001                         curlun->info_valid = 0;
2002                 }
2003         } else {
2004                 fsg->common->curlun = curlun = NULL;
2005                 fsg->bad_lun_okay = 0;
2006
2007                 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2008                  * to use unsupported LUNs; all others may not. */
2009                 if (fsg->common->cmnd[0] != SC_INQUIRY &&
2010                     fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2011                         DBG(fsg, "unsupported LUN %d\n", fsg->common->lun);
2012                         return -EINVAL;
2013                 }
2014         }
2015
2016         /* If a unit attention condition exists, only INQUIRY and
2017          * REQUEST SENSE commands are allowed; anything else must fail. */
2018         if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2019                         fsg->common->cmnd[0] != SC_INQUIRY &&
2020                         fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2021                 curlun->sense_data = curlun->unit_attention_data;
2022                 curlun->unit_attention_data = SS_NO_SENSE;
2023                 return -EINVAL;
2024         }
2025
2026         /* Check that only command bytes listed in the mask are non-zero */
2027         fsg->common->cmnd[1] &= 0x1f;                   // Mask away the LUN
2028         for (i = 1; i < cmnd_size; ++i) {
2029                 if (fsg->common->cmnd[i] && !(mask & (1 << i))) {
2030                         if (curlun)
2031                                 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2032                         return -EINVAL;
2033                 }
2034         }
2035
2036         /* If the medium isn't mounted and the command needs to access
2037          * it, return an error. */
2038         if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
2039                 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2040                 return -EINVAL;
2041         }
2042
2043         return 0;
2044 }
2045
2046
2047 static int do_scsi_command(struct fsg_dev *fsg)
2048 {
2049         struct fsg_buffhd       *bh;
2050         int                     rc;
2051         int                     reply = -EINVAL;
2052         int                     i;
2053         static char             unknown[16];
2054
2055         dump_cdb(fsg->common);
2056
2057         /* Wait for the next buffer to become available for data or status */
2058         bh = fsg->common->next_buffhd_to_drain = fsg->common->next_buffhd_to_fill;
2059         while (bh->state != BUF_STATE_EMPTY) {
2060                 rc = sleep_thread(fsg);
2061                 if (rc)
2062                         return rc;
2063         }
2064         fsg->phase_error = 0;
2065         fsg->short_packet_received = 0;
2066
2067         down_read(&fsg->common->filesem);       // We're using the backing file
2068         switch (fsg->common->cmnd[0]) {
2069
2070         case SC_INQUIRY:
2071                 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2072                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2073                                 (1<<4), 0,
2074                                 "INQUIRY")) == 0)
2075                         reply = do_inquiry(fsg, bh);
2076                 break;
2077
2078         case SC_MODE_SELECT_6:
2079                 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2080                 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2081                                 (1<<1) | (1<<4), 0,
2082                                 "MODE SELECT(6)")) == 0)
2083                         reply = do_mode_select(fsg, bh);
2084                 break;
2085
2086         case SC_MODE_SELECT_10:
2087                 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2088                 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2089                                 (1<<1) | (3<<7), 0,
2090                                 "MODE SELECT(10)")) == 0)
2091                         reply = do_mode_select(fsg, bh);
2092                 break;
2093
2094         case SC_MODE_SENSE_6:
2095                 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2096                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2097                                 (1<<1) | (1<<2) | (1<<4), 0,
2098                                 "MODE SENSE(6)")) == 0)
2099                         reply = do_mode_sense(fsg, bh);
2100                 break;
2101
2102         case SC_MODE_SENSE_10:
2103                 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2104                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2105                                 (1<<1) | (1<<2) | (3<<7), 0,
2106                                 "MODE SENSE(10)")) == 0)
2107                         reply = do_mode_sense(fsg, bh);
2108                 break;
2109
2110         case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2111                 fsg->data_size_from_cmnd = 0;
2112                 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2113                                 (1<<4), 0,
2114                                 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2115                         reply = do_prevent_allow(fsg);
2116                 break;
2117
2118         case SC_READ_6:
2119                 i = fsg->common->cmnd[4];
2120                 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2121                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2122                                 (7<<1) | (1<<4), 1,
2123                                 "READ(6)")) == 0)
2124                         reply = do_read(fsg);
2125                 break;
2126
2127         case SC_READ_10:
2128                 fsg->data_size_from_cmnd =
2129                                 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
2130                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2131                                 (1<<1) | (0xf<<2) | (3<<7), 1,
2132                                 "READ(10)")) == 0)
2133                         reply = do_read(fsg);
2134                 break;
2135
2136         case SC_READ_12:
2137                 fsg->data_size_from_cmnd =
2138                                 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
2139                 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2140                                 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2141                                 "READ(12)")) == 0)
2142                         reply = do_read(fsg);
2143                 break;
2144
2145         case SC_READ_CAPACITY:
2146                 fsg->data_size_from_cmnd = 8;
2147                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2148                                 (0xf<<2) | (1<<8), 1,
2149                                 "READ CAPACITY")) == 0)
2150                         reply = do_read_capacity(fsg, bh);
2151                 break;
2152
2153         case SC_READ_HEADER:
2154                 if (!mod_data.cdrom)
2155                         goto unknown_cmnd;
2156                 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2157                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2158                                 (3<<7) | (0x1f<<1), 1,
2159                                 "READ HEADER")) == 0)
2160                         reply = do_read_header(fsg, bh);
2161                 break;
2162
2163         case SC_READ_TOC:
2164                 if (!mod_data.cdrom)
2165                         goto unknown_cmnd;
2166                 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2167                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2168                                 (7<<6) | (1<<1), 1,
2169                                 "READ TOC")) == 0)
2170                         reply = do_read_toc(fsg, bh);
2171                 break;
2172
2173         case SC_READ_FORMAT_CAPACITIES:
2174                 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2175                 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2176                                 (3<<7), 1,
2177                                 "READ FORMAT CAPACITIES")) == 0)
2178                         reply = do_read_format_capacities(fsg, bh);
2179                 break;
2180
2181         case SC_REQUEST_SENSE:
2182                 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2183                 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2184                                 (1<<4), 0,
2185                                 "REQUEST SENSE")) == 0)
2186                         reply = do_request_sense(fsg, bh);
2187                 break;
2188
2189         case SC_START_STOP_UNIT:
2190                 fsg->data_size_from_cmnd = 0;
2191                 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2192                                 (1<<1) | (1<<4), 0,
2193                                 "START-STOP UNIT")) == 0)
2194                         reply = do_start_stop(fsg);
2195                 break;
2196
2197         case SC_SYNCHRONIZE_CACHE:
2198                 fsg->data_size_from_cmnd = 0;
2199                 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2200                                 (0xf<<2) | (3<<7), 1,
2201                                 "SYNCHRONIZE CACHE")) == 0)
2202                         reply = do_synchronize_cache(fsg);
2203                 break;
2204
2205         case SC_TEST_UNIT_READY:
2206                 fsg->data_size_from_cmnd = 0;
2207                 reply = check_command(fsg, 6, DATA_DIR_NONE,
2208                                 0, 1,
2209                                 "TEST UNIT READY");
2210                 break;
2211
2212         /* Although optional, this command is used by MS-Windows.  We
2213          * support a minimal version: BytChk must be 0. */
2214         case SC_VERIFY:
2215                 fsg->data_size_from_cmnd = 0;
2216                 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2217                                 (1<<1) | (0xf<<2) | (3<<7), 1,
2218                                 "VERIFY")) == 0)
2219                         reply = do_verify(fsg);
2220                 break;
2221
2222         case SC_WRITE_6:
2223                 i = fsg->common->cmnd[4];
2224                 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2225                 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2226                                 (7<<1) | (1<<4), 1,
2227                                 "WRITE(6)")) == 0)
2228                         reply = do_write(fsg);
2229                 break;
2230
2231         case SC_WRITE_10:
2232                 fsg->data_size_from_cmnd =
2233                                 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
2234                 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2235                                 (1<<1) | (0xf<<2) | (3<<7), 1,
2236                                 "WRITE(10)")) == 0)
2237                         reply = do_write(fsg);
2238                 break;
2239
2240         case SC_WRITE_12:
2241                 fsg->data_size_from_cmnd =
2242                                 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
2243                 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2244                                 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2245                                 "WRITE(12)")) == 0)
2246                         reply = do_write(fsg);
2247                 break;
2248
2249         /* Some mandatory commands that we recognize but don't implement.
2250          * They don't mean much in this setting.  It's left as an exercise
2251          * for anyone interested to implement RESERVE and RELEASE in terms
2252          * of Posix locks. */
2253         case SC_FORMAT_UNIT:
2254         case SC_RELEASE:
2255         case SC_RESERVE:
2256         case SC_SEND_DIAGNOSTIC:
2257                 // Fall through
2258
2259         default:
2260  unknown_cmnd:
2261                 fsg->data_size_from_cmnd = 0;
2262                 sprintf(unknown, "Unknown x%02x", fsg->common->cmnd[0]);
2263                 if ((reply = check_command(fsg, fsg->common->cmnd_size,
2264                                 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2265                         fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
2266                         reply = -EINVAL;
2267                 }
2268                 break;
2269         }
2270         up_read(&fsg->common->filesem);
2271
2272         if (reply == -EINTR || signal_pending(current))
2273                 return -EINTR;
2274
2275         /* Set up the single reply buffer for finish_reply() */
2276         if (reply == -EINVAL)
2277                 reply = 0;              // Error reply length
2278         if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2279                 reply = min((u32) reply, fsg->data_size_from_cmnd);
2280                 bh->inreq->length = reply;
2281                 bh->state = BUF_STATE_FULL;
2282                 fsg->residue -= reply;
2283         }                               // Otherwise it's already set
2284
2285         return 0;
2286 }
2287
2288
2289 /*-------------------------------------------------------------------------*/
2290
2291 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2292 {
2293         struct usb_request              *req = bh->outreq;
2294         struct fsg_bulk_cb_wrap *cbw = req->buf;
2295
2296         /* Was this a real packet?  Should it be ignored? */
2297         if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2298                 return -EINVAL;
2299
2300         /* Is the CBW valid? */
2301         if (req->actual != USB_BULK_CB_WRAP_LEN ||
2302                         cbw->Signature != cpu_to_le32(
2303                                 USB_BULK_CB_SIG)) {
2304                 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2305                                 req->actual,
2306                                 le32_to_cpu(cbw->Signature));
2307
2308                 /* The Bulk-only spec says we MUST stall the IN endpoint
2309                  * (6.6.1), so it's unavoidable.  It also says we must
2310                  * retain this state until the next reset, but there's
2311                  * no way to tell the controller driver it should ignore
2312                  * Clear-Feature(HALT) requests.
2313                  *
2314                  * We aren't required to halt the OUT endpoint; instead
2315                  * we can simply accept and discard any data received
2316                  * until the next reset. */
2317                 wedge_bulk_in_endpoint(fsg);
2318                 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2319                 return -EINVAL;
2320         }
2321
2322         /* Is the CBW meaningful? */
2323         if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2324                         cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2325                 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2326                                 "cmdlen %u\n",
2327                                 cbw->Lun, cbw->Flags, cbw->Length);
2328
2329                 /* We can do anything we want here, so let's stall the
2330                  * bulk pipes if we are allowed to. */
2331                 if (mod_data.can_stall) {
2332                         fsg_set_halt(fsg, fsg->bulk_out);
2333                         halt_bulk_in_endpoint(fsg);
2334                 }
2335                 return -EINVAL;
2336         }
2337
2338         /* Save the command for later */
2339         fsg->common->cmnd_size = cbw->Length;
2340         memcpy(fsg->common->cmnd, cbw->CDB, fsg->common->cmnd_size);
2341         if (cbw->Flags & USB_BULK_IN_FLAG)
2342                 fsg->data_dir = DATA_DIR_TO_HOST;
2343         else
2344                 fsg->data_dir = DATA_DIR_FROM_HOST;
2345         fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2346         if (fsg->data_size == 0)
2347                 fsg->data_dir = DATA_DIR_NONE;
2348         fsg->common->lun = cbw->Lun;
2349         fsg->tag = cbw->Tag;
2350         return 0;
2351 }
2352
2353
2354 static int get_next_command(struct fsg_dev *fsg)
2355 {
2356         struct fsg_buffhd       *bh;
2357         int                     rc = 0;
2358
2359         /* Wait for the next buffer to become available */
2360         bh = fsg->common->next_buffhd_to_fill;
2361         while (bh->state != BUF_STATE_EMPTY) {
2362                 rc = sleep_thread(fsg);
2363                 if (rc)
2364                         return rc;
2365         }
2366
2367         /* Queue a request to read a Bulk-only CBW */
2368         set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2369         bh->outreq->short_not_ok = 1;
2370         start_transfer(fsg, fsg->bulk_out, bh->outreq,
2371                        &bh->outreq_busy, &bh->state);
2372
2373         /* We will drain the buffer in software, which means we
2374          * can reuse it for the next filling.  No need to advance
2375          * next_buffhd_to_fill. */
2376
2377         /* Wait for the CBW to arrive */
2378         while (bh->state != BUF_STATE_FULL) {
2379                 rc = sleep_thread(fsg);
2380                 if (rc)
2381                         return rc;
2382         }
2383         smp_rmb();
2384         rc = received_cbw(fsg, bh);
2385         bh->state = BUF_STATE_EMPTY;
2386
2387         return rc;
2388 }
2389
2390
2391 /*-------------------------------------------------------------------------*/
2392
2393 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2394                 const struct usb_endpoint_descriptor *d)
2395 {
2396         int     rc;
2397
2398         ep->driver_data = fsg;
2399         rc = usb_ep_enable(ep, d);
2400         if (rc)
2401                 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2402         return rc;
2403 }
2404
2405 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2406                 struct usb_request **preq)
2407 {
2408         *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2409         if (*preq)
2410                 return 0;
2411         ERROR(fsg, "can't allocate request for %s\n", ep->name);
2412         return -ENOMEM;
2413 }
2414
2415 /*
2416  * Reset interface setting and re-init endpoint state (toggle etc).
2417  * Call with altsetting < 0 to disable the interface.  The only other
2418  * available altsetting is 0, which enables the interface.
2419  */
2420 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2421 {
2422         int     rc = 0;
2423         int     i;
2424         const struct usb_endpoint_descriptor    *d;
2425
2426         if (fsg->running)
2427                 DBG(fsg, "reset interface\n");
2428
2429 reset:
2430         /* Deallocate the requests */
2431         for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2432                 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
2433
2434                 if (bh->inreq) {
2435                         usb_ep_free_request(fsg->bulk_in, bh->inreq);
2436                         bh->inreq = NULL;
2437                 }
2438                 if (bh->outreq) {
2439                         usb_ep_free_request(fsg->bulk_out, bh->outreq);
2440                         bh->outreq = NULL;
2441                 }
2442         }
2443
2444         /* Disable the endpoints */
2445         if (fsg->bulk_in_enabled) {
2446                 usb_ep_disable(fsg->bulk_in);
2447                 fsg->bulk_in_enabled = 0;
2448         }
2449         if (fsg->bulk_out_enabled) {
2450                 usb_ep_disable(fsg->bulk_out);
2451                 fsg->bulk_out_enabled = 0;
2452         }
2453
2454         fsg->running = 0;
2455         if (altsetting < 0 || rc != 0)
2456                 return rc;
2457
2458         DBG(fsg, "set interface %d\n", altsetting);
2459
2460         /* Enable the endpoints */
2461         d = fsg_ep_desc(fsg->gadget,
2462                         &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2463         if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2464                 goto reset;
2465         fsg->bulk_in_enabled = 1;
2466
2467         d = fsg_ep_desc(fsg->gadget,
2468                         &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2469         if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2470                 goto reset;
2471         fsg->bulk_out_enabled = 1;
2472         fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2473         clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2474
2475         /* Allocate the requests */
2476         for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2477                 struct fsg_buffhd       *bh = &fsg->common->buffhds[i];
2478
2479                 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2480                         goto reset;
2481                 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2482                         goto reset;
2483                 bh->inreq->buf = bh->outreq->buf = bh->buf;
2484                 bh->inreq->context = bh->outreq->context = bh;
2485                 bh->inreq->complete = bulk_in_complete;
2486                 bh->outreq->complete = bulk_out_complete;
2487         }
2488
2489         fsg->running = 1;
2490         for (i = 0; i < fsg->common->nluns; ++i)
2491                 fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2492         return rc;
2493 }
2494
2495
2496 /*
2497  * Change our operational configuration.  This code must agree with the code
2498  * that returns config descriptors, and with interface altsetting code.
2499  *
2500  * It's also responsible for power management interactions.  Some
2501  * configurations might not work with our current power sources.
2502  * For now we just assume the gadget is always self-powered.
2503  */
2504 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2505 {
2506         int     rc = 0;
2507
2508         /* Disable the single interface */
2509         if (fsg->config != 0) {
2510                 DBG(fsg, "reset config\n");
2511                 fsg->config = 0;
2512                 rc = do_set_interface(fsg, -1);
2513         }
2514
2515         /* Enable the interface */
2516         if (new_config != 0) {
2517                 fsg->config = new_config;
2518                 if ((rc = do_set_interface(fsg, 0)) != 0)
2519                         fsg->config = 0;        // Reset on errors
2520                 else {
2521                         char *speed;
2522
2523                         switch (fsg->gadget->speed) {
2524                         case USB_SPEED_LOW:     speed = "low";  break;
2525                         case USB_SPEED_FULL:    speed = "full"; break;
2526                         case USB_SPEED_HIGH:    speed = "high"; break;
2527                         default:                speed = "?";    break;
2528                         }
2529                         INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2530                 }
2531         }
2532         return rc;
2533 }
2534
2535
2536 /*-------------------------------------------------------------------------*/
2537
2538 static void handle_exception(struct fsg_dev *fsg)
2539 {
2540         siginfo_t               info;
2541         int                     sig;
2542         int                     i;
2543         struct fsg_buffhd       *bh;
2544         enum fsg_state          old_state;
2545         u8                      new_config;
2546         struct fsg_lun          *curlun;
2547         unsigned int            exception_req_tag;
2548         int                     rc;
2549
2550         /* Clear the existing signals.  Anything but SIGUSR1 is converted
2551          * into a high-priority EXIT exception. */
2552         for (;;) {
2553                 sig = dequeue_signal_lock(current, &current->blocked, &info);
2554                 if (!sig)
2555                         break;
2556                 if (sig != SIGUSR1) {
2557                         if (fsg->state < FSG_STATE_EXIT)
2558                                 DBG(fsg, "Main thread exiting on signal\n");
2559                         raise_exception(fsg, FSG_STATE_EXIT);
2560                 }
2561         }
2562
2563         /* Cancel all the pending transfers */
2564         for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2565                 bh = &fsg->common->buffhds[i];
2566                 if (bh->inreq_busy)
2567                         usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2568                 if (bh->outreq_busy)
2569                         usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2570         }
2571
2572         /* Wait until everything is idle */
2573         for (;;) {
2574                 int num_active = 0;
2575                 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2576                         bh = &fsg->common->buffhds[i];
2577                         num_active += bh->inreq_busy + bh->outreq_busy;
2578                 }
2579                 if (num_active == 0)
2580                         break;
2581                 if (sleep_thread(fsg))
2582                         return;
2583         }
2584
2585         /* Clear out the controller's fifos */
2586         if (fsg->bulk_in_enabled)
2587                 usb_ep_fifo_flush(fsg->bulk_in);
2588         if (fsg->bulk_out_enabled)
2589                 usb_ep_fifo_flush(fsg->bulk_out);
2590
2591         /* Reset the I/O buffer states and pointers, the SCSI
2592          * state, and the exception.  Then invoke the handler. */
2593         spin_lock_irq(&fsg->lock);
2594
2595         for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2596                 bh = &fsg->common->buffhds[i];
2597                 bh->state = BUF_STATE_EMPTY;
2598         }
2599         fsg->common->next_buffhd_to_fill = fsg->common->next_buffhd_to_drain =
2600                         &fsg->common->buffhds[0];
2601
2602         exception_req_tag = fsg->exception_req_tag;
2603         new_config = fsg->new_config;
2604         old_state = fsg->state;
2605
2606         if (old_state == FSG_STATE_ABORT_BULK_OUT)
2607                 fsg->state = FSG_STATE_STATUS_PHASE;
2608         else {
2609                 for (i = 0; i < fsg->common->nluns; ++i) {
2610                         curlun = &fsg->common->luns[i];
2611                         curlun->prevent_medium_removal = 0;
2612                         curlun->sense_data = curlun->unit_attention_data =
2613                                         SS_NO_SENSE;
2614                         curlun->sense_data_info = 0;
2615                         curlun->info_valid = 0;
2616                 }
2617                 fsg->state = FSG_STATE_IDLE;
2618         }
2619         spin_unlock_irq(&fsg->lock);
2620
2621         /* Carry out any extra actions required for the exception */
2622         switch (old_state) {
2623         default:
2624                 break;
2625
2626         case FSG_STATE_ABORT_BULK_OUT:
2627                 send_status(fsg);
2628                 spin_lock_irq(&fsg->lock);
2629                 if (fsg->state == FSG_STATE_STATUS_PHASE)
2630                         fsg->state = FSG_STATE_IDLE;
2631                 spin_unlock_irq(&fsg->lock);
2632                 break;
2633
2634         case FSG_STATE_RESET:
2635                 /* In case we were forced against our will to halt a
2636                  * bulk endpoint, clear the halt now.  (The SuperH UDC
2637                  * requires this.) */
2638                 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2639                         usb_ep_clear_halt(fsg->bulk_in);
2640
2641                 if (fsg->ep0_req_tag == exception_req_tag)
2642                         ep0_queue(fsg); // Complete the status stage
2643
2644                 /* Technically this should go here, but it would only be
2645                  * a waste of time.  Ditto for the INTERFACE_CHANGE and
2646                  * CONFIG_CHANGE cases. */
2647                 // for (i = 0; i < fsg->common->nluns; ++i)
2648                 //      fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2649                 break;
2650
2651         case FSG_STATE_INTERFACE_CHANGE:
2652                 rc = do_set_interface(fsg, 0);
2653                 if (fsg->ep0_req_tag != exception_req_tag)
2654                         break;
2655                 if (rc != 0)                    // STALL on errors
2656                         fsg_set_halt(fsg, fsg->ep0);
2657                 else                            // Complete the status stage
2658                         ep0_queue(fsg);
2659                 break;
2660
2661         case FSG_STATE_CONFIG_CHANGE:
2662                 rc = do_set_config(fsg, new_config);
2663                 if (fsg->ep0_req_tag != exception_req_tag)
2664                         break;
2665                 if (rc != 0)                    // STALL on errors
2666                         fsg_set_halt(fsg, fsg->ep0);
2667                 else                            // Complete the status stage
2668                         ep0_queue(fsg);
2669                 break;
2670
2671         case FSG_STATE_DISCONNECT:
2672                 for (i = 0; i < fsg->common->nluns; ++i)
2673                         fsg_lun_fsync_sub(&fsg->common->luns[i]);
2674                 do_set_config(fsg, 0);          // Unconfigured state
2675                 break;
2676
2677         case FSG_STATE_EXIT:
2678         case FSG_STATE_TERMINATED:
2679                 do_set_config(fsg, 0);                  // Free resources
2680                 spin_lock_irq(&fsg->lock);
2681                 fsg->state = FSG_STATE_TERMINATED;      // Stop the thread
2682                 spin_unlock_irq(&fsg->lock);
2683                 break;
2684         }
2685 }
2686
2687
2688 /*-------------------------------------------------------------------------*/
2689
2690 static int fsg_main_thread(void *fsg_)
2691 {
2692         struct fsg_dev          *fsg = fsg_;
2693
2694         /* Allow the thread to be killed by a signal, but set the signal mask
2695          * to block everything but INT, TERM, KILL, and USR1. */
2696         allow_signal(SIGINT);
2697         allow_signal(SIGTERM);
2698         allow_signal(SIGKILL);
2699         allow_signal(SIGUSR1);
2700
2701         /* Allow the thread to be frozen */
2702         set_freezable();
2703
2704         /* Arrange for userspace references to be interpreted as kernel
2705          * pointers.  That way we can pass a kernel pointer to a routine
2706          * that expects a __user pointer and it will work okay. */
2707         set_fs(get_ds());
2708
2709         /* The main loop */
2710         while (fsg->state != FSG_STATE_TERMINATED) {
2711                 if (exception_in_progress(fsg) || signal_pending(current)) {
2712                         handle_exception(fsg);
2713                         continue;
2714                 }
2715
2716                 if (!fsg->running) {
2717                         sleep_thread(fsg);
2718                         continue;
2719                 }
2720
2721                 if (get_next_command(fsg))
2722                         continue;
2723
2724                 spin_lock_irq(&fsg->lock);
2725                 if (!exception_in_progress(fsg))
2726                         fsg->state = FSG_STATE_DATA_PHASE;
2727                 spin_unlock_irq(&fsg->lock);
2728
2729                 if (do_scsi_command(fsg) || finish_reply(fsg))
2730                         continue;
2731
2732                 spin_lock_irq(&fsg->lock);
2733                 if (!exception_in_progress(fsg))
2734                         fsg->state = FSG_STATE_STATUS_PHASE;
2735                 spin_unlock_irq(&fsg->lock);
2736
2737                 if (send_status(fsg))
2738                         continue;
2739
2740                 spin_lock_irq(&fsg->lock);
2741                 if (!exception_in_progress(fsg))
2742                         fsg->state = FSG_STATE_IDLE;
2743                 spin_unlock_irq(&fsg->lock);
2744                 }
2745
2746         spin_lock_irq(&fsg->lock);
2747         fsg->thread_task = NULL;
2748         spin_unlock_irq(&fsg->lock);
2749
2750         /* If we are exiting because of a signal, unregister the
2751          * gadget driver. */
2752         if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2753                 usb_gadget_unregister_driver(&fsg_driver);
2754
2755         /* Let the unbind and cleanup routines know the thread has exited */
2756         complete_and_exit(&fsg->thread_notifier, 0);
2757 }
2758
2759
2760 /*-------------------------------------------------------------------------*/
2761
2762
2763 /* The write permissions and store_xxx pointers are set in fsg_bind() */
2764 static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
2765 static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
2766
2767
2768 /*-------------------------------------------------------------------------*/
2769
2770 static void fsg_release(struct fsg_dev *fsg)
2771 {
2772         kfree(fsg->common->luns);
2773         kfree(fsg);
2774 }
2775
2776 static void lun_release(struct device *dev)
2777 {
2778 }
2779
2780 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
2781 {
2782         struct fsg_dev          *fsg = get_gadget_data(gadget);
2783         int                     i;
2784         struct fsg_lun          *curlun;
2785         struct usb_request      *req = fsg->ep0req;
2786
2787         DBG(fsg, "unbind\n");
2788         clear_bit(REGISTERED, &fsg->atomic_bitflags);
2789
2790         /* Unregister the sysfs attribute files and the LUNs */
2791         for (i = 0; i < fsg->common->nluns; ++i) {
2792                 curlun = &fsg->common->luns[i];
2793                 if (curlun->registered) {
2794                         device_remove_file(&curlun->dev, &dev_attr_ro);
2795                         device_remove_file(&curlun->dev, &dev_attr_file);
2796                         fsg_lun_close(curlun);
2797                         device_unregister(&curlun->dev);
2798                         curlun->registered = 0;
2799                 }
2800         }
2801
2802         /* If the thread isn't already dead, tell it to exit now */
2803         if (fsg->state != FSG_STATE_TERMINATED) {
2804                 raise_exception(fsg, FSG_STATE_EXIT);
2805                 wait_for_completion(&fsg->thread_notifier);
2806
2807                 /* The cleanup routine waits for this completion also */
2808                 complete(&fsg->thread_notifier);
2809         }
2810
2811         /* Free the request and buffer for endpoint 0 */
2812         if (req) {
2813                 kfree(req->buf);
2814                 usb_ep_free_request(fsg->ep0, req);
2815         }
2816
2817         set_gadget_data(gadget, NULL);
2818 }
2819
2820
2821 static int __init check_parameters(struct fsg_dev *fsg)
2822 {
2823         int     gcnum;
2824
2825         /* Some peripheral controllers are known not to be able to
2826          * halt bulk endpoints correctly.  If one of them is present,
2827          * disable stalls.
2828          */
2829         if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
2830                 mod_data.can_stall = 0;
2831
2832         if (mod_data.release == 0xffff) {       // Parameter wasn't set
2833                 /* The sa1100 controller is not supported */
2834                 if (gadget_is_sa1100(fsg->gadget))
2835                         gcnum = -1;
2836                 else
2837                         gcnum = usb_gadget_controller_number(fsg->gadget);
2838                 if (gcnum >= 0)
2839                         mod_data.release = 0x0300 + gcnum;
2840                 else {
2841                         WARNING(fsg, "controller '%s' not recognized\n",
2842                                 fsg->gadget->name);
2843                         mod_data.release = 0x0399;
2844                 }
2845         }
2846
2847         return 0;
2848 }
2849
2850
2851 static int __init fsg_bind(struct usb_gadget *gadget)
2852 {
2853         struct fsg_dev          *fsg = the_fsg;
2854         int                     rc;
2855         int                     i;
2856         struct fsg_lun          *curlun;
2857         struct usb_ep           *ep;
2858         struct usb_request      *req;
2859         char                    *pathbuf, *p;
2860
2861         fsg->gadget = gadget;
2862         set_gadget_data(gadget, fsg);
2863         fsg->ep0 = gadget->ep0;
2864         fsg->ep0->driver_data = fsg;
2865
2866         if ((rc = check_parameters(fsg)) != 0)
2867                 goto out;
2868
2869         if (mod_data.removable) {       // Enable the store_xxx attributes
2870                 dev_attr_file.attr.mode = 0644;
2871                 dev_attr_file.store = fsg_store_file;
2872                 if (!mod_data.cdrom) {
2873                         dev_attr_ro.attr.mode = 0644;
2874                         dev_attr_ro.store = fsg_store_ro;
2875                 }
2876         }
2877
2878         /* Find out how many LUNs there should be */
2879         i = mod_data.nluns;
2880         if (i == 0)
2881                 i = max(mod_data.num_filenames, 1u);
2882         if (i > FSG_MAX_LUNS) {
2883                 ERROR(fsg, "invalid number of LUNs: %d\n", i);
2884                 rc = -EINVAL;
2885                 goto out;
2886         }
2887
2888         /* Create the LUNs, open their backing files, and register the
2889          * LUN devices in sysfs. */
2890         fsg->common->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
2891         if (!fsg->common->luns) {
2892                 rc = -ENOMEM;
2893                 goto out;
2894         }
2895         fsg->common->nluns = i;
2896
2897         for (i = 0; i < fsg->common->nluns; ++i) {
2898                 curlun = &fsg->common->luns[i];
2899                 curlun->cdrom = !!mod_data.cdrom;
2900                 curlun->ro = mod_data.cdrom || mod_data.ro[i];
2901                 curlun->initially_ro = curlun->ro;
2902                 curlun->removable = mod_data.removable;
2903                 curlun->dev.release = lun_release;
2904                 curlun->dev.parent = &gadget->dev;
2905                 curlun->dev.driver = &fsg_driver.driver;
2906                 dev_set_drvdata(&curlun->dev, &fsg->common->filesem);
2907                 dev_set_name(&curlun->dev,"%s-lun%d",
2908                              dev_name(&gadget->dev), i);
2909
2910                 if ((rc = device_register(&curlun->dev)) != 0) {
2911                         INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
2912                         goto out;
2913                 }
2914                 if ((rc = device_create_file(&curlun->dev,
2915                                         &dev_attr_ro)) != 0 ||
2916                                 (rc = device_create_file(&curlun->dev,
2917                                         &dev_attr_file)) != 0) {
2918                         device_unregister(&curlun->dev);
2919                         goto out;
2920                 }
2921                 curlun->registered = 1;
2922
2923                 if (mod_data.file[i] && *mod_data.file[i]) {
2924                         if ((rc = fsg_lun_open(curlun,
2925                                         mod_data.file[i])) != 0)
2926                                 goto out;
2927                 } else if (!mod_data.removable) {
2928                         ERROR(fsg, "no file given for LUN%d\n", i);
2929                         rc = -EINVAL;
2930                         goto out;
2931                 }
2932         }
2933
2934         /* Find all the endpoints we will use */
2935         usb_ep_autoconfig_reset(gadget);
2936         ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2937         if (!ep)
2938                 goto autoconf_fail;
2939         ep->driver_data = fsg;          // claim the endpoint
2940         fsg->bulk_in = ep;
2941
2942         ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2943         if (!ep)
2944                 goto autoconf_fail;
2945         ep->driver_data = fsg;          // claim the endpoint
2946         fsg->bulk_out = ep;
2947
2948         /* Fix up the descriptors */
2949         device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
2950         device_desc.bcdDevice = cpu_to_le16(mod_data.release);
2951
2952         if (gadget_is_dualspeed(gadget)) {
2953                 /* Assume ep0 uses the same maxpacket value for both speeds */
2954                 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
2955
2956                 /* Assume endpoint addresses are the same for both speeds */
2957                 fsg_hs_bulk_in_desc.bEndpointAddress =
2958                         fsg_fs_bulk_in_desc.bEndpointAddress;
2959                 fsg_hs_bulk_out_desc.bEndpointAddress =
2960                         fsg_fs_bulk_out_desc.bEndpointAddress;
2961         }
2962
2963         if (gadget_is_otg(gadget))
2964                 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
2965
2966         rc = -ENOMEM;
2967
2968         /* Allocate the request and buffer for endpoint 0 */
2969         fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
2970         if (!req)
2971                 goto out;
2972         req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
2973         if (!req->buf)
2974                 goto out;
2975         req->complete = ep0_complete;
2976
2977         /* This should reflect the actual gadget power source */
2978         usb_gadget_set_selfpowered(gadget);
2979
2980         snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
2981                         "%s %s with %s",
2982                         init_utsname()->sysname, init_utsname()->release,
2983                         gadget->name);
2984
2985         /* On a real device, serial[] would be loaded from permanent
2986          * storage.  We just encode it from the driver version string. */
2987         for (i = 0; i < sizeof fsg_string_serial - 2; i += 2) {
2988                 unsigned char           c = DRIVER_VERSION[i / 2];
2989
2990                 if (!c)
2991                         break;
2992                 sprintf(&fsg_string_serial[i], "%02X", c);
2993         }
2994
2995         fsg->thread_task = kthread_create(fsg_main_thread, fsg,
2996                         "file-storage-gadget");
2997         if (IS_ERR(fsg->thread_task)) {
2998                 rc = PTR_ERR(fsg->thread_task);
2999                 goto out;
3000         }
3001
3002         INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3003         INFO(fsg, "Number of LUNs=%d\n", fsg->common->nluns);
3004
3005         pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3006         for (i = 0; i < fsg->common->nluns; ++i) {
3007                 curlun = &fsg->common->luns[i];
3008                 if (fsg_lun_is_open(curlun)) {
3009                         p = NULL;
3010                         if (pathbuf) {
3011                                 p = d_path(&curlun->filp->f_path,
3012                                            pathbuf, PATH_MAX);
3013                                 if (IS_ERR(p))
3014                                         p = NULL;
3015                         }
3016                         LINFO(curlun, "ro=%d, file: %s\n",
3017                                         curlun->ro, (p ? p : "(error)"));
3018                 }
3019         }
3020         kfree(pathbuf);
3021
3022         DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3023                         mod_data.removable, mod_data.can_stall,
3024                         mod_data.cdrom, FSG_BUFLEN);
3025         DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
3026
3027         set_bit(REGISTERED, &fsg->atomic_bitflags);
3028
3029         /* Tell the thread to start working */
3030         wake_up_process(fsg->thread_task);
3031         return 0;
3032
3033 autoconf_fail:
3034         ERROR(fsg, "unable to autoconfigure all endpoints\n");
3035         rc = -ENOTSUPP;
3036
3037 out:
3038         fsg->state = FSG_STATE_TERMINATED;      // The thread is dead
3039         fsg_unbind(gadget);
3040         complete(&fsg->thread_notifier);
3041         return rc;
3042 }
3043
3044
3045 /*-------------------------------------------------------------------------*/
3046
3047 static struct usb_gadget_driver         fsg_driver = {
3048 #ifdef CONFIG_USB_GADGET_DUALSPEED
3049         .speed          = USB_SPEED_HIGH,
3050 #else
3051         .speed          = USB_SPEED_FULL,
3052 #endif
3053         .function       = (char *) fsg_string_product,
3054         .bind           = fsg_bind,
3055         .unbind         = fsg_unbind,
3056         .disconnect     = fsg_disconnect,
3057         .setup          = fsg_setup,
3058
3059         .driver         = {
3060                 .name           = DRIVER_NAME,
3061                 .owner          = THIS_MODULE,
3062                 // .release = ...
3063                 // .suspend = ...
3064                 // .resume = ...
3065         },
3066 };
3067
3068
3069 static int __init fsg_alloc(void)
3070 {
3071         struct fsg_dev          *fsg;
3072         struct fsg_buffhd       *bh;
3073         unsigned                i;
3074
3075         fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3076         if (!fsg)
3077                 return -ENOMEM;
3078
3079         fsg->common = kzalloc(sizeof *fsg->common, GFP_KERNEL);
3080         if (!fsg->common) {
3081                 kfree(fsg);
3082                 return -ENOMEM;
3083         }
3084
3085         bh = fsg->common->buffhds;
3086         i = FSG_NUM_BUFFERS - 1;
3087         do {
3088                 bh->next = bh + 1;
3089         } while (++bh, --i);
3090         bh->next = fsg->common->buffhds;
3091
3092         spin_lock_init(&fsg->lock);
3093         init_rwsem(&fsg->common->filesem);
3094         init_completion(&fsg->thread_notifier);
3095
3096         the_fsg = fsg;
3097         return 0;
3098 }
3099
3100
3101 static int __init fsg_init(void)
3102 {
3103         int             rc;
3104         struct fsg_dev  *fsg;
3105
3106         if ((rc = fsg_alloc()) != 0)
3107                 return rc;
3108         fsg = the_fsg;
3109         if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
3110                 fsg_release(fsg);
3111         return rc;
3112 }
3113 module_init(fsg_init);
3114
3115
3116 static void __exit fsg_cleanup(void)
3117 {
3118         struct fsg_dev  *fsg = the_fsg;
3119
3120         /* Unregister the driver iff the thread hasn't already done so */
3121         if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3122                 usb_gadget_unregister_driver(&fsg_driver);
3123
3124         /* Wait for the thread to finish up */
3125         wait_for_completion(&fsg->thread_notifier);
3126
3127         fsg_release(fsg);
3128 }
3129 module_exit(fsg_cleanup);