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