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