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