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