2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
4 * Copyright (C) 2003-2008 Alan Stern
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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, and release 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.
88 * file=filename[,filename...]
89 * Required if "removable" is not set, names of
90 * the files or block devices used for
92 * ro=b[,b...] Default false, booleans for read-only access
93 * removable Default false, boolean for removable media
94 * luns=N Default N = number of filenames, number of
96 * stall Default determined according to the type of
97 * USB device controller (usually true),
98 * boolean to permit the driver to halt
100 * cdrom Default false, boolean for whether to emulate
102 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
103 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
104 * ATAPI, QIC, UFI, 8070, or SCSI;
106 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
107 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
108 * release=0xRRRR Override the USB release number (bcdDevice)
109 * buflen=N Default N=16384, buffer size used (will be
110 * rounded down to a multiple of
113 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
114 * "removable", "luns", "stall", and "cdrom" options are available; default
115 * values are used for everything else.
117 * The pathnames of the backing files and the ro settings are available in
118 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
119 * gadget's sysfs directory. If the "removable" option is set, writing to
120 * these files will simulate ejecting/loading the medium (writing an empty
121 * line means eject) and adjusting a write-enable tab. Changes to the ro
122 * setting are not allowed when the medium is loaded or if CD-ROM emulation
125 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
126 * The driver's SCSI command interface was based on the "Information
127 * technology - Small Computer System Interface - 2" document from
128 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
129 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
130 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
131 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
132 * document, Revision 1.0, December 14, 1998, available at
133 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
140 * The FSG driver is fairly straightforward. There is a main kernel
141 * thread that handles most of the work. Interrupt routines field
142 * callbacks from the controller driver: bulk- and interrupt-request
143 * completion notifications, endpoint-0 events, and disconnect events.
144 * Completion events are passed to the main thread by wakeup calls. Many
145 * ep0 requests are handled at interrupt time, but SetInterface,
146 * SetConfiguration, and device reset requests are forwarded to the
147 * thread in the form of "exceptions" using SIGUSR1 signals (since they
148 * should interrupt any ongoing file I/O operations).
150 * The thread's main routine implements the standard command/data/status
151 * parts of a SCSI interaction. It and its subroutines are full of tests
152 * for pending signals/exceptions -- all this polling is necessary since
153 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
154 * indication that the driver really wants to be running in userspace.)
155 * An important point is that so long as the thread is alive it keeps an
156 * open reference to the backing file. This will prevent unmounting
157 * the backing file's underlying filesystem and could cause problems
158 * during system shutdown, for example. To prevent such problems, the
159 * thread catches INT, TERM, and KILL signals and converts them into
162 * In normal operation the main thread is started during the gadget's
163 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
164 * exit when it receives a signal, and there's no point leaving the
165 * gadget running when the thread is dead. So just before the thread
166 * exits, it deregisters the gadget driver. This makes things a little
167 * tricky: The driver is deregistered at two places, and the exiting
168 * thread can indirectly call fsg_unbind() which in turn can tell the
169 * thread to exit. The first problem is resolved through the use of the
170 * REGISTERED atomic bitflag; the driver will only be deregistered once.
171 * The second problem is resolved by having fsg_unbind() check
172 * fsg->state; it won't try to stop the thread if the state is already
173 * FSG_STATE_TERMINATED.
175 * To provide maximum throughput, the driver uses a circular pipeline of
176 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
177 * arbitrarily long; in practice the benefits don't justify having more
178 * than 2 stages (i.e., double buffering). But it helps to think of the
179 * pipeline as being a long one. Each buffer head contains a bulk-in and
180 * a bulk-out request pointer (since the buffer can be used for both
181 * output and input -- directions always are given from the host's
182 * point of view) as well as a pointer to the buffer and various state
185 * Use of the pipeline follows a simple protocol. There is a variable
186 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
187 * At any time that buffer head may still be in use from an earlier
188 * request, so each buffer head has a state variable indicating whether
189 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
190 * buffer head to be EMPTY, filling the buffer either by file I/O or by
191 * USB I/O (during which the buffer head is BUSY), and marking the buffer
192 * head FULL when the I/O is complete. Then the buffer will be emptied
193 * (again possibly by USB I/O, during which it is marked BUSY) and
194 * finally marked EMPTY again (possibly by a completion routine).
196 * A module parameter tells the driver to avoid stalling the bulk
197 * endpoints wherever the transport specification allows. This is
198 * necessary for some UDCs like the SuperH, which cannot reliably clear a
199 * halt on a bulk endpoint. However, under certain circumstances the
200 * Bulk-only specification requires a stall. In such cases the driver
201 * will halt the endpoint and set a flag indicating that it should clear
202 * the halt in software during the next device reset. Hopefully this
203 * will permit everything to work correctly. Furthermore, although the
204 * specification allows the bulk-out endpoint to halt when the host sends
205 * too much data, implementing this would cause an unavoidable race.
206 * The driver will always use the "no-stall" approach for OUT transfers.
208 * One subtle point concerns sending status-stage responses for ep0
209 * requests. Some of these requests, such as device reset, can involve
210 * interrupting an ongoing file I/O operation, which might take an
211 * arbitrarily long time. During that delay the host might give up on
212 * the original ep0 request and issue a new one. When that happens the
213 * driver should not notify the host about completion of the original
214 * request, as the host will no longer be waiting for it. So the driver
215 * assigns to each ep0 request a unique tag, and it keeps track of the
216 * tag value of the request associated with a long-running exception
217 * (device-reset, interface-change, or configuration-change). When the
218 * exception handler is finished, the status-stage response is submitted
219 * only if the current ep0 request tag is equal to the exception request
220 * tag. Thus only the most recently received ep0 request will get a
221 * status-stage response.
223 * Warning: This driver source file is too long. It ought to be split up
224 * into a header file plus about 3 separate .c files, to handle the details
225 * of the Gadget, USB Mass Storage, and SCSI protocols.
229 /* #define VERBOSE_DEBUG */
230 /* #define DUMP_MSGS */
233 #include <linux/blkdev.h>
234 #include <linux/completion.h>
235 #include <linux/dcache.h>
236 #include <linux/delay.h>
237 #include <linux/device.h>
238 #include <linux/fcntl.h>
239 #include <linux/file.h>
240 #include <linux/fs.h>
241 #include <linux/kref.h>
242 #include <linux/kthread.h>
243 #include <linux/limits.h>
244 #include <linux/rwsem.h>
245 #include <linux/slab.h>
246 #include <linux/spinlock.h>
247 #include <linux/string.h>
248 #include <linux/freezer.h>
249 #include <linux/utsname.h>
251 #include <linux/usb/ch9.h>
252 #include <linux/usb/gadget.h>
254 #include "gadget_chips.h"
259 * Kbuild is not very cooperative with respect to linking separately
260 * compiled library objects into one module. So for now we won't use
261 * separate compilation ... ensuring init/exit sections work to shrink
262 * the runtime footprint, and giving us at least some parts of what
263 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
265 #include "usbstring.c"
267 #include "epautoconf.c"
269 /*-------------------------------------------------------------------------*/
271 #define DRIVER_DESC "File-backed Storage Gadget"
272 #define DRIVER_NAME "g_file_storage"
273 #define DRIVER_VERSION "20 November 2008"
275 static char fsg_string_manufacturer[64];
276 static const char fsg_string_product[] = DRIVER_DESC;
277 static char fsg_string_serial[13];
278 static const char fsg_string_config[] = "Self-powered";
279 static const char fsg_string_interface[] = "Mass Storage";
282 #include "storage_common.c"
285 MODULE_DESCRIPTION(DRIVER_DESC);
286 MODULE_AUTHOR("Alan Stern");
287 MODULE_LICENSE("Dual BSD/GPL");
290 * This driver assumes self-powered hardware and has no way for users to
291 * trigger remote wakeup. It uses autoconfiguration to select endpoints
292 * and endpoint addresses.
296 /*-------------------------------------------------------------------------*/
299 /* Encapsulate the module parameter settings */
302 char *file[FSG_MAX_LUNS];
303 int ro[FSG_MAX_LUNS];
304 unsigned int num_filenames;
305 unsigned int num_ros;
312 char *transport_parm;
314 unsigned short vendor;
315 unsigned short product;
316 unsigned short release;
320 char *transport_name;
324 } mod_data = { // Default values
325 .transport_parm = "BBB",
326 .protocol_parm = "SCSI",
330 .vendor = FSG_VENDOR_ID,
331 .product = FSG_PRODUCT_ID,
332 .release = 0xffff, // Use controller chip type
337 module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
339 MODULE_PARM_DESC(file, "names of backing files or devices");
341 module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
342 MODULE_PARM_DESC(ro, "true to force read-only");
344 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
345 MODULE_PARM_DESC(luns, "number of LUNs");
347 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
348 MODULE_PARM_DESC(removable, "true to simulate removable media");
350 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
351 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
353 module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
354 MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
357 /* In the non-TEST version, only the module parameters listed above
359 #ifdef CONFIG_USB_FILE_STORAGE_TEST
361 module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
362 MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
364 module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
365 MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
368 module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
369 MODULE_PARM_DESC(vendor, "USB Vendor ID");
371 module_param_named(product, mod_data.product, ushort, S_IRUGO);
372 MODULE_PARM_DESC(product, "USB Product ID");
374 module_param_named(release, mod_data.release, ushort, S_IRUGO);
375 MODULE_PARM_DESC(release, "USB release number");
377 module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
378 MODULE_PARM_DESC(buflen, "I/O buffer size");
380 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
384 * These definitions will permit the compiler to avoid generating code for
385 * parts of the driver that aren't used in the non-TEST version. Even gcc
386 * can recognize when a test of a constant expression yields a dead code
390 #ifdef CONFIG_USB_FILE_STORAGE_TEST
392 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
393 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
394 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
398 #define transport_is_bbb() 1
399 #define transport_is_cbi() 0
400 #define protocol_is_scsi() 1
402 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
405 /*-------------------------------------------------------------------------*/
409 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
411 struct usb_gadget *gadget;
413 /* filesem protects: backing files in use */
414 struct rw_semaphore filesem;
416 /* reference counting: wait until all LUNs are released */
419 struct usb_ep *ep0; // Handy copy of gadget->ep0
420 struct usb_request *ep0req; // For control responses
421 unsigned int ep0_req_tag;
422 const char *ep0req_name;
424 struct usb_request *intreq; // For interrupt responses
426 struct fsg_buffhd *intr_buffhd;
428 unsigned int bulk_out_maxpacket;
429 enum fsg_state state; // For exception handling
430 unsigned int exception_req_tag;
432 u8 config, new_config;
434 unsigned int running : 1;
435 unsigned int bulk_in_enabled : 1;
436 unsigned int bulk_out_enabled : 1;
437 unsigned int intr_in_enabled : 1;
438 unsigned int phase_error : 1;
439 unsigned int short_packet_received : 1;
440 unsigned int bad_lun_okay : 1;
442 unsigned long atomic_bitflags;
444 #define IGNORE_BULK_OUT 1
447 struct usb_ep *bulk_in;
448 struct usb_ep *bulk_out;
449 struct usb_ep *intr_in;
451 struct fsg_buffhd *next_buffhd_to_fill;
452 struct fsg_buffhd *next_buffhd_to_drain;
453 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
455 int thread_wakeup_needed;
456 struct completion thread_notifier;
457 struct task_struct *thread_task;
460 u8 cmnd[MAX_COMMAND_SIZE];
461 enum data_direction data_dir;
463 u32 data_size_from_cmnd;
469 /* The CB protocol offers no way for a host to know when a command
470 * has completed. As a result the next command may arrive early,
471 * and we will still have to handle it. For that reason we need
472 * a buffer to store new commands when using CB (or CBI, which
473 * does not oblige a host to wait for command completion either). */
475 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
478 struct fsg_lun *luns;
479 struct fsg_lun *curlun;
482 typedef void (*fsg_routine_t)(struct fsg_dev *);
484 static int exception_in_progress(struct fsg_dev *fsg)
486 return (fsg->state > FSG_STATE_IDLE);
489 /* Make bulk-out requests be divisible by the maxpacket size */
490 static void set_bulk_out_req_length(struct fsg_dev *fsg,
491 struct fsg_buffhd *bh, unsigned int length)
495 bh->bulk_out_intended_length = length;
496 rem = length % fsg->bulk_out_maxpacket;
498 length += fsg->bulk_out_maxpacket - rem;
499 bh->outreq->length = length;
502 static struct fsg_dev *the_fsg;
503 static struct usb_gadget_driver fsg_driver;
506 /*-------------------------------------------------------------------------*/
508 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
512 if (ep == fsg->bulk_in)
514 else if (ep == fsg->bulk_out)
518 DBG(fsg, "%s set halt\n", name);
519 return usb_ep_set_halt(ep);
523 /*-------------------------------------------------------------------------*/
526 * DESCRIPTORS ... most are static, but strings and (full) configuration
527 * descriptors are built on demand. Also the (static) config and interface
528 * descriptors are adjusted during fsg_bind().
531 /* There is only one configuration. */
532 #define CONFIG_VALUE 1
534 static struct usb_device_descriptor
536 .bLength = sizeof device_desc,
537 .bDescriptorType = USB_DT_DEVICE,
539 .bcdUSB = cpu_to_le16(0x0200),
540 .bDeviceClass = USB_CLASS_PER_INTERFACE,
542 /* The next three values can be overridden by module parameters */
543 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
544 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
545 .bcdDevice = cpu_to_le16(0xffff),
547 .iManufacturer = FSG_STRING_MANUFACTURER,
548 .iProduct = FSG_STRING_PRODUCT,
549 .iSerialNumber = FSG_STRING_SERIAL,
550 .bNumConfigurations = 1,
553 static struct usb_config_descriptor
555 .bLength = sizeof config_desc,
556 .bDescriptorType = USB_DT_CONFIG,
558 /* wTotalLength computed by usb_gadget_config_buf() */
560 .bConfigurationValue = CONFIG_VALUE,
561 .iConfiguration = FSG_STRING_CONFIG,
562 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
563 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
567 static struct usb_qualifier_descriptor
569 .bLength = sizeof dev_qualifier,
570 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
572 .bcdUSB = cpu_to_le16(0x0200),
573 .bDeviceClass = USB_CLASS_PER_INTERFACE,
575 .bNumConfigurations = 1,
581 * Config descriptors must agree with the code that sets configurations
582 * and with code managing interfaces and their altsettings. They must
583 * also handle different speeds and other-speed requests.
585 static int populate_config_buf(struct usb_gadget *gadget,
586 u8 *buf, u8 type, unsigned index)
588 enum usb_device_speed speed = gadget->speed;
590 const struct usb_descriptor_header **function;
595 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
596 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
597 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
598 function = fsg_hs_function;
600 function = fsg_fs_function;
602 /* for now, don't advertise srp-only devices */
603 if (!gadget_is_otg(gadget))
606 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
607 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
612 /*-------------------------------------------------------------------------*/
614 /* These routines may be called in process context or in_irq */
616 /* Caller must hold fsg->lock */
617 static void wakeup_thread(struct fsg_dev *fsg)
619 /* Tell the main thread that something has happened */
620 fsg->thread_wakeup_needed = 1;
621 if (fsg->thread_task)
622 wake_up_process(fsg->thread_task);
626 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
630 /* Do nothing if a higher-priority exception is already in progress.
631 * If a lower-or-equal priority exception is in progress, preempt it
632 * and notify the main thread by sending it a signal. */
633 spin_lock_irqsave(&fsg->lock, flags);
634 if (fsg->state <= new_state) {
635 fsg->exception_req_tag = fsg->ep0_req_tag;
636 fsg->state = new_state;
637 if (fsg->thread_task)
638 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
641 spin_unlock_irqrestore(&fsg->lock, flags);
645 /*-------------------------------------------------------------------------*/
647 /* The disconnect callback and ep0 routines. These always run in_irq,
648 * except that ep0_queue() is called in the main thread to acknowledge
649 * completion of various requests: set config, set interface, and
650 * Bulk-only device reset. */
652 static void fsg_disconnect(struct usb_gadget *gadget)
654 struct fsg_dev *fsg = get_gadget_data(gadget);
656 DBG(fsg, "disconnect or port reset\n");
657 raise_exception(fsg, FSG_STATE_DISCONNECT);
661 static int ep0_queue(struct fsg_dev *fsg)
665 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
666 if (rc != 0 && rc != -ESHUTDOWN) {
668 /* We can't do much more than wait for a reset */
669 WARNING(fsg, "error in submission: %s --> %d\n",
675 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
677 struct fsg_dev *fsg = ep->driver_data;
680 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
681 if (req->status || req->actual != req->length)
682 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
683 req->status, req->actual, req->length);
684 if (req->status == -ECONNRESET) // Request was cancelled
685 usb_ep_fifo_flush(ep);
687 if (req->status == 0 && req->context)
688 ((fsg_routine_t) (req->context))(fsg);
692 /*-------------------------------------------------------------------------*/
694 /* Bulk and interrupt endpoint completion handlers.
695 * These always run in_irq. */
697 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
699 struct fsg_dev *fsg = ep->driver_data;
700 struct fsg_buffhd *bh = req->context;
702 if (req->status || req->actual != req->length)
703 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
704 req->status, req->actual, req->length);
705 if (req->status == -ECONNRESET) // Request was cancelled
706 usb_ep_fifo_flush(ep);
708 /* Hold the lock while we update the request and buffer states */
710 spin_lock(&fsg->lock);
712 bh->state = BUF_STATE_EMPTY;
714 spin_unlock(&fsg->lock);
717 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
719 struct fsg_dev *fsg = ep->driver_data;
720 struct fsg_buffhd *bh = req->context;
722 dump_msg(fsg, "bulk-out", req->buf, req->actual);
723 if (req->status || req->actual != bh->bulk_out_intended_length)
724 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
725 req->status, req->actual,
726 bh->bulk_out_intended_length);
727 if (req->status == -ECONNRESET) // Request was cancelled
728 usb_ep_fifo_flush(ep);
730 /* Hold the lock while we update the request and buffer states */
732 spin_lock(&fsg->lock);
734 bh->state = BUF_STATE_FULL;
736 spin_unlock(&fsg->lock);
740 #ifdef CONFIG_USB_FILE_STORAGE_TEST
741 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
743 struct fsg_dev *fsg = ep->driver_data;
744 struct fsg_buffhd *bh = req->context;
746 if (req->status || req->actual != req->length)
747 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
748 req->status, req->actual, req->length);
749 if (req->status == -ECONNRESET) // Request was cancelled
750 usb_ep_fifo_flush(ep);
752 /* Hold the lock while we update the request and buffer states */
754 spin_lock(&fsg->lock);
755 fsg->intreq_busy = 0;
756 bh->state = BUF_STATE_EMPTY;
758 spin_unlock(&fsg->lock);
762 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
764 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
767 /*-------------------------------------------------------------------------*/
769 /* Ep0 class-specific handlers. These always run in_irq. */
771 #ifdef CONFIG_USB_FILE_STORAGE_TEST
772 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
774 struct usb_request *req = fsg->ep0req;
775 static u8 cbi_reset_cmnd[6] = {
776 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
778 /* Error in command transfer? */
779 if (req->status || req->length != req->actual ||
780 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
782 /* Not all controllers allow a protocol stall after
783 * receiving control-out data, but we'll try anyway. */
784 fsg_set_halt(fsg, fsg->ep0);
785 return; // Wait for reset
788 /* Is it the special reset command? */
789 if (req->actual >= sizeof cbi_reset_cmnd &&
790 memcmp(req->buf, cbi_reset_cmnd,
791 sizeof cbi_reset_cmnd) == 0) {
793 /* Raise an exception to stop the current operation
794 * and reinitialize our state. */
795 DBG(fsg, "cbi reset request\n");
796 raise_exception(fsg, FSG_STATE_RESET);
800 VDBG(fsg, "CB[I] accept device-specific command\n");
801 spin_lock(&fsg->lock);
803 /* Save the command for later */
804 if (fsg->cbbuf_cmnd_size)
805 WARNING(fsg, "CB[I] overwriting previous command\n");
806 fsg->cbbuf_cmnd_size = req->actual;
807 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
810 spin_unlock(&fsg->lock);
814 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
816 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
819 static int class_setup_req(struct fsg_dev *fsg,
820 const struct usb_ctrlrequest *ctrl)
822 struct usb_request *req = fsg->ep0req;
823 int value = -EOPNOTSUPP;
824 u16 w_index = le16_to_cpu(ctrl->wIndex);
825 u16 w_value = le16_to_cpu(ctrl->wValue);
826 u16 w_length = le16_to_cpu(ctrl->wLength);
831 /* Handle Bulk-only class-specific requests */
832 if (transport_is_bbb()) {
833 switch (ctrl->bRequest) {
835 case USB_BULK_RESET_REQUEST:
836 if (ctrl->bRequestType != (USB_DIR_OUT |
837 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
839 if (w_index != 0 || w_value != 0) {
844 /* Raise an exception to stop the current operation
845 * and reinitialize our state. */
846 DBG(fsg, "bulk reset request\n");
847 raise_exception(fsg, FSG_STATE_RESET);
848 value = DELAYED_STATUS;
851 case USB_BULK_GET_MAX_LUN_REQUEST:
852 if (ctrl->bRequestType != (USB_DIR_IN |
853 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
855 if (w_index != 0 || w_value != 0) {
859 VDBG(fsg, "get max LUN\n");
860 *(u8 *) req->buf = fsg->nluns - 1;
866 /* Handle CBI class-specific requests */
868 switch (ctrl->bRequest) {
870 case USB_CBI_ADSC_REQUEST:
871 if (ctrl->bRequestType != (USB_DIR_OUT |
872 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
874 if (w_index != 0 || w_value != 0) {
878 if (w_length > MAX_COMMAND_SIZE) {
883 fsg->ep0req->context = received_cbi_adsc;
888 if (value == -EOPNOTSUPP)
890 "unknown class-specific control req "
891 "%02x.%02x v%04x i%04x l%u\n",
892 ctrl->bRequestType, ctrl->bRequest,
893 le16_to_cpu(ctrl->wValue), w_index, w_length);
898 /*-------------------------------------------------------------------------*/
900 /* Ep0 standard request handlers. These always run in_irq. */
902 static int standard_setup_req(struct fsg_dev *fsg,
903 const struct usb_ctrlrequest *ctrl)
905 struct usb_request *req = fsg->ep0req;
906 int value = -EOPNOTSUPP;
907 u16 w_index = le16_to_cpu(ctrl->wIndex);
908 u16 w_value = le16_to_cpu(ctrl->wValue);
910 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
911 * but config change events will also reconfigure hardware. */
912 switch (ctrl->bRequest) {
914 case USB_REQ_GET_DESCRIPTOR:
915 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
918 switch (w_value >> 8) {
921 VDBG(fsg, "get device descriptor\n");
922 value = sizeof device_desc;
923 memcpy(req->buf, &device_desc, value);
925 case USB_DT_DEVICE_QUALIFIER:
926 VDBG(fsg, "get device qualifier\n");
927 if (!gadget_is_dualspeed(fsg->gadget))
929 value = sizeof dev_qualifier;
930 memcpy(req->buf, &dev_qualifier, value);
933 case USB_DT_OTHER_SPEED_CONFIG:
934 VDBG(fsg, "get other-speed config descriptor\n");
935 if (!gadget_is_dualspeed(fsg->gadget))
939 VDBG(fsg, "get configuration descriptor\n");
941 value = populate_config_buf(fsg->gadget,
948 VDBG(fsg, "get string descriptor\n");
950 /* wIndex == language code */
951 value = usb_gadget_get_string(&fsg_stringtab,
952 w_value & 0xff, req->buf);
957 /* One config, two speeds */
958 case USB_REQ_SET_CONFIGURATION:
959 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
962 VDBG(fsg, "set configuration\n");
963 if (w_value == CONFIG_VALUE || w_value == 0) {
964 fsg->new_config = w_value;
966 /* Raise an exception to wipe out previous transaction
967 * state (queued bufs, etc) and set the new config. */
968 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
969 value = DELAYED_STATUS;
972 case USB_REQ_GET_CONFIGURATION:
973 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
976 VDBG(fsg, "get configuration\n");
977 *(u8 *) req->buf = fsg->config;
981 case USB_REQ_SET_INTERFACE:
982 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
983 USB_RECIP_INTERFACE))
985 if (fsg->config && w_index == 0) {
987 /* Raise an exception to wipe out previous transaction
988 * state (queued bufs, etc) and install the new
989 * interface altsetting. */
990 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
991 value = DELAYED_STATUS;
994 case USB_REQ_GET_INTERFACE:
995 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
996 USB_RECIP_INTERFACE))
1004 VDBG(fsg, "get interface\n");
1005 *(u8 *) req->buf = 0;
1011 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1012 ctrl->bRequestType, ctrl->bRequest,
1013 w_value, w_index, le16_to_cpu(ctrl->wLength));
1020 static int fsg_setup(struct usb_gadget *gadget,
1021 const struct usb_ctrlrequest *ctrl)
1023 struct fsg_dev *fsg = get_gadget_data(gadget);
1025 int w_length = le16_to_cpu(ctrl->wLength);
1027 ++fsg->ep0_req_tag; // Record arrival of a new request
1028 fsg->ep0req->context = NULL;
1029 fsg->ep0req->length = 0;
1030 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1032 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1033 rc = class_setup_req(fsg, ctrl);
1035 rc = standard_setup_req(fsg, ctrl);
1037 /* Respond with data/status or defer until later? */
1038 if (rc >= 0 && rc != DELAYED_STATUS) {
1039 rc = min(rc, w_length);
1040 fsg->ep0req->length = rc;
1041 fsg->ep0req->zero = rc < w_length;
1042 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1043 "ep0-in" : "ep0-out");
1044 rc = ep0_queue(fsg);
1047 /* Device either stalls (rc < 0) or reports success */
1052 /*-------------------------------------------------------------------------*/
1054 /* All the following routines run in process context */
1057 /* Use this for bulk or interrupt transfers, not ep0 */
1058 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1059 struct usb_request *req, int *pbusy,
1060 enum fsg_buffer_state *state)
1064 if (ep == fsg->bulk_in)
1065 dump_msg(fsg, "bulk-in", req->buf, req->length);
1066 else if (ep == fsg->intr_in)
1067 dump_msg(fsg, "intr-in", req->buf, req->length);
1069 spin_lock_irq(&fsg->lock);
1071 *state = BUF_STATE_BUSY;
1072 spin_unlock_irq(&fsg->lock);
1073 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1076 *state = BUF_STATE_EMPTY;
1078 /* We can't do much more than wait for a reset */
1080 /* Note: currently the net2280 driver fails zero-length
1081 * submissions if DMA is enabled. */
1082 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1084 WARNING(fsg, "error in submission: %s --> %d\n",
1090 static int sleep_thread(struct fsg_dev *fsg)
1094 /* Wait until a signal arrives or we are woken up */
1097 set_current_state(TASK_INTERRUPTIBLE);
1098 if (signal_pending(current)) {
1102 if (fsg->thread_wakeup_needed)
1106 __set_current_state(TASK_RUNNING);
1107 fsg->thread_wakeup_needed = 0;
1112 /*-------------------------------------------------------------------------*/
1114 static int do_read(struct fsg_dev *fsg)
1116 struct fsg_lun *curlun = fsg->curlun;
1118 struct fsg_buffhd *bh;
1121 loff_t file_offset, file_offset_tmp;
1122 unsigned int amount;
1123 unsigned int partial_page;
1126 /* Get the starting Logical Block Address and check that it's
1128 if (fsg->cmnd[0] == SC_READ_6)
1129 lba = get_unaligned_be24(&fsg->cmnd[1]);
1131 lba = get_unaligned_be32(&fsg->cmnd[2]);
1133 /* We allow DPO (Disable Page Out = don't save data in the
1134 * cache) and FUA (Force Unit Access = don't read from the
1135 * cache), but we don't implement them. */
1136 if ((fsg->cmnd[1] & ~0x18) != 0) {
1137 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1141 if (lba >= curlun->num_sectors) {
1142 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1145 file_offset = ((loff_t) lba) << 9;
1147 /* Carry out the file reads */
1148 amount_left = fsg->data_size_from_cmnd;
1149 if (unlikely(amount_left == 0))
1150 return -EIO; // No default reply
1154 /* Figure out how much we need to read:
1155 * Try to read the remaining amount.
1156 * But don't read more than the buffer size.
1157 * And don't try to read past the end of the file.
1158 * Finally, if we're not at a page boundary, don't read past
1160 * If this means reading 0 then we were asked to read past
1161 * the end of file. */
1162 amount = min((unsigned int) amount_left, mod_data.buflen);
1163 amount = min((loff_t) amount,
1164 curlun->file_length - file_offset);
1165 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1166 if (partial_page > 0)
1167 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1170 /* Wait for the next buffer to become available */
1171 bh = fsg->next_buffhd_to_fill;
1172 while (bh->state != BUF_STATE_EMPTY) {
1173 rc = sleep_thread(fsg);
1178 /* If we were asked to read past the end of file,
1179 * end with an empty buffer. */
1181 curlun->sense_data =
1182 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1183 curlun->sense_data_info = file_offset >> 9;
1184 curlun->info_valid = 1;
1185 bh->inreq->length = 0;
1186 bh->state = BUF_STATE_FULL;
1190 /* Perform the read */
1191 file_offset_tmp = file_offset;
1192 nread = vfs_read(curlun->filp,
1193 (char __user *) bh->buf,
1194 amount, &file_offset_tmp);
1195 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1196 (unsigned long long) file_offset,
1198 if (signal_pending(current))
1202 LDBG(curlun, "error in file read: %d\n",
1205 } else if (nread < amount) {
1206 LDBG(curlun, "partial file read: %d/%u\n",
1207 (int) nread, amount);
1208 nread -= (nread & 511); // Round down to a block
1210 file_offset += nread;
1211 amount_left -= nread;
1212 fsg->residue -= nread;
1213 bh->inreq->length = nread;
1214 bh->state = BUF_STATE_FULL;
1216 /* If an error occurred, report it and its position */
1217 if (nread < amount) {
1218 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1219 curlun->sense_data_info = file_offset >> 9;
1220 curlun->info_valid = 1;
1224 if (amount_left == 0)
1225 break; // No more left to read
1227 /* Send this buffer and go read some more */
1228 bh->inreq->zero = 0;
1229 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1230 &bh->inreq_busy, &bh->state);
1231 fsg->next_buffhd_to_fill = bh->next;
1234 return -EIO; // No default reply
1238 /*-------------------------------------------------------------------------*/
1240 static int do_write(struct fsg_dev *fsg)
1242 struct fsg_lun *curlun = fsg->curlun;
1244 struct fsg_buffhd *bh;
1246 u32 amount_left_to_req, amount_left_to_write;
1247 loff_t usb_offset, file_offset, file_offset_tmp;
1248 unsigned int amount;
1249 unsigned int partial_page;
1254 curlun->sense_data = SS_WRITE_PROTECTED;
1257 spin_lock(&curlun->filp->f_lock);
1258 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1259 spin_unlock(&curlun->filp->f_lock);
1261 /* Get the starting Logical Block Address and check that it's
1263 if (fsg->cmnd[0] == SC_WRITE_6)
1264 lba = get_unaligned_be24(&fsg->cmnd[1]);
1266 lba = get_unaligned_be32(&fsg->cmnd[2]);
1268 /* We allow DPO (Disable Page Out = don't save data in the
1269 * cache) and FUA (Force Unit Access = write directly to the
1270 * medium). We don't implement DPO; we implement FUA by
1271 * performing synchronous output. */
1272 if ((fsg->cmnd[1] & ~0x18) != 0) {
1273 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1276 if (fsg->cmnd[1] & 0x08) { // FUA
1277 spin_lock(&curlun->filp->f_lock);
1278 curlun->filp->f_flags |= O_SYNC;
1279 spin_unlock(&curlun->filp->f_lock);
1282 if (lba >= curlun->num_sectors) {
1283 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1287 /* Carry out the file writes */
1289 file_offset = usb_offset = ((loff_t) lba) << 9;
1290 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1292 while (amount_left_to_write > 0) {
1294 /* Queue a request for more data from the host */
1295 bh = fsg->next_buffhd_to_fill;
1296 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1298 /* Figure out how much we want to get:
1299 * Try to get the remaining amount.
1300 * But don't get more than the buffer size.
1301 * And don't try to go past the end of the file.
1302 * If we're not at a page boundary,
1303 * don't go past the next page.
1304 * If this means getting 0, then we were asked
1305 * to write past the end of file.
1306 * Finally, round down to a block boundary. */
1307 amount = min(amount_left_to_req, mod_data.buflen);
1308 amount = min((loff_t) amount, curlun->file_length -
1310 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1311 if (partial_page > 0)
1312 amount = min(amount,
1313 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1317 curlun->sense_data =
1318 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1319 curlun->sense_data_info = usb_offset >> 9;
1320 curlun->info_valid = 1;
1323 amount -= (amount & 511);
1326 /* Why were we were asked to transfer a
1332 /* Get the next buffer */
1333 usb_offset += amount;
1334 fsg->usb_amount_left -= amount;
1335 amount_left_to_req -= amount;
1336 if (amount_left_to_req == 0)
1339 /* amount is always divisible by 512, hence by
1340 * the bulk-out maxpacket size */
1341 bh->outreq->length = bh->bulk_out_intended_length =
1343 bh->outreq->short_not_ok = 1;
1344 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1345 &bh->outreq_busy, &bh->state);
1346 fsg->next_buffhd_to_fill = bh->next;
1350 /* Write the received data to the backing file */
1351 bh = fsg->next_buffhd_to_drain;
1352 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1353 break; // We stopped early
1354 if (bh->state == BUF_STATE_FULL) {
1356 fsg->next_buffhd_to_drain = bh->next;
1357 bh->state = BUF_STATE_EMPTY;
1359 /* Did something go wrong with the transfer? */
1360 if (bh->outreq->status != 0) {
1361 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1362 curlun->sense_data_info = file_offset >> 9;
1363 curlun->info_valid = 1;
1367 amount = bh->outreq->actual;
1368 if (curlun->file_length - file_offset < amount) {
1370 "write %u @ %llu beyond end %llu\n",
1371 amount, (unsigned long long) file_offset,
1372 (unsigned long long) curlun->file_length);
1373 amount = curlun->file_length - file_offset;
1376 /* Perform the write */
1377 file_offset_tmp = file_offset;
1378 nwritten = vfs_write(curlun->filp,
1379 (char __user *) bh->buf,
1380 amount, &file_offset_tmp);
1381 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1382 (unsigned long long) file_offset,
1384 if (signal_pending(current))
1385 return -EINTR; // Interrupted!
1388 LDBG(curlun, "error in file write: %d\n",
1391 } else if (nwritten < amount) {
1392 LDBG(curlun, "partial file write: %d/%u\n",
1393 (int) nwritten, amount);
1394 nwritten -= (nwritten & 511);
1395 // Round down to a block
1397 file_offset += nwritten;
1398 amount_left_to_write -= nwritten;
1399 fsg->residue -= nwritten;
1401 /* If an error occurred, report it and its position */
1402 if (nwritten < amount) {
1403 curlun->sense_data = SS_WRITE_ERROR;
1404 curlun->sense_data_info = file_offset >> 9;
1405 curlun->info_valid = 1;
1409 /* Did the host decide to stop early? */
1410 if (bh->outreq->actual != bh->outreq->length) {
1411 fsg->short_packet_received = 1;
1417 /* Wait for something to happen */
1418 rc = sleep_thread(fsg);
1423 return -EIO; // No default reply
1427 /*-------------------------------------------------------------------------*/
1429 static int do_synchronize_cache(struct fsg_dev *fsg)
1431 struct fsg_lun *curlun = fsg->curlun;
1434 /* We ignore the requested LBA and write out all file's
1435 * dirty data buffers. */
1436 rc = fsg_lun_fsync_sub(curlun);
1438 curlun->sense_data = SS_WRITE_ERROR;
1443 /*-------------------------------------------------------------------------*/
1445 static void invalidate_sub(struct fsg_lun *curlun)
1447 struct file *filp = curlun->filp;
1448 struct inode *inode = filp->f_path.dentry->d_inode;
1451 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1452 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1455 static int do_verify(struct fsg_dev *fsg)
1457 struct fsg_lun *curlun = fsg->curlun;
1459 u32 verification_length;
1460 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1461 loff_t file_offset, file_offset_tmp;
1463 unsigned int amount;
1466 /* Get the starting Logical Block Address and check that it's
1468 lba = get_unaligned_be32(&fsg->cmnd[2]);
1469 if (lba >= curlun->num_sectors) {
1470 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1474 /* We allow DPO (Disable Page Out = don't save data in the
1475 * cache) but we don't implement it. */
1476 if ((fsg->cmnd[1] & ~0x10) != 0) {
1477 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1481 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
1482 if (unlikely(verification_length == 0))
1483 return -EIO; // No default reply
1485 /* Prepare to carry out the file verify */
1486 amount_left = verification_length << 9;
1487 file_offset = ((loff_t) lba) << 9;
1489 /* Write out all the dirty buffers before invalidating them */
1490 fsg_lun_fsync_sub(curlun);
1491 if (signal_pending(current))
1494 invalidate_sub(curlun);
1495 if (signal_pending(current))
1498 /* Just try to read the requested blocks */
1499 while (amount_left > 0) {
1501 /* Figure out how much we need to read:
1502 * Try to read the remaining amount, but not more than
1504 * And don't try to read past the end of the file.
1505 * If this means reading 0 then we were asked to read
1506 * past the end of file. */
1507 amount = min((unsigned int) amount_left, mod_data.buflen);
1508 amount = min((loff_t) amount,
1509 curlun->file_length - file_offset);
1511 curlun->sense_data =
1512 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1513 curlun->sense_data_info = file_offset >> 9;
1514 curlun->info_valid = 1;
1518 /* Perform the read */
1519 file_offset_tmp = file_offset;
1520 nread = vfs_read(curlun->filp,
1521 (char __user *) bh->buf,
1522 amount, &file_offset_tmp);
1523 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1524 (unsigned long long) file_offset,
1526 if (signal_pending(current))
1530 LDBG(curlun, "error in file verify: %d\n",
1533 } else if (nread < amount) {
1534 LDBG(curlun, "partial file verify: %d/%u\n",
1535 (int) nread, amount);
1536 nread -= (nread & 511); // Round down to a sector
1539 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1540 curlun->sense_data_info = file_offset >> 9;
1541 curlun->info_valid = 1;
1544 file_offset += nread;
1545 amount_left -= nread;
1551 /*-------------------------------------------------------------------------*/
1553 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1555 u8 *buf = (u8 *) bh->buf;
1557 static char vendor_id[] = "Linux ";
1558 static char product_disk_id[] = "File-Stor Gadget";
1559 static char product_cdrom_id[] = "File-CD Gadget ";
1561 if (!fsg->curlun) { // Unsupported LUNs are okay
1562 fsg->bad_lun_okay = 1;
1564 buf[0] = 0x7f; // Unsupported, no device-type
1565 buf[4] = 31; // Additional length
1570 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
1571 if (mod_data.removable)
1573 buf[2] = 2; // ANSI SCSI level 2
1574 buf[3] = 2; // SCSI-2 INQUIRY data format
1575 buf[4] = 31; // Additional length
1576 // No special options
1577 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1578 (mod_data.cdrom ? product_cdrom_id :
1585 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1587 struct fsg_lun *curlun = fsg->curlun;
1588 u8 *buf = (u8 *) bh->buf;
1593 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1595 * If a REQUEST SENSE command is received from an initiator
1596 * with a pending unit attention condition (before the target
1597 * generates the contingent allegiance condition), then the
1598 * target shall either:
1599 * a) report any pending sense data and preserve the unit
1600 * attention condition on the logical unit, or,
1601 * b) report the unit attention condition, may discard any
1602 * pending sense data, and clear the unit attention
1603 * condition on the logical unit for that initiator.
1605 * FSG normally uses option a); enable this code to use option b).
1608 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1609 curlun->sense_data = curlun->unit_attention_data;
1610 curlun->unit_attention_data = SS_NO_SENSE;
1614 if (!curlun) { // Unsupported LUNs are okay
1615 fsg->bad_lun_okay = 1;
1616 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1620 sd = curlun->sense_data;
1621 sdinfo = curlun->sense_data_info;
1622 valid = curlun->info_valid << 7;
1623 curlun->sense_data = SS_NO_SENSE;
1624 curlun->sense_data_info = 0;
1625 curlun->info_valid = 0;
1629 buf[0] = valid | 0x70; // Valid, current error
1631 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1632 buf[7] = 18 - 8; // Additional sense length
1639 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1641 struct fsg_lun *curlun = fsg->curlun;
1642 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
1643 int pmi = fsg->cmnd[8];
1644 u8 *buf = (u8 *) bh->buf;
1646 /* Check the PMI and LBA fields */
1647 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1648 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1652 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1653 /* Max logical block */
1654 put_unaligned_be32(512, &buf[4]); /* Block length */
1659 static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1661 struct fsg_lun *curlun = fsg->curlun;
1662 int msf = fsg->cmnd[1] & 0x02;
1663 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
1664 u8 *buf = (u8 *) bh->buf;
1666 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1667 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1670 if (lba >= curlun->num_sectors) {
1671 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1676 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1677 store_cdrom_address(&buf[4], msf, lba);
1682 static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1684 struct fsg_lun *curlun = fsg->curlun;
1685 int msf = fsg->cmnd[1] & 0x02;
1686 int start_track = fsg->cmnd[6];
1687 u8 *buf = (u8 *) bh->buf;
1689 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1691 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1696 buf[1] = (20-2); /* TOC data length */
1697 buf[2] = 1; /* First track number */
1698 buf[3] = 1; /* Last track number */
1699 buf[5] = 0x16; /* Data track, copying allowed */
1700 buf[6] = 0x01; /* Only track is number 1 */
1701 store_cdrom_address(&buf[8], msf, 0);
1703 buf[13] = 0x16; /* Lead-out track is data */
1704 buf[14] = 0xAA; /* Lead-out track number */
1705 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1710 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1712 struct fsg_lun *curlun = fsg->curlun;
1713 int mscmnd = fsg->cmnd[0];
1714 u8 *buf = (u8 *) bh->buf;
1717 int changeable_values, all_pages;
1721 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1722 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1725 pc = fsg->cmnd[2] >> 6;
1726 page_code = fsg->cmnd[2] & 0x3f;
1728 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1731 changeable_values = (pc == 1);
1732 all_pages = (page_code == 0x3f);
1734 /* Write the mode parameter header. Fixed values are: default
1735 * medium type, no cache control (DPOFUA), and no block descriptors.
1736 * The only variable value is the WriteProtect bit. We will fill in
1737 * the mode data length later. */
1739 if (mscmnd == SC_MODE_SENSE_6) {
1740 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1743 } else { // SC_MODE_SENSE_10
1744 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1746 limit = 65535; // Should really be mod_data.buflen
1749 /* No block descriptors */
1751 /* The mode pages, in numerical order. The only page we support
1752 * is the Caching page. */
1753 if (page_code == 0x08 || all_pages) {
1755 buf[0] = 0x08; // Page code
1756 buf[1] = 10; // Page length
1757 memset(buf+2, 0, 10); // None of the fields are changeable
1759 if (!changeable_values) {
1760 buf[2] = 0x04; // Write cache enable,
1761 // Read cache not disabled
1762 // No cache retention priorities
1763 put_unaligned_be16(0xffff, &buf[4]);
1764 /* Don't disable prefetch */
1765 /* Minimum prefetch = 0 */
1766 put_unaligned_be16(0xffff, &buf[8]);
1767 /* Maximum prefetch */
1768 put_unaligned_be16(0xffff, &buf[10]);
1769 /* Maximum prefetch ceiling */
1774 /* Check that a valid page was requested and the mode data length
1775 * isn't too long. */
1777 if (!valid_page || len > limit) {
1778 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1782 /* Store the mode data length */
1783 if (mscmnd == SC_MODE_SENSE_6)
1786 put_unaligned_be16(len - 2, buf0);
1791 static int do_start_stop(struct fsg_dev *fsg)
1793 struct fsg_lun *curlun = fsg->curlun;
1796 if (!mod_data.removable) {
1797 curlun->sense_data = SS_INVALID_COMMAND;
1801 // int immed = fsg->cmnd[1] & 0x01;
1802 loej = fsg->cmnd[4] & 0x02;
1803 start = fsg->cmnd[4] & 0x01;
1805 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1806 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1807 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1808 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1814 /* Are we allowed to unload the media? */
1815 if (curlun->prevent_medium_removal) {
1816 LDBG(curlun, "unload attempt prevented\n");
1817 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1820 if (loej) { // Simulate an unload/eject
1821 up_read(&fsg->filesem);
1822 down_write(&fsg->filesem);
1823 fsg_lun_close(curlun);
1824 up_write(&fsg->filesem);
1825 down_read(&fsg->filesem);
1829 /* Our emulation doesn't support mounting; the medium is
1830 * available for use as soon as it is loaded. */
1831 if (!fsg_lun_is_open(curlun)) {
1832 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1841 static int do_prevent_allow(struct fsg_dev *fsg)
1843 struct fsg_lun *curlun = fsg->curlun;
1846 if (!mod_data.removable) {
1847 curlun->sense_data = SS_INVALID_COMMAND;
1851 prevent = fsg->cmnd[4] & 0x01;
1852 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1853 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1857 if (curlun->prevent_medium_removal && !prevent)
1858 fsg_lun_fsync_sub(curlun);
1859 curlun->prevent_medium_removal = prevent;
1864 static int do_read_format_capacities(struct fsg_dev *fsg,
1865 struct fsg_buffhd *bh)
1867 struct fsg_lun *curlun = fsg->curlun;
1868 u8 *buf = (u8 *) bh->buf;
1870 buf[0] = buf[1] = buf[2] = 0;
1871 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1874 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1875 /* Number of blocks */
1876 put_unaligned_be32(512, &buf[4]); /* Block length */
1877 buf[4] = 0x02; /* Current capacity */
1882 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1884 struct fsg_lun *curlun = fsg->curlun;
1886 /* We don't support MODE SELECT */
1887 curlun->sense_data = SS_INVALID_COMMAND;
1892 /*-------------------------------------------------------------------------*/
1894 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1898 rc = fsg_set_halt(fsg, fsg->bulk_in);
1900 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1902 if (rc != -EAGAIN) {
1903 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1908 /* Wait for a short time and then try again */
1909 if (msleep_interruptible(100) != 0)
1911 rc = usb_ep_set_halt(fsg->bulk_in);
1916 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1920 DBG(fsg, "bulk-in set wedge\n");
1921 rc = usb_ep_set_wedge(fsg->bulk_in);
1923 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1925 if (rc != -EAGAIN) {
1926 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1931 /* Wait for a short time and then try again */
1932 if (msleep_interruptible(100) != 0)
1934 rc = usb_ep_set_wedge(fsg->bulk_in);
1939 static int pad_with_zeros(struct fsg_dev *fsg)
1941 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1942 u32 nkeep = bh->inreq->length;
1946 bh->state = BUF_STATE_EMPTY; // For the first iteration
1947 fsg->usb_amount_left = nkeep + fsg->residue;
1948 while (fsg->usb_amount_left > 0) {
1950 /* Wait for the next buffer to be free */
1951 while (bh->state != BUF_STATE_EMPTY) {
1952 rc = sleep_thread(fsg);
1957 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
1958 memset(bh->buf + nkeep, 0, nsend - nkeep);
1959 bh->inreq->length = nsend;
1960 bh->inreq->zero = 0;
1961 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1962 &bh->inreq_busy, &bh->state);
1963 bh = fsg->next_buffhd_to_fill = bh->next;
1964 fsg->usb_amount_left -= nsend;
1970 static int throw_away_data(struct fsg_dev *fsg)
1972 struct fsg_buffhd *bh;
1976 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1977 fsg->usb_amount_left > 0) {
1979 /* Throw away the data in a filled buffer */
1980 if (bh->state == BUF_STATE_FULL) {
1982 bh->state = BUF_STATE_EMPTY;
1983 fsg->next_buffhd_to_drain = bh->next;
1985 /* A short packet or an error ends everything */
1986 if (bh->outreq->actual != bh->outreq->length ||
1987 bh->outreq->status != 0) {
1988 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1994 /* Try to submit another request if we need one */
1995 bh = fsg->next_buffhd_to_fill;
1996 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1997 amount = min(fsg->usb_amount_left,
1998 (u32) mod_data.buflen);
2000 /* amount is always divisible by 512, hence by
2001 * the bulk-out maxpacket size */
2002 bh->outreq->length = bh->bulk_out_intended_length =
2004 bh->outreq->short_not_ok = 1;
2005 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2006 &bh->outreq_busy, &bh->state);
2007 fsg->next_buffhd_to_fill = bh->next;
2008 fsg->usb_amount_left -= amount;
2012 /* Otherwise wait for something to happen */
2013 rc = sleep_thread(fsg);
2021 static int finish_reply(struct fsg_dev *fsg)
2023 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2026 switch (fsg->data_dir) {
2028 break; // Nothing to send
2030 /* If we don't know whether the host wants to read or write,
2031 * this must be CB or CBI with an unknown command. We mustn't
2032 * try to send or receive any data. So stall both bulk pipes
2033 * if we can and wait for a reset. */
2034 case DATA_DIR_UNKNOWN:
2035 if (mod_data.can_stall) {
2036 fsg_set_halt(fsg, fsg->bulk_out);
2037 rc = halt_bulk_in_endpoint(fsg);
2041 /* All but the last buffer of data must have already been sent */
2042 case DATA_DIR_TO_HOST:
2043 if (fsg->data_size == 0)
2044 ; // Nothing to send
2046 /* If there's no residue, simply send the last buffer */
2047 else if (fsg->residue == 0) {
2048 bh->inreq->zero = 0;
2049 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2050 &bh->inreq_busy, &bh->state);
2051 fsg->next_buffhd_to_fill = bh->next;
2054 /* There is a residue. For CB and CBI, simply mark the end
2055 * of the data with a short packet. However, if we are
2056 * allowed to stall, there was no data at all (residue ==
2057 * data_size), and the command failed (invalid LUN or
2058 * sense data is set), then halt the bulk-in endpoint
2060 else if (!transport_is_bbb()) {
2061 if (mod_data.can_stall &&
2062 fsg->residue == fsg->data_size &&
2063 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2064 bh->state = BUF_STATE_EMPTY;
2065 rc = halt_bulk_in_endpoint(fsg);
2067 bh->inreq->zero = 1;
2068 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2069 &bh->inreq_busy, &bh->state);
2070 fsg->next_buffhd_to_fill = bh->next;
2074 /* For Bulk-only, if we're allowed to stall then send the
2075 * short packet and halt the bulk-in endpoint. If we can't
2076 * stall, pad out the remaining data with 0's. */
2078 if (mod_data.can_stall) {
2079 bh->inreq->zero = 1;
2080 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2081 &bh->inreq_busy, &bh->state);
2082 fsg->next_buffhd_to_fill = bh->next;
2083 rc = halt_bulk_in_endpoint(fsg);
2085 rc = pad_with_zeros(fsg);
2089 /* We have processed all we want from the data the host has sent.
2090 * There may still be outstanding bulk-out requests. */
2091 case DATA_DIR_FROM_HOST:
2092 if (fsg->residue == 0)
2093 ; // Nothing to receive
2095 /* Did the host stop sending unexpectedly early? */
2096 else if (fsg->short_packet_received) {
2097 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2101 /* We haven't processed all the incoming data. Even though
2102 * we may be allowed to stall, doing so would cause a race.
2103 * The controller may already have ACK'ed all the remaining
2104 * bulk-out packets, in which case the host wouldn't see a
2105 * STALL. Not realizing the endpoint was halted, it wouldn't
2106 * clear the halt -- leading to problems later on. */
2108 else if (mod_data.can_stall) {
2109 fsg_set_halt(fsg, fsg->bulk_out);
2110 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2115 /* We can't stall. Read in the excess data and throw it
2118 rc = throw_away_data(fsg);
2125 static int send_status(struct fsg_dev *fsg)
2127 struct fsg_lun *curlun = fsg->curlun;
2128 struct fsg_buffhd *bh;
2130 u8 status = USB_STATUS_PASS;
2133 /* Wait for the next buffer to become available */
2134 bh = fsg->next_buffhd_to_fill;
2135 while (bh->state != BUF_STATE_EMPTY) {
2136 rc = sleep_thread(fsg);
2142 sd = curlun->sense_data;
2143 sdinfo = curlun->sense_data_info;
2144 } else if (fsg->bad_lun_okay)
2147 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2149 if (fsg->phase_error) {
2150 DBG(fsg, "sending phase-error status\n");
2151 status = USB_STATUS_PHASE_ERROR;
2152 sd = SS_INVALID_COMMAND;
2153 } else if (sd != SS_NO_SENSE) {
2154 DBG(fsg, "sending command-failure status\n");
2155 status = USB_STATUS_FAIL;
2156 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2158 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2161 if (transport_is_bbb()) {
2162 struct bulk_cs_wrap *csw = bh->buf;
2164 /* Store and send the Bulk-only CSW */
2165 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
2166 csw->Tag = fsg->tag;
2167 csw->Residue = cpu_to_le32(fsg->residue);
2168 csw->Status = status;
2170 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2171 bh->inreq->zero = 0;
2172 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2173 &bh->inreq_busy, &bh->state);
2175 } else if (mod_data.transport_type == USB_PR_CB) {
2177 /* Control-Bulk transport has no status phase! */
2180 } else { // USB_PR_CBI
2181 struct interrupt_data *buf = bh->buf;
2183 /* Store and send the Interrupt data. UFI sends the ASC
2184 * and ASCQ bytes. Everything else sends a Type (which
2185 * is always 0) and the status Value. */
2186 if (mod_data.protocol_type == USB_SC_UFI) {
2187 buf->bType = ASC(sd);
2188 buf->bValue = ASCQ(sd);
2191 buf->bValue = status;
2193 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2195 fsg->intr_buffhd = bh; // Point to the right buffhd
2196 fsg->intreq->buf = bh->inreq->buf;
2197 fsg->intreq->context = bh;
2198 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2199 &fsg->intreq_busy, &bh->state);
2202 fsg->next_buffhd_to_fill = bh->next;
2207 /*-------------------------------------------------------------------------*/
2209 /* Check whether the command is properly formed and whether its data size
2210 * and direction agree with the values we already have. */
2211 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2212 enum data_direction data_dir, unsigned int mask,
2213 int needs_medium, const char *name)
2216 int lun = fsg->cmnd[1] >> 5;
2217 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2219 struct fsg_lun *curlun;
2221 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2222 * Transparent SCSI doesn't pad. */
2223 if (protocol_is_scsi())
2226 /* There's some disagreement as to whether RBC pads commands or not.
2227 * We'll play it safe and accept either form. */
2228 else if (mod_data.protocol_type == USB_SC_RBC) {
2229 if (fsg->cmnd_size == 12)
2232 /* All the other protocols pad to 12 bytes */
2237 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2238 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2240 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2241 name, cmnd_size, dirletter[(int) data_dir],
2242 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2244 /* We can't reply at all until we know the correct data direction
2246 if (fsg->data_size_from_cmnd == 0)
2247 data_dir = DATA_DIR_NONE;
2248 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2249 fsg->data_dir = data_dir;
2250 fsg->data_size = fsg->data_size_from_cmnd;
2252 } else { // Bulk-only
2253 if (fsg->data_size < fsg->data_size_from_cmnd) {
2255 /* Host data size < Device data size is a phase error.
2256 * Carry out the command, but only transfer as much
2257 * as we are allowed. */
2258 fsg->data_size_from_cmnd = fsg->data_size;
2259 fsg->phase_error = 1;
2262 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2264 /* Conflicting data directions is a phase error */
2265 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2266 fsg->phase_error = 1;
2270 /* Verify the length of the command itself */
2271 if (cmnd_size != fsg->cmnd_size) {
2273 /* Special case workaround: There are plenty of buggy SCSI
2274 * implementations. Many have issues with cbw->Length
2275 * field passing a wrong command size. For those cases we
2276 * always try to work around the problem by using the length
2277 * sent by the host side provided it is at least as large
2278 * as the correct command length.
2279 * Examples of such cases would be MS-Windows, which issues
2280 * REQUEST SENSE with cbw->Length == 12 where it should
2281 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2282 * REQUEST SENSE with cbw->Length == 10 where it should
2285 if (cmnd_size <= fsg->cmnd_size) {
2286 DBG(fsg, "%s is buggy! Expected length %d "
2287 "but we got %d\n", name,
2288 cmnd_size, fsg->cmnd_size);
2289 cmnd_size = fsg->cmnd_size;
2291 fsg->phase_error = 1;
2296 /* Check that the LUN values are consistent */
2297 if (transport_is_bbb()) {
2298 if (fsg->lun != lun)
2299 DBG(fsg, "using LUN %d from CBW, "
2300 "not LUN %d from CDB\n",
2303 fsg->lun = lun; // Use LUN from the command
2306 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2307 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2308 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2309 curlun->sense_data = SS_NO_SENSE;
2310 curlun->sense_data_info = 0;
2311 curlun->info_valid = 0;
2314 fsg->curlun = curlun = NULL;
2315 fsg->bad_lun_okay = 0;
2317 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2318 * to use unsupported LUNs; all others may not. */
2319 if (fsg->cmnd[0] != SC_INQUIRY &&
2320 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2321 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2326 /* If a unit attention condition exists, only INQUIRY and
2327 * REQUEST SENSE commands are allowed; anything else must fail. */
2328 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2329 fsg->cmnd[0] != SC_INQUIRY &&
2330 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2331 curlun->sense_data = curlun->unit_attention_data;
2332 curlun->unit_attention_data = SS_NO_SENSE;
2336 /* Check that only command bytes listed in the mask are non-zero */
2337 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2338 for (i = 1; i < cmnd_size; ++i) {
2339 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2341 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2346 /* If the medium isn't mounted and the command needs to access
2347 * it, return an error. */
2348 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
2349 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2357 static int do_scsi_command(struct fsg_dev *fsg)
2359 struct fsg_buffhd *bh;
2361 int reply = -EINVAL;
2363 static char unknown[16];
2367 /* Wait for the next buffer to become available for data or status */
2368 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2369 while (bh->state != BUF_STATE_EMPTY) {
2370 rc = sleep_thread(fsg);
2374 fsg->phase_error = 0;
2375 fsg->short_packet_received = 0;
2377 down_read(&fsg->filesem); // We're using the backing file
2378 switch (fsg->cmnd[0]) {
2381 fsg->data_size_from_cmnd = fsg->cmnd[4];
2382 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2385 reply = do_inquiry(fsg, bh);
2388 case SC_MODE_SELECT_6:
2389 fsg->data_size_from_cmnd = fsg->cmnd[4];
2390 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2392 "MODE SELECT(6)")) == 0)
2393 reply = do_mode_select(fsg, bh);
2396 case SC_MODE_SELECT_10:
2397 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2398 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2400 "MODE SELECT(10)")) == 0)
2401 reply = do_mode_select(fsg, bh);
2404 case SC_MODE_SENSE_6:
2405 fsg->data_size_from_cmnd = fsg->cmnd[4];
2406 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2407 (1<<1) | (1<<2) | (1<<4), 0,
2408 "MODE SENSE(6)")) == 0)
2409 reply = do_mode_sense(fsg, bh);
2412 case SC_MODE_SENSE_10:
2413 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2414 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2415 (1<<1) | (1<<2) | (3<<7), 0,
2416 "MODE SENSE(10)")) == 0)
2417 reply = do_mode_sense(fsg, bh);
2420 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2421 fsg->data_size_from_cmnd = 0;
2422 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2424 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2425 reply = do_prevent_allow(fsg);
2430 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2431 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2434 reply = do_read(fsg);
2438 fsg->data_size_from_cmnd =
2439 get_unaligned_be16(&fsg->cmnd[7]) << 9;
2440 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2441 (1<<1) | (0xf<<2) | (3<<7), 1,
2443 reply = do_read(fsg);
2447 fsg->data_size_from_cmnd =
2448 get_unaligned_be32(&fsg->cmnd[6]) << 9;
2449 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2450 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2452 reply = do_read(fsg);
2455 case SC_READ_CAPACITY:
2456 fsg->data_size_from_cmnd = 8;
2457 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2458 (0xf<<2) | (1<<8), 1,
2459 "READ CAPACITY")) == 0)
2460 reply = do_read_capacity(fsg, bh);
2463 case SC_READ_HEADER:
2464 if (!mod_data.cdrom)
2466 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2467 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2468 (3<<7) | (0x1f<<1), 1,
2469 "READ HEADER")) == 0)
2470 reply = do_read_header(fsg, bh);
2474 if (!mod_data.cdrom)
2476 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2477 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2480 reply = do_read_toc(fsg, bh);
2483 case SC_READ_FORMAT_CAPACITIES:
2484 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2485 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2487 "READ FORMAT CAPACITIES")) == 0)
2488 reply = do_read_format_capacities(fsg, bh);
2491 case SC_REQUEST_SENSE:
2492 fsg->data_size_from_cmnd = fsg->cmnd[4];
2493 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2495 "REQUEST SENSE")) == 0)
2496 reply = do_request_sense(fsg, bh);
2499 case SC_START_STOP_UNIT:
2500 fsg->data_size_from_cmnd = 0;
2501 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2503 "START-STOP UNIT")) == 0)
2504 reply = do_start_stop(fsg);
2507 case SC_SYNCHRONIZE_CACHE:
2508 fsg->data_size_from_cmnd = 0;
2509 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2510 (0xf<<2) | (3<<7), 1,
2511 "SYNCHRONIZE CACHE")) == 0)
2512 reply = do_synchronize_cache(fsg);
2515 case SC_TEST_UNIT_READY:
2516 fsg->data_size_from_cmnd = 0;
2517 reply = check_command(fsg, 6, DATA_DIR_NONE,
2522 /* Although optional, this command is used by MS-Windows. We
2523 * support a minimal version: BytChk must be 0. */
2525 fsg->data_size_from_cmnd = 0;
2526 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2527 (1<<1) | (0xf<<2) | (3<<7), 1,
2529 reply = do_verify(fsg);
2534 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2535 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2538 reply = do_write(fsg);
2542 fsg->data_size_from_cmnd =
2543 get_unaligned_be16(&fsg->cmnd[7]) << 9;
2544 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2545 (1<<1) | (0xf<<2) | (3<<7), 1,
2547 reply = do_write(fsg);
2551 fsg->data_size_from_cmnd =
2552 get_unaligned_be32(&fsg->cmnd[6]) << 9;
2553 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2554 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2556 reply = do_write(fsg);
2559 /* Some mandatory commands that we recognize but don't implement.
2560 * They don't mean much in this setting. It's left as an exercise
2561 * for anyone interested to implement RESERVE and RELEASE in terms
2562 * of Posix locks. */
2563 case SC_FORMAT_UNIT:
2566 case SC_SEND_DIAGNOSTIC:
2571 fsg->data_size_from_cmnd = 0;
2572 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2573 if ((reply = check_command(fsg, fsg->cmnd_size,
2574 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2575 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2580 up_read(&fsg->filesem);
2582 if (reply == -EINTR || signal_pending(current))
2585 /* Set up the single reply buffer for finish_reply() */
2586 if (reply == -EINVAL)
2587 reply = 0; // Error reply length
2588 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2589 reply = min((u32) reply, fsg->data_size_from_cmnd);
2590 bh->inreq->length = reply;
2591 bh->state = BUF_STATE_FULL;
2592 fsg->residue -= reply;
2593 } // Otherwise it's already set
2599 /*-------------------------------------------------------------------------*/
2601 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2603 struct usb_request *req = bh->outreq;
2604 struct fsg_bulk_cb_wrap *cbw = req->buf;
2606 /* Was this a real packet? Should it be ignored? */
2607 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2610 /* Is the CBW valid? */
2611 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2612 cbw->Signature != cpu_to_le32(
2614 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2616 le32_to_cpu(cbw->Signature));
2618 /* The Bulk-only spec says we MUST stall the IN endpoint
2619 * (6.6.1), so it's unavoidable. It also says we must
2620 * retain this state until the next reset, but there's
2621 * no way to tell the controller driver it should ignore
2622 * Clear-Feature(HALT) requests.
2624 * We aren't required to halt the OUT endpoint; instead
2625 * we can simply accept and discard any data received
2626 * until the next reset. */
2627 wedge_bulk_in_endpoint(fsg);
2628 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2632 /* Is the CBW meaningful? */
2633 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2634 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2635 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2637 cbw->Lun, cbw->Flags, cbw->Length);
2639 /* We can do anything we want here, so let's stall the
2640 * bulk pipes if we are allowed to. */
2641 if (mod_data.can_stall) {
2642 fsg_set_halt(fsg, fsg->bulk_out);
2643 halt_bulk_in_endpoint(fsg);
2648 /* Save the command for later */
2649 fsg->cmnd_size = cbw->Length;
2650 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2651 if (cbw->Flags & USB_BULK_IN_FLAG)
2652 fsg->data_dir = DATA_DIR_TO_HOST;
2654 fsg->data_dir = DATA_DIR_FROM_HOST;
2655 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2656 if (fsg->data_size == 0)
2657 fsg->data_dir = DATA_DIR_NONE;
2658 fsg->lun = cbw->Lun;
2659 fsg->tag = cbw->Tag;
2664 static int get_next_command(struct fsg_dev *fsg)
2666 struct fsg_buffhd *bh;
2669 if (transport_is_bbb()) {
2671 /* Wait for the next buffer to become available */
2672 bh = fsg->next_buffhd_to_fill;
2673 while (bh->state != BUF_STATE_EMPTY) {
2674 rc = sleep_thread(fsg);
2679 /* Queue a request to read a Bulk-only CBW */
2680 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2681 bh->outreq->short_not_ok = 1;
2682 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2683 &bh->outreq_busy, &bh->state);
2685 /* We will drain the buffer in software, which means we
2686 * can reuse it for the next filling. No need to advance
2687 * next_buffhd_to_fill. */
2689 /* Wait for the CBW to arrive */
2690 while (bh->state != BUF_STATE_FULL) {
2691 rc = sleep_thread(fsg);
2696 rc = received_cbw(fsg, bh);
2697 bh->state = BUF_STATE_EMPTY;
2699 } else { // USB_PR_CB or USB_PR_CBI
2701 /* Wait for the next command to arrive */
2702 while (fsg->cbbuf_cmnd_size == 0) {
2703 rc = sleep_thread(fsg);
2708 /* Is the previous status interrupt request still busy?
2709 * The host is allowed to skip reading the status,
2710 * so we must cancel it. */
2711 if (fsg->intreq_busy)
2712 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2714 /* Copy the command and mark the buffer empty */
2715 fsg->data_dir = DATA_DIR_UNKNOWN;
2716 spin_lock_irq(&fsg->lock);
2717 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2718 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2719 fsg->cbbuf_cmnd_size = 0;
2720 spin_unlock_irq(&fsg->lock);
2726 /*-------------------------------------------------------------------------*/
2728 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2729 const struct usb_endpoint_descriptor *d)
2733 ep->driver_data = fsg;
2734 rc = usb_ep_enable(ep, d);
2736 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2740 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2741 struct usb_request **preq)
2743 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2746 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2751 * Reset interface setting and re-init endpoint state (toggle etc).
2752 * Call with altsetting < 0 to disable the interface. The only other
2753 * available altsetting is 0, which enables the interface.
2755 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2759 const struct usb_endpoint_descriptor *d;
2762 DBG(fsg, "reset interface\n");
2765 /* Deallocate the requests */
2766 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2767 struct fsg_buffhd *bh = &fsg->buffhds[i];
2770 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2774 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2779 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2783 /* Disable the endpoints */
2784 if (fsg->bulk_in_enabled) {
2785 usb_ep_disable(fsg->bulk_in);
2786 fsg->bulk_in_enabled = 0;
2788 if (fsg->bulk_out_enabled) {
2789 usb_ep_disable(fsg->bulk_out);
2790 fsg->bulk_out_enabled = 0;
2792 if (fsg->intr_in_enabled) {
2793 usb_ep_disable(fsg->intr_in);
2794 fsg->intr_in_enabled = 0;
2798 if (altsetting < 0 || rc != 0)
2801 DBG(fsg, "set interface %d\n", altsetting);
2803 /* Enable the endpoints */
2804 d = fsg_ep_desc(fsg->gadget,
2805 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2806 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2808 fsg->bulk_in_enabled = 1;
2810 d = fsg_ep_desc(fsg->gadget,
2811 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2812 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2814 fsg->bulk_out_enabled = 1;
2815 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2816 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2818 if (transport_is_cbi()) {
2819 d = fsg_ep_desc(fsg->gadget,
2820 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
2821 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2823 fsg->intr_in_enabled = 1;
2826 /* Allocate the requests */
2827 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2828 struct fsg_buffhd *bh = &fsg->buffhds[i];
2830 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2832 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2834 bh->inreq->buf = bh->outreq->buf = bh->buf;
2835 bh->inreq->context = bh->outreq->context = bh;
2836 bh->inreq->complete = bulk_in_complete;
2837 bh->outreq->complete = bulk_out_complete;
2839 if (transport_is_cbi()) {
2840 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2842 fsg->intreq->complete = intr_in_complete;
2846 for (i = 0; i < fsg->nluns; ++i)
2847 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2853 * Change our operational configuration. This code must agree with the code
2854 * that returns config descriptors, and with interface altsetting code.
2856 * It's also responsible for power management interactions. Some
2857 * configurations might not work with our current power sources.
2858 * For now we just assume the gadget is always self-powered.
2860 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2864 /* Disable the single interface */
2865 if (fsg->config != 0) {
2866 DBG(fsg, "reset config\n");
2868 rc = do_set_interface(fsg, -1);
2871 /* Enable the interface */
2872 if (new_config != 0) {
2873 fsg->config = new_config;
2874 if ((rc = do_set_interface(fsg, 0)) != 0)
2875 fsg->config = 0; // Reset on errors
2879 switch (fsg->gadget->speed) {
2880 case USB_SPEED_LOW: speed = "low"; break;
2881 case USB_SPEED_FULL: speed = "full"; break;
2882 case USB_SPEED_HIGH: speed = "high"; break;
2883 default: speed = "?"; break;
2885 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2892 /*-------------------------------------------------------------------------*/
2894 static void handle_exception(struct fsg_dev *fsg)
2900 struct fsg_buffhd *bh;
2901 enum fsg_state old_state;
2903 struct fsg_lun *curlun;
2904 unsigned int exception_req_tag;
2907 /* Clear the existing signals. Anything but SIGUSR1 is converted
2908 * into a high-priority EXIT exception. */
2910 sig = dequeue_signal_lock(current, ¤t->blocked, &info);
2913 if (sig != SIGUSR1) {
2914 if (fsg->state < FSG_STATE_EXIT)
2915 DBG(fsg, "Main thread exiting on signal\n");
2916 raise_exception(fsg, FSG_STATE_EXIT);
2920 /* Cancel all the pending transfers */
2921 if (fsg->intreq_busy)
2922 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2923 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2924 bh = &fsg->buffhds[i];
2926 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2927 if (bh->outreq_busy)
2928 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2931 /* Wait until everything is idle */
2933 num_active = fsg->intreq_busy;
2934 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2935 bh = &fsg->buffhds[i];
2936 num_active += bh->inreq_busy + bh->outreq_busy;
2938 if (num_active == 0)
2940 if (sleep_thread(fsg))
2944 /* Clear out the controller's fifos */
2945 if (fsg->bulk_in_enabled)
2946 usb_ep_fifo_flush(fsg->bulk_in);
2947 if (fsg->bulk_out_enabled)
2948 usb_ep_fifo_flush(fsg->bulk_out);
2949 if (fsg->intr_in_enabled)
2950 usb_ep_fifo_flush(fsg->intr_in);
2952 /* Reset the I/O buffer states and pointers, the SCSI
2953 * state, and the exception. Then invoke the handler. */
2954 spin_lock_irq(&fsg->lock);
2956 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2957 bh = &fsg->buffhds[i];
2958 bh->state = BUF_STATE_EMPTY;
2960 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2963 exception_req_tag = fsg->exception_req_tag;
2964 new_config = fsg->new_config;
2965 old_state = fsg->state;
2967 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2968 fsg->state = FSG_STATE_STATUS_PHASE;
2970 for (i = 0; i < fsg->nluns; ++i) {
2971 curlun = &fsg->luns[i];
2972 curlun->prevent_medium_removal = 0;
2973 curlun->sense_data = curlun->unit_attention_data =
2975 curlun->sense_data_info = 0;
2976 curlun->info_valid = 0;
2978 fsg->state = FSG_STATE_IDLE;
2980 spin_unlock_irq(&fsg->lock);
2982 /* Carry out any extra actions required for the exception */
2983 switch (old_state) {
2987 case FSG_STATE_ABORT_BULK_OUT:
2989 spin_lock_irq(&fsg->lock);
2990 if (fsg->state == FSG_STATE_STATUS_PHASE)
2991 fsg->state = FSG_STATE_IDLE;
2992 spin_unlock_irq(&fsg->lock);
2995 case FSG_STATE_RESET:
2996 /* In case we were forced against our will to halt a
2997 * bulk endpoint, clear the halt now. (The SuperH UDC
2998 * requires this.) */
2999 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
3000 usb_ep_clear_halt(fsg->bulk_in);
3002 if (transport_is_bbb()) {
3003 if (fsg->ep0_req_tag == exception_req_tag)
3004 ep0_queue(fsg); // Complete the status stage
3006 } else if (transport_is_cbi())
3007 send_status(fsg); // Status by interrupt pipe
3009 /* Technically this should go here, but it would only be
3010 * a waste of time. Ditto for the INTERFACE_CHANGE and
3011 * CONFIG_CHANGE cases. */
3012 // for (i = 0; i < fsg->nluns; ++i)
3013 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3016 case FSG_STATE_INTERFACE_CHANGE:
3017 rc = do_set_interface(fsg, 0);
3018 if (fsg->ep0_req_tag != exception_req_tag)
3020 if (rc != 0) // STALL on errors
3021 fsg_set_halt(fsg, fsg->ep0);
3022 else // Complete the status stage
3026 case FSG_STATE_CONFIG_CHANGE:
3027 rc = do_set_config(fsg, new_config);
3028 if (fsg->ep0_req_tag != exception_req_tag)
3030 if (rc != 0) // STALL on errors
3031 fsg_set_halt(fsg, fsg->ep0);
3032 else // Complete the status stage
3036 case FSG_STATE_DISCONNECT:
3037 for (i = 0; i < fsg->nluns; ++i)
3038 fsg_lun_fsync_sub(fsg->luns + i);
3039 do_set_config(fsg, 0); // Unconfigured state
3042 case FSG_STATE_EXIT:
3043 case FSG_STATE_TERMINATED:
3044 do_set_config(fsg, 0); // Free resources
3045 spin_lock_irq(&fsg->lock);
3046 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3047 spin_unlock_irq(&fsg->lock);
3053 /*-------------------------------------------------------------------------*/
3055 static int fsg_main_thread(void *fsg_)
3057 struct fsg_dev *fsg = fsg_;
3059 /* Allow the thread to be killed by a signal, but set the signal mask
3060 * to block everything but INT, TERM, KILL, and USR1. */
3061 allow_signal(SIGINT);
3062 allow_signal(SIGTERM);
3063 allow_signal(SIGKILL);
3064 allow_signal(SIGUSR1);
3066 /* Allow the thread to be frozen */
3069 /* Arrange for userspace references to be interpreted as kernel
3070 * pointers. That way we can pass a kernel pointer to a routine
3071 * that expects a __user pointer and it will work okay. */
3075 while (fsg->state != FSG_STATE_TERMINATED) {
3076 if (exception_in_progress(fsg) || signal_pending(current)) {
3077 handle_exception(fsg);
3081 if (!fsg->running) {
3086 if (get_next_command(fsg))
3089 spin_lock_irq(&fsg->lock);
3090 if (!exception_in_progress(fsg))
3091 fsg->state = FSG_STATE_DATA_PHASE;
3092 spin_unlock_irq(&fsg->lock);
3094 if (do_scsi_command(fsg) || finish_reply(fsg))
3097 spin_lock_irq(&fsg->lock);
3098 if (!exception_in_progress(fsg))
3099 fsg->state = FSG_STATE_STATUS_PHASE;
3100 spin_unlock_irq(&fsg->lock);
3102 if (send_status(fsg))
3105 spin_lock_irq(&fsg->lock);
3106 if (!exception_in_progress(fsg))
3107 fsg->state = FSG_STATE_IDLE;
3108 spin_unlock_irq(&fsg->lock);
3111 spin_lock_irq(&fsg->lock);
3112 fsg->thread_task = NULL;
3113 spin_unlock_irq(&fsg->lock);
3115 /* If we are exiting because of a signal, unregister the
3117 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3118 usb_gadget_unregister_driver(&fsg_driver);
3120 /* Let the unbind and cleanup routines know the thread has exited */
3121 complete_and_exit(&fsg->thread_notifier, 0);
3125 /*-------------------------------------------------------------------------*/
3128 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3129 static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
3130 static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
3133 /*-------------------------------------------------------------------------*/
3135 static void fsg_release(struct kref *ref)
3137 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3143 static void lun_release(struct device *dev)
3145 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3146 struct fsg_dev *fsg =
3147 container_of(filesem, struct fsg_dev, filesem);
3149 kref_put(&fsg->ref, fsg_release);
3152 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
3154 struct fsg_dev *fsg = get_gadget_data(gadget);
3156 struct fsg_lun *curlun;
3157 struct usb_request *req = fsg->ep0req;
3159 DBG(fsg, "unbind\n");
3160 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3162 /* Unregister the sysfs attribute files and the LUNs */
3163 for (i = 0; i < fsg->nluns; ++i) {
3164 curlun = &fsg->luns[i];
3165 if (curlun->registered) {
3166 device_remove_file(&curlun->dev, &dev_attr_ro);
3167 device_remove_file(&curlun->dev, &dev_attr_file);
3168 fsg_lun_close(curlun);
3169 device_unregister(&curlun->dev);
3170 curlun->registered = 0;
3174 /* If the thread isn't already dead, tell it to exit now */
3175 if (fsg->state != FSG_STATE_TERMINATED) {
3176 raise_exception(fsg, FSG_STATE_EXIT);
3177 wait_for_completion(&fsg->thread_notifier);
3179 /* The cleanup routine waits for this completion also */
3180 complete(&fsg->thread_notifier);
3183 /* Free the data buffers */
3184 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
3185 kfree(fsg->buffhds[i].buf);
3187 /* Free the request and buffer for endpoint 0 */
3190 usb_ep_free_request(fsg->ep0, req);
3193 set_gadget_data(gadget, NULL);
3197 static int __init check_parameters(struct fsg_dev *fsg)
3202 /* Store the default values */
3203 mod_data.transport_type = USB_PR_BULK;
3204 mod_data.transport_name = "Bulk-only";
3205 mod_data.protocol_type = USB_SC_SCSI;
3206 mod_data.protocol_name = "Transparent SCSI";
3208 /* Some peripheral controllers are known not to be able to
3209 * halt bulk endpoints correctly. If one of them is present,
3212 if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
3213 mod_data.can_stall = 0;
3215 if (mod_data.release == 0xffff) { // Parameter wasn't set
3216 /* The sa1100 controller is not supported */
3217 if (gadget_is_sa1100(fsg->gadget))
3220 gcnum = usb_gadget_controller_number(fsg->gadget);
3222 mod_data.release = 0x0300 + gcnum;
3224 WARNING(fsg, "controller '%s' not recognized\n",
3226 mod_data.release = 0x0399;
3230 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3232 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3233 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3234 ; // Use default setting
3235 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3236 mod_data.transport_type = USB_PR_CB;
3237 mod_data.transport_name = "Control-Bulk";
3238 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3239 mod_data.transport_type = USB_PR_CBI;
3240 mod_data.transport_name = "Control-Bulk-Interrupt";
3242 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3246 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3247 prot == USB_SC_SCSI) {
3248 ; // Use default setting
3249 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3250 prot == USB_SC_RBC) {
3251 mod_data.protocol_type = USB_SC_RBC;
3252 mod_data.protocol_name = "RBC";
3253 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3254 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3255 prot == USB_SC_8020) {
3256 mod_data.protocol_type = USB_SC_8020;
3257 mod_data.protocol_name = "8020i (ATAPI)";
3258 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3259 prot == USB_SC_QIC) {
3260 mod_data.protocol_type = USB_SC_QIC;
3261 mod_data.protocol_name = "QIC-157";
3262 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3263 prot == USB_SC_UFI) {
3264 mod_data.protocol_type = USB_SC_UFI;
3265 mod_data.protocol_name = "UFI";
3266 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3267 prot == USB_SC_8070) {
3268 mod_data.protocol_type = USB_SC_8070;
3269 mod_data.protocol_name = "8070i";
3271 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3275 mod_data.buflen &= PAGE_CACHE_MASK;
3276 if (mod_data.buflen <= 0) {
3277 ERROR(fsg, "invalid buflen\n");
3280 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3286 static int __init fsg_bind(struct usb_gadget *gadget)
3288 struct fsg_dev *fsg = the_fsg;
3291 struct fsg_lun *curlun;
3293 struct usb_request *req;
3296 fsg->gadget = gadget;
3297 set_gadget_data(gadget, fsg);
3298 fsg->ep0 = gadget->ep0;
3299 fsg->ep0->driver_data = fsg;
3301 if ((rc = check_parameters(fsg)) != 0)
3304 if (mod_data.removable) { // Enable the store_xxx attributes
3305 dev_attr_file.attr.mode = 0644;
3306 dev_attr_file.store = fsg_store_file;
3307 if (!mod_data.cdrom) {
3308 dev_attr_ro.attr.mode = 0644;
3309 dev_attr_ro.store = fsg_store_ro;
3313 /* Find out how many LUNs there should be */
3316 i = max(mod_data.num_filenames, 1u);
3317 if (i > FSG_MAX_LUNS) {
3318 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3323 /* Create the LUNs, open their backing files, and register the
3324 * LUN devices in sysfs. */
3325 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
3332 for (i = 0; i < fsg->nluns; ++i) {
3333 curlun = &fsg->luns[i];
3334 curlun->cdrom = !!mod_data.cdrom;
3335 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3336 curlun->initially_ro = curlun->ro;
3337 curlun->removable = mod_data.removable;
3338 curlun->dev.release = lun_release;
3339 curlun->dev.parent = &gadget->dev;
3340 curlun->dev.driver = &fsg_driver.driver;
3341 dev_set_drvdata(&curlun->dev, &fsg->filesem);
3342 dev_set_name(&curlun->dev,"%s-lun%d",
3343 dev_name(&gadget->dev), i);
3345 if ((rc = device_register(&curlun->dev)) != 0) {
3346 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
3349 if ((rc = device_create_file(&curlun->dev,
3350 &dev_attr_ro)) != 0 ||
3351 (rc = device_create_file(&curlun->dev,
3352 &dev_attr_file)) != 0) {
3353 device_unregister(&curlun->dev);
3356 curlun->registered = 1;
3357 kref_get(&fsg->ref);
3359 if (mod_data.file[i] && *mod_data.file[i]) {
3360 if ((rc = fsg_lun_open(curlun,
3361 mod_data.file[i])) != 0)
3363 } else if (!mod_data.removable) {
3364 ERROR(fsg, "no file given for LUN%d\n", i);
3370 /* Find all the endpoints we will use */
3371 usb_ep_autoconfig_reset(gadget);
3372 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3375 ep->driver_data = fsg; // claim the endpoint
3378 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3381 ep->driver_data = fsg; // claim the endpoint
3384 if (transport_is_cbi()) {
3385 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
3388 ep->driver_data = fsg; // claim the endpoint
3392 /* Fix up the descriptors */
3393 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3394 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3395 device_desc.idProduct = cpu_to_le16(mod_data.product);
3396 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3398 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
3399 fsg_intf_desc.bNumEndpoints = i;
3400 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3401 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3402 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3404 if (gadget_is_dualspeed(gadget)) {
3405 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3407 /* Assume ep0 uses the same maxpacket value for both speeds */
3408 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3410 /* Assume endpoint addresses are the same for both speeds */
3411 fsg_hs_bulk_in_desc.bEndpointAddress =
3412 fsg_fs_bulk_in_desc.bEndpointAddress;
3413 fsg_hs_bulk_out_desc.bEndpointAddress =
3414 fsg_fs_bulk_out_desc.bEndpointAddress;
3415 fsg_hs_intr_in_desc.bEndpointAddress =
3416 fsg_fs_intr_in_desc.bEndpointAddress;
3419 if (gadget_is_otg(gadget))
3420 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
3424 /* Allocate the request and buffer for endpoint 0 */
3425 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3428 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
3431 req->complete = ep0_complete;
3433 /* Allocate the data buffers */
3434 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
3435 struct fsg_buffhd *bh = &fsg->buffhds[i];
3437 /* Allocate for the bulk-in endpoint. We assume that
3438 * the buffer will also work with the bulk-out (and
3439 * interrupt-in) endpoint. */
3440 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
3445 fsg->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3447 /* This should reflect the actual gadget power source */
3448 usb_gadget_set_selfpowered(gadget);
3450 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3452 init_utsname()->sysname, init_utsname()->release,
3455 /* On a real device, serial[] would be loaded from permanent
3456 * storage. We just encode it from the driver version string. */
3457 for (i = 0; i < sizeof fsg_string_serial - 2; i += 2) {
3458 unsigned char c = DRIVER_VERSION[i / 2];
3462 sprintf(&fsg_string_serial[i], "%02X", c);
3465 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3466 "file-storage-gadget");
3467 if (IS_ERR(fsg->thread_task)) {
3468 rc = PTR_ERR(fsg->thread_task);
3472 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3473 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3475 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3476 for (i = 0; i < fsg->nluns; ++i) {
3477 curlun = &fsg->luns[i];
3478 if (fsg_lun_is_open(curlun)) {
3481 p = d_path(&curlun->filp->f_path,
3486 LINFO(curlun, "ro=%d, file: %s\n",
3487 curlun->ro, (p ? p : "(error)"));
3492 DBG(fsg, "transport=%s (x%02x)\n",
3493 mod_data.transport_name, mod_data.transport_type);
3494 DBG(fsg, "protocol=%s (x%02x)\n",
3495 mod_data.protocol_name, mod_data.protocol_type);
3496 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3497 mod_data.vendor, mod_data.product, mod_data.release);
3498 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3499 mod_data.removable, mod_data.can_stall,
3500 mod_data.cdrom, mod_data.buflen);
3501 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
3503 set_bit(REGISTERED, &fsg->atomic_bitflags);
3505 /* Tell the thread to start working */
3506 wake_up_process(fsg->thread_task);
3510 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3514 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3516 complete(&fsg->thread_notifier);
3521 /*-------------------------------------------------------------------------*/
3523 static void fsg_suspend(struct usb_gadget *gadget)
3525 struct fsg_dev *fsg = get_gadget_data(gadget);
3527 DBG(fsg, "suspend\n");
3528 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3531 static void fsg_resume(struct usb_gadget *gadget)
3533 struct fsg_dev *fsg = get_gadget_data(gadget);
3535 DBG(fsg, "resume\n");
3536 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3540 /*-------------------------------------------------------------------------*/
3542 static struct usb_gadget_driver fsg_driver = {
3543 #ifdef CONFIG_USB_GADGET_DUALSPEED
3544 .speed = USB_SPEED_HIGH,
3546 .speed = USB_SPEED_FULL,
3548 .function = (char *) fsg_string_product,
3550 .unbind = fsg_unbind,
3551 .disconnect = fsg_disconnect,
3553 .suspend = fsg_suspend,
3554 .resume = fsg_resume,
3557 .name = DRIVER_NAME,
3558 .owner = THIS_MODULE,
3566 static int __init fsg_alloc(void)
3568 struct fsg_dev *fsg;
3570 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3573 spin_lock_init(&fsg->lock);
3574 init_rwsem(&fsg->filesem);
3575 kref_init(&fsg->ref);
3576 init_completion(&fsg->thread_notifier);
3583 static int __init fsg_init(void)
3586 struct fsg_dev *fsg;
3588 if ((rc = fsg_alloc()) != 0)
3591 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
3592 kref_put(&fsg->ref, fsg_release);
3595 module_init(fsg_init);
3598 static void __exit fsg_cleanup(void)
3600 struct fsg_dev *fsg = the_fsg;
3602 /* Unregister the driver iff the thread hasn't already done so */
3603 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3604 usb_gadget_unregister_driver(&fsg_driver);
3606 /* Wait for the thread to finish up */
3607 wait_for_completion(&fsg->thread_notifier);
3609 kref_put(&fsg->ref, fsg_release);
3611 module_exit(fsg_cleanup);