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