include: replace linux/module.h with "struct module" wherever possible
[linux-2.6/next.git] / drivers / usb / gadget / file_storage.c
blobcf875be9c57d2d726c89bfad5cf4157a78145e9e
1 /*
2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
4 * Copyright (C) 2003-2008 Alan Stern
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions, and the following disclaimer,
12 * without modification.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The names of the above-listed copyright holders may not be used
17 * to endorse or promote products derived from this software without
18 * specific prior written permission.
20 * ALTERNATIVELY, this software may be distributed under the terms of the
21 * GNU General Public License ("GPL") as published by the Free Software
22 * Foundation, either version 2 of that License or (at your option) any
23 * later version.
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * The File-backed Storage Gadget acts as a USB Mass Storage device,
41 * appearing to the host as a disk drive or as a CD-ROM drive. In addition
42 * to providing an example of a genuinely useful gadget driver for a USB
43 * device, it also illustrates a technique of double-buffering for increased
44 * throughput. Last but not least, it gives an easy way to probe the
45 * behavior of the Mass Storage drivers in a USB host.
47 * Backing storage is provided by a regular file or a block device, specified
48 * by the "file" module parameter. Access can be limited to read-only by
49 * setting the optional "ro" module parameter. (For CD-ROM emulation,
50 * access is always read-only.) The gadget will indicate that it has
51 * removable media if the optional "removable" module parameter is set.
53 * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
54 * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
55 * by the optional "transport" module parameter. It also supports the
56 * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
57 * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
58 * the optional "protocol" module parameter. In addition, the default
59 * Vendor ID, Product ID, release number and serial number can be overridden.
61 * There is support for multiple logical units (LUNs), each of which has
62 * its own backing file. The number of LUNs can be set using the optional
63 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
64 * files are specified using comma-separated lists for "file" and "ro".
65 * The default number of LUNs is taken from the number of "file" elements;
66 * it is 1 if "file" is not given. If "removable" is not set then a backing
67 * file must be specified for each LUN. If it is set, then an unspecified
68 * or empty backing filename means the LUN's medium is not loaded. Ideally
69 * each LUN would be settable independently as a disk drive or a CD-ROM
70 * drive, but currently all LUNs have to be the same type. The CD-ROM
71 * emulation includes a single data track and no audio tracks; hence there
72 * need be only one backing file per LUN. Note also that the CD-ROM block
73 * length is set to 512 rather than the more common value 2048.
75 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
76 * needed (an interrupt-out endpoint is also needed for CBI). The memory
77 * requirement amounts to two 16K buffers, size configurable by a parameter.
78 * Support is included for both full-speed and high-speed operation.
80 * Note that the driver is slightly non-portable in that it assumes a
81 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
82 * interrupt-in endpoints. With most device controllers this isn't an
83 * issue, but there may be some with hardware restrictions that prevent
84 * a buffer from being used by more than one endpoint.
86 * Module options:
88 * file=filename[,filename...]
89 * Required if "removable" is not set, names of
90 * the files or block devices used for
91 * backing storage
92 * serial=HHHH... Required serial number (string of hex chars)
93 * ro=b[,b...] Default false, booleans for read-only access
94 * removable Default false, boolean for removable media
95 * luns=N Default N = number of filenames, number of
96 * LUNs to support
97 * nofua=b[,b...] Default false, booleans for ignore FUA flag
98 * in SCSI WRITE(10,12) commands
99 * stall Default determined according to the type of
100 * USB device controller (usually true),
101 * boolean to permit the driver to halt
102 * bulk endpoints
103 * cdrom Default false, boolean for whether to emulate
104 * a CD-ROM drive
105 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
106 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
107 * ATAPI, QIC, UFI, 8070, or SCSI;
108 * also 1 - 6)
109 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
110 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
111 * release=0xRRRR Override the USB release number (bcdDevice)
112 * buflen=N Default N=16384, buffer size used (will be
113 * rounded down to a multiple of
114 * PAGE_CACHE_SIZE)
116 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "serial", "ro",
117 * "removable", "luns", "nofua", "stall", and "cdrom" options are available;
118 * default values are used for everything else.
120 * The pathnames of the backing files and the ro settings are available in
121 * the attribute files "file", "nofua", and "ro" in the lun<n> subdirectory of
122 * the gadget's sysfs directory. If the "removable" option is set, writing to
123 * these files will simulate ejecting/loading the medium (writing an empty
124 * line means eject) and adjusting a write-enable tab. Changes to the ro
125 * setting are not allowed when the medium is loaded or if CD-ROM emulation
126 * is being used.
128 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
129 * The driver's SCSI command interface was based on the "Information
130 * technology - Small Computer System Interface - 2" document from
131 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
132 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
133 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
134 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
135 * document, Revision 1.0, December 14, 1998, available at
136 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
141 * Driver Design
143 * The FSG driver is fairly straightforward. There is a main kernel
144 * thread that handles most of the work. Interrupt routines field
145 * callbacks from the controller driver: bulk- and interrupt-request
146 * completion notifications, endpoint-0 events, and disconnect events.
147 * Completion events are passed to the main thread by wakeup calls. Many
148 * ep0 requests are handled at interrupt time, but SetInterface,
149 * SetConfiguration, and device reset requests are forwarded to the
150 * thread in the form of "exceptions" using SIGUSR1 signals (since they
151 * should interrupt any ongoing file I/O operations).
153 * The thread's main routine implements the standard command/data/status
154 * parts of a SCSI interaction. It and its subroutines are full of tests
155 * for pending signals/exceptions -- all this polling is necessary since
156 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
157 * indication that the driver really wants to be running in userspace.)
158 * An important point is that so long as the thread is alive it keeps an
159 * open reference to the backing file. This will prevent unmounting
160 * the backing file's underlying filesystem and could cause problems
161 * during system shutdown, for example. To prevent such problems, the
162 * thread catches INT, TERM, and KILL signals and converts them into
163 * an EXIT exception.
165 * In normal operation the main thread is started during the gadget's
166 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
167 * exit when it receives a signal, and there's no point leaving the
168 * gadget running when the thread is dead. So just before the thread
169 * exits, it deregisters the gadget driver. This makes things a little
170 * tricky: The driver is deregistered at two places, and the exiting
171 * thread can indirectly call fsg_unbind() which in turn can tell the
172 * thread to exit. The first problem is resolved through the use of the
173 * REGISTERED atomic bitflag; the driver will only be deregistered once.
174 * The second problem is resolved by having fsg_unbind() check
175 * fsg->state; it won't try to stop the thread if the state is already
176 * FSG_STATE_TERMINATED.
178 * To provide maximum throughput, the driver uses a circular pipeline of
179 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
180 * arbitrarily long; in practice the benefits don't justify having more
181 * than 2 stages (i.e., double buffering). But it helps to think of the
182 * pipeline as being a long one. Each buffer head contains a bulk-in and
183 * a bulk-out request pointer (since the buffer can be used for both
184 * output and input -- directions always are given from the host's
185 * point of view) as well as a pointer to the buffer and various state
186 * variables.
188 * Use of the pipeline follows a simple protocol. There is a variable
189 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
190 * At any time that buffer head may still be in use from an earlier
191 * request, so each buffer head has a state variable indicating whether
192 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
193 * buffer head to be EMPTY, filling the buffer either by file I/O or by
194 * USB I/O (during which the buffer head is BUSY), and marking the buffer
195 * head FULL when the I/O is complete. Then the buffer will be emptied
196 * (again possibly by USB I/O, during which it is marked BUSY) and
197 * finally marked EMPTY again (possibly by a completion routine).
199 * A module parameter tells the driver to avoid stalling the bulk
200 * endpoints wherever the transport specification allows. This is
201 * necessary for some UDCs like the SuperH, which cannot reliably clear a
202 * halt on a bulk endpoint. However, under certain circumstances the
203 * Bulk-only specification requires a stall. In such cases the driver
204 * will halt the endpoint and set a flag indicating that it should clear
205 * the halt in software during the next device reset. Hopefully this
206 * will permit everything to work correctly. Furthermore, although the
207 * specification allows the bulk-out endpoint to halt when the host sends
208 * too much data, implementing this would cause an unavoidable race.
209 * The driver will always use the "no-stall" approach for OUT transfers.
211 * One subtle point concerns sending status-stage responses for ep0
212 * requests. Some of these requests, such as device reset, can involve
213 * interrupting an ongoing file I/O operation, which might take an
214 * arbitrarily long time. During that delay the host might give up on
215 * the original ep0 request and issue a new one. When that happens the
216 * driver should not notify the host about completion of the original
217 * request, as the host will no longer be waiting for it. So the driver
218 * assigns to each ep0 request a unique tag, and it keeps track of the
219 * tag value of the request associated with a long-running exception
220 * (device-reset, interface-change, or configuration-change). When the
221 * exception handler is finished, the status-stage response is submitted
222 * only if the current ep0 request tag is equal to the exception request
223 * tag. Thus only the most recently received ep0 request will get a
224 * status-stage response.
226 * Warning: This driver source file is too long. It ought to be split up
227 * into a header file plus about 3 separate .c files, to handle the details
228 * of the Gadget, USB Mass Storage, and SCSI protocols.
232 /* #define VERBOSE_DEBUG */
233 /* #define DUMP_MSGS */
236 #include <linux/blkdev.h>
237 #include <linux/completion.h>
238 #include <linux/dcache.h>
239 #include <linux/delay.h>
240 #include <linux/device.h>
241 #include <linux/fcntl.h>
242 #include <linux/file.h>
243 #include <linux/fs.h>
244 #include <linux/kref.h>
245 #include <linux/kthread.h>
246 #include <linux/limits.h>
247 #include <linux/module.h>
248 #include <linux/rwsem.h>
249 #include <linux/slab.h>
250 #include <linux/spinlock.h>
251 #include <linux/string.h>
252 #include <linux/freezer.h>
253 #include <linux/utsname.h>
255 #include <linux/usb/ch9.h>
256 #include <linux/usb/gadget.h>
258 #include "gadget_chips.h"
263 * Kbuild is not very cooperative with respect to linking separately
264 * compiled library objects into one module. So for now we won't use
265 * separate compilation ... ensuring init/exit sections work to shrink
266 * the runtime footprint, and giving us at least some parts of what
267 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
269 #include "usbstring.c"
270 #include "config.c"
271 #include "epautoconf.c"
273 /*-------------------------------------------------------------------------*/
275 #define DRIVER_DESC "File-backed Storage Gadget"
276 #define DRIVER_NAME "g_file_storage"
277 #define DRIVER_VERSION "1 September 2010"
279 static char fsg_string_manufacturer[64];
280 static const char fsg_string_product[] = DRIVER_DESC;
281 static const char fsg_string_config[] = "Self-powered";
282 static const char fsg_string_interface[] = "Mass Storage";
285 #include "storage_common.c"
288 MODULE_DESCRIPTION(DRIVER_DESC);
289 MODULE_AUTHOR("Alan Stern");
290 MODULE_LICENSE("Dual BSD/GPL");
293 * This driver assumes self-powered hardware and has no way for users to
294 * trigger remote wakeup. It uses autoconfiguration to select endpoints
295 * and endpoint addresses.
299 /*-------------------------------------------------------------------------*/
302 /* Encapsulate the module parameter settings */
304 static struct {
305 char *file[FSG_MAX_LUNS];
306 char *serial;
307 int ro[FSG_MAX_LUNS];
308 int nofua[FSG_MAX_LUNS];
309 unsigned int num_filenames;
310 unsigned int num_ros;
311 unsigned int num_nofuas;
312 unsigned int nluns;
314 int removable;
315 int can_stall;
316 int cdrom;
318 char *transport_parm;
319 char *protocol_parm;
320 unsigned short vendor;
321 unsigned short product;
322 unsigned short release;
323 unsigned int buflen;
325 int transport_type;
326 char *transport_name;
327 int protocol_type;
328 char *protocol_name;
330 } mod_data = { // Default values
331 .transport_parm = "BBB",
332 .protocol_parm = "SCSI",
333 .removable = 0,
334 .can_stall = 1,
335 .cdrom = 0,
336 .vendor = FSG_VENDOR_ID,
337 .product = FSG_PRODUCT_ID,
338 .release = 0xffff, // Use controller chip type
339 .buflen = 16384,
343 module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
344 S_IRUGO);
345 MODULE_PARM_DESC(file, "names of backing files or devices");
347 module_param_named(serial, mod_data.serial, charp, S_IRUGO);
348 MODULE_PARM_DESC(serial, "USB serial number");
350 module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
351 MODULE_PARM_DESC(ro, "true to force read-only");
353 module_param_array_named(nofua, mod_data.nofua, bool, &mod_data.num_nofuas,
354 S_IRUGO);
355 MODULE_PARM_DESC(nofua, "true to ignore SCSI WRITE(10,12) FUA bit");
357 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
358 MODULE_PARM_DESC(luns, "number of LUNs");
360 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
361 MODULE_PARM_DESC(removable, "true to simulate removable media");
363 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
364 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
366 module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
367 MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
369 /* In the non-TEST version, only the module parameters listed above
370 * are available. */
371 #ifdef CONFIG_USB_FILE_STORAGE_TEST
373 module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
374 MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
376 module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
377 MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
378 "8070, or SCSI)");
380 module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
381 MODULE_PARM_DESC(vendor, "USB Vendor ID");
383 module_param_named(product, mod_data.product, ushort, S_IRUGO);
384 MODULE_PARM_DESC(product, "USB Product ID");
386 module_param_named(release, mod_data.release, ushort, S_IRUGO);
387 MODULE_PARM_DESC(release, "USB release number");
389 module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
390 MODULE_PARM_DESC(buflen, "I/O buffer size");
392 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
396 * These definitions will permit the compiler to avoid generating code for
397 * parts of the driver that aren't used in the non-TEST version. Even gcc
398 * can recognize when a test of a constant expression yields a dead code
399 * path.
402 #ifdef CONFIG_USB_FILE_STORAGE_TEST
404 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
405 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
406 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
408 #else
410 #define transport_is_bbb() 1
411 #define transport_is_cbi() 0
412 #define protocol_is_scsi() 1
414 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
417 /*-------------------------------------------------------------------------*/
420 struct fsg_dev {
421 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
422 spinlock_t lock;
423 struct usb_gadget *gadget;
425 /* filesem protects: backing files in use */
426 struct rw_semaphore filesem;
428 /* reference counting: wait until all LUNs are released */
429 struct kref ref;
431 struct usb_ep *ep0; // Handy copy of gadget->ep0
432 struct usb_request *ep0req; // For control responses
433 unsigned int ep0_req_tag;
434 const char *ep0req_name;
436 struct usb_request *intreq; // For interrupt responses
437 int intreq_busy;
438 struct fsg_buffhd *intr_buffhd;
440 unsigned int bulk_out_maxpacket;
441 enum fsg_state state; // For exception handling
442 unsigned int exception_req_tag;
444 u8 config, new_config;
446 unsigned int running : 1;
447 unsigned int bulk_in_enabled : 1;
448 unsigned int bulk_out_enabled : 1;
449 unsigned int intr_in_enabled : 1;
450 unsigned int phase_error : 1;
451 unsigned int short_packet_received : 1;
452 unsigned int bad_lun_okay : 1;
454 unsigned long atomic_bitflags;
455 #define REGISTERED 0
456 #define IGNORE_BULK_OUT 1
457 #define SUSPENDED 2
459 struct usb_ep *bulk_in;
460 struct usb_ep *bulk_out;
461 struct usb_ep *intr_in;
463 struct fsg_buffhd *next_buffhd_to_fill;
464 struct fsg_buffhd *next_buffhd_to_drain;
465 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
467 int thread_wakeup_needed;
468 struct completion thread_notifier;
469 struct task_struct *thread_task;
471 int cmnd_size;
472 u8 cmnd[MAX_COMMAND_SIZE];
473 enum data_direction data_dir;
474 u32 data_size;
475 u32 data_size_from_cmnd;
476 u32 tag;
477 unsigned int lun;
478 u32 residue;
479 u32 usb_amount_left;
481 /* The CB protocol offers no way for a host to know when a command
482 * has completed. As a result the next command may arrive early,
483 * and we will still have to handle it. For that reason we need
484 * a buffer to store new commands when using CB (or CBI, which
485 * does not oblige a host to wait for command completion either). */
486 int cbbuf_cmnd_size;
487 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
489 unsigned int nluns;
490 struct fsg_lun *luns;
491 struct fsg_lun *curlun;
494 typedef void (*fsg_routine_t)(struct fsg_dev *);
496 static int exception_in_progress(struct fsg_dev *fsg)
498 return (fsg->state > FSG_STATE_IDLE);
501 /* Make bulk-out requests be divisible by the maxpacket size */
502 static void set_bulk_out_req_length(struct fsg_dev *fsg,
503 struct fsg_buffhd *bh, unsigned int length)
505 unsigned int rem;
507 bh->bulk_out_intended_length = length;
508 rem = length % fsg->bulk_out_maxpacket;
509 if (rem > 0)
510 length += fsg->bulk_out_maxpacket - rem;
511 bh->outreq->length = length;
514 static struct fsg_dev *the_fsg;
515 static struct usb_gadget_driver fsg_driver;
518 /*-------------------------------------------------------------------------*/
520 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
522 const char *name;
524 if (ep == fsg->bulk_in)
525 name = "bulk-in";
526 else if (ep == fsg->bulk_out)
527 name = "bulk-out";
528 else
529 name = ep->name;
530 DBG(fsg, "%s set halt\n", name);
531 return usb_ep_set_halt(ep);
535 /*-------------------------------------------------------------------------*/
538 * DESCRIPTORS ... most are static, but strings and (full) configuration
539 * descriptors are built on demand. Also the (static) config and interface
540 * descriptors are adjusted during fsg_bind().
543 /* There is only one configuration. */
544 #define CONFIG_VALUE 1
546 static struct usb_device_descriptor
547 device_desc = {
548 .bLength = sizeof device_desc,
549 .bDescriptorType = USB_DT_DEVICE,
551 .bcdUSB = cpu_to_le16(0x0200),
552 .bDeviceClass = USB_CLASS_PER_INTERFACE,
554 /* The next three values can be overridden by module parameters */
555 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
556 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
557 .bcdDevice = cpu_to_le16(0xffff),
559 .iManufacturer = FSG_STRING_MANUFACTURER,
560 .iProduct = FSG_STRING_PRODUCT,
561 .iSerialNumber = FSG_STRING_SERIAL,
562 .bNumConfigurations = 1,
565 static struct usb_config_descriptor
566 config_desc = {
567 .bLength = sizeof config_desc,
568 .bDescriptorType = USB_DT_CONFIG,
570 /* wTotalLength computed by usb_gadget_config_buf() */
571 .bNumInterfaces = 1,
572 .bConfigurationValue = CONFIG_VALUE,
573 .iConfiguration = FSG_STRING_CONFIG,
574 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
575 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
579 static struct usb_qualifier_descriptor
580 dev_qualifier = {
581 .bLength = sizeof dev_qualifier,
582 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
584 .bcdUSB = cpu_to_le16(0x0200),
585 .bDeviceClass = USB_CLASS_PER_INTERFACE,
587 .bNumConfigurations = 1,
593 * Config descriptors must agree with the code that sets configurations
594 * and with code managing interfaces and their altsettings. They must
595 * also handle different speeds and other-speed requests.
597 static int populate_config_buf(struct usb_gadget *gadget,
598 u8 *buf, u8 type, unsigned index)
600 enum usb_device_speed speed = gadget->speed;
601 int len;
602 const struct usb_descriptor_header **function;
604 if (index > 0)
605 return -EINVAL;
607 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
608 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
609 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
610 ? (const struct usb_descriptor_header **)fsg_hs_function
611 : (const struct usb_descriptor_header **)fsg_fs_function;
613 /* for now, don't advertise srp-only devices */
614 if (!gadget_is_otg(gadget))
615 function++;
617 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
618 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
619 return len;
623 /*-------------------------------------------------------------------------*/
625 /* These routines may be called in process context or in_irq */
627 /* Caller must hold fsg->lock */
628 static void wakeup_thread(struct fsg_dev *fsg)
630 /* Tell the main thread that something has happened */
631 fsg->thread_wakeup_needed = 1;
632 if (fsg->thread_task)
633 wake_up_process(fsg->thread_task);
637 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
639 unsigned long flags;
641 /* Do nothing if a higher-priority exception is already in progress.
642 * If a lower-or-equal priority exception is in progress, preempt it
643 * and notify the main thread by sending it a signal. */
644 spin_lock_irqsave(&fsg->lock, flags);
645 if (fsg->state <= new_state) {
646 fsg->exception_req_tag = fsg->ep0_req_tag;
647 fsg->state = new_state;
648 if (fsg->thread_task)
649 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
650 fsg->thread_task);
652 spin_unlock_irqrestore(&fsg->lock, flags);
656 /*-------------------------------------------------------------------------*/
658 /* The disconnect callback and ep0 routines. These always run in_irq,
659 * except that ep0_queue() is called in the main thread to acknowledge
660 * completion of various requests: set config, set interface, and
661 * Bulk-only device reset. */
663 static void fsg_disconnect(struct usb_gadget *gadget)
665 struct fsg_dev *fsg = get_gadget_data(gadget);
667 DBG(fsg, "disconnect or port reset\n");
668 raise_exception(fsg, FSG_STATE_DISCONNECT);
672 static int ep0_queue(struct fsg_dev *fsg)
674 int rc;
676 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
677 if (rc != 0 && rc != -ESHUTDOWN) {
679 /* We can't do much more than wait for a reset */
680 WARNING(fsg, "error in submission: %s --> %d\n",
681 fsg->ep0->name, rc);
683 return rc;
686 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
688 struct fsg_dev *fsg = ep->driver_data;
690 if (req->actual > 0)
691 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
692 if (req->status || req->actual != req->length)
693 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
694 req->status, req->actual, req->length);
695 if (req->status == -ECONNRESET) // Request was cancelled
696 usb_ep_fifo_flush(ep);
698 if (req->status == 0 && req->context)
699 ((fsg_routine_t) (req->context))(fsg);
703 /*-------------------------------------------------------------------------*/
705 /* Bulk and interrupt endpoint completion handlers.
706 * These always run in_irq. */
708 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
710 struct fsg_dev *fsg = ep->driver_data;
711 struct fsg_buffhd *bh = req->context;
713 if (req->status || req->actual != req->length)
714 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
715 req->status, req->actual, req->length);
716 if (req->status == -ECONNRESET) // Request was cancelled
717 usb_ep_fifo_flush(ep);
719 /* Hold the lock while we update the request and buffer states */
720 smp_wmb();
721 spin_lock(&fsg->lock);
722 bh->inreq_busy = 0;
723 bh->state = BUF_STATE_EMPTY;
724 wakeup_thread(fsg);
725 spin_unlock(&fsg->lock);
728 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
730 struct fsg_dev *fsg = ep->driver_data;
731 struct fsg_buffhd *bh = req->context;
733 dump_msg(fsg, "bulk-out", req->buf, req->actual);
734 if (req->status || req->actual != bh->bulk_out_intended_length)
735 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
736 req->status, req->actual,
737 bh->bulk_out_intended_length);
738 if (req->status == -ECONNRESET) // Request was cancelled
739 usb_ep_fifo_flush(ep);
741 /* Hold the lock while we update the request and buffer states */
742 smp_wmb();
743 spin_lock(&fsg->lock);
744 bh->outreq_busy = 0;
745 bh->state = BUF_STATE_FULL;
746 wakeup_thread(fsg);
747 spin_unlock(&fsg->lock);
751 #ifdef CONFIG_USB_FILE_STORAGE_TEST
752 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
754 struct fsg_dev *fsg = ep->driver_data;
755 struct fsg_buffhd *bh = req->context;
757 if (req->status || req->actual != req->length)
758 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
759 req->status, req->actual, req->length);
760 if (req->status == -ECONNRESET) // Request was cancelled
761 usb_ep_fifo_flush(ep);
763 /* Hold the lock while we update the request and buffer states */
764 smp_wmb();
765 spin_lock(&fsg->lock);
766 fsg->intreq_busy = 0;
767 bh->state = BUF_STATE_EMPTY;
768 wakeup_thread(fsg);
769 spin_unlock(&fsg->lock);
772 #else
773 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
775 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
778 /*-------------------------------------------------------------------------*/
780 /* Ep0 class-specific handlers. These always run in_irq. */
782 #ifdef CONFIG_USB_FILE_STORAGE_TEST
783 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
785 struct usb_request *req = fsg->ep0req;
786 static u8 cbi_reset_cmnd[6] = {
787 SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
789 /* Error in command transfer? */
790 if (req->status || req->length != req->actual ||
791 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
793 /* Not all controllers allow a protocol stall after
794 * receiving control-out data, but we'll try anyway. */
795 fsg_set_halt(fsg, fsg->ep0);
796 return; // Wait for reset
799 /* Is it the special reset command? */
800 if (req->actual >= sizeof cbi_reset_cmnd &&
801 memcmp(req->buf, cbi_reset_cmnd,
802 sizeof cbi_reset_cmnd) == 0) {
804 /* Raise an exception to stop the current operation
805 * and reinitialize our state. */
806 DBG(fsg, "cbi reset request\n");
807 raise_exception(fsg, FSG_STATE_RESET);
808 return;
811 VDBG(fsg, "CB[I] accept device-specific command\n");
812 spin_lock(&fsg->lock);
814 /* Save the command for later */
815 if (fsg->cbbuf_cmnd_size)
816 WARNING(fsg, "CB[I] overwriting previous command\n");
817 fsg->cbbuf_cmnd_size = req->actual;
818 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
820 wakeup_thread(fsg);
821 spin_unlock(&fsg->lock);
824 #else
825 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
827 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
830 static int class_setup_req(struct fsg_dev *fsg,
831 const struct usb_ctrlrequest *ctrl)
833 struct usb_request *req = fsg->ep0req;
834 int value = -EOPNOTSUPP;
835 u16 w_index = le16_to_cpu(ctrl->wIndex);
836 u16 w_value = le16_to_cpu(ctrl->wValue);
837 u16 w_length = le16_to_cpu(ctrl->wLength);
839 if (!fsg->config)
840 return value;
842 /* Handle Bulk-only class-specific requests */
843 if (transport_is_bbb()) {
844 switch (ctrl->bRequest) {
846 case USB_BULK_RESET_REQUEST:
847 if (ctrl->bRequestType != (USB_DIR_OUT |
848 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
849 break;
850 if (w_index != 0 || w_value != 0) {
851 value = -EDOM;
852 break;
855 /* Raise an exception to stop the current operation
856 * and reinitialize our state. */
857 DBG(fsg, "bulk reset request\n");
858 raise_exception(fsg, FSG_STATE_RESET);
859 value = DELAYED_STATUS;
860 break;
862 case USB_BULK_GET_MAX_LUN_REQUEST:
863 if (ctrl->bRequestType != (USB_DIR_IN |
864 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
865 break;
866 if (w_index != 0 || w_value != 0) {
867 value = -EDOM;
868 break;
870 VDBG(fsg, "get max LUN\n");
871 *(u8 *) req->buf = fsg->nluns - 1;
872 value = 1;
873 break;
877 /* Handle CBI class-specific requests */
878 else {
879 switch (ctrl->bRequest) {
881 case USB_CBI_ADSC_REQUEST:
882 if (ctrl->bRequestType != (USB_DIR_OUT |
883 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
884 break;
885 if (w_index != 0 || w_value != 0) {
886 value = -EDOM;
887 break;
889 if (w_length > MAX_COMMAND_SIZE) {
890 value = -EOVERFLOW;
891 break;
893 value = w_length;
894 fsg->ep0req->context = received_cbi_adsc;
895 break;
899 if (value == -EOPNOTSUPP)
900 VDBG(fsg,
901 "unknown class-specific control req "
902 "%02x.%02x v%04x i%04x l%u\n",
903 ctrl->bRequestType, ctrl->bRequest,
904 le16_to_cpu(ctrl->wValue), w_index, w_length);
905 return value;
909 /*-------------------------------------------------------------------------*/
911 /* Ep0 standard request handlers. These always run in_irq. */
913 static int standard_setup_req(struct fsg_dev *fsg,
914 const struct usb_ctrlrequest *ctrl)
916 struct usb_request *req = fsg->ep0req;
917 int value = -EOPNOTSUPP;
918 u16 w_index = le16_to_cpu(ctrl->wIndex);
919 u16 w_value = le16_to_cpu(ctrl->wValue);
921 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
922 * but config change events will also reconfigure hardware. */
923 switch (ctrl->bRequest) {
925 case USB_REQ_GET_DESCRIPTOR:
926 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
927 USB_RECIP_DEVICE))
928 break;
929 switch (w_value >> 8) {
931 case USB_DT_DEVICE:
932 VDBG(fsg, "get device descriptor\n");
933 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
934 value = sizeof device_desc;
935 memcpy(req->buf, &device_desc, value);
936 break;
937 case USB_DT_DEVICE_QUALIFIER:
938 VDBG(fsg, "get device qualifier\n");
939 if (!gadget_is_dualspeed(fsg->gadget))
940 break;
942 * Assume ep0 uses the same maxpacket value for both
943 * speeds
945 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
946 value = sizeof dev_qualifier;
947 memcpy(req->buf, &dev_qualifier, value);
948 break;
950 case USB_DT_OTHER_SPEED_CONFIG:
951 VDBG(fsg, "get other-speed config descriptor\n");
952 if (!gadget_is_dualspeed(fsg->gadget))
953 break;
954 goto get_config;
955 case USB_DT_CONFIG:
956 VDBG(fsg, "get configuration descriptor\n");
957 get_config:
958 value = populate_config_buf(fsg->gadget,
959 req->buf,
960 w_value >> 8,
961 w_value & 0xff);
962 break;
964 case USB_DT_STRING:
965 VDBG(fsg, "get string descriptor\n");
967 /* wIndex == language code */
968 value = usb_gadget_get_string(&fsg_stringtab,
969 w_value & 0xff, req->buf);
970 break;
972 break;
974 /* One config, two speeds */
975 case USB_REQ_SET_CONFIGURATION:
976 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
977 USB_RECIP_DEVICE))
978 break;
979 VDBG(fsg, "set configuration\n");
980 if (w_value == CONFIG_VALUE || w_value == 0) {
981 fsg->new_config = w_value;
983 /* Raise an exception to wipe out previous transaction
984 * state (queued bufs, etc) and set the new config. */
985 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
986 value = DELAYED_STATUS;
988 break;
989 case USB_REQ_GET_CONFIGURATION:
990 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
991 USB_RECIP_DEVICE))
992 break;
993 VDBG(fsg, "get configuration\n");
994 *(u8 *) req->buf = fsg->config;
995 value = 1;
996 break;
998 case USB_REQ_SET_INTERFACE:
999 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1000 USB_RECIP_INTERFACE))
1001 break;
1002 if (fsg->config && w_index == 0) {
1004 /* Raise an exception to wipe out previous transaction
1005 * state (queued bufs, etc) and install the new
1006 * interface altsetting. */
1007 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1008 value = DELAYED_STATUS;
1010 break;
1011 case USB_REQ_GET_INTERFACE:
1012 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1013 USB_RECIP_INTERFACE))
1014 break;
1015 if (!fsg->config)
1016 break;
1017 if (w_index != 0) {
1018 value = -EDOM;
1019 break;
1021 VDBG(fsg, "get interface\n");
1022 *(u8 *) req->buf = 0;
1023 value = 1;
1024 break;
1026 default:
1027 VDBG(fsg,
1028 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1029 ctrl->bRequestType, ctrl->bRequest,
1030 w_value, w_index, le16_to_cpu(ctrl->wLength));
1033 return value;
1037 static int fsg_setup(struct usb_gadget *gadget,
1038 const struct usb_ctrlrequest *ctrl)
1040 struct fsg_dev *fsg = get_gadget_data(gadget);
1041 int rc;
1042 int w_length = le16_to_cpu(ctrl->wLength);
1044 ++fsg->ep0_req_tag; // Record arrival of a new request
1045 fsg->ep0req->context = NULL;
1046 fsg->ep0req->length = 0;
1047 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1049 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1050 rc = class_setup_req(fsg, ctrl);
1051 else
1052 rc = standard_setup_req(fsg, ctrl);
1054 /* Respond with data/status or defer until later? */
1055 if (rc >= 0 && rc != DELAYED_STATUS) {
1056 rc = min(rc, w_length);
1057 fsg->ep0req->length = rc;
1058 fsg->ep0req->zero = rc < w_length;
1059 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1060 "ep0-in" : "ep0-out");
1061 rc = ep0_queue(fsg);
1064 /* Device either stalls (rc < 0) or reports success */
1065 return rc;
1069 /*-------------------------------------------------------------------------*/
1071 /* All the following routines run in process context */
1074 /* Use this for bulk or interrupt transfers, not ep0 */
1075 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1076 struct usb_request *req, int *pbusy,
1077 enum fsg_buffer_state *state)
1079 int rc;
1081 if (ep == fsg->bulk_in)
1082 dump_msg(fsg, "bulk-in", req->buf, req->length);
1083 else if (ep == fsg->intr_in)
1084 dump_msg(fsg, "intr-in", req->buf, req->length);
1086 spin_lock_irq(&fsg->lock);
1087 *pbusy = 1;
1088 *state = BUF_STATE_BUSY;
1089 spin_unlock_irq(&fsg->lock);
1090 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1091 if (rc != 0) {
1092 *pbusy = 0;
1093 *state = BUF_STATE_EMPTY;
1095 /* We can't do much more than wait for a reset */
1097 /* Note: currently the net2280 driver fails zero-length
1098 * submissions if DMA is enabled. */
1099 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1100 req->length == 0))
1101 WARNING(fsg, "error in submission: %s --> %d\n",
1102 ep->name, rc);
1107 static int sleep_thread(struct fsg_dev *fsg)
1109 int rc = 0;
1111 /* Wait until a signal arrives or we are woken up */
1112 for (;;) {
1113 try_to_freeze();
1114 set_current_state(TASK_INTERRUPTIBLE);
1115 if (signal_pending(current)) {
1116 rc = -EINTR;
1117 break;
1119 if (fsg->thread_wakeup_needed)
1120 break;
1121 schedule();
1123 __set_current_state(TASK_RUNNING);
1124 fsg->thread_wakeup_needed = 0;
1125 return rc;
1129 /*-------------------------------------------------------------------------*/
1131 static int do_read(struct fsg_dev *fsg)
1133 struct fsg_lun *curlun = fsg->curlun;
1134 u32 lba;
1135 struct fsg_buffhd *bh;
1136 int rc;
1137 u32 amount_left;
1138 loff_t file_offset, file_offset_tmp;
1139 unsigned int amount;
1140 unsigned int partial_page;
1141 ssize_t nread;
1143 /* Get the starting Logical Block Address and check that it's
1144 * not too big */
1145 if (fsg->cmnd[0] == READ_6)
1146 lba = get_unaligned_be24(&fsg->cmnd[1]);
1147 else {
1148 lba = get_unaligned_be32(&fsg->cmnd[2]);
1150 /* We allow DPO (Disable Page Out = don't save data in the
1151 * cache) and FUA (Force Unit Access = don't read from the
1152 * cache), but we don't implement them. */
1153 if ((fsg->cmnd[1] & ~0x18) != 0) {
1154 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1155 return -EINVAL;
1158 if (lba >= curlun->num_sectors) {
1159 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1160 return -EINVAL;
1162 file_offset = ((loff_t) lba) << 9;
1164 /* Carry out the file reads */
1165 amount_left = fsg->data_size_from_cmnd;
1166 if (unlikely(amount_left == 0))
1167 return -EIO; // No default reply
1169 for (;;) {
1171 /* Figure out how much we need to read:
1172 * Try to read the remaining amount.
1173 * But don't read more than the buffer size.
1174 * And don't try to read past the end of the file.
1175 * Finally, if we're not at a page boundary, don't read past
1176 * the next page.
1177 * If this means reading 0 then we were asked to read past
1178 * the end of file. */
1179 amount = min((unsigned int) amount_left, mod_data.buflen);
1180 amount = min((loff_t) amount,
1181 curlun->file_length - file_offset);
1182 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1183 if (partial_page > 0)
1184 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1185 partial_page);
1187 /* Wait for the next buffer to become available */
1188 bh = fsg->next_buffhd_to_fill;
1189 while (bh->state != BUF_STATE_EMPTY) {
1190 rc = sleep_thread(fsg);
1191 if (rc)
1192 return rc;
1195 /* If we were asked to read past the end of file,
1196 * end with an empty buffer. */
1197 if (amount == 0) {
1198 curlun->sense_data =
1199 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1200 curlun->sense_data_info = file_offset >> 9;
1201 curlun->info_valid = 1;
1202 bh->inreq->length = 0;
1203 bh->state = BUF_STATE_FULL;
1204 break;
1207 /* Perform the read */
1208 file_offset_tmp = file_offset;
1209 nread = vfs_read(curlun->filp,
1210 (char __user *) bh->buf,
1211 amount, &file_offset_tmp);
1212 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1213 (unsigned long long) file_offset,
1214 (int) nread);
1215 if (signal_pending(current))
1216 return -EINTR;
1218 if (nread < 0) {
1219 LDBG(curlun, "error in file read: %d\n",
1220 (int) nread);
1221 nread = 0;
1222 } else if (nread < amount) {
1223 LDBG(curlun, "partial file read: %d/%u\n",
1224 (int) nread, amount);
1225 nread -= (nread & 511); // Round down to a block
1227 file_offset += nread;
1228 amount_left -= nread;
1229 fsg->residue -= nread;
1230 bh->inreq->length = nread;
1231 bh->state = BUF_STATE_FULL;
1233 /* If an error occurred, report it and its position */
1234 if (nread < amount) {
1235 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1236 curlun->sense_data_info = file_offset >> 9;
1237 curlun->info_valid = 1;
1238 break;
1241 if (amount_left == 0)
1242 break; // No more left to read
1244 /* Send this buffer and go read some more */
1245 bh->inreq->zero = 0;
1246 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1247 &bh->inreq_busy, &bh->state);
1248 fsg->next_buffhd_to_fill = bh->next;
1251 return -EIO; // No default reply
1255 /*-------------------------------------------------------------------------*/
1257 static int do_write(struct fsg_dev *fsg)
1259 struct fsg_lun *curlun = fsg->curlun;
1260 u32 lba;
1261 struct fsg_buffhd *bh;
1262 int get_some_more;
1263 u32 amount_left_to_req, amount_left_to_write;
1264 loff_t usb_offset, file_offset, file_offset_tmp;
1265 unsigned int amount;
1266 unsigned int partial_page;
1267 ssize_t nwritten;
1268 int rc;
1270 if (curlun->ro) {
1271 curlun->sense_data = SS_WRITE_PROTECTED;
1272 return -EINVAL;
1274 spin_lock(&curlun->filp->f_lock);
1275 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1276 spin_unlock(&curlun->filp->f_lock);
1278 /* Get the starting Logical Block Address and check that it's
1279 * not too big */
1280 if (fsg->cmnd[0] == WRITE_6)
1281 lba = get_unaligned_be24(&fsg->cmnd[1]);
1282 else {
1283 lba = get_unaligned_be32(&fsg->cmnd[2]);
1285 /* We allow DPO (Disable Page Out = don't save data in the
1286 * cache) and FUA (Force Unit Access = write directly to the
1287 * medium). We don't implement DPO; we implement FUA by
1288 * performing synchronous output. */
1289 if ((fsg->cmnd[1] & ~0x18) != 0) {
1290 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1291 return -EINVAL;
1293 /* FUA */
1294 if (!curlun->nofua && (fsg->cmnd[1] & 0x08)) {
1295 spin_lock(&curlun->filp->f_lock);
1296 curlun->filp->f_flags |= O_DSYNC;
1297 spin_unlock(&curlun->filp->f_lock);
1300 if (lba >= curlun->num_sectors) {
1301 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1302 return -EINVAL;
1305 /* Carry out the file writes */
1306 get_some_more = 1;
1307 file_offset = usb_offset = ((loff_t) lba) << 9;
1308 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1310 while (amount_left_to_write > 0) {
1312 /* Queue a request for more data from the host */
1313 bh = fsg->next_buffhd_to_fill;
1314 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1316 /* Figure out how much we want to get:
1317 * Try to get the remaining amount.
1318 * But don't get more than the buffer size.
1319 * And don't try to go past the end of the file.
1320 * If we're not at a page boundary,
1321 * don't go past the next page.
1322 * If this means getting 0, then we were asked
1323 * to write past the end of file.
1324 * Finally, round down to a block boundary. */
1325 amount = min(amount_left_to_req, mod_data.buflen);
1326 amount = min((loff_t) amount, curlun->file_length -
1327 usb_offset);
1328 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1329 if (partial_page > 0)
1330 amount = min(amount,
1331 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1333 if (amount == 0) {
1334 get_some_more = 0;
1335 curlun->sense_data =
1336 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1337 curlun->sense_data_info = usb_offset >> 9;
1338 curlun->info_valid = 1;
1339 continue;
1341 amount -= (amount & 511);
1342 if (amount == 0) {
1344 /* Why were we were asked to transfer a
1345 * partial block? */
1346 get_some_more = 0;
1347 continue;
1350 /* Get the next buffer */
1351 usb_offset += amount;
1352 fsg->usb_amount_left -= amount;
1353 amount_left_to_req -= amount;
1354 if (amount_left_to_req == 0)
1355 get_some_more = 0;
1357 /* amount is always divisible by 512, hence by
1358 * the bulk-out maxpacket size */
1359 bh->outreq->length = bh->bulk_out_intended_length =
1360 amount;
1361 bh->outreq->short_not_ok = 1;
1362 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1363 &bh->outreq_busy, &bh->state);
1364 fsg->next_buffhd_to_fill = bh->next;
1365 continue;
1368 /* Write the received data to the backing file */
1369 bh = fsg->next_buffhd_to_drain;
1370 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1371 break; // We stopped early
1372 if (bh->state == BUF_STATE_FULL) {
1373 smp_rmb();
1374 fsg->next_buffhd_to_drain = bh->next;
1375 bh->state = BUF_STATE_EMPTY;
1377 /* Did something go wrong with the transfer? */
1378 if (bh->outreq->status != 0) {
1379 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1380 curlun->sense_data_info = file_offset >> 9;
1381 curlun->info_valid = 1;
1382 break;
1385 amount = bh->outreq->actual;
1386 if (curlun->file_length - file_offset < amount) {
1387 LERROR(curlun,
1388 "write %u @ %llu beyond end %llu\n",
1389 amount, (unsigned long long) file_offset,
1390 (unsigned long long) curlun->file_length);
1391 amount = curlun->file_length - file_offset;
1394 /* Perform the write */
1395 file_offset_tmp = file_offset;
1396 nwritten = vfs_write(curlun->filp,
1397 (char __user *) bh->buf,
1398 amount, &file_offset_tmp);
1399 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1400 (unsigned long long) file_offset,
1401 (int) nwritten);
1402 if (signal_pending(current))
1403 return -EINTR; // Interrupted!
1405 if (nwritten < 0) {
1406 LDBG(curlun, "error in file write: %d\n",
1407 (int) nwritten);
1408 nwritten = 0;
1409 } else if (nwritten < amount) {
1410 LDBG(curlun, "partial file write: %d/%u\n",
1411 (int) nwritten, amount);
1412 nwritten -= (nwritten & 511);
1413 // Round down to a block
1415 file_offset += nwritten;
1416 amount_left_to_write -= nwritten;
1417 fsg->residue -= nwritten;
1419 /* If an error occurred, report it and its position */
1420 if (nwritten < amount) {
1421 curlun->sense_data = SS_WRITE_ERROR;
1422 curlun->sense_data_info = file_offset >> 9;
1423 curlun->info_valid = 1;
1424 break;
1427 /* Did the host decide to stop early? */
1428 if (bh->outreq->actual != bh->outreq->length) {
1429 fsg->short_packet_received = 1;
1430 break;
1432 continue;
1435 /* Wait for something to happen */
1436 rc = sleep_thread(fsg);
1437 if (rc)
1438 return rc;
1441 return -EIO; // No default reply
1445 /*-------------------------------------------------------------------------*/
1447 static int do_synchronize_cache(struct fsg_dev *fsg)
1449 struct fsg_lun *curlun = fsg->curlun;
1450 int rc;
1452 /* We ignore the requested LBA and write out all file's
1453 * dirty data buffers. */
1454 rc = fsg_lun_fsync_sub(curlun);
1455 if (rc)
1456 curlun->sense_data = SS_WRITE_ERROR;
1457 return 0;
1461 /*-------------------------------------------------------------------------*/
1463 static void invalidate_sub(struct fsg_lun *curlun)
1465 struct file *filp = curlun->filp;
1466 struct inode *inode = filp->f_path.dentry->d_inode;
1467 unsigned long rc;
1469 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1470 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1473 static int do_verify(struct fsg_dev *fsg)
1475 struct fsg_lun *curlun = fsg->curlun;
1476 u32 lba;
1477 u32 verification_length;
1478 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1479 loff_t file_offset, file_offset_tmp;
1480 u32 amount_left;
1481 unsigned int amount;
1482 ssize_t nread;
1484 /* Get the starting Logical Block Address and check that it's
1485 * not too big */
1486 lba = get_unaligned_be32(&fsg->cmnd[2]);
1487 if (lba >= curlun->num_sectors) {
1488 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1489 return -EINVAL;
1492 /* We allow DPO (Disable Page Out = don't save data in the
1493 * cache) but we don't implement it. */
1494 if ((fsg->cmnd[1] & ~0x10) != 0) {
1495 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1496 return -EINVAL;
1499 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
1500 if (unlikely(verification_length == 0))
1501 return -EIO; // No default reply
1503 /* Prepare to carry out the file verify */
1504 amount_left = verification_length << 9;
1505 file_offset = ((loff_t) lba) << 9;
1507 /* Write out all the dirty buffers before invalidating them */
1508 fsg_lun_fsync_sub(curlun);
1509 if (signal_pending(current))
1510 return -EINTR;
1512 invalidate_sub(curlun);
1513 if (signal_pending(current))
1514 return -EINTR;
1516 /* Just try to read the requested blocks */
1517 while (amount_left > 0) {
1519 /* Figure out how much we need to read:
1520 * Try to read the remaining amount, but not more than
1521 * the buffer size.
1522 * And don't try to read past the end of the file.
1523 * If this means reading 0 then we were asked to read
1524 * past the end of file. */
1525 amount = min((unsigned int) amount_left, mod_data.buflen);
1526 amount = min((loff_t) amount,
1527 curlun->file_length - file_offset);
1528 if (amount == 0) {
1529 curlun->sense_data =
1530 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1531 curlun->sense_data_info = file_offset >> 9;
1532 curlun->info_valid = 1;
1533 break;
1536 /* Perform the read */
1537 file_offset_tmp = file_offset;
1538 nread = vfs_read(curlun->filp,
1539 (char __user *) bh->buf,
1540 amount, &file_offset_tmp);
1541 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1542 (unsigned long long) file_offset,
1543 (int) nread);
1544 if (signal_pending(current))
1545 return -EINTR;
1547 if (nread < 0) {
1548 LDBG(curlun, "error in file verify: %d\n",
1549 (int) nread);
1550 nread = 0;
1551 } else if (nread < amount) {
1552 LDBG(curlun, "partial file verify: %d/%u\n",
1553 (int) nread, amount);
1554 nread -= (nread & 511); // Round down to a sector
1556 if (nread == 0) {
1557 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1558 curlun->sense_data_info = file_offset >> 9;
1559 curlun->info_valid = 1;
1560 break;
1562 file_offset += nread;
1563 amount_left -= nread;
1565 return 0;
1569 /*-------------------------------------------------------------------------*/
1571 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1573 u8 *buf = (u8 *) bh->buf;
1575 static char vendor_id[] = "Linux ";
1576 static char product_disk_id[] = "File-Stor Gadget";
1577 static char product_cdrom_id[] = "File-CD Gadget ";
1579 if (!fsg->curlun) { // Unsupported LUNs are okay
1580 fsg->bad_lun_okay = 1;
1581 memset(buf, 0, 36);
1582 buf[0] = 0x7f; // Unsupported, no device-type
1583 buf[4] = 31; // Additional length
1584 return 36;
1587 memset(buf, 0, 8);
1588 buf[0] = (mod_data.cdrom ? TYPE_ROM : TYPE_DISK);
1589 if (mod_data.removable)
1590 buf[1] = 0x80;
1591 buf[2] = 2; // ANSI SCSI level 2
1592 buf[3] = 2; // SCSI-2 INQUIRY data format
1593 buf[4] = 31; // Additional length
1594 // No special options
1595 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1596 (mod_data.cdrom ? product_cdrom_id :
1597 product_disk_id),
1598 mod_data.release);
1599 return 36;
1603 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1605 struct fsg_lun *curlun = fsg->curlun;
1606 u8 *buf = (u8 *) bh->buf;
1607 u32 sd, sdinfo;
1608 int valid;
1611 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1613 * If a REQUEST SENSE command is received from an initiator
1614 * with a pending unit attention condition (before the target
1615 * generates the contingent allegiance condition), then the
1616 * target shall either:
1617 * a) report any pending sense data and preserve the unit
1618 * attention condition on the logical unit, or,
1619 * b) report the unit attention condition, may discard any
1620 * pending sense data, and clear the unit attention
1621 * condition on the logical unit for that initiator.
1623 * FSG normally uses option a); enable this code to use option b).
1625 #if 0
1626 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1627 curlun->sense_data = curlun->unit_attention_data;
1628 curlun->unit_attention_data = SS_NO_SENSE;
1630 #endif
1632 if (!curlun) { // Unsupported LUNs are okay
1633 fsg->bad_lun_okay = 1;
1634 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1635 sdinfo = 0;
1636 valid = 0;
1637 } else {
1638 sd = curlun->sense_data;
1639 sdinfo = curlun->sense_data_info;
1640 valid = curlun->info_valid << 7;
1641 curlun->sense_data = SS_NO_SENSE;
1642 curlun->sense_data_info = 0;
1643 curlun->info_valid = 0;
1646 memset(buf, 0, 18);
1647 buf[0] = valid | 0x70; // Valid, current error
1648 buf[2] = SK(sd);
1649 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1650 buf[7] = 18 - 8; // Additional sense length
1651 buf[12] = ASC(sd);
1652 buf[13] = ASCQ(sd);
1653 return 18;
1657 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1659 struct fsg_lun *curlun = fsg->curlun;
1660 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
1661 int pmi = fsg->cmnd[8];
1662 u8 *buf = (u8 *) bh->buf;
1664 /* Check the PMI and LBA fields */
1665 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1666 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1667 return -EINVAL;
1670 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1671 /* Max logical block */
1672 put_unaligned_be32(512, &buf[4]); /* Block length */
1673 return 8;
1677 static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1679 struct fsg_lun *curlun = fsg->curlun;
1680 int msf = fsg->cmnd[1] & 0x02;
1681 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
1682 u8 *buf = (u8 *) bh->buf;
1684 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1685 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1686 return -EINVAL;
1688 if (lba >= curlun->num_sectors) {
1689 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1690 return -EINVAL;
1693 memset(buf, 0, 8);
1694 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1695 store_cdrom_address(&buf[4], msf, lba);
1696 return 8;
1700 static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1702 struct fsg_lun *curlun = fsg->curlun;
1703 int msf = fsg->cmnd[1] & 0x02;
1704 int start_track = fsg->cmnd[6];
1705 u8 *buf = (u8 *) bh->buf;
1707 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1708 start_track > 1) {
1709 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1710 return -EINVAL;
1713 memset(buf, 0, 20);
1714 buf[1] = (20-2); /* TOC data length */
1715 buf[2] = 1; /* First track number */
1716 buf[3] = 1; /* Last track number */
1717 buf[5] = 0x16; /* Data track, copying allowed */
1718 buf[6] = 0x01; /* Only track is number 1 */
1719 store_cdrom_address(&buf[8], msf, 0);
1721 buf[13] = 0x16; /* Lead-out track is data */
1722 buf[14] = 0xAA; /* Lead-out track number */
1723 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1724 return 20;
1728 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1730 struct fsg_lun *curlun = fsg->curlun;
1731 int mscmnd = fsg->cmnd[0];
1732 u8 *buf = (u8 *) bh->buf;
1733 u8 *buf0 = buf;
1734 int pc, page_code;
1735 int changeable_values, all_pages;
1736 int valid_page = 0;
1737 int len, limit;
1739 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1740 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1741 return -EINVAL;
1743 pc = fsg->cmnd[2] >> 6;
1744 page_code = fsg->cmnd[2] & 0x3f;
1745 if (pc == 3) {
1746 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1747 return -EINVAL;
1749 changeable_values = (pc == 1);
1750 all_pages = (page_code == 0x3f);
1752 /* Write the mode parameter header. Fixed values are: default
1753 * medium type, no cache control (DPOFUA), and no block descriptors.
1754 * The only variable value is the WriteProtect bit. We will fill in
1755 * the mode data length later. */
1756 memset(buf, 0, 8);
1757 if (mscmnd == MODE_SENSE) {
1758 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1759 buf += 4;
1760 limit = 255;
1761 } else { // MODE_SENSE_10
1762 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1763 buf += 8;
1764 limit = 65535; // Should really be mod_data.buflen
1767 /* No block descriptors */
1769 /* The mode pages, in numerical order. The only page we support
1770 * is the Caching page. */
1771 if (page_code == 0x08 || all_pages) {
1772 valid_page = 1;
1773 buf[0] = 0x08; // Page code
1774 buf[1] = 10; // Page length
1775 memset(buf+2, 0, 10); // None of the fields are changeable
1777 if (!changeable_values) {
1778 buf[2] = 0x04; // Write cache enable,
1779 // Read cache not disabled
1780 // No cache retention priorities
1781 put_unaligned_be16(0xffff, &buf[4]);
1782 /* Don't disable prefetch */
1783 /* Minimum prefetch = 0 */
1784 put_unaligned_be16(0xffff, &buf[8]);
1785 /* Maximum prefetch */
1786 put_unaligned_be16(0xffff, &buf[10]);
1787 /* Maximum prefetch ceiling */
1789 buf += 12;
1792 /* Check that a valid page was requested and the mode data length
1793 * isn't too long. */
1794 len = buf - buf0;
1795 if (!valid_page || len > limit) {
1796 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1797 return -EINVAL;
1800 /* Store the mode data length */
1801 if (mscmnd == MODE_SENSE)
1802 buf0[0] = len - 1;
1803 else
1804 put_unaligned_be16(len - 2, buf0);
1805 return len;
1809 static int do_start_stop(struct fsg_dev *fsg)
1811 struct fsg_lun *curlun = fsg->curlun;
1812 int loej, start;
1814 if (!mod_data.removable) {
1815 curlun->sense_data = SS_INVALID_COMMAND;
1816 return -EINVAL;
1819 // int immed = fsg->cmnd[1] & 0x01;
1820 loej = fsg->cmnd[4] & 0x02;
1821 start = fsg->cmnd[4] & 0x01;
1823 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1824 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1825 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1826 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1827 return -EINVAL;
1830 if (!start) {
1832 /* Are we allowed to unload the media? */
1833 if (curlun->prevent_medium_removal) {
1834 LDBG(curlun, "unload attempt prevented\n");
1835 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1836 return -EINVAL;
1838 if (loej) { // Simulate an unload/eject
1839 up_read(&fsg->filesem);
1840 down_write(&fsg->filesem);
1841 fsg_lun_close(curlun);
1842 up_write(&fsg->filesem);
1843 down_read(&fsg->filesem);
1845 } else {
1847 /* Our emulation doesn't support mounting; the medium is
1848 * available for use as soon as it is loaded. */
1849 if (!fsg_lun_is_open(curlun)) {
1850 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1851 return -EINVAL;
1854 #endif
1855 return 0;
1859 static int do_prevent_allow(struct fsg_dev *fsg)
1861 struct fsg_lun *curlun = fsg->curlun;
1862 int prevent;
1864 if (!mod_data.removable) {
1865 curlun->sense_data = SS_INVALID_COMMAND;
1866 return -EINVAL;
1869 prevent = fsg->cmnd[4] & 0x01;
1870 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1871 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1872 return -EINVAL;
1875 if (curlun->prevent_medium_removal && !prevent)
1876 fsg_lun_fsync_sub(curlun);
1877 curlun->prevent_medium_removal = prevent;
1878 return 0;
1882 static int do_read_format_capacities(struct fsg_dev *fsg,
1883 struct fsg_buffhd *bh)
1885 struct fsg_lun *curlun = fsg->curlun;
1886 u8 *buf = (u8 *) bh->buf;
1888 buf[0] = buf[1] = buf[2] = 0;
1889 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1890 buf += 4;
1892 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1893 /* Number of blocks */
1894 put_unaligned_be32(512, &buf[4]); /* Block length */
1895 buf[4] = 0x02; /* Current capacity */
1896 return 12;
1900 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1902 struct fsg_lun *curlun = fsg->curlun;
1904 /* We don't support MODE SELECT */
1905 curlun->sense_data = SS_INVALID_COMMAND;
1906 return -EINVAL;
1910 /*-------------------------------------------------------------------------*/
1912 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1914 int rc;
1916 rc = fsg_set_halt(fsg, fsg->bulk_in);
1917 if (rc == -EAGAIN)
1918 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1919 while (rc != 0) {
1920 if (rc != -EAGAIN) {
1921 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1922 rc = 0;
1923 break;
1926 /* Wait for a short time and then try again */
1927 if (msleep_interruptible(100) != 0)
1928 return -EINTR;
1929 rc = usb_ep_set_halt(fsg->bulk_in);
1931 return rc;
1934 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1936 int rc;
1938 DBG(fsg, "bulk-in set wedge\n");
1939 rc = usb_ep_set_wedge(fsg->bulk_in);
1940 if (rc == -EAGAIN)
1941 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1942 while (rc != 0) {
1943 if (rc != -EAGAIN) {
1944 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1945 rc = 0;
1946 break;
1949 /* Wait for a short time and then try again */
1950 if (msleep_interruptible(100) != 0)
1951 return -EINTR;
1952 rc = usb_ep_set_wedge(fsg->bulk_in);
1954 return rc;
1957 static int throw_away_data(struct fsg_dev *fsg)
1959 struct fsg_buffhd *bh;
1960 u32 amount;
1961 int rc;
1963 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1964 fsg->usb_amount_left > 0) {
1966 /* Throw away the data in a filled buffer */
1967 if (bh->state == BUF_STATE_FULL) {
1968 smp_rmb();
1969 bh->state = BUF_STATE_EMPTY;
1970 fsg->next_buffhd_to_drain = bh->next;
1972 /* A short packet or an error ends everything */
1973 if (bh->outreq->actual != bh->outreq->length ||
1974 bh->outreq->status != 0) {
1975 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1976 return -EINTR;
1978 continue;
1981 /* Try to submit another request if we need one */
1982 bh = fsg->next_buffhd_to_fill;
1983 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1984 amount = min(fsg->usb_amount_left,
1985 (u32) mod_data.buflen);
1987 /* amount is always divisible by 512, hence by
1988 * the bulk-out maxpacket size */
1989 bh->outreq->length = bh->bulk_out_intended_length =
1990 amount;
1991 bh->outreq->short_not_ok = 1;
1992 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1993 &bh->outreq_busy, &bh->state);
1994 fsg->next_buffhd_to_fill = bh->next;
1995 fsg->usb_amount_left -= amount;
1996 continue;
1999 /* Otherwise wait for something to happen */
2000 rc = sleep_thread(fsg);
2001 if (rc)
2002 return rc;
2004 return 0;
2008 static int finish_reply(struct fsg_dev *fsg)
2010 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2011 int rc = 0;
2013 switch (fsg->data_dir) {
2014 case DATA_DIR_NONE:
2015 break; // Nothing to send
2017 /* If we don't know whether the host wants to read or write,
2018 * this must be CB or CBI with an unknown command. We mustn't
2019 * try to send or receive any data. So stall both bulk pipes
2020 * if we can and wait for a reset. */
2021 case DATA_DIR_UNKNOWN:
2022 if (mod_data.can_stall) {
2023 fsg_set_halt(fsg, fsg->bulk_out);
2024 rc = halt_bulk_in_endpoint(fsg);
2026 break;
2028 /* All but the last buffer of data must have already been sent */
2029 case DATA_DIR_TO_HOST:
2030 if (fsg->data_size == 0)
2031 ; // Nothing to send
2033 /* If there's no residue, simply send the last buffer */
2034 else if (fsg->residue == 0) {
2035 bh->inreq->zero = 0;
2036 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2037 &bh->inreq_busy, &bh->state);
2038 fsg->next_buffhd_to_fill = bh->next;
2041 /* There is a residue. For CB and CBI, simply mark the end
2042 * of the data with a short packet. However, if we are
2043 * allowed to stall, there was no data at all (residue ==
2044 * data_size), and the command failed (invalid LUN or
2045 * sense data is set), then halt the bulk-in endpoint
2046 * instead. */
2047 else if (!transport_is_bbb()) {
2048 if (mod_data.can_stall &&
2049 fsg->residue == fsg->data_size &&
2050 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2051 bh->state = BUF_STATE_EMPTY;
2052 rc = halt_bulk_in_endpoint(fsg);
2053 } else {
2054 bh->inreq->zero = 1;
2055 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2056 &bh->inreq_busy, &bh->state);
2057 fsg->next_buffhd_to_fill = bh->next;
2062 * For Bulk-only, mark the end of the data with a short
2063 * packet. If we are allowed to stall, halt the bulk-in
2064 * endpoint. (Note: This violates the Bulk-Only Transport
2065 * specification, which requires us to pad the data if we
2066 * don't halt the endpoint. Presumably nobody will mind.)
2068 else {
2069 bh->inreq->zero = 1;
2070 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2071 &bh->inreq_busy, &bh->state);
2072 fsg->next_buffhd_to_fill = bh->next;
2073 if (mod_data.can_stall)
2074 rc = halt_bulk_in_endpoint(fsg);
2076 break;
2078 /* We have processed all we want from the data the host has sent.
2079 * There may still be outstanding bulk-out requests. */
2080 case DATA_DIR_FROM_HOST:
2081 if (fsg->residue == 0)
2082 ; // Nothing to receive
2084 /* Did the host stop sending unexpectedly early? */
2085 else if (fsg->short_packet_received) {
2086 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2087 rc = -EINTR;
2090 /* We haven't processed all the incoming data. Even though
2091 * we may be allowed to stall, doing so would cause a race.
2092 * The controller may already have ACK'ed all the remaining
2093 * bulk-out packets, in which case the host wouldn't see a
2094 * STALL. Not realizing the endpoint was halted, it wouldn't
2095 * clear the halt -- leading to problems later on. */
2096 #if 0
2097 else if (mod_data.can_stall) {
2098 fsg_set_halt(fsg, fsg->bulk_out);
2099 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2100 rc = -EINTR;
2102 #endif
2104 /* We can't stall. Read in the excess data and throw it
2105 * all away. */
2106 else
2107 rc = throw_away_data(fsg);
2108 break;
2110 return rc;
2114 static int send_status(struct fsg_dev *fsg)
2116 struct fsg_lun *curlun = fsg->curlun;
2117 struct fsg_buffhd *bh;
2118 int rc;
2119 u8 status = USB_STATUS_PASS;
2120 u32 sd, sdinfo = 0;
2122 /* Wait for the next buffer to become available */
2123 bh = fsg->next_buffhd_to_fill;
2124 while (bh->state != BUF_STATE_EMPTY) {
2125 rc = sleep_thread(fsg);
2126 if (rc)
2127 return rc;
2130 if (curlun) {
2131 sd = curlun->sense_data;
2132 sdinfo = curlun->sense_data_info;
2133 } else if (fsg->bad_lun_okay)
2134 sd = SS_NO_SENSE;
2135 else
2136 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2138 if (fsg->phase_error) {
2139 DBG(fsg, "sending phase-error status\n");
2140 status = USB_STATUS_PHASE_ERROR;
2141 sd = SS_INVALID_COMMAND;
2142 } else if (sd != SS_NO_SENSE) {
2143 DBG(fsg, "sending command-failure status\n");
2144 status = USB_STATUS_FAIL;
2145 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2146 " info x%x\n",
2147 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2150 if (transport_is_bbb()) {
2151 struct bulk_cs_wrap *csw = bh->buf;
2153 /* Store and send the Bulk-only CSW */
2154 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
2155 csw->Tag = fsg->tag;
2156 csw->Residue = cpu_to_le32(fsg->residue);
2157 csw->Status = status;
2159 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2160 bh->inreq->zero = 0;
2161 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2162 &bh->inreq_busy, &bh->state);
2164 } else if (mod_data.transport_type == USB_PR_CB) {
2166 /* Control-Bulk transport has no status phase! */
2167 return 0;
2169 } else { // USB_PR_CBI
2170 struct interrupt_data *buf = bh->buf;
2172 /* Store and send the Interrupt data. UFI sends the ASC
2173 * and ASCQ bytes. Everything else sends a Type (which
2174 * is always 0) and the status Value. */
2175 if (mod_data.protocol_type == USB_SC_UFI) {
2176 buf->bType = ASC(sd);
2177 buf->bValue = ASCQ(sd);
2178 } else {
2179 buf->bType = 0;
2180 buf->bValue = status;
2182 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2184 fsg->intr_buffhd = bh; // Point to the right buffhd
2185 fsg->intreq->buf = bh->inreq->buf;
2186 fsg->intreq->context = bh;
2187 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2188 &fsg->intreq_busy, &bh->state);
2191 fsg->next_buffhd_to_fill = bh->next;
2192 return 0;
2196 /*-------------------------------------------------------------------------*/
2198 /* Check whether the command is properly formed and whether its data size
2199 * and direction agree with the values we already have. */
2200 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2201 enum data_direction data_dir, unsigned int mask,
2202 int needs_medium, const char *name)
2204 int i;
2205 int lun = fsg->cmnd[1] >> 5;
2206 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2207 char hdlen[20];
2208 struct fsg_lun *curlun;
2210 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2211 * Transparent SCSI doesn't pad. */
2212 if (protocol_is_scsi())
2215 /* There's some disagreement as to whether RBC pads commands or not.
2216 * We'll play it safe and accept either form. */
2217 else if (mod_data.protocol_type == USB_SC_RBC) {
2218 if (fsg->cmnd_size == 12)
2219 cmnd_size = 12;
2221 /* All the other protocols pad to 12 bytes */
2222 } else
2223 cmnd_size = 12;
2225 hdlen[0] = 0;
2226 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2227 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2228 fsg->data_size);
2229 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2230 name, cmnd_size, dirletter[(int) data_dir],
2231 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2233 /* We can't reply at all until we know the correct data direction
2234 * and size. */
2235 if (fsg->data_size_from_cmnd == 0)
2236 data_dir = DATA_DIR_NONE;
2237 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2238 fsg->data_dir = data_dir;
2239 fsg->data_size = fsg->data_size_from_cmnd;
2241 } else { // Bulk-only
2242 if (fsg->data_size < fsg->data_size_from_cmnd) {
2244 /* Host data size < Device data size is a phase error.
2245 * Carry out the command, but only transfer as much
2246 * as we are allowed. */
2247 fsg->data_size_from_cmnd = fsg->data_size;
2248 fsg->phase_error = 1;
2251 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2253 /* Conflicting data directions is a phase error */
2254 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2255 fsg->phase_error = 1;
2256 return -EINVAL;
2259 /* Verify the length of the command itself */
2260 if (cmnd_size != fsg->cmnd_size) {
2262 /* Special case workaround: There are plenty of buggy SCSI
2263 * implementations. Many have issues with cbw->Length
2264 * field passing a wrong command size. For those cases we
2265 * always try to work around the problem by using the length
2266 * sent by the host side provided it is at least as large
2267 * as the correct command length.
2268 * Examples of such cases would be MS-Windows, which issues
2269 * REQUEST SENSE with cbw->Length == 12 where it should
2270 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2271 * REQUEST SENSE with cbw->Length == 10 where it should
2272 * be 6 as well.
2274 if (cmnd_size <= fsg->cmnd_size) {
2275 DBG(fsg, "%s is buggy! Expected length %d "
2276 "but we got %d\n", name,
2277 cmnd_size, fsg->cmnd_size);
2278 cmnd_size = fsg->cmnd_size;
2279 } else {
2280 fsg->phase_error = 1;
2281 return -EINVAL;
2285 /* Check that the LUN values are consistent */
2286 if (transport_is_bbb()) {
2287 if (fsg->lun != lun)
2288 DBG(fsg, "using LUN %d from CBW, "
2289 "not LUN %d from CDB\n",
2290 fsg->lun, lun);
2291 } else
2292 fsg->lun = lun; // Use LUN from the command
2294 /* Check the LUN */
2295 if (fsg->lun < fsg->nluns) {
2296 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2297 if (fsg->cmnd[0] != REQUEST_SENSE) {
2298 curlun->sense_data = SS_NO_SENSE;
2299 curlun->sense_data_info = 0;
2300 curlun->info_valid = 0;
2302 } else {
2303 fsg->curlun = curlun = NULL;
2304 fsg->bad_lun_okay = 0;
2306 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2307 * to use unsupported LUNs; all others may not. */
2308 if (fsg->cmnd[0] != INQUIRY &&
2309 fsg->cmnd[0] != REQUEST_SENSE) {
2310 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2311 return -EINVAL;
2315 /* If a unit attention condition exists, only INQUIRY and
2316 * REQUEST SENSE commands are allowed; anything else must fail. */
2317 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2318 fsg->cmnd[0] != INQUIRY &&
2319 fsg->cmnd[0] != REQUEST_SENSE) {
2320 curlun->sense_data = curlun->unit_attention_data;
2321 curlun->unit_attention_data = SS_NO_SENSE;
2322 return -EINVAL;
2325 /* Check that only command bytes listed in the mask are non-zero */
2326 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2327 for (i = 1; i < cmnd_size; ++i) {
2328 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2329 if (curlun)
2330 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2331 return -EINVAL;
2335 /* If the medium isn't mounted and the command needs to access
2336 * it, return an error. */
2337 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
2338 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2339 return -EINVAL;
2342 return 0;
2346 static int do_scsi_command(struct fsg_dev *fsg)
2348 struct fsg_buffhd *bh;
2349 int rc;
2350 int reply = -EINVAL;
2351 int i;
2352 static char unknown[16];
2354 dump_cdb(fsg);
2356 /* Wait for the next buffer to become available for data or status */
2357 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2358 while (bh->state != BUF_STATE_EMPTY) {
2359 rc = sleep_thread(fsg);
2360 if (rc)
2361 return rc;
2363 fsg->phase_error = 0;
2364 fsg->short_packet_received = 0;
2366 down_read(&fsg->filesem); // We're using the backing file
2367 switch (fsg->cmnd[0]) {
2369 case INQUIRY:
2370 fsg->data_size_from_cmnd = fsg->cmnd[4];
2371 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2372 (1<<4), 0,
2373 "INQUIRY")) == 0)
2374 reply = do_inquiry(fsg, bh);
2375 break;
2377 case MODE_SELECT:
2378 fsg->data_size_from_cmnd = fsg->cmnd[4];
2379 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2380 (1<<1) | (1<<4), 0,
2381 "MODE SELECT(6)")) == 0)
2382 reply = do_mode_select(fsg, bh);
2383 break;
2385 case MODE_SELECT_10:
2386 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2387 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2388 (1<<1) | (3<<7), 0,
2389 "MODE SELECT(10)")) == 0)
2390 reply = do_mode_select(fsg, bh);
2391 break;
2393 case MODE_SENSE:
2394 fsg->data_size_from_cmnd = fsg->cmnd[4];
2395 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2396 (1<<1) | (1<<2) | (1<<4), 0,
2397 "MODE SENSE(6)")) == 0)
2398 reply = do_mode_sense(fsg, bh);
2399 break;
2401 case MODE_SENSE_10:
2402 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2403 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2404 (1<<1) | (1<<2) | (3<<7), 0,
2405 "MODE SENSE(10)")) == 0)
2406 reply = do_mode_sense(fsg, bh);
2407 break;
2409 case ALLOW_MEDIUM_REMOVAL:
2410 fsg->data_size_from_cmnd = 0;
2411 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2412 (1<<4), 0,
2413 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2414 reply = do_prevent_allow(fsg);
2415 break;
2417 case READ_6:
2418 i = fsg->cmnd[4];
2419 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2420 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2421 (7<<1) | (1<<4), 1,
2422 "READ(6)")) == 0)
2423 reply = do_read(fsg);
2424 break;
2426 case READ_10:
2427 fsg->data_size_from_cmnd =
2428 get_unaligned_be16(&fsg->cmnd[7]) << 9;
2429 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2430 (1<<1) | (0xf<<2) | (3<<7), 1,
2431 "READ(10)")) == 0)
2432 reply = do_read(fsg);
2433 break;
2435 case READ_12:
2436 fsg->data_size_from_cmnd =
2437 get_unaligned_be32(&fsg->cmnd[6]) << 9;
2438 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2439 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2440 "READ(12)")) == 0)
2441 reply = do_read(fsg);
2442 break;
2444 case READ_CAPACITY:
2445 fsg->data_size_from_cmnd = 8;
2446 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2447 (0xf<<2) | (1<<8), 1,
2448 "READ CAPACITY")) == 0)
2449 reply = do_read_capacity(fsg, bh);
2450 break;
2452 case READ_HEADER:
2453 if (!mod_data.cdrom)
2454 goto unknown_cmnd;
2455 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2456 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2457 (3<<7) | (0x1f<<1), 1,
2458 "READ HEADER")) == 0)
2459 reply = do_read_header(fsg, bh);
2460 break;
2462 case READ_TOC:
2463 if (!mod_data.cdrom)
2464 goto unknown_cmnd;
2465 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2466 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2467 (7<<6) | (1<<1), 1,
2468 "READ TOC")) == 0)
2469 reply = do_read_toc(fsg, bh);
2470 break;
2472 case READ_FORMAT_CAPACITIES:
2473 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2474 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2475 (3<<7), 1,
2476 "READ FORMAT CAPACITIES")) == 0)
2477 reply = do_read_format_capacities(fsg, bh);
2478 break;
2480 case REQUEST_SENSE:
2481 fsg->data_size_from_cmnd = fsg->cmnd[4];
2482 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2483 (1<<4), 0,
2484 "REQUEST SENSE")) == 0)
2485 reply = do_request_sense(fsg, bh);
2486 break;
2488 case START_STOP:
2489 fsg->data_size_from_cmnd = 0;
2490 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2491 (1<<1) | (1<<4), 0,
2492 "START-STOP UNIT")) == 0)
2493 reply = do_start_stop(fsg);
2494 break;
2496 case SYNCHRONIZE_CACHE:
2497 fsg->data_size_from_cmnd = 0;
2498 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2499 (0xf<<2) | (3<<7), 1,
2500 "SYNCHRONIZE CACHE")) == 0)
2501 reply = do_synchronize_cache(fsg);
2502 break;
2504 case TEST_UNIT_READY:
2505 fsg->data_size_from_cmnd = 0;
2506 reply = check_command(fsg, 6, DATA_DIR_NONE,
2507 0, 1,
2508 "TEST UNIT READY");
2509 break;
2511 /* Although optional, this command is used by MS-Windows. We
2512 * support a minimal version: BytChk must be 0. */
2513 case VERIFY:
2514 fsg->data_size_from_cmnd = 0;
2515 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2516 (1<<1) | (0xf<<2) | (3<<7), 1,
2517 "VERIFY")) == 0)
2518 reply = do_verify(fsg);
2519 break;
2521 case WRITE_6:
2522 i = fsg->cmnd[4];
2523 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2524 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2525 (7<<1) | (1<<4), 1,
2526 "WRITE(6)")) == 0)
2527 reply = do_write(fsg);
2528 break;
2530 case WRITE_10:
2531 fsg->data_size_from_cmnd =
2532 get_unaligned_be16(&fsg->cmnd[7]) << 9;
2533 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2534 (1<<1) | (0xf<<2) | (3<<7), 1,
2535 "WRITE(10)")) == 0)
2536 reply = do_write(fsg);
2537 break;
2539 case WRITE_12:
2540 fsg->data_size_from_cmnd =
2541 get_unaligned_be32(&fsg->cmnd[6]) << 9;
2542 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2543 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2544 "WRITE(12)")) == 0)
2545 reply = do_write(fsg);
2546 break;
2548 /* Some mandatory commands that we recognize but don't implement.
2549 * They don't mean much in this setting. It's left as an exercise
2550 * for anyone interested to implement RESERVE and RELEASE in terms
2551 * of Posix locks. */
2552 case FORMAT_UNIT:
2553 case RELEASE:
2554 case RESERVE:
2555 case SEND_DIAGNOSTIC:
2556 // Fall through
2558 default:
2559 unknown_cmnd:
2560 fsg->data_size_from_cmnd = 0;
2561 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2562 if ((reply = check_command(fsg, fsg->cmnd_size,
2563 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2564 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2565 reply = -EINVAL;
2567 break;
2569 up_read(&fsg->filesem);
2571 if (reply == -EINTR || signal_pending(current))
2572 return -EINTR;
2574 /* Set up the single reply buffer for finish_reply() */
2575 if (reply == -EINVAL)
2576 reply = 0; // Error reply length
2577 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2578 reply = min((u32) reply, fsg->data_size_from_cmnd);
2579 bh->inreq->length = reply;
2580 bh->state = BUF_STATE_FULL;
2581 fsg->residue -= reply;
2582 } // Otherwise it's already set
2584 return 0;
2588 /*-------------------------------------------------------------------------*/
2590 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2592 struct usb_request *req = bh->outreq;
2593 struct fsg_bulk_cb_wrap *cbw = req->buf;
2595 /* Was this a real packet? Should it be ignored? */
2596 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2597 return -EINVAL;
2599 /* Is the CBW valid? */
2600 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2601 cbw->Signature != cpu_to_le32(
2602 USB_BULK_CB_SIG)) {
2603 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2604 req->actual,
2605 le32_to_cpu(cbw->Signature));
2607 /* The Bulk-only spec says we MUST stall the IN endpoint
2608 * (6.6.1), so it's unavoidable. It also says we must
2609 * retain this state until the next reset, but there's
2610 * no way to tell the controller driver it should ignore
2611 * Clear-Feature(HALT) requests.
2613 * We aren't required to halt the OUT endpoint; instead
2614 * we can simply accept and discard any data received
2615 * until the next reset. */
2616 wedge_bulk_in_endpoint(fsg);
2617 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2618 return -EINVAL;
2621 /* Is the CBW meaningful? */
2622 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2623 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2624 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2625 "cmdlen %u\n",
2626 cbw->Lun, cbw->Flags, cbw->Length);
2628 /* We can do anything we want here, so let's stall the
2629 * bulk pipes if we are allowed to. */
2630 if (mod_data.can_stall) {
2631 fsg_set_halt(fsg, fsg->bulk_out);
2632 halt_bulk_in_endpoint(fsg);
2634 return -EINVAL;
2637 /* Save the command for later */
2638 fsg->cmnd_size = cbw->Length;
2639 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2640 if (cbw->Flags & USB_BULK_IN_FLAG)
2641 fsg->data_dir = DATA_DIR_TO_HOST;
2642 else
2643 fsg->data_dir = DATA_DIR_FROM_HOST;
2644 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2645 if (fsg->data_size == 0)
2646 fsg->data_dir = DATA_DIR_NONE;
2647 fsg->lun = cbw->Lun;
2648 fsg->tag = cbw->Tag;
2649 return 0;
2653 static int get_next_command(struct fsg_dev *fsg)
2655 struct fsg_buffhd *bh;
2656 int rc = 0;
2658 if (transport_is_bbb()) {
2660 /* Wait for the next buffer to become available */
2661 bh = fsg->next_buffhd_to_fill;
2662 while (bh->state != BUF_STATE_EMPTY) {
2663 rc = sleep_thread(fsg);
2664 if (rc)
2665 return rc;
2668 /* Queue a request to read a Bulk-only CBW */
2669 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2670 bh->outreq->short_not_ok = 1;
2671 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2672 &bh->outreq_busy, &bh->state);
2674 /* We will drain the buffer in software, which means we
2675 * can reuse it for the next filling. No need to advance
2676 * next_buffhd_to_fill. */
2678 /* Wait for the CBW to arrive */
2679 while (bh->state != BUF_STATE_FULL) {
2680 rc = sleep_thread(fsg);
2681 if (rc)
2682 return rc;
2684 smp_rmb();
2685 rc = received_cbw(fsg, bh);
2686 bh->state = BUF_STATE_EMPTY;
2688 } else { // USB_PR_CB or USB_PR_CBI
2690 /* Wait for the next command to arrive */
2691 while (fsg->cbbuf_cmnd_size == 0) {
2692 rc = sleep_thread(fsg);
2693 if (rc)
2694 return rc;
2697 /* Is the previous status interrupt request still busy?
2698 * The host is allowed to skip reading the status,
2699 * so we must cancel it. */
2700 if (fsg->intreq_busy)
2701 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2703 /* Copy the command and mark the buffer empty */
2704 fsg->data_dir = DATA_DIR_UNKNOWN;
2705 spin_lock_irq(&fsg->lock);
2706 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2707 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2708 fsg->cbbuf_cmnd_size = 0;
2709 spin_unlock_irq(&fsg->lock);
2711 return rc;
2715 /*-------------------------------------------------------------------------*/
2717 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2718 const struct usb_endpoint_descriptor *d)
2720 int rc;
2722 ep->driver_data = fsg;
2723 ep->desc = d;
2724 rc = usb_ep_enable(ep);
2725 if (rc)
2726 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2727 return rc;
2730 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2731 struct usb_request **preq)
2733 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2734 if (*preq)
2735 return 0;
2736 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2737 return -ENOMEM;
2741 * Reset interface setting and re-init endpoint state (toggle etc).
2742 * Call with altsetting < 0 to disable the interface. The only other
2743 * available altsetting is 0, which enables the interface.
2745 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2747 int rc = 0;
2748 int i;
2749 const struct usb_endpoint_descriptor *d;
2751 if (fsg->running)
2752 DBG(fsg, "reset interface\n");
2754 reset:
2755 /* Deallocate the requests */
2756 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2757 struct fsg_buffhd *bh = &fsg->buffhds[i];
2759 if (bh->inreq) {
2760 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2761 bh->inreq = NULL;
2763 if (bh->outreq) {
2764 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2765 bh->outreq = NULL;
2768 if (fsg->intreq) {
2769 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2770 fsg->intreq = NULL;
2773 /* Disable the endpoints */
2774 if (fsg->bulk_in_enabled) {
2775 usb_ep_disable(fsg->bulk_in);
2776 fsg->bulk_in_enabled = 0;
2778 if (fsg->bulk_out_enabled) {
2779 usb_ep_disable(fsg->bulk_out);
2780 fsg->bulk_out_enabled = 0;
2782 if (fsg->intr_in_enabled) {
2783 usb_ep_disable(fsg->intr_in);
2784 fsg->intr_in_enabled = 0;
2787 fsg->running = 0;
2788 if (altsetting < 0 || rc != 0)
2789 return rc;
2791 DBG(fsg, "set interface %d\n", altsetting);
2793 /* Enable the endpoints */
2794 d = fsg_ep_desc(fsg->gadget,
2795 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2796 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2797 goto reset;
2798 fsg->bulk_in_enabled = 1;
2800 d = fsg_ep_desc(fsg->gadget,
2801 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2802 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2803 goto reset;
2804 fsg->bulk_out_enabled = 1;
2805 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2806 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2808 if (transport_is_cbi()) {
2809 d = fsg_ep_desc(fsg->gadget,
2810 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
2811 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2812 goto reset;
2813 fsg->intr_in_enabled = 1;
2816 /* Allocate the requests */
2817 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2818 struct fsg_buffhd *bh = &fsg->buffhds[i];
2820 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2821 goto reset;
2822 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2823 goto reset;
2824 bh->inreq->buf = bh->outreq->buf = bh->buf;
2825 bh->inreq->context = bh->outreq->context = bh;
2826 bh->inreq->complete = bulk_in_complete;
2827 bh->outreq->complete = bulk_out_complete;
2829 if (transport_is_cbi()) {
2830 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2831 goto reset;
2832 fsg->intreq->complete = intr_in_complete;
2835 fsg->running = 1;
2836 for (i = 0; i < fsg->nluns; ++i)
2837 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2838 return rc;
2843 * Change our operational configuration. This code must agree with the code
2844 * that returns config descriptors, and with interface altsetting code.
2846 * It's also responsible for power management interactions. Some
2847 * configurations might not work with our current power sources.
2848 * For now we just assume the gadget is always self-powered.
2850 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2852 int rc = 0;
2854 /* Disable the single interface */
2855 if (fsg->config != 0) {
2856 DBG(fsg, "reset config\n");
2857 fsg->config = 0;
2858 rc = do_set_interface(fsg, -1);
2861 /* Enable the interface */
2862 if (new_config != 0) {
2863 fsg->config = new_config;
2864 if ((rc = do_set_interface(fsg, 0)) != 0)
2865 fsg->config = 0; // Reset on errors
2866 else {
2867 char *speed;
2869 switch (fsg->gadget->speed) {
2870 case USB_SPEED_LOW: speed = "low"; break;
2871 case USB_SPEED_FULL: speed = "full"; break;
2872 case USB_SPEED_HIGH: speed = "high"; break;
2873 default: speed = "?"; break;
2875 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2878 return rc;
2882 /*-------------------------------------------------------------------------*/
2884 static void handle_exception(struct fsg_dev *fsg)
2886 siginfo_t info;
2887 int sig;
2888 int i;
2889 int num_active;
2890 struct fsg_buffhd *bh;
2891 enum fsg_state old_state;
2892 u8 new_config;
2893 struct fsg_lun *curlun;
2894 unsigned int exception_req_tag;
2895 int rc;
2897 /* Clear the existing signals. Anything but SIGUSR1 is converted
2898 * into a high-priority EXIT exception. */
2899 for (;;) {
2900 sig = dequeue_signal_lock(current, &current->blocked, &info);
2901 if (!sig)
2902 break;
2903 if (sig != SIGUSR1) {
2904 if (fsg->state < FSG_STATE_EXIT)
2905 DBG(fsg, "Main thread exiting on signal\n");
2906 raise_exception(fsg, FSG_STATE_EXIT);
2910 /* Cancel all the pending transfers */
2911 if (fsg->intreq_busy)
2912 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2913 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2914 bh = &fsg->buffhds[i];
2915 if (bh->inreq_busy)
2916 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2917 if (bh->outreq_busy)
2918 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2921 /* Wait until everything is idle */
2922 for (;;) {
2923 num_active = fsg->intreq_busy;
2924 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2925 bh = &fsg->buffhds[i];
2926 num_active += bh->inreq_busy + bh->outreq_busy;
2928 if (num_active == 0)
2929 break;
2930 if (sleep_thread(fsg))
2931 return;
2934 /* Clear out the controller's fifos */
2935 if (fsg->bulk_in_enabled)
2936 usb_ep_fifo_flush(fsg->bulk_in);
2937 if (fsg->bulk_out_enabled)
2938 usb_ep_fifo_flush(fsg->bulk_out);
2939 if (fsg->intr_in_enabled)
2940 usb_ep_fifo_flush(fsg->intr_in);
2942 /* Reset the I/O buffer states and pointers, the SCSI
2943 * state, and the exception. Then invoke the handler. */
2944 spin_lock_irq(&fsg->lock);
2946 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2947 bh = &fsg->buffhds[i];
2948 bh->state = BUF_STATE_EMPTY;
2950 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2951 &fsg->buffhds[0];
2953 exception_req_tag = fsg->exception_req_tag;
2954 new_config = fsg->new_config;
2955 old_state = fsg->state;
2957 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2958 fsg->state = FSG_STATE_STATUS_PHASE;
2959 else {
2960 for (i = 0; i < fsg->nluns; ++i) {
2961 curlun = &fsg->luns[i];
2962 curlun->prevent_medium_removal = 0;
2963 curlun->sense_data = curlun->unit_attention_data =
2964 SS_NO_SENSE;
2965 curlun->sense_data_info = 0;
2966 curlun->info_valid = 0;
2968 fsg->state = FSG_STATE_IDLE;
2970 spin_unlock_irq(&fsg->lock);
2972 /* Carry out any extra actions required for the exception */
2973 switch (old_state) {
2974 default:
2975 break;
2977 case FSG_STATE_ABORT_BULK_OUT:
2978 send_status(fsg);
2979 spin_lock_irq(&fsg->lock);
2980 if (fsg->state == FSG_STATE_STATUS_PHASE)
2981 fsg->state = FSG_STATE_IDLE;
2982 spin_unlock_irq(&fsg->lock);
2983 break;
2985 case FSG_STATE_RESET:
2986 /* In case we were forced against our will to halt a
2987 * bulk endpoint, clear the halt now. (The SuperH UDC
2988 * requires this.) */
2989 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2990 usb_ep_clear_halt(fsg->bulk_in);
2992 if (transport_is_bbb()) {
2993 if (fsg->ep0_req_tag == exception_req_tag)
2994 ep0_queue(fsg); // Complete the status stage
2996 } else if (transport_is_cbi())
2997 send_status(fsg); // Status by interrupt pipe
2999 /* Technically this should go here, but it would only be
3000 * a waste of time. Ditto for the INTERFACE_CHANGE and
3001 * CONFIG_CHANGE cases. */
3002 // for (i = 0; i < fsg->nluns; ++i)
3003 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3004 break;
3006 case FSG_STATE_INTERFACE_CHANGE:
3007 rc = do_set_interface(fsg, 0);
3008 if (fsg->ep0_req_tag != exception_req_tag)
3009 break;
3010 if (rc != 0) // STALL on errors
3011 fsg_set_halt(fsg, fsg->ep0);
3012 else // Complete the status stage
3013 ep0_queue(fsg);
3014 break;
3016 case FSG_STATE_CONFIG_CHANGE:
3017 rc = do_set_config(fsg, new_config);
3018 if (fsg->ep0_req_tag != exception_req_tag)
3019 break;
3020 if (rc != 0) // STALL on errors
3021 fsg_set_halt(fsg, fsg->ep0);
3022 else // Complete the status stage
3023 ep0_queue(fsg);
3024 break;
3026 case FSG_STATE_DISCONNECT:
3027 for (i = 0; i < fsg->nluns; ++i)
3028 fsg_lun_fsync_sub(fsg->luns + i);
3029 do_set_config(fsg, 0); // Unconfigured state
3030 break;
3032 case FSG_STATE_EXIT:
3033 case FSG_STATE_TERMINATED:
3034 do_set_config(fsg, 0); // Free resources
3035 spin_lock_irq(&fsg->lock);
3036 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3037 spin_unlock_irq(&fsg->lock);
3038 break;
3043 /*-------------------------------------------------------------------------*/
3045 static int fsg_main_thread(void *fsg_)
3047 struct fsg_dev *fsg = fsg_;
3049 /* Allow the thread to be killed by a signal, but set the signal mask
3050 * to block everything but INT, TERM, KILL, and USR1. */
3051 allow_signal(SIGINT);
3052 allow_signal(SIGTERM);
3053 allow_signal(SIGKILL);
3054 allow_signal(SIGUSR1);
3056 /* Allow the thread to be frozen */
3057 set_freezable();
3059 /* Arrange for userspace references to be interpreted as kernel
3060 * pointers. That way we can pass a kernel pointer to a routine
3061 * that expects a __user pointer and it will work okay. */
3062 set_fs(get_ds());
3064 /* The main loop */
3065 while (fsg->state != FSG_STATE_TERMINATED) {
3066 if (exception_in_progress(fsg) || signal_pending(current)) {
3067 handle_exception(fsg);
3068 continue;
3071 if (!fsg->running) {
3072 sleep_thread(fsg);
3073 continue;
3076 if (get_next_command(fsg))
3077 continue;
3079 spin_lock_irq(&fsg->lock);
3080 if (!exception_in_progress(fsg))
3081 fsg->state = FSG_STATE_DATA_PHASE;
3082 spin_unlock_irq(&fsg->lock);
3084 if (do_scsi_command(fsg) || finish_reply(fsg))
3085 continue;
3087 spin_lock_irq(&fsg->lock);
3088 if (!exception_in_progress(fsg))
3089 fsg->state = FSG_STATE_STATUS_PHASE;
3090 spin_unlock_irq(&fsg->lock);
3092 if (send_status(fsg))
3093 continue;
3095 spin_lock_irq(&fsg->lock);
3096 if (!exception_in_progress(fsg))
3097 fsg->state = FSG_STATE_IDLE;
3098 spin_unlock_irq(&fsg->lock);
3101 spin_lock_irq(&fsg->lock);
3102 fsg->thread_task = NULL;
3103 spin_unlock_irq(&fsg->lock);
3105 /* If we are exiting because of a signal, unregister the
3106 * gadget driver. */
3107 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3108 usb_gadget_unregister_driver(&fsg_driver);
3110 /* Let the unbind and cleanup routines know the thread has exited */
3111 complete_and_exit(&fsg->thread_notifier, 0);
3115 /*-------------------------------------------------------------------------*/
3118 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3119 static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
3120 static DEVICE_ATTR(nofua, 0644, fsg_show_nofua, NULL);
3121 static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
3124 /*-------------------------------------------------------------------------*/
3126 static void fsg_release(struct kref *ref)
3128 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3130 kfree(fsg->luns);
3131 kfree(fsg);
3134 static void lun_release(struct device *dev)
3136 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3137 struct fsg_dev *fsg =
3138 container_of(filesem, struct fsg_dev, filesem);
3140 kref_put(&fsg->ref, fsg_release);
3143 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
3145 struct fsg_dev *fsg = get_gadget_data(gadget);
3146 int i;
3147 struct fsg_lun *curlun;
3148 struct usb_request *req = fsg->ep0req;
3150 DBG(fsg, "unbind\n");
3151 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3153 /* Unregister the sysfs attribute files and the LUNs */
3154 for (i = 0; i < fsg->nluns; ++i) {
3155 curlun = &fsg->luns[i];
3156 if (curlun->registered) {
3157 device_remove_file(&curlun->dev, &dev_attr_nofua);
3158 device_remove_file(&curlun->dev, &dev_attr_ro);
3159 device_remove_file(&curlun->dev, &dev_attr_file);
3160 fsg_lun_close(curlun);
3161 device_unregister(&curlun->dev);
3162 curlun->registered = 0;
3166 /* If the thread isn't already dead, tell it to exit now */
3167 if (fsg->state != FSG_STATE_TERMINATED) {
3168 raise_exception(fsg, FSG_STATE_EXIT);
3169 wait_for_completion(&fsg->thread_notifier);
3171 /* The cleanup routine waits for this completion also */
3172 complete(&fsg->thread_notifier);
3175 /* Free the data buffers */
3176 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
3177 kfree(fsg->buffhds[i].buf);
3179 /* Free the request and buffer for endpoint 0 */
3180 if (req) {
3181 kfree(req->buf);
3182 usb_ep_free_request(fsg->ep0, req);
3185 set_gadget_data(gadget, NULL);
3189 static int __init check_parameters(struct fsg_dev *fsg)
3191 int prot;
3192 int gcnum;
3194 /* Store the default values */
3195 mod_data.transport_type = USB_PR_BULK;
3196 mod_data.transport_name = "Bulk-only";
3197 mod_data.protocol_type = USB_SC_SCSI;
3198 mod_data.protocol_name = "Transparent SCSI";
3200 /* Some peripheral controllers are known not to be able to
3201 * halt bulk endpoints correctly. If one of them is present,
3202 * disable stalls.
3204 if (gadget_is_at91(fsg->gadget))
3205 mod_data.can_stall = 0;
3207 if (mod_data.release == 0xffff) { // Parameter wasn't set
3208 gcnum = usb_gadget_controller_number(fsg->gadget);
3209 if (gcnum >= 0)
3210 mod_data.release = 0x0300 + gcnum;
3211 else {
3212 WARNING(fsg, "controller '%s' not recognized\n",
3213 fsg->gadget->name);
3214 mod_data.release = 0x0399;
3218 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3220 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3221 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3222 ; // Use default setting
3223 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3224 mod_data.transport_type = USB_PR_CB;
3225 mod_data.transport_name = "Control-Bulk";
3226 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3227 mod_data.transport_type = USB_PR_CBI;
3228 mod_data.transport_name = "Control-Bulk-Interrupt";
3229 } else {
3230 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3231 return -EINVAL;
3234 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3235 prot == USB_SC_SCSI) {
3236 ; // Use default setting
3237 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3238 prot == USB_SC_RBC) {
3239 mod_data.protocol_type = USB_SC_RBC;
3240 mod_data.protocol_name = "RBC";
3241 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3242 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3243 prot == USB_SC_8020) {
3244 mod_data.protocol_type = USB_SC_8020;
3245 mod_data.protocol_name = "8020i (ATAPI)";
3246 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3247 prot == USB_SC_QIC) {
3248 mod_data.protocol_type = USB_SC_QIC;
3249 mod_data.protocol_name = "QIC-157";
3250 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3251 prot == USB_SC_UFI) {
3252 mod_data.protocol_type = USB_SC_UFI;
3253 mod_data.protocol_name = "UFI";
3254 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3255 prot == USB_SC_8070) {
3256 mod_data.protocol_type = USB_SC_8070;
3257 mod_data.protocol_name = "8070i";
3258 } else {
3259 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3260 return -EINVAL;
3263 mod_data.buflen &= PAGE_CACHE_MASK;
3264 if (mod_data.buflen <= 0) {
3265 ERROR(fsg, "invalid buflen\n");
3266 return -ETOOSMALL;
3269 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3271 /* Serial string handling.
3272 * On a real device, the serial string would be loaded
3273 * from permanent storage. */
3274 if (mod_data.serial) {
3275 const char *ch;
3276 unsigned len = 0;
3278 /* Sanity check :
3279 * The CB[I] specification limits the serial string to
3280 * 12 uppercase hexadecimal characters.
3281 * BBB need at least 12 uppercase hexadecimal characters,
3282 * with a maximum of 126. */
3283 for (ch = mod_data.serial; *ch; ++ch) {
3284 ++len;
3285 if ((*ch < '0' || *ch > '9') &&
3286 (*ch < 'A' || *ch > 'F')) { /* not uppercase hex */
3287 WARNING(fsg,
3288 "Invalid serial string character: %c\n",
3289 *ch);
3290 goto no_serial;
3293 if (len > 126 ||
3294 (mod_data.transport_type == USB_PR_BULK && len < 12) ||
3295 (mod_data.transport_type != USB_PR_BULK && len > 12)) {
3296 WARNING(fsg, "Invalid serial string length!\n");
3297 goto no_serial;
3299 fsg_strings[FSG_STRING_SERIAL - 1].s = mod_data.serial;
3300 } else {
3301 WARNING(fsg, "No serial-number string provided!\n");
3302 no_serial:
3303 device_desc.iSerialNumber = 0;
3306 return 0;
3310 static int __init fsg_bind(struct usb_gadget *gadget)
3312 struct fsg_dev *fsg = the_fsg;
3313 int rc;
3314 int i;
3315 struct fsg_lun *curlun;
3316 struct usb_ep *ep;
3317 struct usb_request *req;
3318 char *pathbuf, *p;
3320 fsg->gadget = gadget;
3321 set_gadget_data(gadget, fsg);
3322 fsg->ep0 = gadget->ep0;
3323 fsg->ep0->driver_data = fsg;
3325 if ((rc = check_parameters(fsg)) != 0)
3326 goto out;
3328 if (mod_data.removable) { // Enable the store_xxx attributes
3329 dev_attr_file.attr.mode = 0644;
3330 dev_attr_file.store = fsg_store_file;
3331 if (!mod_data.cdrom) {
3332 dev_attr_ro.attr.mode = 0644;
3333 dev_attr_ro.store = fsg_store_ro;
3337 /* Only for removable media? */
3338 dev_attr_nofua.attr.mode = 0644;
3339 dev_attr_nofua.store = fsg_store_nofua;
3341 /* Find out how many LUNs there should be */
3342 i = mod_data.nluns;
3343 if (i == 0)
3344 i = max(mod_data.num_filenames, 1u);
3345 if (i > FSG_MAX_LUNS) {
3346 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3347 rc = -EINVAL;
3348 goto out;
3351 /* Create the LUNs, open their backing files, and register the
3352 * LUN devices in sysfs. */
3353 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
3354 if (!fsg->luns) {
3355 rc = -ENOMEM;
3356 goto out;
3358 fsg->nluns = i;
3360 for (i = 0; i < fsg->nluns; ++i) {
3361 curlun = &fsg->luns[i];
3362 curlun->cdrom = !!mod_data.cdrom;
3363 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3364 curlun->initially_ro = curlun->ro;
3365 curlun->removable = mod_data.removable;
3366 curlun->nofua = mod_data.nofua[i];
3367 curlun->dev.release = lun_release;
3368 curlun->dev.parent = &gadget->dev;
3369 curlun->dev.driver = &fsg_driver.driver;
3370 dev_set_drvdata(&curlun->dev, &fsg->filesem);
3371 dev_set_name(&curlun->dev,"%s-lun%d",
3372 dev_name(&gadget->dev), i);
3374 kref_get(&fsg->ref);
3375 rc = device_register(&curlun->dev);
3376 if (rc) {
3377 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
3378 put_device(&curlun->dev);
3379 goto out;
3381 curlun->registered = 1;
3383 rc = device_create_file(&curlun->dev, &dev_attr_ro);
3384 if (rc)
3385 goto out;
3386 rc = device_create_file(&curlun->dev, &dev_attr_nofua);
3387 if (rc)
3388 goto out;
3389 rc = device_create_file(&curlun->dev, &dev_attr_file);
3390 if (rc)
3391 goto out;
3393 if (mod_data.file[i] && *mod_data.file[i]) {
3394 rc = fsg_lun_open(curlun, mod_data.file[i]);
3395 if (rc)
3396 goto out;
3397 } else if (!mod_data.removable) {
3398 ERROR(fsg, "no file given for LUN%d\n", i);
3399 rc = -EINVAL;
3400 goto out;
3404 /* Find all the endpoints we will use */
3405 usb_ep_autoconfig_reset(gadget);
3406 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3407 if (!ep)
3408 goto autoconf_fail;
3409 ep->driver_data = fsg; // claim the endpoint
3410 fsg->bulk_in = ep;
3412 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3413 if (!ep)
3414 goto autoconf_fail;
3415 ep->driver_data = fsg; // claim the endpoint
3416 fsg->bulk_out = ep;
3418 if (transport_is_cbi()) {
3419 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
3420 if (!ep)
3421 goto autoconf_fail;
3422 ep->driver_data = fsg; // claim the endpoint
3423 fsg->intr_in = ep;
3426 /* Fix up the descriptors */
3427 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3428 device_desc.idProduct = cpu_to_le16(mod_data.product);
3429 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3431 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
3432 fsg_intf_desc.bNumEndpoints = i;
3433 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3434 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3435 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3437 if (gadget_is_dualspeed(gadget)) {
3438 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3440 /* Assume endpoint addresses are the same for both speeds */
3441 fsg_hs_bulk_in_desc.bEndpointAddress =
3442 fsg_fs_bulk_in_desc.bEndpointAddress;
3443 fsg_hs_bulk_out_desc.bEndpointAddress =
3444 fsg_fs_bulk_out_desc.bEndpointAddress;
3445 fsg_hs_intr_in_desc.bEndpointAddress =
3446 fsg_fs_intr_in_desc.bEndpointAddress;
3449 if (gadget_is_otg(gadget))
3450 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
3452 rc = -ENOMEM;
3454 /* Allocate the request and buffer for endpoint 0 */
3455 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3456 if (!req)
3457 goto out;
3458 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
3459 if (!req->buf)
3460 goto out;
3461 req->complete = ep0_complete;
3463 /* Allocate the data buffers */
3464 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
3465 struct fsg_buffhd *bh = &fsg->buffhds[i];
3467 /* Allocate for the bulk-in endpoint. We assume that
3468 * the buffer will also work with the bulk-out (and
3469 * interrupt-in) endpoint. */
3470 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
3471 if (!bh->buf)
3472 goto out;
3473 bh->next = bh + 1;
3475 fsg->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3477 /* This should reflect the actual gadget power source */
3478 usb_gadget_set_selfpowered(gadget);
3480 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3481 "%s %s with %s",
3482 init_utsname()->sysname, init_utsname()->release,
3483 gadget->name);
3485 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3486 "file-storage-gadget");
3487 if (IS_ERR(fsg->thread_task)) {
3488 rc = PTR_ERR(fsg->thread_task);
3489 goto out;
3492 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3493 INFO(fsg, "NOTE: This driver is deprecated. "
3494 "Consider using g_mass_storage instead.\n");
3495 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3497 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3498 for (i = 0; i < fsg->nluns; ++i) {
3499 curlun = &fsg->luns[i];
3500 if (fsg_lun_is_open(curlun)) {
3501 p = NULL;
3502 if (pathbuf) {
3503 p = d_path(&curlun->filp->f_path,
3504 pathbuf, PATH_MAX);
3505 if (IS_ERR(p))
3506 p = NULL;
3508 LINFO(curlun, "ro=%d, nofua=%d, file: %s\n",
3509 curlun->ro, curlun->nofua, (p ? p : "(error)"));
3512 kfree(pathbuf);
3514 DBG(fsg, "transport=%s (x%02x)\n",
3515 mod_data.transport_name, mod_data.transport_type);
3516 DBG(fsg, "protocol=%s (x%02x)\n",
3517 mod_data.protocol_name, mod_data.protocol_type);
3518 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3519 mod_data.vendor, mod_data.product, mod_data.release);
3520 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3521 mod_data.removable, mod_data.can_stall,
3522 mod_data.cdrom, mod_data.buflen);
3523 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
3525 set_bit(REGISTERED, &fsg->atomic_bitflags);
3527 /* Tell the thread to start working */
3528 wake_up_process(fsg->thread_task);
3529 return 0;
3531 autoconf_fail:
3532 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3533 rc = -ENOTSUPP;
3535 out:
3536 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3537 fsg_unbind(gadget);
3538 complete(&fsg->thread_notifier);
3539 return rc;
3543 /*-------------------------------------------------------------------------*/
3545 static void fsg_suspend(struct usb_gadget *gadget)
3547 struct fsg_dev *fsg = get_gadget_data(gadget);
3549 DBG(fsg, "suspend\n");
3550 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3553 static void fsg_resume(struct usb_gadget *gadget)
3555 struct fsg_dev *fsg = get_gadget_data(gadget);
3557 DBG(fsg, "resume\n");
3558 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3562 /*-------------------------------------------------------------------------*/
3564 static struct usb_gadget_driver fsg_driver = {
3565 #ifdef CONFIG_USB_GADGET_DUALSPEED
3566 .speed = USB_SPEED_HIGH,
3567 #else
3568 .speed = USB_SPEED_FULL,
3569 #endif
3570 .function = (char *) fsg_string_product,
3571 .unbind = fsg_unbind,
3572 .disconnect = fsg_disconnect,
3573 .setup = fsg_setup,
3574 .suspend = fsg_suspend,
3575 .resume = fsg_resume,
3577 .driver = {
3578 .name = DRIVER_NAME,
3579 .owner = THIS_MODULE,
3580 // .release = ...
3581 // .suspend = ...
3582 // .resume = ...
3587 static int __init fsg_alloc(void)
3589 struct fsg_dev *fsg;
3591 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3592 if (!fsg)
3593 return -ENOMEM;
3594 spin_lock_init(&fsg->lock);
3595 init_rwsem(&fsg->filesem);
3596 kref_init(&fsg->ref);
3597 init_completion(&fsg->thread_notifier);
3599 the_fsg = fsg;
3600 return 0;
3604 static int __init fsg_init(void)
3606 int rc;
3607 struct fsg_dev *fsg;
3609 if ((rc = fsg_alloc()) != 0)
3610 return rc;
3611 fsg = the_fsg;
3612 if ((rc = usb_gadget_probe_driver(&fsg_driver, fsg_bind)) != 0)
3613 kref_put(&fsg->ref, fsg_release);
3614 return rc;
3616 module_init(fsg_init);
3619 static void __exit fsg_cleanup(void)
3621 struct fsg_dev *fsg = the_fsg;
3623 /* Unregister the driver iff the thread hasn't already done so */
3624 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3625 usb_gadget_unregister_driver(&fsg_driver);
3627 /* Wait for the thread to finish up */
3628 wait_for_completion(&fsg->thread_notifier);
3630 kref_put(&fsg->ref, fsg_release);
3632 module_exit(fsg_cleanup);