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