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";
281 MODULE_DESCRIPTION(DRIVER_DESC);
282 MODULE_AUTHOR("Alan Stern");
283 MODULE_LICENSE("Dual BSD/GPL");
285 /* Thanks to NetChip Technologies for donating this product ID.
287 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
288 * Instead: allocate your own, using normal USB-IF procedures. */
289 #define FSG_VENDOR_ID 0x0525 // NetChip
290 #define FSG_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
294 * This driver assumes self-powered hardware and has no way for users to
295 * trigger remote wakeup. It uses autoconfiguration to select endpoints
296 * and endpoint addresses.
300 /*-------------------------------------------------------------------------*/
303 /* Encapsulate the module parameter settings */
305 #define FSG_MAX_LUNS 8
308 char *file[FSG_MAX_LUNS];
309 int ro[FSG_MAX_LUNS];
310 unsigned int num_filenames;
311 unsigned int num_ros;
318 char *transport_parm;
320 unsigned short vendor;
321 unsigned short product;
322 unsigned short release;
326 char *transport_name;
330 } mod_data = { // Default values
331 .transport_parm = "BBB",
332 .protocol_parm = "SCSI",
336 .vendor = FSG_VENDOR_ID,
337 .product = FSG_PRODUCT_ID,
338 .release = 0xffff, // Use controller chip type
343 module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
345 MODULE_PARM_DESC(file, "names of backing files or devices");
347 module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
348 MODULE_PARM_DESC(ro, "true to force read-only");
350 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
351 MODULE_PARM_DESC(luns, "number of LUNs");
353 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
354 MODULE_PARM_DESC(removable, "true to simulate removable media");
356 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
357 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
359 module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
360 MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
363 /* In the non-TEST version, only the module parameters listed above
365 #ifdef CONFIG_USB_FILE_STORAGE_TEST
367 module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
368 MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
370 module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
371 MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
374 module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
375 MODULE_PARM_DESC(vendor, "USB Vendor ID");
377 module_param_named(product, mod_data.product, ushort, S_IRUGO);
378 MODULE_PARM_DESC(product, "USB Product ID");
380 module_param_named(release, mod_data.release, ushort, S_IRUGO);
381 MODULE_PARM_DESC(release, "USB release number");
383 module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
384 MODULE_PARM_DESC(buflen, "I/O buffer size");
386 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
390 * These definitions will permit the compiler to avoid generating code for
391 * parts of the driver that aren't used in the non-TEST version. Even gcc
392 * can recognize when a test of a constant expression yields a dead code
396 #ifdef CONFIG_USB_FILE_STORAGE_TEST
398 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
399 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
400 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
404 #define transport_is_bbb() 1
405 #define transport_is_cbi() 0
406 #define protocol_is_scsi() 1
408 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
411 /*-------------------------------------------------------------------------*/
413 #include "storage_common.c"
415 /*-------------------------------------------------------------------------*/
419 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
421 struct usb_gadget *gadget;
423 /* filesem protects: backing files in use */
424 struct rw_semaphore filesem;
426 /* reference counting: wait until all LUNs are released */
429 struct usb_ep *ep0; // Handy copy of gadget->ep0
430 struct usb_request *ep0req; // For control responses
431 unsigned int ep0_req_tag;
432 const char *ep0req_name;
434 struct usb_request *intreq; // For interrupt responses
436 struct fsg_buffhd *intr_buffhd;
438 unsigned int bulk_out_maxpacket;
439 enum fsg_state state; // For exception handling
440 unsigned int exception_req_tag;
442 u8 config, new_config;
444 unsigned int running : 1;
445 unsigned int bulk_in_enabled : 1;
446 unsigned int bulk_out_enabled : 1;
447 unsigned int intr_in_enabled : 1;
448 unsigned int phase_error : 1;
449 unsigned int short_packet_received : 1;
450 unsigned int bad_lun_okay : 1;
452 unsigned long atomic_bitflags;
454 #define IGNORE_BULK_OUT 1
457 struct usb_ep *bulk_in;
458 struct usb_ep *bulk_out;
459 struct usb_ep *intr_in;
461 struct fsg_buffhd *next_buffhd_to_fill;
462 struct fsg_buffhd *next_buffhd_to_drain;
463 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
465 int thread_wakeup_needed;
466 struct completion thread_notifier;
467 struct task_struct *thread_task;
470 u8 cmnd[MAX_COMMAND_SIZE];
471 enum data_direction data_dir;
473 u32 data_size_from_cmnd;
479 /* The CB protocol offers no way for a host to know when a command
480 * has completed. As a result the next command may arrive early,
481 * and we will still have to handle it. For that reason we need
482 * a buffer to store new commands when using CB (or CBI, which
483 * does not oblige a host to wait for command completion either). */
485 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
488 struct fsg_lun *luns;
489 struct fsg_lun *curlun;
492 typedef void (*fsg_routine_t)(struct fsg_dev *);
494 static int exception_in_progress(struct fsg_dev *fsg)
496 return (fsg->state > FSG_STATE_IDLE);
499 /* Make bulk-out requests be divisible by the maxpacket size */
500 static void set_bulk_out_req_length(struct fsg_dev *fsg,
501 struct fsg_buffhd *bh, unsigned int length)
505 bh->bulk_out_intended_length = length;
506 rem = length % fsg->bulk_out_maxpacket;
508 length += fsg->bulk_out_maxpacket - rem;
509 bh->outreq->length = length;
512 static struct fsg_dev *the_fsg;
513 static struct usb_gadget_driver fsg_driver;
516 /*-------------------------------------------------------------------------*/
518 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
522 if (ep == fsg->bulk_in)
524 else if (ep == fsg->bulk_out)
528 DBG(fsg, "%s set halt\n", name);
529 return usb_ep_set_halt(ep);
533 /*-------------------------------------------------------------------------*/
536 * DESCRIPTORS ... most are static, but strings and (full) configuration
537 * descriptors are built on demand. Also the (static) config and interface
538 * descriptors are adjusted during fsg_bind().
541 /* There is only one configuration. */
542 #define CONFIG_VALUE 1
544 static struct usb_device_descriptor
546 .bLength = sizeof device_desc,
547 .bDescriptorType = USB_DT_DEVICE,
549 .bcdUSB = cpu_to_le16(0x0200),
550 .bDeviceClass = USB_CLASS_PER_INTERFACE,
552 /* The next three values can be overridden by module parameters */
553 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
554 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
555 .bcdDevice = cpu_to_le16(0xffff),
557 .iManufacturer = FSG_STRING_MANUFACTURER,
558 .iProduct = FSG_STRING_PRODUCT,
559 .iSerialNumber = FSG_STRING_SERIAL,
560 .bNumConfigurations = 1,
563 static struct usb_config_descriptor
565 .bLength = sizeof config_desc,
566 .bDescriptorType = USB_DT_CONFIG,
568 /* wTotalLength computed by usb_gadget_config_buf() */
570 .bConfigurationValue = CONFIG_VALUE,
571 .iConfiguration = FSG_STRING_CONFIG,
572 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
573 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
577 static struct usb_qualifier_descriptor
579 .bLength = sizeof dev_qualifier,
580 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
582 .bcdUSB = cpu_to_le16(0x0200),
583 .bDeviceClass = USB_CLASS_PER_INTERFACE,
585 .bNumConfigurations = 1,
591 * Config descriptors must agree with the code that sets configurations
592 * and with code managing interfaces and their altsettings. They must
593 * also handle different speeds and other-speed requests.
595 static int populate_config_buf(struct usb_gadget *gadget,
596 u8 *buf, u8 type, unsigned index)
598 enum usb_device_speed speed = gadget->speed;
600 const struct usb_descriptor_header **function;
605 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
606 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
607 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
608 function = fsg_hs_function;
610 function = fsg_fs_function;
612 /* for now, don't advertise srp-only devices */
613 if (!gadget_is_otg(gadget))
616 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
617 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
622 /*-------------------------------------------------------------------------*/
624 /* These routines may be called in process context or in_irq */
626 /* Caller must hold fsg->lock */
627 static void wakeup_thread(struct fsg_dev *fsg)
629 /* Tell the main thread that something has happened */
630 fsg->thread_wakeup_needed = 1;
631 if (fsg->thread_task)
632 wake_up_process(fsg->thread_task);
636 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
640 /* Do nothing if a higher-priority exception is already in progress.
641 * If a lower-or-equal priority exception is in progress, preempt it
642 * and notify the main thread by sending it a signal. */
643 spin_lock_irqsave(&fsg->lock, flags);
644 if (fsg->state <= new_state) {
645 fsg->exception_req_tag = fsg->ep0_req_tag;
646 fsg->state = new_state;
647 if (fsg->thread_task)
648 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
651 spin_unlock_irqrestore(&fsg->lock, flags);
655 /*-------------------------------------------------------------------------*/
657 /* The disconnect callback and ep0 routines. These always run in_irq,
658 * except that ep0_queue() is called in the main thread to acknowledge
659 * completion of various requests: set config, set interface, and
660 * Bulk-only device reset. */
662 static void fsg_disconnect(struct usb_gadget *gadget)
664 struct fsg_dev *fsg = get_gadget_data(gadget);
666 DBG(fsg, "disconnect or port reset\n");
667 raise_exception(fsg, FSG_STATE_DISCONNECT);
671 static int ep0_queue(struct fsg_dev *fsg)
675 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
676 if (rc != 0 && rc != -ESHUTDOWN) {
678 /* We can't do much more than wait for a reset */
679 WARNING(fsg, "error in submission: %s --> %d\n",
685 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
687 struct fsg_dev *fsg = ep->driver_data;
690 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
691 if (req->status || req->actual != req->length)
692 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
693 req->status, req->actual, req->length);
694 if (req->status == -ECONNRESET) // Request was cancelled
695 usb_ep_fifo_flush(ep);
697 if (req->status == 0 && req->context)
698 ((fsg_routine_t) (req->context))(fsg);
702 /*-------------------------------------------------------------------------*/
704 /* Bulk and interrupt endpoint completion handlers.
705 * These always run in_irq. */
707 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
709 struct fsg_dev *fsg = ep->driver_data;
710 struct fsg_buffhd *bh = req->context;
712 if (req->status || req->actual != req->length)
713 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
714 req->status, req->actual, req->length);
715 if (req->status == -ECONNRESET) // Request was cancelled
716 usb_ep_fifo_flush(ep);
718 /* Hold the lock while we update the request and buffer states */
720 spin_lock(&fsg->lock);
722 bh->state = BUF_STATE_EMPTY;
724 spin_unlock(&fsg->lock);
727 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
729 struct fsg_dev *fsg = ep->driver_data;
730 struct fsg_buffhd *bh = req->context;
732 dump_msg(fsg, "bulk-out", req->buf, req->actual);
733 if (req->status || req->actual != bh->bulk_out_intended_length)
734 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
735 req->status, req->actual,
736 bh->bulk_out_intended_length);
737 if (req->status == -ECONNRESET) // Request was cancelled
738 usb_ep_fifo_flush(ep);
740 /* Hold the lock while we update the request and buffer states */
742 spin_lock(&fsg->lock);
744 bh->state = BUF_STATE_FULL;
746 spin_unlock(&fsg->lock);
750 #ifdef CONFIG_USB_FILE_STORAGE_TEST
751 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
753 struct fsg_dev *fsg = ep->driver_data;
754 struct fsg_buffhd *bh = req->context;
756 if (req->status || req->actual != req->length)
757 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
758 req->status, req->actual, req->length);
759 if (req->status == -ECONNRESET) // Request was cancelled
760 usb_ep_fifo_flush(ep);
762 /* Hold the lock while we update the request and buffer states */
764 spin_lock(&fsg->lock);
765 fsg->intreq_busy = 0;
766 bh->state = BUF_STATE_EMPTY;
768 spin_unlock(&fsg->lock);
772 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
774 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
777 /*-------------------------------------------------------------------------*/
779 /* Ep0 class-specific handlers. These always run in_irq. */
781 #ifdef CONFIG_USB_FILE_STORAGE_TEST
782 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
784 struct usb_request *req = fsg->ep0req;
785 static u8 cbi_reset_cmnd[6] = {
786 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
788 /* Error in command transfer? */
789 if (req->status || req->length != req->actual ||
790 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
792 /* Not all controllers allow a protocol stall after
793 * receiving control-out data, but we'll try anyway. */
794 fsg_set_halt(fsg, fsg->ep0);
795 return; // Wait for reset
798 /* Is it the special reset command? */
799 if (req->actual >= sizeof cbi_reset_cmnd &&
800 memcmp(req->buf, cbi_reset_cmnd,
801 sizeof cbi_reset_cmnd) == 0) {
803 /* Raise an exception to stop the current operation
804 * and reinitialize our state. */
805 DBG(fsg, "cbi reset request\n");
806 raise_exception(fsg, FSG_STATE_RESET);
810 VDBG(fsg, "CB[I] accept device-specific command\n");
811 spin_lock(&fsg->lock);
813 /* Save the command for later */
814 if (fsg->cbbuf_cmnd_size)
815 WARNING(fsg, "CB[I] overwriting previous command\n");
816 fsg->cbbuf_cmnd_size = req->actual;
817 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
820 spin_unlock(&fsg->lock);
824 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
826 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
829 static int class_setup_req(struct fsg_dev *fsg,
830 const struct usb_ctrlrequest *ctrl)
832 struct usb_request *req = fsg->ep0req;
833 int value = -EOPNOTSUPP;
834 u16 w_index = le16_to_cpu(ctrl->wIndex);
835 u16 w_value = le16_to_cpu(ctrl->wValue);
836 u16 w_length = le16_to_cpu(ctrl->wLength);
841 /* Handle Bulk-only class-specific requests */
842 if (transport_is_bbb()) {
843 switch (ctrl->bRequest) {
845 case USB_BULK_RESET_REQUEST:
846 if (ctrl->bRequestType != (USB_DIR_OUT |
847 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
849 if (w_index != 0 || w_value != 0) {
854 /* Raise an exception to stop the current operation
855 * and reinitialize our state. */
856 DBG(fsg, "bulk reset request\n");
857 raise_exception(fsg, FSG_STATE_RESET);
858 value = DELAYED_STATUS;
861 case USB_BULK_GET_MAX_LUN_REQUEST:
862 if (ctrl->bRequestType != (USB_DIR_IN |
863 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
865 if (w_index != 0 || w_value != 0) {
869 VDBG(fsg, "get max LUN\n");
870 *(u8 *) req->buf = fsg->nluns - 1;
876 /* Handle CBI class-specific requests */
878 switch (ctrl->bRequest) {
880 case USB_CBI_ADSC_REQUEST:
881 if (ctrl->bRequestType != (USB_DIR_OUT |
882 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
884 if (w_index != 0 || w_value != 0) {
888 if (w_length > MAX_COMMAND_SIZE) {
893 fsg->ep0req->context = received_cbi_adsc;
898 if (value == -EOPNOTSUPP)
900 "unknown class-specific control req "
901 "%02x.%02x v%04x i%04x l%u\n",
902 ctrl->bRequestType, ctrl->bRequest,
903 le16_to_cpu(ctrl->wValue), w_index, w_length);
908 /*-------------------------------------------------------------------------*/
910 /* Ep0 standard request handlers. These always run in_irq. */
912 static int standard_setup_req(struct fsg_dev *fsg,
913 const struct usb_ctrlrequest *ctrl)
915 struct usb_request *req = fsg->ep0req;
916 int value = -EOPNOTSUPP;
917 u16 w_index = le16_to_cpu(ctrl->wIndex);
918 u16 w_value = le16_to_cpu(ctrl->wValue);
920 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
921 * but config change events will also reconfigure hardware. */
922 switch (ctrl->bRequest) {
924 case USB_REQ_GET_DESCRIPTOR:
925 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
928 switch (w_value >> 8) {
931 VDBG(fsg, "get device descriptor\n");
932 value = sizeof device_desc;
933 memcpy(req->buf, &device_desc, value);
935 case USB_DT_DEVICE_QUALIFIER:
936 VDBG(fsg, "get device qualifier\n");
937 if (!gadget_is_dualspeed(fsg->gadget))
939 value = sizeof dev_qualifier;
940 memcpy(req->buf, &dev_qualifier, value);
943 case USB_DT_OTHER_SPEED_CONFIG:
944 VDBG(fsg, "get other-speed config descriptor\n");
945 if (!gadget_is_dualspeed(fsg->gadget))
949 VDBG(fsg, "get configuration descriptor\n");
951 value = populate_config_buf(fsg->gadget,
958 VDBG(fsg, "get string descriptor\n");
960 /* wIndex == language code */
961 value = usb_gadget_get_string(&fsg_stringtab,
962 w_value & 0xff, req->buf);
967 /* One config, two speeds */
968 case USB_REQ_SET_CONFIGURATION:
969 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
972 VDBG(fsg, "set configuration\n");
973 if (w_value == CONFIG_VALUE || w_value == 0) {
974 fsg->new_config = w_value;
976 /* Raise an exception to wipe out previous transaction
977 * state (queued bufs, etc) and set the new config. */
978 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
979 value = DELAYED_STATUS;
982 case USB_REQ_GET_CONFIGURATION:
983 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
986 VDBG(fsg, "get configuration\n");
987 *(u8 *) req->buf = fsg->config;
991 case USB_REQ_SET_INTERFACE:
992 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
993 USB_RECIP_INTERFACE))
995 if (fsg->config && w_index == 0) {
997 /* Raise an exception to wipe out previous transaction
998 * state (queued bufs, etc) and install the new
999 * interface altsetting. */
1000 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1001 value = DELAYED_STATUS;
1004 case USB_REQ_GET_INTERFACE:
1005 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1006 USB_RECIP_INTERFACE))
1014 VDBG(fsg, "get interface\n");
1015 *(u8 *) req->buf = 0;
1021 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1022 ctrl->bRequestType, ctrl->bRequest,
1023 w_value, w_index, le16_to_cpu(ctrl->wLength));
1030 static int fsg_setup(struct usb_gadget *gadget,
1031 const struct usb_ctrlrequest *ctrl)
1033 struct fsg_dev *fsg = get_gadget_data(gadget);
1035 int w_length = le16_to_cpu(ctrl->wLength);
1037 ++fsg->ep0_req_tag; // Record arrival of a new request
1038 fsg->ep0req->context = NULL;
1039 fsg->ep0req->length = 0;
1040 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1042 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1043 rc = class_setup_req(fsg, ctrl);
1045 rc = standard_setup_req(fsg, ctrl);
1047 /* Respond with data/status or defer until later? */
1048 if (rc >= 0 && rc != DELAYED_STATUS) {
1049 rc = min(rc, w_length);
1050 fsg->ep0req->length = rc;
1051 fsg->ep0req->zero = rc < w_length;
1052 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1053 "ep0-in" : "ep0-out");
1054 rc = ep0_queue(fsg);
1057 /* Device either stalls (rc < 0) or reports success */
1062 /*-------------------------------------------------------------------------*/
1064 /* All the following routines run in process context */
1067 /* Use this for bulk or interrupt transfers, not ep0 */
1068 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1069 struct usb_request *req, int *pbusy,
1070 enum fsg_buffer_state *state)
1074 if (ep == fsg->bulk_in)
1075 dump_msg(fsg, "bulk-in", req->buf, req->length);
1076 else if (ep == fsg->intr_in)
1077 dump_msg(fsg, "intr-in", req->buf, req->length);
1079 spin_lock_irq(&fsg->lock);
1081 *state = BUF_STATE_BUSY;
1082 spin_unlock_irq(&fsg->lock);
1083 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1086 *state = BUF_STATE_EMPTY;
1088 /* We can't do much more than wait for a reset */
1090 /* Note: currently the net2280 driver fails zero-length
1091 * submissions if DMA is enabled. */
1092 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1094 WARNING(fsg, "error in submission: %s --> %d\n",
1100 static int sleep_thread(struct fsg_dev *fsg)
1104 /* Wait until a signal arrives or we are woken up */
1107 set_current_state(TASK_INTERRUPTIBLE);
1108 if (signal_pending(current)) {
1112 if (fsg->thread_wakeup_needed)
1116 __set_current_state(TASK_RUNNING);
1117 fsg->thread_wakeup_needed = 0;
1122 /*-------------------------------------------------------------------------*/
1124 static int do_read(struct fsg_dev *fsg)
1126 struct fsg_lun *curlun = fsg->curlun;
1128 struct fsg_buffhd *bh;
1131 loff_t file_offset, file_offset_tmp;
1132 unsigned int amount;
1133 unsigned int partial_page;
1136 /* Get the starting Logical Block Address and check that it's
1138 if (fsg->cmnd[0] == SC_READ_6)
1139 lba = get_unaligned_be24(&fsg->cmnd[1]);
1141 lba = get_unaligned_be32(&fsg->cmnd[2]);
1143 /* We allow DPO (Disable Page Out = don't save data in the
1144 * cache) and FUA (Force Unit Access = don't read from the
1145 * cache), but we don't implement them. */
1146 if ((fsg->cmnd[1] & ~0x18) != 0) {
1147 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1151 if (lba >= curlun->num_sectors) {
1152 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1155 file_offset = ((loff_t) lba) << 9;
1157 /* Carry out the file reads */
1158 amount_left = fsg->data_size_from_cmnd;
1159 if (unlikely(amount_left == 0))
1160 return -EIO; // No default reply
1164 /* Figure out how much we need to read:
1165 * Try to read the remaining amount.
1166 * But don't read more than the buffer size.
1167 * And don't try to read past the end of the file.
1168 * Finally, if we're not at a page boundary, don't read past
1170 * If this means reading 0 then we were asked to read past
1171 * the end of file. */
1172 amount = min((unsigned int) amount_left, mod_data.buflen);
1173 amount = min((loff_t) amount,
1174 curlun->file_length - file_offset);
1175 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1176 if (partial_page > 0)
1177 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1180 /* Wait for the next buffer to become available */
1181 bh = fsg->next_buffhd_to_fill;
1182 while (bh->state != BUF_STATE_EMPTY) {
1183 rc = sleep_thread(fsg);
1188 /* If we were asked to read past the end of file,
1189 * end with an empty buffer. */
1191 curlun->sense_data =
1192 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1193 curlun->sense_data_info = file_offset >> 9;
1194 curlun->info_valid = 1;
1195 bh->inreq->length = 0;
1196 bh->state = BUF_STATE_FULL;
1200 /* Perform the read */
1201 file_offset_tmp = file_offset;
1202 nread = vfs_read(curlun->filp,
1203 (char __user *) bh->buf,
1204 amount, &file_offset_tmp);
1205 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1206 (unsigned long long) file_offset,
1208 if (signal_pending(current))
1212 LDBG(curlun, "error in file read: %d\n",
1215 } else if (nread < amount) {
1216 LDBG(curlun, "partial file read: %d/%u\n",
1217 (int) nread, amount);
1218 nread -= (nread & 511); // Round down to a block
1220 file_offset += nread;
1221 amount_left -= nread;
1222 fsg->residue -= nread;
1223 bh->inreq->length = nread;
1224 bh->state = BUF_STATE_FULL;
1226 /* If an error occurred, report it and its position */
1227 if (nread < amount) {
1228 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1229 curlun->sense_data_info = file_offset >> 9;
1230 curlun->info_valid = 1;
1234 if (amount_left == 0)
1235 break; // No more left to read
1237 /* Send this buffer and go read some more */
1238 bh->inreq->zero = 0;
1239 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1240 &bh->inreq_busy, &bh->state);
1241 fsg->next_buffhd_to_fill = bh->next;
1244 return -EIO; // No default reply
1248 /*-------------------------------------------------------------------------*/
1250 static int do_write(struct fsg_dev *fsg)
1252 struct fsg_lun *curlun = fsg->curlun;
1254 struct fsg_buffhd *bh;
1256 u32 amount_left_to_req, amount_left_to_write;
1257 loff_t usb_offset, file_offset, file_offset_tmp;
1258 unsigned int amount;
1259 unsigned int partial_page;
1264 curlun->sense_data = SS_WRITE_PROTECTED;
1267 spin_lock(&curlun->filp->f_lock);
1268 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1269 spin_unlock(&curlun->filp->f_lock);
1271 /* Get the starting Logical Block Address and check that it's
1273 if (fsg->cmnd[0] == SC_WRITE_6)
1274 lba = get_unaligned_be24(&fsg->cmnd[1]);
1276 lba = get_unaligned_be32(&fsg->cmnd[2]);
1278 /* We allow DPO (Disable Page Out = don't save data in the
1279 * cache) and FUA (Force Unit Access = write directly to the
1280 * medium). We don't implement DPO; we implement FUA by
1281 * performing synchronous output. */
1282 if ((fsg->cmnd[1] & ~0x18) != 0) {
1283 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1286 if (fsg->cmnd[1] & 0x08) { // FUA
1287 spin_lock(&curlun->filp->f_lock);
1288 curlun->filp->f_flags |= O_SYNC;
1289 spin_unlock(&curlun->filp->f_lock);
1292 if (lba >= curlun->num_sectors) {
1293 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1297 /* Carry out the file writes */
1299 file_offset = usb_offset = ((loff_t) lba) << 9;
1300 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1302 while (amount_left_to_write > 0) {
1304 /* Queue a request for more data from the host */
1305 bh = fsg->next_buffhd_to_fill;
1306 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1308 /* Figure out how much we want to get:
1309 * Try to get the remaining amount.
1310 * But don't get more than the buffer size.
1311 * And don't try to go past the end of the file.
1312 * If we're not at a page boundary,
1313 * don't go past the next page.
1314 * If this means getting 0, then we were asked
1315 * to write past the end of file.
1316 * Finally, round down to a block boundary. */
1317 amount = min(amount_left_to_req, mod_data.buflen);
1318 amount = min((loff_t) amount, curlun->file_length -
1320 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1321 if (partial_page > 0)
1322 amount = min(amount,
1323 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1327 curlun->sense_data =
1328 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1329 curlun->sense_data_info = usb_offset >> 9;
1330 curlun->info_valid = 1;
1333 amount -= (amount & 511);
1336 /* Why were we were asked to transfer a
1342 /* Get the next buffer */
1343 usb_offset += amount;
1344 fsg->usb_amount_left -= amount;
1345 amount_left_to_req -= amount;
1346 if (amount_left_to_req == 0)
1349 /* amount is always divisible by 512, hence by
1350 * the bulk-out maxpacket size */
1351 bh->outreq->length = bh->bulk_out_intended_length =
1353 bh->outreq->short_not_ok = 1;
1354 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1355 &bh->outreq_busy, &bh->state);
1356 fsg->next_buffhd_to_fill = bh->next;
1360 /* Write the received data to the backing file */
1361 bh = fsg->next_buffhd_to_drain;
1362 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1363 break; // We stopped early
1364 if (bh->state == BUF_STATE_FULL) {
1366 fsg->next_buffhd_to_drain = bh->next;
1367 bh->state = BUF_STATE_EMPTY;
1369 /* Did something go wrong with the transfer? */
1370 if (bh->outreq->status != 0) {
1371 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1372 curlun->sense_data_info = file_offset >> 9;
1373 curlun->info_valid = 1;
1377 amount = bh->outreq->actual;
1378 if (curlun->file_length - file_offset < amount) {
1380 "write %u @ %llu beyond end %llu\n",
1381 amount, (unsigned long long) file_offset,
1382 (unsigned long long) curlun->file_length);
1383 amount = curlun->file_length - file_offset;
1386 /* Perform the write */
1387 file_offset_tmp = file_offset;
1388 nwritten = vfs_write(curlun->filp,
1389 (char __user *) bh->buf,
1390 amount, &file_offset_tmp);
1391 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1392 (unsigned long long) file_offset,
1394 if (signal_pending(current))
1395 return -EINTR; // Interrupted!
1398 LDBG(curlun, "error in file write: %d\n",
1401 } else if (nwritten < amount) {
1402 LDBG(curlun, "partial file write: %d/%u\n",
1403 (int) nwritten, amount);
1404 nwritten -= (nwritten & 511);
1405 // Round down to a block
1407 file_offset += nwritten;
1408 amount_left_to_write -= nwritten;
1409 fsg->residue -= nwritten;
1411 /* If an error occurred, report it and its position */
1412 if (nwritten < amount) {
1413 curlun->sense_data = SS_WRITE_ERROR;
1414 curlun->sense_data_info = file_offset >> 9;
1415 curlun->info_valid = 1;
1419 /* Did the host decide to stop early? */
1420 if (bh->outreq->actual != bh->outreq->length) {
1421 fsg->short_packet_received = 1;
1427 /* Wait for something to happen */
1428 rc = sleep_thread(fsg);
1433 return -EIO; // No default reply
1437 /*-------------------------------------------------------------------------*/
1439 static int do_synchronize_cache(struct fsg_dev *fsg)
1441 struct fsg_lun *curlun = fsg->curlun;
1444 /* We ignore the requested LBA and write out all file's
1445 * dirty data buffers. */
1446 rc = fsg_lun_fsync_sub(curlun);
1448 curlun->sense_data = SS_WRITE_ERROR;
1453 /*-------------------------------------------------------------------------*/
1455 static void invalidate_sub(struct fsg_lun *curlun)
1457 struct file *filp = curlun->filp;
1458 struct inode *inode = filp->f_path.dentry->d_inode;
1461 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1462 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1465 static int do_verify(struct fsg_dev *fsg)
1467 struct fsg_lun *curlun = fsg->curlun;
1469 u32 verification_length;
1470 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1471 loff_t file_offset, file_offset_tmp;
1473 unsigned int amount;
1476 /* Get the starting Logical Block Address and check that it's
1478 lba = get_unaligned_be32(&fsg->cmnd[2]);
1479 if (lba >= curlun->num_sectors) {
1480 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1484 /* We allow DPO (Disable Page Out = don't save data in the
1485 * cache) but we don't implement it. */
1486 if ((fsg->cmnd[1] & ~0x10) != 0) {
1487 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1491 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
1492 if (unlikely(verification_length == 0))
1493 return -EIO; // No default reply
1495 /* Prepare to carry out the file verify */
1496 amount_left = verification_length << 9;
1497 file_offset = ((loff_t) lba) << 9;
1499 /* Write out all the dirty buffers before invalidating them */
1500 fsg_lun_fsync_sub(curlun);
1501 if (signal_pending(current))
1504 invalidate_sub(curlun);
1505 if (signal_pending(current))
1508 /* Just try to read the requested blocks */
1509 while (amount_left > 0) {
1511 /* Figure out how much we need to read:
1512 * Try to read the remaining amount, but not more than
1514 * And don't try to read past the end of the file.
1515 * If this means reading 0 then we were asked to read
1516 * past the end of file. */
1517 amount = min((unsigned int) amount_left, mod_data.buflen);
1518 amount = min((loff_t) amount,
1519 curlun->file_length - file_offset);
1521 curlun->sense_data =
1522 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1523 curlun->sense_data_info = file_offset >> 9;
1524 curlun->info_valid = 1;
1528 /* Perform the read */
1529 file_offset_tmp = file_offset;
1530 nread = vfs_read(curlun->filp,
1531 (char __user *) bh->buf,
1532 amount, &file_offset_tmp);
1533 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1534 (unsigned long long) file_offset,
1536 if (signal_pending(current))
1540 LDBG(curlun, "error in file verify: %d\n",
1543 } else if (nread < amount) {
1544 LDBG(curlun, "partial file verify: %d/%u\n",
1545 (int) nread, amount);
1546 nread -= (nread & 511); // Round down to a sector
1549 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1550 curlun->sense_data_info = file_offset >> 9;
1551 curlun->info_valid = 1;
1554 file_offset += nread;
1555 amount_left -= nread;
1561 /*-------------------------------------------------------------------------*/
1563 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1565 u8 *buf = (u8 *) bh->buf;
1567 static char vendor_id[] = "Linux ";
1568 static char product_disk_id[] = "File-Stor Gadget";
1569 static char product_cdrom_id[] = "File-CD Gadget ";
1571 if (!fsg->curlun) { // Unsupported LUNs are okay
1572 fsg->bad_lun_okay = 1;
1574 buf[0] = 0x7f; // Unsupported, no device-type
1575 buf[4] = 31; // Additional length
1580 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
1581 if (mod_data.removable)
1583 buf[2] = 2; // ANSI SCSI level 2
1584 buf[3] = 2; // SCSI-2 INQUIRY data format
1585 buf[4] = 31; // Additional length
1586 // No special options
1587 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1588 (mod_data.cdrom ? product_cdrom_id :
1595 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1597 struct fsg_lun *curlun = fsg->curlun;
1598 u8 *buf = (u8 *) bh->buf;
1603 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1605 * If a REQUEST SENSE command is received from an initiator
1606 * with a pending unit attention condition (before the target
1607 * generates the contingent allegiance condition), then the
1608 * target shall either:
1609 * a) report any pending sense data and preserve the unit
1610 * attention condition on the logical unit, or,
1611 * b) report the unit attention condition, may discard any
1612 * pending sense data, and clear the unit attention
1613 * condition on the logical unit for that initiator.
1615 * FSG normally uses option a); enable this code to use option b).
1618 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1619 curlun->sense_data = curlun->unit_attention_data;
1620 curlun->unit_attention_data = SS_NO_SENSE;
1624 if (!curlun) { // Unsupported LUNs are okay
1625 fsg->bad_lun_okay = 1;
1626 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1630 sd = curlun->sense_data;
1631 sdinfo = curlun->sense_data_info;
1632 valid = curlun->info_valid << 7;
1633 curlun->sense_data = SS_NO_SENSE;
1634 curlun->sense_data_info = 0;
1635 curlun->info_valid = 0;
1639 buf[0] = valid | 0x70; // Valid, current error
1641 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1642 buf[7] = 18 - 8; // Additional sense length
1649 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1651 struct fsg_lun *curlun = fsg->curlun;
1652 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
1653 int pmi = fsg->cmnd[8];
1654 u8 *buf = (u8 *) bh->buf;
1656 /* Check the PMI and LBA fields */
1657 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1658 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1662 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1663 /* Max logical block */
1664 put_unaligned_be32(512, &buf[4]); /* Block length */
1669 static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1671 struct fsg_lun *curlun = fsg->curlun;
1672 int msf = fsg->cmnd[1] & 0x02;
1673 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
1674 u8 *buf = (u8 *) bh->buf;
1676 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1677 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1680 if (lba >= curlun->num_sectors) {
1681 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1686 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1687 store_cdrom_address(&buf[4], msf, lba);
1692 static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1694 struct fsg_lun *curlun = fsg->curlun;
1695 int msf = fsg->cmnd[1] & 0x02;
1696 int start_track = fsg->cmnd[6];
1697 u8 *buf = (u8 *) bh->buf;
1699 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1701 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1706 buf[1] = (20-2); /* TOC data length */
1707 buf[2] = 1; /* First track number */
1708 buf[3] = 1; /* Last track number */
1709 buf[5] = 0x16; /* Data track, copying allowed */
1710 buf[6] = 0x01; /* Only track is number 1 */
1711 store_cdrom_address(&buf[8], msf, 0);
1713 buf[13] = 0x16; /* Lead-out track is data */
1714 buf[14] = 0xAA; /* Lead-out track number */
1715 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1720 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1722 struct fsg_lun *curlun = fsg->curlun;
1723 int mscmnd = fsg->cmnd[0];
1724 u8 *buf = (u8 *) bh->buf;
1727 int changeable_values, all_pages;
1731 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1732 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1735 pc = fsg->cmnd[2] >> 6;
1736 page_code = fsg->cmnd[2] & 0x3f;
1738 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1741 changeable_values = (pc == 1);
1742 all_pages = (page_code == 0x3f);
1744 /* Write the mode parameter header. Fixed values are: default
1745 * medium type, no cache control (DPOFUA), and no block descriptors.
1746 * The only variable value is the WriteProtect bit. We will fill in
1747 * the mode data length later. */
1749 if (mscmnd == SC_MODE_SENSE_6) {
1750 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1753 } else { // SC_MODE_SENSE_10
1754 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1756 limit = 65535; // Should really be mod_data.buflen
1759 /* No block descriptors */
1761 /* The mode pages, in numerical order. The only page we support
1762 * is the Caching page. */
1763 if (page_code == 0x08 || all_pages) {
1765 buf[0] = 0x08; // Page code
1766 buf[1] = 10; // Page length
1767 memset(buf+2, 0, 10); // None of the fields are changeable
1769 if (!changeable_values) {
1770 buf[2] = 0x04; // Write cache enable,
1771 // Read cache not disabled
1772 // No cache retention priorities
1773 put_unaligned_be16(0xffff, &buf[4]);
1774 /* Don't disable prefetch */
1775 /* Minimum prefetch = 0 */
1776 put_unaligned_be16(0xffff, &buf[8]);
1777 /* Maximum prefetch */
1778 put_unaligned_be16(0xffff, &buf[10]);
1779 /* Maximum prefetch ceiling */
1784 /* Check that a valid page was requested and the mode data length
1785 * isn't too long. */
1787 if (!valid_page || len > limit) {
1788 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1792 /* Store the mode data length */
1793 if (mscmnd == SC_MODE_SENSE_6)
1796 put_unaligned_be16(len - 2, buf0);
1801 static int do_start_stop(struct fsg_dev *fsg)
1803 struct fsg_lun *curlun = fsg->curlun;
1806 if (!mod_data.removable) {
1807 curlun->sense_data = SS_INVALID_COMMAND;
1811 // int immed = fsg->cmnd[1] & 0x01;
1812 loej = fsg->cmnd[4] & 0x02;
1813 start = fsg->cmnd[4] & 0x01;
1815 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1816 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1817 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1818 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1824 /* Are we allowed to unload the media? */
1825 if (curlun->prevent_medium_removal) {
1826 LDBG(curlun, "unload attempt prevented\n");
1827 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1830 if (loej) { // Simulate an unload/eject
1831 up_read(&fsg->filesem);
1832 down_write(&fsg->filesem);
1833 fsg_lun_close(curlun);
1834 up_write(&fsg->filesem);
1835 down_read(&fsg->filesem);
1839 /* Our emulation doesn't support mounting; the medium is
1840 * available for use as soon as it is loaded. */
1841 if (!fsg_lun_is_open(curlun)) {
1842 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1851 static int do_prevent_allow(struct fsg_dev *fsg)
1853 struct fsg_lun *curlun = fsg->curlun;
1856 if (!mod_data.removable) {
1857 curlun->sense_data = SS_INVALID_COMMAND;
1861 prevent = fsg->cmnd[4] & 0x01;
1862 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1863 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1867 if (curlun->prevent_medium_removal && !prevent)
1868 fsg_lun_fsync_sub(curlun);
1869 curlun->prevent_medium_removal = prevent;
1874 static int do_read_format_capacities(struct fsg_dev *fsg,
1875 struct fsg_buffhd *bh)
1877 struct fsg_lun *curlun = fsg->curlun;
1878 u8 *buf = (u8 *) bh->buf;
1880 buf[0] = buf[1] = buf[2] = 0;
1881 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1884 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1885 /* Number of blocks */
1886 put_unaligned_be32(512, &buf[4]); /* Block length */
1887 buf[4] = 0x02; /* Current capacity */
1892 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1894 struct fsg_lun *curlun = fsg->curlun;
1896 /* We don't support MODE SELECT */
1897 curlun->sense_data = SS_INVALID_COMMAND;
1902 /*-------------------------------------------------------------------------*/
1904 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1908 rc = fsg_set_halt(fsg, fsg->bulk_in);
1910 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1912 if (rc != -EAGAIN) {
1913 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1918 /* Wait for a short time and then try again */
1919 if (msleep_interruptible(100) != 0)
1921 rc = usb_ep_set_halt(fsg->bulk_in);
1926 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1930 DBG(fsg, "bulk-in set wedge\n");
1931 rc = usb_ep_set_wedge(fsg->bulk_in);
1933 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1935 if (rc != -EAGAIN) {
1936 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1941 /* Wait for a short time and then try again */
1942 if (msleep_interruptible(100) != 0)
1944 rc = usb_ep_set_wedge(fsg->bulk_in);
1949 static int pad_with_zeros(struct fsg_dev *fsg)
1951 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1952 u32 nkeep = bh->inreq->length;
1956 bh->state = BUF_STATE_EMPTY; // For the first iteration
1957 fsg->usb_amount_left = nkeep + fsg->residue;
1958 while (fsg->usb_amount_left > 0) {
1960 /* Wait for the next buffer to be free */
1961 while (bh->state != BUF_STATE_EMPTY) {
1962 rc = sleep_thread(fsg);
1967 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
1968 memset(bh->buf + nkeep, 0, nsend - nkeep);
1969 bh->inreq->length = nsend;
1970 bh->inreq->zero = 0;
1971 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1972 &bh->inreq_busy, &bh->state);
1973 bh = fsg->next_buffhd_to_fill = bh->next;
1974 fsg->usb_amount_left -= nsend;
1980 static int throw_away_data(struct fsg_dev *fsg)
1982 struct fsg_buffhd *bh;
1986 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1987 fsg->usb_amount_left > 0) {
1989 /* Throw away the data in a filled buffer */
1990 if (bh->state == BUF_STATE_FULL) {
1992 bh->state = BUF_STATE_EMPTY;
1993 fsg->next_buffhd_to_drain = bh->next;
1995 /* A short packet or an error ends everything */
1996 if (bh->outreq->actual != bh->outreq->length ||
1997 bh->outreq->status != 0) {
1998 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2004 /* Try to submit another request if we need one */
2005 bh = fsg->next_buffhd_to_fill;
2006 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2007 amount = min(fsg->usb_amount_left,
2008 (u32) mod_data.buflen);
2010 /* amount is always divisible by 512, hence by
2011 * the bulk-out maxpacket size */
2012 bh->outreq->length = bh->bulk_out_intended_length =
2014 bh->outreq->short_not_ok = 1;
2015 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2016 &bh->outreq_busy, &bh->state);
2017 fsg->next_buffhd_to_fill = bh->next;
2018 fsg->usb_amount_left -= amount;
2022 /* Otherwise wait for something to happen */
2023 rc = sleep_thread(fsg);
2031 static int finish_reply(struct fsg_dev *fsg)
2033 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2036 switch (fsg->data_dir) {
2038 break; // Nothing to send
2040 /* If we don't know whether the host wants to read or write,
2041 * this must be CB or CBI with an unknown command. We mustn't
2042 * try to send or receive any data. So stall both bulk pipes
2043 * if we can and wait for a reset. */
2044 case DATA_DIR_UNKNOWN:
2045 if (mod_data.can_stall) {
2046 fsg_set_halt(fsg, fsg->bulk_out);
2047 rc = halt_bulk_in_endpoint(fsg);
2051 /* All but the last buffer of data must have already been sent */
2052 case DATA_DIR_TO_HOST:
2053 if (fsg->data_size == 0)
2054 ; // Nothing to send
2056 /* If there's no residue, simply send the last buffer */
2057 else if (fsg->residue == 0) {
2058 bh->inreq->zero = 0;
2059 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2060 &bh->inreq_busy, &bh->state);
2061 fsg->next_buffhd_to_fill = bh->next;
2064 /* There is a residue. For CB and CBI, simply mark the end
2065 * of the data with a short packet. However, if we are
2066 * allowed to stall, there was no data at all (residue ==
2067 * data_size), and the command failed (invalid LUN or
2068 * sense data is set), then halt the bulk-in endpoint
2070 else if (!transport_is_bbb()) {
2071 if (mod_data.can_stall &&
2072 fsg->residue == fsg->data_size &&
2073 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2074 bh->state = BUF_STATE_EMPTY;
2075 rc = halt_bulk_in_endpoint(fsg);
2077 bh->inreq->zero = 1;
2078 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2079 &bh->inreq_busy, &bh->state);
2080 fsg->next_buffhd_to_fill = bh->next;
2084 /* For Bulk-only, if we're allowed to stall then send the
2085 * short packet and halt the bulk-in endpoint. If we can't
2086 * stall, pad out the remaining data with 0's. */
2088 if (mod_data.can_stall) {
2089 bh->inreq->zero = 1;
2090 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2091 &bh->inreq_busy, &bh->state);
2092 fsg->next_buffhd_to_fill = bh->next;
2093 rc = halt_bulk_in_endpoint(fsg);
2095 rc = pad_with_zeros(fsg);
2099 /* We have processed all we want from the data the host has sent.
2100 * There may still be outstanding bulk-out requests. */
2101 case DATA_DIR_FROM_HOST:
2102 if (fsg->residue == 0)
2103 ; // Nothing to receive
2105 /* Did the host stop sending unexpectedly early? */
2106 else if (fsg->short_packet_received) {
2107 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2111 /* We haven't processed all the incoming data. Even though
2112 * we may be allowed to stall, doing so would cause a race.
2113 * The controller may already have ACK'ed all the remaining
2114 * bulk-out packets, in which case the host wouldn't see a
2115 * STALL. Not realizing the endpoint was halted, it wouldn't
2116 * clear the halt -- leading to problems later on. */
2118 else if (mod_data.can_stall) {
2119 fsg_set_halt(fsg, fsg->bulk_out);
2120 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2125 /* We can't stall. Read in the excess data and throw it
2128 rc = throw_away_data(fsg);
2135 static int send_status(struct fsg_dev *fsg)
2137 struct fsg_lun *curlun = fsg->curlun;
2138 struct fsg_buffhd *bh;
2140 u8 status = USB_STATUS_PASS;
2143 /* Wait for the next buffer to become available */
2144 bh = fsg->next_buffhd_to_fill;
2145 while (bh->state != BUF_STATE_EMPTY) {
2146 rc = sleep_thread(fsg);
2152 sd = curlun->sense_data;
2153 sdinfo = curlun->sense_data_info;
2154 } else if (fsg->bad_lun_okay)
2157 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2159 if (fsg->phase_error) {
2160 DBG(fsg, "sending phase-error status\n");
2161 status = USB_STATUS_PHASE_ERROR;
2162 sd = SS_INVALID_COMMAND;
2163 } else if (sd != SS_NO_SENSE) {
2164 DBG(fsg, "sending command-failure status\n");
2165 status = USB_STATUS_FAIL;
2166 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2168 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2171 if (transport_is_bbb()) {
2172 struct bulk_cs_wrap *csw = bh->buf;
2174 /* Store and send the Bulk-only CSW */
2175 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
2176 csw->Tag = fsg->tag;
2177 csw->Residue = cpu_to_le32(fsg->residue);
2178 csw->Status = status;
2180 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2181 bh->inreq->zero = 0;
2182 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2183 &bh->inreq_busy, &bh->state);
2185 } else if (mod_data.transport_type == USB_PR_CB) {
2187 /* Control-Bulk transport has no status phase! */
2190 } else { // USB_PR_CBI
2191 struct interrupt_data *buf = bh->buf;
2193 /* Store and send the Interrupt data. UFI sends the ASC
2194 * and ASCQ bytes. Everything else sends a Type (which
2195 * is always 0) and the status Value. */
2196 if (mod_data.protocol_type == USB_SC_UFI) {
2197 buf->bType = ASC(sd);
2198 buf->bValue = ASCQ(sd);
2201 buf->bValue = status;
2203 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2205 fsg->intr_buffhd = bh; // Point to the right buffhd
2206 fsg->intreq->buf = bh->inreq->buf;
2207 fsg->intreq->context = bh;
2208 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2209 &fsg->intreq_busy, &bh->state);
2212 fsg->next_buffhd_to_fill = bh->next;
2217 /*-------------------------------------------------------------------------*/
2219 /* Check whether the command is properly formed and whether its data size
2220 * and direction agree with the values we already have. */
2221 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2222 enum data_direction data_dir, unsigned int mask,
2223 int needs_medium, const char *name)
2226 int lun = fsg->cmnd[1] >> 5;
2227 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2229 struct fsg_lun *curlun;
2231 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2232 * Transparent SCSI doesn't pad. */
2233 if (protocol_is_scsi())
2236 /* There's some disagreement as to whether RBC pads commands or not.
2237 * We'll play it safe and accept either form. */
2238 else if (mod_data.protocol_type == USB_SC_RBC) {
2239 if (fsg->cmnd_size == 12)
2242 /* All the other protocols pad to 12 bytes */
2247 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2248 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2250 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2251 name, cmnd_size, dirletter[(int) data_dir],
2252 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2254 /* We can't reply at all until we know the correct data direction
2256 if (fsg->data_size_from_cmnd == 0)
2257 data_dir = DATA_DIR_NONE;
2258 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2259 fsg->data_dir = data_dir;
2260 fsg->data_size = fsg->data_size_from_cmnd;
2262 } else { // Bulk-only
2263 if (fsg->data_size < fsg->data_size_from_cmnd) {
2265 /* Host data size < Device data size is a phase error.
2266 * Carry out the command, but only transfer as much
2267 * as we are allowed. */
2268 fsg->data_size_from_cmnd = fsg->data_size;
2269 fsg->phase_error = 1;
2272 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2274 /* Conflicting data directions is a phase error */
2275 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2276 fsg->phase_error = 1;
2280 /* Verify the length of the command itself */
2281 if (cmnd_size != fsg->cmnd_size) {
2283 /* Special case workaround: There are plenty of buggy SCSI
2284 * implementations. Many have issues with cbw->Length
2285 * field passing a wrong command size. For those cases we
2286 * always try to work around the problem by using the length
2287 * sent by the host side provided it is at least as large
2288 * as the correct command length.
2289 * Examples of such cases would be MS-Windows, which issues
2290 * REQUEST SENSE with cbw->Length == 12 where it should
2291 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2292 * REQUEST SENSE with cbw->Length == 10 where it should
2295 if (cmnd_size <= fsg->cmnd_size) {
2296 DBG(fsg, "%s is buggy! Expected length %d "
2297 "but we got %d\n", name,
2298 cmnd_size, fsg->cmnd_size);
2299 cmnd_size = fsg->cmnd_size;
2301 fsg->phase_error = 1;
2306 /* Check that the LUN values are consistent */
2307 if (transport_is_bbb()) {
2308 if (fsg->lun != lun)
2309 DBG(fsg, "using LUN %d from CBW, "
2310 "not LUN %d from CDB\n",
2313 fsg->lun = lun; // Use LUN from the command
2316 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2317 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2318 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2319 curlun->sense_data = SS_NO_SENSE;
2320 curlun->sense_data_info = 0;
2321 curlun->info_valid = 0;
2324 fsg->curlun = curlun = NULL;
2325 fsg->bad_lun_okay = 0;
2327 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2328 * to use unsupported LUNs; all others may not. */
2329 if (fsg->cmnd[0] != SC_INQUIRY &&
2330 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2331 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2336 /* If a unit attention condition exists, only INQUIRY and
2337 * REQUEST SENSE commands are allowed; anything else must fail. */
2338 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2339 fsg->cmnd[0] != SC_INQUIRY &&
2340 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2341 curlun->sense_data = curlun->unit_attention_data;
2342 curlun->unit_attention_data = SS_NO_SENSE;
2346 /* Check that only command bytes listed in the mask are non-zero */
2347 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2348 for (i = 1; i < cmnd_size; ++i) {
2349 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2351 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2356 /* If the medium isn't mounted and the command needs to access
2357 * it, return an error. */
2358 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
2359 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2367 static int do_scsi_command(struct fsg_dev *fsg)
2369 struct fsg_buffhd *bh;
2371 int reply = -EINVAL;
2373 static char unknown[16];
2377 /* Wait for the next buffer to become available for data or status */
2378 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2379 while (bh->state != BUF_STATE_EMPTY) {
2380 rc = sleep_thread(fsg);
2384 fsg->phase_error = 0;
2385 fsg->short_packet_received = 0;
2387 down_read(&fsg->filesem); // We're using the backing file
2388 switch (fsg->cmnd[0]) {
2391 fsg->data_size_from_cmnd = fsg->cmnd[4];
2392 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2395 reply = do_inquiry(fsg, bh);
2398 case SC_MODE_SELECT_6:
2399 fsg->data_size_from_cmnd = fsg->cmnd[4];
2400 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2402 "MODE SELECT(6)")) == 0)
2403 reply = do_mode_select(fsg, bh);
2406 case SC_MODE_SELECT_10:
2407 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2408 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2410 "MODE SELECT(10)")) == 0)
2411 reply = do_mode_select(fsg, bh);
2414 case SC_MODE_SENSE_6:
2415 fsg->data_size_from_cmnd = fsg->cmnd[4];
2416 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2417 (1<<1) | (1<<2) | (1<<4), 0,
2418 "MODE SENSE(6)")) == 0)
2419 reply = do_mode_sense(fsg, bh);
2422 case SC_MODE_SENSE_10:
2423 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2424 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2425 (1<<1) | (1<<2) | (3<<7), 0,
2426 "MODE SENSE(10)")) == 0)
2427 reply = do_mode_sense(fsg, bh);
2430 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2431 fsg->data_size_from_cmnd = 0;
2432 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2434 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2435 reply = do_prevent_allow(fsg);
2440 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2441 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2444 reply = do_read(fsg);
2448 fsg->data_size_from_cmnd =
2449 get_unaligned_be16(&fsg->cmnd[7]) << 9;
2450 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2451 (1<<1) | (0xf<<2) | (3<<7), 1,
2453 reply = do_read(fsg);
2457 fsg->data_size_from_cmnd =
2458 get_unaligned_be32(&fsg->cmnd[6]) << 9;
2459 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2460 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2462 reply = do_read(fsg);
2465 case SC_READ_CAPACITY:
2466 fsg->data_size_from_cmnd = 8;
2467 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2468 (0xf<<2) | (1<<8), 1,
2469 "READ CAPACITY")) == 0)
2470 reply = do_read_capacity(fsg, bh);
2473 case SC_READ_HEADER:
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,
2478 (3<<7) | (0x1f<<1), 1,
2479 "READ HEADER")) == 0)
2480 reply = do_read_header(fsg, bh);
2484 if (!mod_data.cdrom)
2486 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2487 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2490 reply = do_read_toc(fsg, bh);
2493 case SC_READ_FORMAT_CAPACITIES:
2494 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
2495 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2497 "READ FORMAT CAPACITIES")) == 0)
2498 reply = do_read_format_capacities(fsg, bh);
2501 case SC_REQUEST_SENSE:
2502 fsg->data_size_from_cmnd = fsg->cmnd[4];
2503 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2505 "REQUEST SENSE")) == 0)
2506 reply = do_request_sense(fsg, bh);
2509 case SC_START_STOP_UNIT:
2510 fsg->data_size_from_cmnd = 0;
2511 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2513 "START-STOP UNIT")) == 0)
2514 reply = do_start_stop(fsg);
2517 case SC_SYNCHRONIZE_CACHE:
2518 fsg->data_size_from_cmnd = 0;
2519 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2520 (0xf<<2) | (3<<7), 1,
2521 "SYNCHRONIZE CACHE")) == 0)
2522 reply = do_synchronize_cache(fsg);
2525 case SC_TEST_UNIT_READY:
2526 fsg->data_size_from_cmnd = 0;
2527 reply = check_command(fsg, 6, DATA_DIR_NONE,
2532 /* Although optional, this command is used by MS-Windows. We
2533 * support a minimal version: BytChk must be 0. */
2535 fsg->data_size_from_cmnd = 0;
2536 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2537 (1<<1) | (0xf<<2) | (3<<7), 1,
2539 reply = do_verify(fsg);
2544 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2545 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2548 reply = do_write(fsg);
2552 fsg->data_size_from_cmnd =
2553 get_unaligned_be16(&fsg->cmnd[7]) << 9;
2554 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2555 (1<<1) | (0xf<<2) | (3<<7), 1,
2557 reply = do_write(fsg);
2561 fsg->data_size_from_cmnd =
2562 get_unaligned_be32(&fsg->cmnd[6]) << 9;
2563 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2564 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2566 reply = do_write(fsg);
2569 /* Some mandatory commands that we recognize but don't implement.
2570 * They don't mean much in this setting. It's left as an exercise
2571 * for anyone interested to implement RESERVE and RELEASE in terms
2572 * of Posix locks. */
2573 case SC_FORMAT_UNIT:
2576 case SC_SEND_DIAGNOSTIC:
2581 fsg->data_size_from_cmnd = 0;
2582 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2583 if ((reply = check_command(fsg, fsg->cmnd_size,
2584 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2585 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2590 up_read(&fsg->filesem);
2592 if (reply == -EINTR || signal_pending(current))
2595 /* Set up the single reply buffer for finish_reply() */
2596 if (reply == -EINVAL)
2597 reply = 0; // Error reply length
2598 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2599 reply = min((u32) reply, fsg->data_size_from_cmnd);
2600 bh->inreq->length = reply;
2601 bh->state = BUF_STATE_FULL;
2602 fsg->residue -= reply;
2603 } // Otherwise it's already set
2609 /*-------------------------------------------------------------------------*/
2611 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2613 struct usb_request *req = bh->outreq;
2614 struct fsg_bulk_cb_wrap *cbw = req->buf;
2616 /* Was this a real packet? Should it be ignored? */
2617 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2620 /* Is the CBW valid? */
2621 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2622 cbw->Signature != cpu_to_le32(
2624 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2626 le32_to_cpu(cbw->Signature));
2628 /* The Bulk-only spec says we MUST stall the IN endpoint
2629 * (6.6.1), so it's unavoidable. It also says we must
2630 * retain this state until the next reset, but there's
2631 * no way to tell the controller driver it should ignore
2632 * Clear-Feature(HALT) requests.
2634 * We aren't required to halt the OUT endpoint; instead
2635 * we can simply accept and discard any data received
2636 * until the next reset. */
2637 wedge_bulk_in_endpoint(fsg);
2638 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2642 /* Is the CBW meaningful? */
2643 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2644 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2645 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2647 cbw->Lun, cbw->Flags, cbw->Length);
2649 /* We can do anything we want here, so let's stall the
2650 * bulk pipes if we are allowed to. */
2651 if (mod_data.can_stall) {
2652 fsg_set_halt(fsg, fsg->bulk_out);
2653 halt_bulk_in_endpoint(fsg);
2658 /* Save the command for later */
2659 fsg->cmnd_size = cbw->Length;
2660 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2661 if (cbw->Flags & USB_BULK_IN_FLAG)
2662 fsg->data_dir = DATA_DIR_TO_HOST;
2664 fsg->data_dir = DATA_DIR_FROM_HOST;
2665 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2666 if (fsg->data_size == 0)
2667 fsg->data_dir = DATA_DIR_NONE;
2668 fsg->lun = cbw->Lun;
2669 fsg->tag = cbw->Tag;
2674 static int get_next_command(struct fsg_dev *fsg)
2676 struct fsg_buffhd *bh;
2679 if (transport_is_bbb()) {
2681 /* Wait for the next buffer to become available */
2682 bh = fsg->next_buffhd_to_fill;
2683 while (bh->state != BUF_STATE_EMPTY) {
2684 rc = sleep_thread(fsg);
2689 /* Queue a request to read a Bulk-only CBW */
2690 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2691 bh->outreq->short_not_ok = 1;
2692 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2693 &bh->outreq_busy, &bh->state);
2695 /* We will drain the buffer in software, which means we
2696 * can reuse it for the next filling. No need to advance
2697 * next_buffhd_to_fill. */
2699 /* Wait for the CBW to arrive */
2700 while (bh->state != BUF_STATE_FULL) {
2701 rc = sleep_thread(fsg);
2706 rc = received_cbw(fsg, bh);
2707 bh->state = BUF_STATE_EMPTY;
2709 } else { // USB_PR_CB or USB_PR_CBI
2711 /* Wait for the next command to arrive */
2712 while (fsg->cbbuf_cmnd_size == 0) {
2713 rc = sleep_thread(fsg);
2718 /* Is the previous status interrupt request still busy?
2719 * The host is allowed to skip reading the status,
2720 * so we must cancel it. */
2721 if (fsg->intreq_busy)
2722 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2724 /* Copy the command and mark the buffer empty */
2725 fsg->data_dir = DATA_DIR_UNKNOWN;
2726 spin_lock_irq(&fsg->lock);
2727 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2728 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2729 fsg->cbbuf_cmnd_size = 0;
2730 spin_unlock_irq(&fsg->lock);
2736 /*-------------------------------------------------------------------------*/
2738 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2739 const struct usb_endpoint_descriptor *d)
2743 ep->driver_data = fsg;
2744 rc = usb_ep_enable(ep, d);
2746 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2750 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2751 struct usb_request **preq)
2753 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2756 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2761 * Reset interface setting and re-init endpoint state (toggle etc).
2762 * Call with altsetting < 0 to disable the interface. The only other
2763 * available altsetting is 0, which enables the interface.
2765 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2769 const struct usb_endpoint_descriptor *d;
2772 DBG(fsg, "reset interface\n");
2775 /* Deallocate the requests */
2776 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2777 struct fsg_buffhd *bh = &fsg->buffhds[i];
2780 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2784 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2789 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2793 /* Disable the endpoints */
2794 if (fsg->bulk_in_enabled) {
2795 usb_ep_disable(fsg->bulk_in);
2796 fsg->bulk_in_enabled = 0;
2798 if (fsg->bulk_out_enabled) {
2799 usb_ep_disable(fsg->bulk_out);
2800 fsg->bulk_out_enabled = 0;
2802 if (fsg->intr_in_enabled) {
2803 usb_ep_disable(fsg->intr_in);
2804 fsg->intr_in_enabled = 0;
2808 if (altsetting < 0 || rc != 0)
2811 DBG(fsg, "set interface %d\n", altsetting);
2813 /* Enable the endpoints */
2814 d = fsg_ep_desc(fsg->gadget,
2815 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2816 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2818 fsg->bulk_in_enabled = 1;
2820 d = fsg_ep_desc(fsg->gadget,
2821 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2822 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2824 fsg->bulk_out_enabled = 1;
2825 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2826 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2828 if (transport_is_cbi()) {
2829 d = fsg_ep_desc(fsg->gadget,
2830 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
2831 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2833 fsg->intr_in_enabled = 1;
2836 /* Allocate the requests */
2837 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2838 struct fsg_buffhd *bh = &fsg->buffhds[i];
2840 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2842 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2844 bh->inreq->buf = bh->outreq->buf = bh->buf;
2845 bh->inreq->context = bh->outreq->context = bh;
2846 bh->inreq->complete = bulk_in_complete;
2847 bh->outreq->complete = bulk_out_complete;
2849 if (transport_is_cbi()) {
2850 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2852 fsg->intreq->complete = intr_in_complete;
2856 for (i = 0; i < fsg->nluns; ++i)
2857 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2863 * Change our operational configuration. This code must agree with the code
2864 * that returns config descriptors, and with interface altsetting code.
2866 * It's also responsible for power management interactions. Some
2867 * configurations might not work with our current power sources.
2868 * For now we just assume the gadget is always self-powered.
2870 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2874 /* Disable the single interface */
2875 if (fsg->config != 0) {
2876 DBG(fsg, "reset config\n");
2878 rc = do_set_interface(fsg, -1);
2881 /* Enable the interface */
2882 if (new_config != 0) {
2883 fsg->config = new_config;
2884 if ((rc = do_set_interface(fsg, 0)) != 0)
2885 fsg->config = 0; // Reset on errors
2889 switch (fsg->gadget->speed) {
2890 case USB_SPEED_LOW: speed = "low"; break;
2891 case USB_SPEED_FULL: speed = "full"; break;
2892 case USB_SPEED_HIGH: speed = "high"; break;
2893 default: speed = "?"; break;
2895 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2902 /*-------------------------------------------------------------------------*/
2904 static void handle_exception(struct fsg_dev *fsg)
2910 struct fsg_buffhd *bh;
2911 enum fsg_state old_state;
2913 struct fsg_lun *curlun;
2914 unsigned int exception_req_tag;
2917 /* Clear the existing signals. Anything but SIGUSR1 is converted
2918 * into a high-priority EXIT exception. */
2920 sig = dequeue_signal_lock(current, ¤t->blocked, &info);
2923 if (sig != SIGUSR1) {
2924 if (fsg->state < FSG_STATE_EXIT)
2925 DBG(fsg, "Main thread exiting on signal\n");
2926 raise_exception(fsg, FSG_STATE_EXIT);
2930 /* Cancel all the pending transfers */
2931 if (fsg->intreq_busy)
2932 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2933 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2934 bh = &fsg->buffhds[i];
2936 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2937 if (bh->outreq_busy)
2938 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2941 /* Wait until everything is idle */
2943 num_active = fsg->intreq_busy;
2944 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2945 bh = &fsg->buffhds[i];
2946 num_active += bh->inreq_busy + bh->outreq_busy;
2948 if (num_active == 0)
2950 if (sleep_thread(fsg))
2954 /* Clear out the controller's fifos */
2955 if (fsg->bulk_in_enabled)
2956 usb_ep_fifo_flush(fsg->bulk_in);
2957 if (fsg->bulk_out_enabled)
2958 usb_ep_fifo_flush(fsg->bulk_out);
2959 if (fsg->intr_in_enabled)
2960 usb_ep_fifo_flush(fsg->intr_in);
2962 /* Reset the I/O buffer states and pointers, the SCSI
2963 * state, and the exception. Then invoke the handler. */
2964 spin_lock_irq(&fsg->lock);
2966 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2967 bh = &fsg->buffhds[i];
2968 bh->state = BUF_STATE_EMPTY;
2970 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2973 exception_req_tag = fsg->exception_req_tag;
2974 new_config = fsg->new_config;
2975 old_state = fsg->state;
2977 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2978 fsg->state = FSG_STATE_STATUS_PHASE;
2980 for (i = 0; i < fsg->nluns; ++i) {
2981 curlun = &fsg->luns[i];
2982 curlun->prevent_medium_removal = 0;
2983 curlun->sense_data = curlun->unit_attention_data =
2985 curlun->sense_data_info = 0;
2986 curlun->info_valid = 0;
2988 fsg->state = FSG_STATE_IDLE;
2990 spin_unlock_irq(&fsg->lock);
2992 /* Carry out any extra actions required for the exception */
2993 switch (old_state) {
2997 case FSG_STATE_ABORT_BULK_OUT:
2999 spin_lock_irq(&fsg->lock);
3000 if (fsg->state == FSG_STATE_STATUS_PHASE)
3001 fsg->state = FSG_STATE_IDLE;
3002 spin_unlock_irq(&fsg->lock);
3005 case FSG_STATE_RESET:
3006 /* In case we were forced against our will to halt a
3007 * bulk endpoint, clear the halt now. (The SuperH UDC
3008 * requires this.) */
3009 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
3010 usb_ep_clear_halt(fsg->bulk_in);
3012 if (transport_is_bbb()) {