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