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