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