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