2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
4 * Copyright (C) 2003, 2004 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. In addition to providing an
42 * example of a genuinely useful gadget driver for a USB device, it also
43 * illustrates a technique of double-buffering for increased throughput.
44 * Last but not least, it gives an easy way to probe the behavior of the
45 * 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.
51 * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
52 * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
53 * by the optional "transport" module parameter. It also supports the
54 * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
55 * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
56 * the optional "protocol" module parameter. For testing purposes the
57 * gadget will indicate that it has removable media if the optional
58 * "removable" module parameter is set. In addition, the default Vendor ID,
59 * 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.
70 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
71 * needed (an interrupt-out endpoint is also needed for CBI). The memory
72 * requirement amounts to two 16K buffers, size configurable by a parameter.
73 * Support is included for both full-speed and high-speed operation.
77 * file=filename[,filename...]
78 * Required if "removable" is not set, names of
79 * the files or block devices used for
81 * ro=b[,b...] Default false, booleans for read-only access
82 * luns=N Default N = number of filenames, number of
84 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
85 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
86 * ATAPI, QIC, UFI, 8070, or SCSI;
88 * removable Default false, boolean for removable media
89 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
90 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
91 * release=0xRRRR Override the USB release number (bcdDevice)
92 * buflen=N Default N=16384, buffer size used (will be
93 * rounded down to a multiple of
95 * stall Default determined according to the type of
96 * USB device controller (usually true),
97 * boolean to permit the driver to halt
100 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file" and "ro"
101 * options are available; default values are used for everything else.
103 * The pathnames of the backing files and the ro settings are available in
104 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
105 * gadget's sysfs directory. If CONFIG_USB_FILE_STORAGE_TEST and the
106 * "removable" option are both set, writing to these files will simulate
107 * ejecting/loading the medium (writing an empty line means eject) and
108 * adjusting a write-enable tab. Changes to the ro setting are not allowed
109 * when the medium is loaded.
111 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
118 * The FSG driver is fairly straightforward. There is a main kernel
119 * thread that handles most of the work. Interrupt routines field
120 * callbacks from the controller driver: bulk- and interrupt-request
121 * completion notifications, endpoint-0 events, and disconnect events.
122 * Completion events are passed to the main thread by wakeup calls. Many
123 * ep0 requests are handled at interrupt time, but SetInterface,
124 * SetConfiguration, and device reset requests are forwarded to the
125 * thread in the form of "exceptions" using SIGUSR1 signals (since they
126 * should interrupt any ongoing file I/O operations).
128 * The thread's main routine implements the standard command/data/status
129 * parts of a SCSI interaction. It and its subroutines are full of tests
130 * for pending signals/exceptions -- all this polling is necessary since
131 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
132 * indication that the driver really wants to be running in userspace.)
133 * An important point is that so long as the thread is alive it keeps an
134 * open reference to the backing file. This will prevent unmounting
135 * the backing file's underlying filesystem and could cause problems
136 * during system shutdown, for example. To prevent such problems, the
137 * thread catches INT, TERM, and KILL signals and converts them into
140 * In normal operation the main thread is started during the gadget's
141 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
142 * exit when it receives a signal, and there's no point leaving the
143 * gadget running when the thread is dead. So just before the thread
144 * exits, it deregisters the gadget driver. This makes things a little
145 * tricky: The driver is deregistered at two places, and the exiting
146 * thread can indirectly call fsg_unbind() which in turn can tell the
147 * thread to exit. The first problem is resolved through the use of the
148 * REGISTERED atomic bitflag; the driver will only be deregistered once.
149 * The second problem is resolved by having fsg_unbind() check
150 * fsg->state; it won't try to stop the thread if the state is already
151 * FSG_STATE_TERMINATED.
153 * To provide maximum throughput, the driver uses a circular pipeline of
154 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
155 * arbitrarily long; in practice the benefits don't justify having more
156 * than 2 stages (i.e., double buffering). But it helps to think of the
157 * pipeline as being a long one. Each buffer head contains a bulk-in and
158 * a bulk-out request pointer (since the buffer can be used for both
159 * output and input -- directions always are given from the host's
160 * point of view) as well as a pointer to the buffer and various state
163 * Use of the pipeline follows a simple protocol. There is a variable
164 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
165 * At any time that buffer head may still be in use from an earlier
166 * request, so each buffer head has a state variable indicating whether
167 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
168 * buffer head to be EMPTY, filling the buffer either by file I/O or by
169 * USB I/O (during which the buffer head is BUSY), and marking the buffer
170 * head FULL when the I/O is complete. Then the buffer will be emptied
171 * (again possibly by USB I/O, during which it is marked BUSY) and
172 * finally marked EMPTY again (possibly by a completion routine).
174 * A module parameter tells the driver to avoid stalling the bulk
175 * endpoints wherever the transport specification allows. This is
176 * necessary for some UDCs like the SuperH, which cannot reliably clear a
177 * halt on a bulk endpoint. However, under certain circumstances the
178 * Bulk-only specification requires a stall. In such cases the driver
179 * will halt the endpoint and set a flag indicating that it should clear
180 * the halt in software during the next device reset. Hopefully this
181 * will permit everything to work correctly.
183 * One subtle point concerns sending status-stage responses for ep0
184 * requests. Some of these requests, such as device reset, can involve
185 * interrupting an ongoing file I/O operation, which might take an
186 * arbitrarily long time. During that delay the host might give up on
187 * the original ep0 request and issue a new one. When that happens the
188 * driver should not notify the host about completion of the original
189 * request, as the host will no longer be waiting for it. So the driver
190 * assigns to each ep0 request a unique tag, and it keeps track of the
191 * tag value of the request associated with a long-running exception
192 * (device-reset, interface-change, or configuration-change). When the
193 * exception handler is finished, the status-stage response is submitted
194 * only if the current ep0 request tag is equal to the exception request
195 * tag. Thus only the most recently received ep0 request will get a
196 * status-stage response.
198 * Warning: This driver source file is too long. It ought to be split up
199 * into a header file plus about 3 separate .c files, to handle the details
200 * of the Gadget, USB Mass Storage, and SCSI protocols.
208 #include <linux/config.h>
210 #include <asm/system.h>
211 #include <asm/uaccess.h>
213 #include <linux/bitops.h>
214 #include <linux/blkdev.h>
215 #include <linux/compiler.h>
216 #include <linux/completion.h>
217 #include <linux/dcache.h>
218 #include <linux/device.h>
219 #include <linux/fcntl.h>
220 #include <linux/file.h>
221 #include <linux/fs.h>
222 #include <linux/init.h>
223 #include <linux/kernel.h>
224 #include <linux/limits.h>
225 #include <linux/list.h>
226 #include <linux/module.h>
227 #include <linux/moduleparam.h>
228 #include <linux/pagemap.h>
229 #include <linux/rwsem.h>
230 #include <linux/sched.h>
231 #include <linux/signal.h>
232 #include <linux/slab.h>
233 #include <linux/spinlock.h>
234 #include <linux/string.h>
235 #include <linux/uts.h>
236 #include <linux/version.h>
237 #include <linux/wait.h>
239 #include <linux/usb_ch9.h>
240 #include <linux/usb_gadget.h>
242 #include "gadget_chips.h"
245 /*-------------------------------------------------------------------------*/
247 #define DRIVER_DESC "File-backed Storage Gadget"
248 #define DRIVER_NAME "g_file_storage"
249 #define DRIVER_VERSION "21 March 2004"
251 static const char longname[] = DRIVER_DESC;
252 static const char shortname[] = DRIVER_NAME;
254 MODULE_DESCRIPTION(DRIVER_DESC);
255 MODULE_AUTHOR("Alan Stern");
256 MODULE_LICENSE("Dual BSD/GPL");
258 /* Thanks to NetChip Technologies for donating this product ID.
260 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
261 * Instead: allocate your own, using normal USB-IF procedures. */
262 #define DRIVER_VENDOR_ID 0x0525 // NetChip
263 #define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
267 * This driver assumes self-powered hardware and has no way for users to
268 * trigger remote wakeup. It uses autoconfiguration to select endpoints
269 * and endpoint addresses.
273 /*-------------------------------------------------------------------------*/
275 #define xprintk(f,level,fmt,args...) \
276 dev_printk(level , &(f)->gadget->dev , fmt , ## args)
277 #define yprintk(l,level,fmt,args...) \
278 dev_printk(level , &(l)->dev , fmt , ## args)
281 #define DBG(fsg,fmt,args...) \
282 xprintk(fsg , KERN_DEBUG , fmt , ## args)
283 #define LDBG(lun,fmt,args...) \
284 yprintk(lun , KERN_DEBUG , fmt , ## args)
285 #define MDBG(fmt,args...) \
286 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
288 #define DBG(fsg,fmt,args...) \
290 #define LDBG(lun,fmt,args...) \
292 #define MDBG(fmt,args...) \
302 #define VDBG(fsg,fmt,args...) \
304 #define VLDBG(lun,fmt,args...) \
308 #define ERROR(fsg,fmt,args...) \
309 xprintk(fsg , KERN_ERR , fmt , ## args)
310 #define LERROR(lun,fmt,args...) \
311 yprintk(lun , KERN_ERR , fmt , ## args)
313 #define WARN(fsg,fmt,args...) \
314 xprintk(fsg , KERN_WARNING , fmt , ## args)
315 #define LWARN(lun,fmt,args...) \
316 yprintk(lun , KERN_WARNING , fmt , ## args)
318 #define INFO(fsg,fmt,args...) \
319 xprintk(fsg , KERN_INFO , fmt , ## args)
320 #define LINFO(lun,fmt,args...) \
321 yprintk(lun , KERN_INFO , fmt , ## args)
323 #define MINFO(fmt,args...) \
324 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
327 /*-------------------------------------------------------------------------*/
329 /* Encapsulate the module parameter settings */
333 /* Arggh! There should be a module_param_array_named macro! */
334 static char *file[MAX_LUNS] = {NULL, };
335 static int ro[MAX_LUNS] = {0, };
342 char *transport_parm;
345 unsigned short vendor;
346 unsigned short product;
347 unsigned short release;
352 char *transport_name;
356 } mod_data = { // Default values
357 .transport_parm = "BBB",
358 .protocol_parm = "SCSI",
360 .vendor = DRIVER_VENDOR_ID,
361 .product = DRIVER_PRODUCT_ID,
362 .release = 0xffff, // Use controller chip type
368 module_param_array(file, charp, mod_data.num_filenames, S_IRUGO);
369 MODULE_PARM_DESC(file, "names of backing files or devices");
371 module_param_array(ro, bool, mod_data.num_ros, S_IRUGO);
372 MODULE_PARM_DESC(ro, "true to force read-only");
375 /* In the non-TEST version, only the file and ro module parameters
377 #ifdef CONFIG_USB_FILE_STORAGE_TEST
379 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
380 MODULE_PARM_DESC(luns, "number of LUNs");
382 module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
383 MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
385 module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
386 MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
389 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
390 MODULE_PARM_DESC(removable, "true to simulate removable media");
392 module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
393 MODULE_PARM_DESC(vendor, "USB Vendor ID");
395 module_param_named(product, mod_data.product, ushort, S_IRUGO);
396 MODULE_PARM_DESC(product, "USB Product ID");
398 module_param_named(release, mod_data.release, ushort, S_IRUGO);
399 MODULE_PARM_DESC(release, "USB release number");
401 module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
402 MODULE_PARM_DESC(buflen, "I/O buffer size");
404 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
405 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
407 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
410 /*-------------------------------------------------------------------------*/
412 /* USB protocol value = the transport method */
413 #define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
414 #define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
415 #define USB_PR_BULK 0x50 // Bulk-only
417 /* USB subclass value = the protocol encapsulation */
418 #define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
419 #define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
420 #define USB_SC_QIC 0x03 // QIC-157 (tape)
421 #define USB_SC_UFI 0x04 // UFI (floppy)
422 #define USB_SC_8070 0x05 // SFF-8070i (removable)
423 #define USB_SC_SCSI 0x06 // Transparent SCSI
425 /* Bulk-only data structures */
427 /* Command Block Wrapper */
428 struct bulk_cb_wrap {
429 u32 Signature; // Contains 'USBC'
430 u32 Tag; // Unique per command id
431 u32 DataTransferLength; // Size of the data
432 u8 Flags; // Direction in bit 7
433 u8 Lun; // LUN (normally 0)
434 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
435 u8 CDB[16]; // Command Data Block
438 #define USB_BULK_CB_WRAP_LEN 31
439 #define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
440 #define USB_BULK_IN_FLAG 0x80
442 /* Command Status Wrapper */
443 struct bulk_cs_wrap {
444 u32 Signature; // Should = 'USBS'
445 u32 Tag; // Same as original command
446 u32 Residue; // Amount not transferred
447 u8 Status; // See below
450 #define USB_BULK_CS_WRAP_LEN 13
451 #define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
452 #define USB_STATUS_PASS 0
453 #define USB_STATUS_FAIL 1
454 #define USB_STATUS_PHASE_ERROR 2
456 /* Bulk-only class specific requests */
457 #define USB_BULK_RESET_REQUEST 0xff
458 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
461 /* CBI Interrupt data structure */
462 struct interrupt_data {
467 #define CBI_INTERRUPT_DATA_LEN 2
469 /* CBI Accept Device-Specific Command request */
470 #define USB_CBI_ADSC_REQUEST 0x00
473 #define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
475 /* SCSI commands that we recognize */
476 #define SC_FORMAT_UNIT 0x04
477 #define SC_INQUIRY 0x12
478 #define SC_MODE_SELECT_6 0x15
479 #define SC_MODE_SELECT_10 0x55
480 #define SC_MODE_SENSE_6 0x1a
481 #define SC_MODE_SENSE_10 0x5a
482 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
483 #define SC_READ_6 0x08
484 #define SC_READ_10 0x28
485 #define SC_READ_12 0xa8
486 #define SC_READ_CAPACITY 0x25
487 #define SC_READ_FORMAT_CAPACITIES 0x23
488 #define SC_RELEASE 0x17
489 #define SC_REQUEST_SENSE 0x03
490 #define SC_RESERVE 0x16
491 #define SC_SEND_DIAGNOSTIC 0x1d
492 #define SC_START_STOP_UNIT 0x1b
493 #define SC_SYNCHRONIZE_CACHE 0x35
494 #define SC_TEST_UNIT_READY 0x00
495 #define SC_VERIFY 0x2f
496 #define SC_WRITE_6 0x0a
497 #define SC_WRITE_10 0x2a
498 #define SC_WRITE_12 0xaa
500 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
501 #define SS_NO_SENSE 0
502 #define SS_COMMUNICATION_FAILURE 0x040800
503 #define SS_INVALID_COMMAND 0x052000
504 #define SS_INVALID_FIELD_IN_CDB 0x052400
505 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
506 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
507 #define SS_MEDIUM_NOT_PRESENT 0x023a00
508 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
509 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
510 #define SS_RESET_OCCURRED 0x062900
511 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
512 #define SS_UNRECOVERED_READ_ERROR 0x031100
513 #define SS_WRITE_ERROR 0x030c02
514 #define SS_WRITE_PROTECTED 0x072700
516 #define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
517 #define ASC(x) ((u8) ((x) >> 8))
518 #define ASCQ(x) ((u8) (x))
521 /*-------------------------------------------------------------------------*/
524 * These definitions will permit the compiler to avoid generating code for
525 * parts of the driver that aren't used in the non-TEST version. Even gcc
526 * can recognize when a test of a constant expression yields a dead code
529 * Also, in the non-TEST version, open_backing_file() is only used during
530 * initialization and the sysfs attribute store_xxx routines aren't used
531 * at all. We will define NORMALLY_INIT to mark them as __init so they
532 * don't occupy kernel code space unnecessarily.
535 #ifdef CONFIG_USB_FILE_STORAGE_TEST
537 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
538 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
539 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
540 #define backing_file_is_open(curlun) ((curlun)->filp != NULL)
541 #define NORMALLY_INIT
545 #define transport_is_bbb() 1
546 #define transport_is_cbi() 0
547 #define protocol_is_scsi() 1
548 #define backing_file_is_open(curlun) 1
549 #define NORMALLY_INIT __init
551 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
560 unsigned int prevent_medium_removal : 1;
561 unsigned int registered : 1;
565 u32 unit_attention_data;
570 static inline struct lun *dev_to_lun(struct device *dev)
572 return container_of(dev, struct lun, dev);
576 /* Big enough to hold our biggest descriptor */
577 #define EP0_BUFSIZE 256
578 #define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
580 /* Number of buffers we will use. 2 is enough for double-buffering */
581 #define NUM_BUFFERS 2
583 enum fsg_buffer_state {
592 volatile enum fsg_buffer_state state;
593 struct fsg_buffhd *next;
595 /* The NetChip 2280 is faster, and handles some protocol faults
596 * better, if we don't submit any short bulk-out read requests.
597 * So we will record the intended request length here. */
598 unsigned int bulk_out_intended_length;
600 struct usb_request *inreq;
601 volatile int inreq_busy;
602 struct usb_request *outreq;
603 volatile int outreq_busy;
607 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
608 FSG_STATE_DATA_PHASE,
609 FSG_STATE_STATUS_PHASE,
612 FSG_STATE_ABORT_BULK_OUT,
614 FSG_STATE_INTERFACE_CHANGE,
615 FSG_STATE_CONFIG_CHANGE,
616 FSG_STATE_DISCONNECT,
621 enum data_direction {
622 DATA_DIR_UNKNOWN = 0,
629 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
631 struct usb_gadget *gadget;
633 /* filesem protects: backing files in use */
634 struct rw_semaphore filesem;
636 struct usb_ep *ep0; // Handy copy of gadget->ep0
637 struct usb_request *ep0req; // For control responses
638 volatile unsigned int ep0_req_tag;
639 const char *ep0req_name;
641 struct usb_request *intreq; // For interrupt responses
642 volatile int intreq_busy;
643 struct fsg_buffhd *intr_buffhd;
645 unsigned int bulk_out_maxpacket;
646 enum fsg_state state; // For exception handling
647 unsigned int exception_req_tag;
649 u8 config, new_config;
651 unsigned int running : 1;
652 unsigned int bulk_in_enabled : 1;
653 unsigned int bulk_out_enabled : 1;
654 unsigned int intr_in_enabled : 1;
655 unsigned int phase_error : 1;
656 unsigned int short_packet_received : 1;
657 unsigned int bad_lun_okay : 1;
659 unsigned long atomic_bitflags;
661 #define CLEAR_BULK_HALTS 1
663 struct usb_ep *bulk_in;
664 struct usb_ep *bulk_out;
665 struct usb_ep *intr_in;
667 struct fsg_buffhd *next_buffhd_to_fill;
668 struct fsg_buffhd *next_buffhd_to_drain;
669 struct fsg_buffhd buffhds[NUM_BUFFERS];
671 wait_queue_head_t thread_wqh;
672 int thread_wakeup_needed;
673 struct completion thread_notifier;
675 struct task_struct *thread_task;
676 sigset_t thread_signal_mask;
679 u8 cmnd[MAX_COMMAND_SIZE];
680 enum data_direction data_dir;
682 u32 data_size_from_cmnd;
688 /* The CB protocol offers no way for a host to know when a command
689 * has completed. As a result the next command may arrive early,
690 * and we will still have to handle it. For that reason we need
691 * a buffer to store new commands when using CB (or CBI, which
692 * does not oblige a host to wait for command completion either). */
694 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
699 struct completion lun_released;
702 typedef void (*fsg_routine_t)(struct fsg_dev *);
704 static int inline exception_in_progress(struct fsg_dev *fsg)
706 return (fsg->state > FSG_STATE_IDLE);
709 /* Make bulk-out requests be divisible by the maxpacket size */
710 static void inline set_bulk_out_req_length(struct fsg_dev *fsg,
711 struct fsg_buffhd *bh, unsigned int length)
715 bh->bulk_out_intended_length = length;
716 rem = length % fsg->bulk_out_maxpacket;
718 length += fsg->bulk_out_maxpacket - rem;
719 bh->outreq->length = length;
722 static struct fsg_dev *the_fsg;
723 static struct usb_gadget_driver fsg_driver;
725 static void close_backing_file(struct lun *curlun);
726 static void close_all_backing_files(struct fsg_dev *fsg);
729 /*-------------------------------------------------------------------------*/
733 static void dump_msg(struct fsg_dev *fsg, const char *label,
734 const u8 *buf, unsigned int length)
736 unsigned int start, num, i;
741 DBG(fsg, "%s, length %u:\n", label, length);
745 num = min(length, 16u);
747 for (i = 0; i < num; ++i) {
750 sprintf(p, " %02x", buf[i]);
754 printk(KERN_DEBUG "%6x: %s\n", start, line);
761 static void inline dump_cdb(struct fsg_dev *fsg)
766 static void inline dump_msg(struct fsg_dev *fsg, const char *label,
767 const u8 *buf, unsigned int length)
770 static void inline dump_cdb(struct fsg_dev *fsg)
773 char cmdbuf[3*MAX_COMMAND_SIZE + 1];
775 for (i = 0; i < fsg->cmnd_size; ++i)
776 sprintf(cmdbuf + i*3, " %02x", fsg->cmnd[i]);
777 VDBG(fsg, "SCSI CDB: %s\n", cmdbuf);
780 #endif /* DUMP_MSGS */
783 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
787 if (ep == fsg->bulk_in)
789 else if (ep == fsg->bulk_out)
793 DBG(fsg, "%s set halt\n", name);
794 return usb_ep_set_halt(ep);
798 /*-------------------------------------------------------------------------*/
800 /* Routines for unaligned data access */
802 static u16 inline get_be16(u8 *buf)
804 return ((u16) buf[0] << 8) | ((u16) buf[1]);
807 static u32 inline get_be32(u8 *buf)
809 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
810 ((u32) buf[2] << 8) | ((u32) buf[3]);
813 static void inline put_be16(u8 *buf, u16 val)
819 static void inline put_be32(u8 *buf, u32 val)
828 /*-------------------------------------------------------------------------*/
831 * DESCRIPTORS ... most are static, but strings and (full) configuration
832 * descriptors are built on demand. Also the (static) config and interface
833 * descriptors are adjusted during fsg_bind().
835 #define STRING_MANUFACTURER 1
836 #define STRING_PRODUCT 2
837 #define STRING_SERIAL 3
839 /* There is only one configuration. */
840 #define CONFIG_VALUE 1
842 static struct usb_device_descriptor
844 .bLength = sizeof device_desc,
845 .bDescriptorType = USB_DT_DEVICE,
847 .bcdUSB = __constant_cpu_to_le16(0x0200),
848 .bDeviceClass = USB_CLASS_PER_INTERFACE,
850 /* The next three values can be overridden by module parameters */
851 .idVendor = __constant_cpu_to_le16(DRIVER_VENDOR_ID),
852 .idProduct = __constant_cpu_to_le16(DRIVER_PRODUCT_ID),
853 .bcdDevice = __constant_cpu_to_le16(0xffff),
855 .iManufacturer = STRING_MANUFACTURER,
856 .iProduct = STRING_PRODUCT,
857 .iSerialNumber = STRING_SERIAL,
858 .bNumConfigurations = 1,
861 static struct usb_config_descriptor
863 .bLength = sizeof config_desc,
864 .bDescriptorType = USB_DT_CONFIG,
866 /* wTotalLength computed by usb_gadget_config_buf() */
868 .bConfigurationValue = CONFIG_VALUE,
869 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
870 .bMaxPower = 1, // self-powered
873 /* There is only one interface. */
875 static struct usb_interface_descriptor
877 .bLength = sizeof intf_desc,
878 .bDescriptorType = USB_DT_INTERFACE,
880 .bNumEndpoints = 2, // Adjusted during fsg_bind()
881 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
882 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
883 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
886 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
887 * and interrupt-in. */
889 static struct usb_endpoint_descriptor
891 .bLength = USB_DT_ENDPOINT_SIZE,
892 .bDescriptorType = USB_DT_ENDPOINT,
894 .bEndpointAddress = USB_DIR_IN,
895 .bmAttributes = USB_ENDPOINT_XFER_BULK,
896 /* wMaxPacketSize set by autoconfiguration */
899 static struct usb_endpoint_descriptor
901 .bLength = USB_DT_ENDPOINT_SIZE,
902 .bDescriptorType = USB_DT_ENDPOINT,
904 .bEndpointAddress = USB_DIR_OUT,
905 .bmAttributes = USB_ENDPOINT_XFER_BULK,
906 /* wMaxPacketSize set by autoconfiguration */
909 static struct usb_endpoint_descriptor
911 .bLength = USB_DT_ENDPOINT_SIZE,
912 .bDescriptorType = USB_DT_ENDPOINT,
914 .bEndpointAddress = USB_DIR_IN,
915 .bmAttributes = USB_ENDPOINT_XFER_INT,
916 .wMaxPacketSize = __constant_cpu_to_le16(2),
917 .bInterval = 32, // frames -> 32 ms
920 static const struct usb_descriptor_header *fs_function[] = {
921 (struct usb_descriptor_header *) &intf_desc,
922 (struct usb_descriptor_header *) &fs_bulk_in_desc,
923 (struct usb_descriptor_header *) &fs_bulk_out_desc,
924 (struct usb_descriptor_header *) &fs_intr_in_desc,
929 #ifdef CONFIG_USB_GADGET_DUALSPEED
932 * USB 2.0 devices need to expose both high speed and full speed
933 * descriptors, unless they only run at full speed.
935 * That means alternate endpoint descriptors (bigger packets)
936 * and a "device qualifier" ... plus more construction options
937 * for the config descriptor.
939 static struct usb_qualifier_descriptor
941 .bLength = sizeof dev_qualifier,
942 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
944 .bcdUSB = __constant_cpu_to_le16(0x0200),
945 .bDeviceClass = USB_CLASS_PER_INTERFACE,
947 .bNumConfigurations = 1,
950 static struct usb_endpoint_descriptor
952 .bLength = USB_DT_ENDPOINT_SIZE,
953 .bDescriptorType = USB_DT_ENDPOINT,
955 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
956 .bmAttributes = USB_ENDPOINT_XFER_BULK,
957 .wMaxPacketSize = __constant_cpu_to_le16(512),
960 static struct usb_endpoint_descriptor
962 .bLength = USB_DT_ENDPOINT_SIZE,
963 .bDescriptorType = USB_DT_ENDPOINT,
965 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
966 .bmAttributes = USB_ENDPOINT_XFER_BULK,
967 .wMaxPacketSize = __constant_cpu_to_le16(512),
968 .bInterval = 1, // NAK every 1 uframe
971 static struct usb_endpoint_descriptor
973 .bLength = USB_DT_ENDPOINT_SIZE,
974 .bDescriptorType = USB_DT_ENDPOINT,
976 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
977 .bmAttributes = USB_ENDPOINT_XFER_INT,
978 .wMaxPacketSize = __constant_cpu_to_le16(2),
979 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
982 static const struct usb_descriptor_header *hs_function[] = {
983 (struct usb_descriptor_header *) &intf_desc,
984 (struct usb_descriptor_header *) &hs_bulk_in_desc,
985 (struct usb_descriptor_header *) &hs_bulk_out_desc,
986 (struct usb_descriptor_header *) &hs_intr_in_desc,
990 /* Maxpacket and other transfer characteristics vary by speed. */
991 #define ep_desc(g,fs,hs) (((g)->speed==USB_SPEED_HIGH) ? (hs) : (fs))
995 /* If there's no high speed support, always use the full-speed descriptor. */
996 #define ep_desc(g,fs,hs) fs
998 #endif /* !CONFIG_USB_GADGET_DUALSPEED */
1001 /* The CBI specification limits the serial string to 12 uppercase hexadecimal
1003 static char manufacturer[40];
1004 static char serial[13];
1006 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1007 static struct usb_string strings[] = {
1008 {STRING_MANUFACTURER, manufacturer},
1009 {STRING_PRODUCT, longname},
1010 {STRING_SERIAL, serial},
1014 static struct usb_gadget_strings stringtab = {
1015 .language = 0x0409, // en-us
1021 * Config descriptors must agree with the code that sets configurations
1022 * and with code managing interfaces and their altsettings. They must
1023 * also handle different speeds and other-speed requests.
1025 static int populate_config_buf(enum usb_device_speed speed,
1026 u8 *buf, u8 type, unsigned index)
1029 const struct usb_descriptor_header **function;
1034 #ifdef CONFIG_USB_GADGET_DUALSPEED
1035 if (type == USB_DT_OTHER_SPEED_CONFIG)
1036 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
1037 if (speed == USB_SPEED_HIGH)
1038 function = hs_function;
1041 function = fs_function;
1043 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
1046 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1051 /*-------------------------------------------------------------------------*/
1053 /* These routines may be called in process context or in_irq */
1055 static void wakeup_thread(struct fsg_dev *fsg)
1057 /* Tell the main thread that something has happened */
1058 fsg->thread_wakeup_needed = 1;
1059 wake_up_all(&fsg->thread_wqh);
1063 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
1065 unsigned long flags;
1066 struct task_struct *thread_task;
1068 /* Do nothing if a higher-priority exception is already in progress.
1069 * If a lower-or-equal priority exception is in progress, preempt it
1070 * and notify the main thread by sending it a signal. */
1071 spin_lock_irqsave(&fsg->lock, flags);
1072 if (fsg->state <= new_state) {
1073 fsg->exception_req_tag = fsg->ep0_req_tag;
1074 fsg->state = new_state;
1075 thread_task = fsg->thread_task;
1077 send_sig_info(SIGUSR1, SEND_SIG_FORCED, thread_task);
1079 spin_unlock_irqrestore(&fsg->lock, flags);
1083 /*-------------------------------------------------------------------------*/
1085 /* The disconnect callback and ep0 routines. These always run in_irq,
1086 * except that ep0_queue() is called in the main thread to acknowledge
1087 * completion of various requests: set config, set interface, and
1088 * Bulk-only device reset. */
1090 static void fsg_disconnect(struct usb_gadget *gadget)
1092 struct fsg_dev *fsg = get_gadget_data(gadget);
1094 DBG(fsg, "disconnect or port reset\n");
1095 raise_exception(fsg, FSG_STATE_DISCONNECT);
1099 static int ep0_queue(struct fsg_dev *fsg)
1103 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
1104 if (rc != 0 && rc != -ESHUTDOWN) {
1106 /* We can't do much more than wait for a reset */
1107 WARN(fsg, "error in submission: %s --> %d\n",
1108 fsg->ep0->name, rc);
1113 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
1115 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1117 if (req->actual > 0)
1118 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
1119 if (req->status || req->actual != req->length)
1120 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1121 req->status, req->actual, req->length);
1122 if (req->status == -ECONNRESET) // Request was cancelled
1123 usb_ep_fifo_flush(ep);
1125 if (req->status == 0 && req->context)
1126 ((fsg_routine_t) (req->context))(fsg);
1130 /*-------------------------------------------------------------------------*/
1132 /* Bulk and interrupt endpoint completion handlers.
1133 * These always run in_irq. */
1135 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
1137 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1138 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1140 if (req->status || req->actual != req->length)
1141 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1142 req->status, req->actual, req->length);
1143 if (req->status == -ECONNRESET) // Request was cancelled
1144 usb_ep_fifo_flush(ep);
1146 /* Hold the lock while we update the request and buffer states */
1147 spin_lock(&fsg->lock);
1149 bh->state = BUF_STATE_EMPTY;
1150 spin_unlock(&fsg->lock);
1154 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
1156 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1157 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1159 dump_msg(fsg, "bulk-out", req->buf, req->actual);
1160 if (req->status || req->actual != bh->bulk_out_intended_length)
1161 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1162 req->status, req->actual,
1163 bh->bulk_out_intended_length);
1164 if (req->status == -ECONNRESET) // Request was cancelled
1165 usb_ep_fifo_flush(ep);
1167 /* Hold the lock while we update the request and buffer states */
1168 spin_lock(&fsg->lock);
1169 bh->outreq_busy = 0;
1170 bh->state = BUF_STATE_FULL;
1171 spin_unlock(&fsg->lock);
1175 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1177 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1178 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1179 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1181 if (req->status || req->actual != req->length)
1182 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1183 req->status, req->actual, req->length);
1184 if (req->status == -ECONNRESET) // Request was cancelled
1185 usb_ep_fifo_flush(ep);
1187 /* Hold the lock while we update the request and buffer states */
1188 spin_lock(&fsg->lock);
1189 fsg->intreq_busy = 0;
1190 bh->state = BUF_STATE_EMPTY;
1191 spin_unlock(&fsg->lock);
1193 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1197 /*-------------------------------------------------------------------------*/
1199 /* Ep0 class-specific handlers. These always run in_irq. */
1201 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1203 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1204 struct usb_request *req = fsg->ep0req;
1205 static u8 cbi_reset_cmnd[6] = {
1206 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
1208 /* Error in command transfer? */
1209 if (req->status || req->length != req->actual ||
1210 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
1212 /* Not all controllers allow a protocol stall after
1213 * receiving control-out data, but we'll try anyway. */
1214 fsg_set_halt(fsg, fsg->ep0);
1215 return; // Wait for reset
1218 /* Is it the special reset command? */
1219 if (req->actual >= sizeof cbi_reset_cmnd &&
1220 memcmp(req->buf, cbi_reset_cmnd,
1221 sizeof cbi_reset_cmnd) == 0) {
1223 /* Raise an exception to stop the current operation
1224 * and reinitialize our state. */
1225 DBG(fsg, "cbi reset request\n");
1226 raise_exception(fsg, FSG_STATE_RESET);
1230 VDBG(fsg, "CB[I] accept device-specific command\n");
1231 spin_lock(&fsg->lock);
1233 /* Save the command for later */
1234 if (fsg->cbbuf_cmnd_size)
1235 WARN(fsg, "CB[I] overwriting previous command\n");
1236 fsg->cbbuf_cmnd_size = req->actual;
1237 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
1239 spin_unlock(&fsg->lock);
1241 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1245 static int class_setup_req(struct fsg_dev *fsg,
1246 const struct usb_ctrlrequest *ctrl)
1248 struct usb_request *req = fsg->ep0req;
1249 int value = -EOPNOTSUPP;
1254 /* Handle Bulk-only class-specific requests */
1255 if (transport_is_bbb()) {
1256 switch (ctrl->bRequest) {
1258 case USB_BULK_RESET_REQUEST:
1259 if (ctrl->bRequestType != (USB_DIR_OUT |
1260 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1262 if (ctrl->wIndex != 0) {
1267 /* Raise an exception to stop the current operation
1268 * and reinitialize our state. */
1269 DBG(fsg, "bulk reset request\n");
1270 raise_exception(fsg, FSG_STATE_RESET);
1271 value = DELAYED_STATUS;
1274 case USB_BULK_GET_MAX_LUN_REQUEST:
1275 if (ctrl->bRequestType != (USB_DIR_IN |
1276 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1278 if (ctrl->wIndex != 0) {
1282 VDBG(fsg, "get max LUN\n");
1283 *(u8 *) req->buf = fsg->nluns - 1;
1284 value = min(ctrl->wLength, (u16) 1);
1289 /* Handle CBI class-specific requests */
1291 switch (ctrl->bRequest) {
1293 case USB_CBI_ADSC_REQUEST:
1294 if (ctrl->bRequestType != (USB_DIR_OUT |
1295 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1297 if (ctrl->wIndex != 0) {
1301 if (ctrl->wLength > MAX_COMMAND_SIZE) {
1305 value = ctrl->wLength;
1306 fsg->ep0req->context = received_cbi_adsc;
1311 if (value == -EOPNOTSUPP)
1313 "unknown class-specific control req "
1314 "%02x.%02x v%04x i%04x l%u\n",
1315 ctrl->bRequestType, ctrl->bRequest,
1316 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1321 /*-------------------------------------------------------------------------*/
1323 /* Ep0 standard request handlers. These always run in_irq. */
1325 static int standard_setup_req(struct fsg_dev *fsg,
1326 const struct usb_ctrlrequest *ctrl)
1328 struct usb_request *req = fsg->ep0req;
1329 int value = -EOPNOTSUPP;
1331 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1332 * but config change events will also reconfigure hardware. */
1333 switch (ctrl->bRequest) {
1335 case USB_REQ_GET_DESCRIPTOR:
1336 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1339 switch (ctrl->wValue >> 8) {
1342 VDBG(fsg, "get device descriptor\n");
1343 value = min(ctrl->wLength, (u16) sizeof device_desc);
1344 memcpy(req->buf, &device_desc, value);
1346 #ifdef CONFIG_USB_GADGET_DUALSPEED
1347 case USB_DT_DEVICE_QUALIFIER:
1348 VDBG(fsg, "get device qualifier\n");
1349 if (!fsg->gadget->is_dualspeed)
1351 value = min(ctrl->wLength, (u16) sizeof dev_qualifier);
1352 memcpy(req->buf, &dev_qualifier, value);
1355 case USB_DT_OTHER_SPEED_CONFIG:
1356 VDBG(fsg, "get other-speed config descriptor\n");
1357 if (!fsg->gadget->is_dualspeed)
1362 VDBG(fsg, "get configuration descriptor\n");
1363 #ifdef CONFIG_USB_GADGET_DUALSPEED
1366 value = populate_config_buf(fsg->gadget->speed,
1369 ctrl->wValue & 0xff);
1371 value = min(ctrl->wLength, (u16) value);
1375 VDBG(fsg, "get string descriptor\n");
1377 /* wIndex == language code */
1378 value = usb_gadget_get_string(&stringtab,
1379 ctrl->wValue & 0xff, req->buf);
1381 value = min(ctrl->wLength, (u16) value);
1386 /* One config, two speeds */
1387 case USB_REQ_SET_CONFIGURATION:
1388 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
1391 VDBG(fsg, "set configuration\n");
1392 if (ctrl->wValue == CONFIG_VALUE || ctrl->wValue == 0) {
1393 fsg->new_config = ctrl->wValue;
1395 /* Raise an exception to wipe out previous transaction
1396 * state (queued bufs, etc) and set the new config. */
1397 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1398 value = DELAYED_STATUS;
1401 case USB_REQ_GET_CONFIGURATION:
1402 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1405 VDBG(fsg, "get configuration\n");
1406 *(u8 *) req->buf = fsg->config;
1407 value = min(ctrl->wLength, (u16) 1);
1410 case USB_REQ_SET_INTERFACE:
1411 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1412 USB_RECIP_INTERFACE))
1414 if (fsg->config && ctrl->wIndex == 0) {
1416 /* Raise an exception to wipe out previous transaction
1417 * state (queued bufs, etc) and install the new
1418 * interface altsetting. */
1419 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1420 value = DELAYED_STATUS;
1423 case USB_REQ_GET_INTERFACE:
1424 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1425 USB_RECIP_INTERFACE))
1429 if (ctrl->wIndex != 0) {
1433 VDBG(fsg, "get interface\n");
1434 *(u8 *) req->buf = 0;
1435 value = min(ctrl->wLength, (u16) 1);
1440 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1441 ctrl->bRequestType, ctrl->bRequest,
1442 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1449 static int fsg_setup(struct usb_gadget *gadget,
1450 const struct usb_ctrlrequest *ctrl)
1452 struct fsg_dev *fsg = get_gadget_data(gadget);
1455 ++fsg->ep0_req_tag; // Record arrival of a new request
1456 fsg->ep0req->context = NULL;
1457 fsg->ep0req->length = 0;
1458 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1460 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1461 rc = class_setup_req(fsg, ctrl);
1463 rc = standard_setup_req(fsg, ctrl);
1465 /* Respond with data/status or defer until later? */
1466 if (rc >= 0 && rc != DELAYED_STATUS) {
1467 fsg->ep0req->length = rc;
1468 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1469 "ep0-in" : "ep0-out");
1470 rc = ep0_queue(fsg);
1473 /* Device either stalls (rc < 0) or reports success */
1478 /*-------------------------------------------------------------------------*/
1480 /* All the following routines run in process context */
1483 /* Use this for bulk or interrupt transfers, not ep0 */
1484 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1485 struct usb_request *req, volatile int *pbusy,
1486 volatile enum fsg_buffer_state *state)
1490 if (ep == fsg->bulk_in)
1491 dump_msg(fsg, "bulk-in", req->buf, req->length);
1492 else if (ep == fsg->intr_in)
1493 dump_msg(fsg, "intr-in", req->buf, req->length);
1495 *state = BUF_STATE_BUSY;
1496 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1499 *state = BUF_STATE_EMPTY;
1501 /* We can't do much more than wait for a reset */
1503 /* Note: currently the net2280 driver fails zero-length
1504 * submissions if DMA is enabled. */
1505 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1507 WARN(fsg, "error in submission: %s --> %d\n",
1513 static int sleep_thread(struct fsg_dev *fsg)
1517 /* Wait until a signal arrives or we are woken up */
1518 rc = wait_event_interruptible(fsg->thread_wqh,
1519 fsg->thread_wakeup_needed);
1520 fsg->thread_wakeup_needed = 0;
1521 return (rc ? -EINTR : 0);
1525 /*-------------------------------------------------------------------------*/
1527 static int do_read(struct fsg_dev *fsg)
1529 struct lun *curlun = fsg->curlun;
1531 struct fsg_buffhd *bh;
1534 loff_t file_offset, file_offset_tmp;
1535 unsigned int amount;
1536 unsigned int partial_page;
1539 /* Get the starting Logical Block Address and check that it's
1541 if (fsg->cmnd[0] == SC_READ_6)
1542 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1544 lba = get_be32(&fsg->cmnd[2]);
1546 /* We allow DPO (Disable Page Out = don't save data in the
1547 * cache) and FUA (Force Unit Access = don't read from the
1548 * cache), but we don't implement them. */
1549 if ((fsg->cmnd[1] & ~0x18) != 0) {
1550 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1554 if (lba >= curlun->num_sectors) {
1555 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1558 file_offset = ((loff_t) lba) << 9;
1560 /* Carry out the file reads */
1561 amount_left = fsg->data_size_from_cmnd;
1562 if (unlikely(amount_left == 0))
1563 return -EIO; // No default reply
1567 /* Figure out how much we need to read:
1568 * Try to read the remaining amount.
1569 * But don't read more than the buffer size.
1570 * And don't try to read past the end of the file.
1571 * Finally, if we're not at a page boundary, don't read past
1573 * If this means reading 0 then we were asked to read past
1574 * the end of file. */
1575 amount = min((unsigned int) amount_left, mod_data.buflen);
1576 amount = min((loff_t) amount,
1577 curlun->file_length - file_offset);
1578 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1579 if (partial_page > 0)
1580 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1583 /* Wait for the next buffer to become available */
1584 bh = fsg->next_buffhd_to_fill;
1585 while (bh->state != BUF_STATE_EMPTY) {
1586 if ((rc = sleep_thread(fsg)) != 0)
1590 /* If we were asked to read past the end of file,
1591 * end with an empty buffer. */
1593 curlun->sense_data =
1594 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1595 curlun->sense_data_info = file_offset >> 9;
1596 bh->inreq->length = 0;
1597 bh->state = BUF_STATE_FULL;
1601 /* Perform the read */
1602 file_offset_tmp = file_offset;
1603 nread = vfs_read(curlun->filp,
1604 (char __user *) bh->buf,
1605 amount, &file_offset_tmp);
1606 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1607 (unsigned long long) file_offset,
1609 if (signal_pending(current))
1613 LDBG(curlun, "error in file read: %d\n",
1616 } else if (nread < amount) {
1617 LDBG(curlun, "partial file read: %d/%u\n",
1618 (int) nread, amount);
1619 nread -= (nread & 511); // Round down to a block
1621 file_offset += nread;
1622 amount_left -= nread;
1623 fsg->residue -= nread;
1624 bh->inreq->length = nread;
1625 bh->state = BUF_STATE_FULL;
1627 /* If an error occurred, report it and its position */
1628 if (nread < amount) {
1629 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1630 curlun->sense_data_info = file_offset >> 9;
1634 if (amount_left == 0)
1635 break; // No more left to read
1637 /* Send this buffer and go read some more */
1638 bh->inreq->zero = 0;
1639 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1640 &bh->inreq_busy, &bh->state);
1641 fsg->next_buffhd_to_fill = bh->next;
1644 return -EIO; // No default reply
1648 /*-------------------------------------------------------------------------*/
1650 static int do_write(struct fsg_dev *fsg)
1652 struct lun *curlun = fsg->curlun;
1654 struct fsg_buffhd *bh;
1656 u32 amount_left_to_req, amount_left_to_write;
1657 loff_t usb_offset, file_offset, file_offset_tmp;
1658 unsigned int amount;
1659 unsigned int partial_page;
1664 curlun->sense_data = SS_WRITE_PROTECTED;
1667 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1669 /* Get the starting Logical Block Address and check that it's
1671 if (fsg->cmnd[0] == SC_WRITE_6)
1672 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1674 lba = get_be32(&fsg->cmnd[2]);
1676 /* We allow DPO (Disable Page Out = don't save data in the
1677 * cache) and FUA (Force Unit Access = write directly to the
1678 * medium). We don't implement DPO; we implement FUA by
1679 * performing synchronous output. */
1680 if ((fsg->cmnd[1] & ~0x18) != 0) {
1681 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1684 if (fsg->cmnd[1] & 0x08) // FUA
1685 curlun->filp->f_flags |= O_SYNC;
1687 if (lba >= curlun->num_sectors) {
1688 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1692 /* Carry out the file writes */
1694 file_offset = usb_offset = ((loff_t) lba) << 9;
1695 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1697 while (amount_left_to_write > 0) {
1699 /* Queue a request for more data from the host */
1700 bh = fsg->next_buffhd_to_fill;
1701 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1703 /* Figure out how much we want to get:
1704 * Try to get the remaining amount.
1705 * But don't get more than the buffer size.
1706 * And don't try to go past the end of the file.
1707 * If we're not at a page boundary,
1708 * don't go past the next page.
1709 * If this means getting 0, then we were asked
1710 * to write past the end of file.
1711 * Finally, round down to a block boundary. */
1712 amount = min(amount_left_to_req, mod_data.buflen);
1713 amount = min((loff_t) amount, curlun->file_length -
1715 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1716 if (partial_page > 0)
1717 amount = min(amount,
1718 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1722 curlun->sense_data =
1723 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1724 curlun->sense_data_info = usb_offset >> 9;
1727 amount -= (amount & 511);
1730 /* Why were we were asked to transfer a
1736 /* Get the next buffer */
1737 usb_offset += amount;
1738 fsg->usb_amount_left -= amount;
1739 amount_left_to_req -= amount;
1740 if (amount_left_to_req == 0)
1743 /* amount is always divisible by 512, hence by
1744 * the bulk-out maxpacket size */
1745 bh->outreq->length = bh->bulk_out_intended_length =
1747 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1748 &bh->outreq_busy, &bh->state);
1749 fsg->next_buffhd_to_fill = bh->next;
1753 /* Write the received data to the backing file */
1754 bh = fsg->next_buffhd_to_drain;
1755 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1756 break; // We stopped early
1757 if (bh->state == BUF_STATE_FULL) {
1758 fsg->next_buffhd_to_drain = bh->next;
1759 bh->state = BUF_STATE_EMPTY;
1761 /* Did something go wrong with the transfer? */
1762 if (bh->outreq->status != 0) {
1763 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1764 curlun->sense_data_info = file_offset >> 9;
1768 amount = bh->outreq->actual;
1769 if (curlun->file_length - file_offset < amount) {
1771 "write %u @ %llu beyond end %llu\n",
1772 amount, (unsigned long long) file_offset,
1773 (unsigned long long) curlun->file_length);
1774 amount = curlun->file_length - file_offset;
1777 /* Perform the write */
1778 file_offset_tmp = file_offset;
1779 nwritten = vfs_write(curlun->filp,
1780 (char __user *) bh->buf,
1781 amount, &file_offset_tmp);
1782 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1783 (unsigned long long) file_offset,
1785 if (signal_pending(current))
1786 return -EINTR; // Interrupted!
1789 LDBG(curlun, "error in file write: %d\n",
1792 } else if (nwritten < amount) {
1793 LDBG(curlun, "partial file write: %d/%u\n",
1794 (int) nwritten, amount);
1795 nwritten -= (nwritten & 511);
1796 // Round down to a block
1798 file_offset += nwritten;
1799 amount_left_to_write -= nwritten;
1800 fsg->residue -= nwritten;
1802 /* If an error occurred, report it and its position */
1803 if (nwritten < amount) {
1804 curlun->sense_data = SS_WRITE_ERROR;
1805 curlun->sense_data_info = file_offset >> 9;
1809 /* Did the host decide to stop early? */
1810 if (bh->outreq->actual != bh->outreq->length) {
1811 fsg->short_packet_received = 1;
1817 /* Wait for something to happen */
1818 if ((rc = sleep_thread(fsg)) != 0)
1822 return -EIO; // No default reply
1826 /*-------------------------------------------------------------------------*/
1828 /* Sync the file data, don't bother with the metadata.
1829 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1830 static int fsync_sub(struct lun *curlun)
1832 struct file *filp = curlun->filp;
1833 struct inode *inode;
1836 if (curlun->ro || !filp)
1838 if (!filp->f_op->fsync)
1841 inode = filp->f_dentry->d_inode;
1842 down(&inode->i_sem);
1843 current->flags |= PF_SYNCWRITE;
1844 rc = filemap_fdatawrite(inode->i_mapping);
1845 err = filp->f_op->fsync(filp, filp->f_dentry, 1);
1848 err = filemap_fdatawait(inode->i_mapping);
1851 current->flags &= ~PF_SYNCWRITE;
1853 VLDBG(curlun, "fdatasync -> %d\n", rc);
1857 static void fsync_all(struct fsg_dev *fsg)
1861 for (i = 0; i < fsg->nluns; ++i)
1862 fsync_sub(&fsg->luns[i]);
1865 static int do_synchronize_cache(struct fsg_dev *fsg)
1867 struct lun *curlun = fsg->curlun;
1870 /* We ignore the requested LBA and write out all file's
1871 * dirty data buffers. */
1872 rc = fsync_sub(curlun);
1874 curlun->sense_data = SS_WRITE_ERROR;
1879 /*-------------------------------------------------------------------------*/
1881 static void invalidate_sub(struct lun *curlun)
1883 struct file *filp = curlun->filp;
1884 struct inode *inode = filp->f_dentry->d_inode;
1887 rc = invalidate_inode_pages(inode->i_mapping);
1888 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1891 static int do_verify(struct fsg_dev *fsg)
1893 struct lun *curlun = fsg->curlun;
1895 u32 verification_length;
1896 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1897 loff_t file_offset, file_offset_tmp;
1899 unsigned int amount;
1902 /* Get the starting Logical Block Address and check that it's
1904 lba = get_be32(&fsg->cmnd[2]);
1905 if (lba >= curlun->num_sectors) {
1906 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1910 /* We allow DPO (Disable Page Out = don't save data in the
1911 * cache) but we don't implement it. */
1912 if ((fsg->cmnd[1] & ~0x10) != 0) {
1913 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1917 verification_length = get_be16(&fsg->cmnd[7]);
1918 if (unlikely(verification_length == 0))
1919 return -EIO; // No default reply
1921 /* Prepare to carry out the file verify */
1922 amount_left = verification_length << 9;
1923 file_offset = ((loff_t) lba) << 9;
1925 /* Write out all the dirty buffers before invalidating them */
1927 if (signal_pending(current))
1930 invalidate_sub(curlun);
1931 if (signal_pending(current))
1934 /* Just try to read the requested blocks */
1935 while (amount_left > 0) {
1937 /* Figure out how much we need to read:
1938 * Try to read the remaining amount, but not more than
1940 * And don't try to read past the end of the file.
1941 * If this means reading 0 then we were asked to read
1942 * past the end of file. */
1943 amount = min((unsigned int) amount_left, mod_data.buflen);
1944 amount = min((loff_t) amount,
1945 curlun->file_length - file_offset);
1947 curlun->sense_data =
1948 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1949 curlun->sense_data_info = file_offset >> 9;
1953 /* Perform the read */
1954 file_offset_tmp = file_offset;
1955 nread = vfs_read(curlun->filp,
1956 (char __user *) bh->buf,
1957 amount, &file_offset_tmp);
1958 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1959 (unsigned long long) file_offset,
1961 if (signal_pending(current))
1965 LDBG(curlun, "error in file verify: %d\n",
1968 } else if (nread < amount) {
1969 LDBG(curlun, "partial file verify: %d/%u\n",
1970 (int) nread, amount);
1971 nread -= (nread & 511); // Round down to a sector
1974 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1975 curlun->sense_data_info = file_offset >> 9;
1978 file_offset += nread;
1979 amount_left -= nread;
1985 /*-------------------------------------------------------------------------*/
1987 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1989 u8 *buf = (u8 *) bh->buf;
1991 static char vendor_id[] = "Linux ";
1992 static char product_id[] = "File-Stor Gadget";
1994 if (!fsg->curlun) { // Unsupported LUNs are okay
1995 fsg->bad_lun_okay = 1;
1997 buf[0] = 0x7f; // Unsupported, no device-type
2001 memset(buf, 0, 8); // Non-removable, direct-access device
2002 if (mod_data.removable)
2004 buf[2] = 2; // ANSI SCSI level 2
2005 buf[3] = 2; // SCSI-2 INQUIRY data format
2006 buf[4] = 31; // Additional length
2007 // No special options
2008 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id, product_id,
2014 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2016 struct lun *curlun = fsg->curlun;
2017 u8 *buf = (u8 *) bh->buf;
2021 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2023 * If a REQUEST SENSE command is received from an initiator
2024 * with a pending unit attention condition (before the target
2025 * generates the contingent allegiance condition), then the
2026 * target shall either:
2027 * a) report any pending sense data and preserve the unit
2028 * attention condition on the logical unit, or,
2029 * b) report the unit attention condition, may discard any
2030 * pending sense data, and clear the unit attention
2031 * condition on the logical unit for that initiator.
2033 * FSG normally uses option a); enable this code to use option b).
2036 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2037 curlun->sense_data = curlun->unit_attention_data;
2038 curlun->unit_attention_data = SS_NO_SENSE;
2042 if (!curlun) { // Unsupported LUNs are okay
2043 fsg->bad_lun_okay = 1;
2044 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2047 sd = curlun->sense_data;
2048 sdinfo = curlun->sense_data_info;
2049 curlun->sense_data = SS_NO_SENSE;
2050 curlun->sense_data_info = 0;
2054 buf[0] = 0x80 | 0x70; // Valid, current error
2056 put_be32(&buf[3], sdinfo); // Sense information
2057 buf[7] = 18 - 8; // Additional sense length
2064 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2066 struct lun *curlun = fsg->curlun;
2067 u32 lba = get_be32(&fsg->cmnd[2]);
2068 int pmi = fsg->cmnd[8];
2069 u8 *buf = (u8 *) bh->buf;
2071 /* Check the PMI and LBA fields */
2072 if (pmi > 1 || (pmi == 0 && lba != 0)) {
2073 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2077 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block
2078 put_be32(&buf[4], 512); // Block length
2083 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2085 struct lun *curlun = fsg->curlun;
2086 int mscmnd = fsg->cmnd[0];
2087 u8 *buf = (u8 *) bh->buf;
2090 int changeable_values, all_pages;
2094 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
2095 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2098 pc = fsg->cmnd[2] >> 6;
2099 page_code = fsg->cmnd[2] & 0x3f;
2101 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2104 changeable_values = (pc == 1);
2105 all_pages = (page_code == 0x3f);
2107 /* Write the mode parameter header. Fixed values are: default
2108 * medium type, no cache control (DPOFUA), and no block descriptors.
2109 * The only variable value is the WriteProtect bit. We will fill in
2110 * the mode data length later. */
2112 if (mscmnd == SC_MODE_SENSE_6) {
2113 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2116 } else { // SC_MODE_SENSE_10
2117 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2119 limit = 65535; // Should really be mod_data.buflen
2122 /* No block descriptors */
2124 /* The mode pages, in numerical order. The only page we support
2125 * is the Caching page. */
2126 if (page_code == 0x08 || all_pages) {
2128 buf[0] = 0x08; // Page code
2129 buf[1] = 10; // Page length
2130 memset(buf+2, 0, 10); // None of the fields are changeable
2132 if (!changeable_values) {
2133 buf[2] = 0x04; // Write cache enable,
2134 // Read cache not disabled
2135 // No cache retention priorities
2136 put_be16(&buf[4], 0xffff); // Don't disable prefetch
2137 // Minimum prefetch = 0
2138 put_be16(&buf[8], 0xffff); // Maximum prefetch
2139 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2144 /* Check that a valid page was requested and the mode data length
2145 * isn't too long. */
2147 if (!valid_page || len > limit) {
2148 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2152 /* Store the mode data length */
2153 if (mscmnd == SC_MODE_SENSE_6)
2156 put_be16(buf0, len - 2);
2161 static int do_start_stop(struct fsg_dev *fsg)
2163 struct lun *curlun = fsg->curlun;
2166 if (!mod_data.removable) {
2167 curlun->sense_data = SS_INVALID_COMMAND;
2171 // int immed = fsg->cmnd[1] & 0x01;
2172 loej = fsg->cmnd[4] & 0x02;
2173 start = fsg->cmnd[4] & 0x01;
2175 #ifdef CONFIG_USB_FILE_STORAGE_TEST
2176 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
2177 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
2178 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2184 /* Are we allowed to unload the media? */
2185 if (curlun->prevent_medium_removal) {
2186 LDBG(curlun, "unload attempt prevented\n");
2187 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2190 if (loej) { // Simulate an unload/eject
2191 up_read(&fsg->filesem);
2192 down_write(&fsg->filesem);
2193 close_backing_file(curlun);
2194 up_write(&fsg->filesem);
2195 down_read(&fsg->filesem);
2199 /* Our emulation doesn't support mounting; the medium is
2200 * available for use as soon as it is loaded. */
2201 if (!backing_file_is_open(curlun)) {
2202 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2211 static int do_prevent_allow(struct fsg_dev *fsg)
2213 struct lun *curlun = fsg->curlun;
2216 if (!mod_data.removable) {
2217 curlun->sense_data = SS_INVALID_COMMAND;
2221 prevent = fsg->cmnd[4] & 0x01;
2222 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
2223 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2227 if (curlun->prevent_medium_removal && !prevent)
2229 curlun->prevent_medium_removal = prevent;
2234 static int do_read_format_capacities(struct fsg_dev *fsg,
2235 struct fsg_buffhd *bh)
2237 struct lun *curlun = fsg->curlun;
2238 u8 *buf = (u8 *) bh->buf;
2240 buf[0] = buf[1] = buf[2] = 0;
2241 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
2244 put_be32(&buf[0], curlun->num_sectors); // Number of blocks
2245 put_be32(&buf[4], 512); // Block length
2246 buf[4] = 0x02; // Current capacity
2251 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2253 struct lun *curlun = fsg->curlun;
2255 /* We don't support MODE SELECT */
2256 curlun->sense_data = SS_INVALID_COMMAND;
2261 /*-------------------------------------------------------------------------*/
2263 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2267 rc = fsg_set_halt(fsg, fsg->bulk_in);
2269 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2271 if (rc != -EAGAIN) {
2272 WARN(fsg, "usb_ep_set_halt -> %d\n", rc);
2277 /* Wait for a short time and then try again */
2278 set_current_state(TASK_INTERRUPTIBLE);
2279 if (schedule_timeout(HZ / 10) != 0)
2281 rc = usb_ep_set_halt(fsg->bulk_in);
2286 static int pad_with_zeros(struct fsg_dev *fsg)
2288 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2289 u32 nkeep = bh->inreq->length;
2293 bh->state = BUF_STATE_EMPTY; // For the first iteration
2294 fsg->usb_amount_left = nkeep + fsg->residue;
2295 while (fsg->usb_amount_left > 0) {
2297 /* Wait for the next buffer to be free */
2298 while (bh->state != BUF_STATE_EMPTY) {
2299 if ((rc = sleep_thread(fsg)) != 0)
2303 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2304 memset(bh->buf + nkeep, 0, nsend - nkeep);
2305 bh->inreq->length = nsend;
2306 bh->inreq->zero = 0;
2307 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2308 &bh->inreq_busy, &bh->state);
2309 bh = fsg->next_buffhd_to_fill = bh->next;
2310 fsg->usb_amount_left -= nsend;
2316 static int throw_away_data(struct fsg_dev *fsg)
2318 struct fsg_buffhd *bh;
2322 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2323 fsg->usb_amount_left > 0) {
2325 /* Throw away the data in a filled buffer */
2326 if (bh->state == BUF_STATE_FULL) {
2327 bh->state = BUF_STATE_EMPTY;
2328 fsg->next_buffhd_to_drain = bh->next;
2330 /* A short packet or an error ends everything */
2331 if (bh->outreq->actual != bh->outreq->length ||
2332 bh->outreq->status != 0) {
2333 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2339 /* Try to submit another request if we need one */
2340 bh = fsg->next_buffhd_to_fill;
2341 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2342 amount = min(fsg->usb_amount_left,
2343 (u32) mod_data.buflen);
2345 /* amount is always divisible by 512, hence by
2346 * the bulk-out maxpacket size */
2347 bh->outreq->length = bh->bulk_out_intended_length =
2349 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2350 &bh->outreq_busy, &bh->state);
2351 fsg->next_buffhd_to_fill = bh->next;
2352 fsg->usb_amount_left -= amount;
2356 /* Otherwise wait for something to happen */
2357 if ((rc = sleep_thread(fsg)) != 0)
2364 static int finish_reply(struct fsg_dev *fsg)
2366 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2369 switch (fsg->data_dir) {
2371 break; // Nothing to send
2373 /* If we don't know whether the host wants to read or write,
2374 * this must be CB or CBI with an unknown command. We mustn't
2375 * try to send or receive any data. So stall both bulk pipes
2376 * if we can and wait for a reset. */
2377 case DATA_DIR_UNKNOWN:
2378 if (mod_data.can_stall) {
2379 fsg_set_halt(fsg, fsg->bulk_out);
2380 rc = halt_bulk_in_endpoint(fsg);
2384 /* All but the last buffer of data must have already been sent */
2385 case DATA_DIR_TO_HOST:
2386 if (fsg->data_size == 0)
2387 ; // Nothing to send
2389 /* If there's no residue, simply send the last buffer */
2390 else if (fsg->residue == 0) {
2391 bh->inreq->zero = 0;
2392 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2393 &bh->inreq_busy, &bh->state);
2394 fsg->next_buffhd_to_fill = bh->next;
2397 /* There is a residue. For CB and CBI, simply mark the end
2398 * of the data with a short packet. However, if we are
2399 * allowed to stall, there was no data at all (residue ==
2400 * data_size), and the command failed (invalid LUN or
2401 * sense data is set), then halt the bulk-in endpoint
2403 else if (!transport_is_bbb()) {
2404 if (mod_data.can_stall &&
2405 fsg->residue == fsg->data_size &&
2406 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2407 bh->state = BUF_STATE_EMPTY;
2408 rc = halt_bulk_in_endpoint(fsg);
2410 bh->inreq->zero = 1;
2411 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2412 &bh->inreq_busy, &bh->state);
2413 fsg->next_buffhd_to_fill = bh->next;
2417 /* For Bulk-only, if we're allowed to stall then send the
2418 * short packet and halt the bulk-in endpoint. If we can't
2419 * stall, pad out the remaining data with 0's. */
2421 if (mod_data.can_stall) {
2422 bh->inreq->zero = 1;
2423 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2424 &bh->inreq_busy, &bh->state);
2425 fsg->next_buffhd_to_fill = bh->next;
2426 rc = halt_bulk_in_endpoint(fsg);
2428 rc = pad_with_zeros(fsg);
2432 /* We have processed all we want from the data the host has sent.
2433 * There may still be outstanding bulk-out requests. */
2434 case DATA_DIR_FROM_HOST:
2435 if (fsg->residue == 0)
2436 ; // Nothing to receive
2438 /* Did the host stop sending unexpectedly early? */
2439 else if (fsg->short_packet_received) {
2440 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2444 /* We haven't processed all the incoming data. If we are
2445 * allowed to stall, halt the bulk-out endpoint and cancel
2446 * any outstanding requests. */
2447 else if (mod_data.can_stall) {
2448 fsg_set_halt(fsg, fsg->bulk_out);
2449 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2453 /* We can't stall. Read in the excess data and throw it
2456 rc = throw_away_data(fsg);
2463 static int send_status(struct fsg_dev *fsg)
2465 struct lun *curlun = fsg->curlun;
2466 struct fsg_buffhd *bh;
2468 u8 status = USB_STATUS_PASS;
2471 /* Wait for the next buffer to become available */
2472 bh = fsg->next_buffhd_to_fill;
2473 while (bh->state != BUF_STATE_EMPTY) {
2474 if ((rc = sleep_thread(fsg)) != 0)
2479 sd = curlun->sense_data;
2480 sdinfo = curlun->sense_data_info;
2481 } else if (fsg->bad_lun_okay)
2484 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2486 if (fsg->phase_error) {
2487 DBG(fsg, "sending phase-error status\n");
2488 status = USB_STATUS_PHASE_ERROR;
2489 sd = SS_INVALID_COMMAND;
2490 } else if (sd != SS_NO_SENSE) {
2491 DBG(fsg, "sending command-failure status\n");
2492 status = USB_STATUS_FAIL;
2493 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2495 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2498 if (transport_is_bbb()) {
2499 struct bulk_cs_wrap *csw = (struct bulk_cs_wrap *) bh->buf;
2501 /* Store and send the Bulk-only CSW */
2502 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
2503 csw->Tag = fsg->tag;
2504 csw->Residue = fsg->residue;
2505 csw->Status = status;
2507 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2508 bh->inreq->zero = 0;
2509 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2510 &bh->inreq_busy, &bh->state);
2512 } else if (mod_data.transport_type == USB_PR_CB) {
2514 /* Control-Bulk transport has no status stage! */
2517 } else { // USB_PR_CBI
2518 struct interrupt_data *buf = (struct interrupt_data *)
2521 /* Store and send the Interrupt data. UFI sends the ASC
2522 * and ASCQ bytes. Everything else sends a Type (which
2523 * is always 0) and the status Value. */
2524 if (mod_data.protocol_type == USB_SC_UFI) {
2525 buf->bType = ASC(sd);
2526 buf->bValue = ASCQ(sd);
2529 buf->bValue = status;
2531 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2533 fsg->intr_buffhd = bh; // Point to the right buffhd
2534 fsg->intreq->buf = bh->inreq->buf;
2535 fsg->intreq->dma = bh->inreq->dma;
2536 fsg->intreq->context = bh;
2537 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2538 &fsg->intreq_busy, &bh->state);
2541 fsg->next_buffhd_to_fill = bh->next;
2546 /*-------------------------------------------------------------------------*/
2548 /* Check whether the command is properly formed and whether its data size
2549 * and direction agree with the values we already have. */
2550 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2551 enum data_direction data_dir, unsigned int mask,
2552 int needs_medium, const char *name)
2555 int lun = fsg->cmnd[1] >> 5;
2556 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2560 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2561 * Transparent SCSI doesn't pad. */
2562 if (protocol_is_scsi())
2565 /* There's some disagreement as to whether RBC pads commands or not.
2566 * We'll play it safe and accept either form. */
2567 else if (mod_data.protocol_type == USB_SC_RBC) {
2568 if (fsg->cmnd_size == 12)
2571 /* All the other protocols pad to 12 bytes */
2576 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2577 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2579 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2580 name, cmnd_size, dirletter[(int) data_dir],
2581 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2583 /* We can't reply at all until we know the correct data direction
2585 if (fsg->data_size_from_cmnd == 0)
2586 data_dir = DATA_DIR_NONE;
2587 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2588 fsg->data_dir = data_dir;
2589 fsg->data_size = fsg->data_size_from_cmnd;
2591 } else { // Bulk-only
2592 if (fsg->data_size < fsg->data_size_from_cmnd) {
2594 /* Host data size < Device data size is a phase error.
2595 * Carry out the command, but only transfer as much
2596 * as we are allowed. */
2597 fsg->data_size_from_cmnd = fsg->data_size;
2598 fsg->phase_error = 1;
2601 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2603 /* Conflicting data directions is a phase error */
2604 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0)
2607 /* Verify the length of the command itself */
2608 if (cmnd_size != fsg->cmnd_size) {
2610 /* Special case workaround: MS-Windows issues REQUEST SENSE
2611 * with cbw->Length == 12 (it should be 6). */
2612 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
2613 cmnd_size = fsg->cmnd_size;
2618 /* Check that the LUN values are oonsistent */
2619 if (transport_is_bbb()) {
2620 if (fsg->lun != lun)
2621 DBG(fsg, "using LUN %d from CBW, "
2622 "not LUN %d from CDB\n",
2625 fsg->lun = lun; // Use LUN from the command
2628 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2629 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2630 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2631 curlun->sense_data = SS_NO_SENSE;
2632 curlun->sense_data_info = 0;
2635 fsg->curlun = curlun = NULL;
2636 fsg->bad_lun_okay = 0;
2638 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2639 * to use unsupported LUNs; all others may not. */
2640 if (fsg->cmnd[0] != SC_INQUIRY &&
2641 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2642 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2647 /* If a unit attention condition exists, only INQUIRY and
2648 * REQUEST SENSE commands are allowed; anything else must fail. */
2649 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2650 fsg->cmnd[0] != SC_INQUIRY &&
2651 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2652 curlun->sense_data = curlun->unit_attention_data;
2653 curlun->unit_attention_data = SS_NO_SENSE;
2657 /* Check that only command bytes listed in the mask are non-zero */
2658 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2659 for (i = 1; i < cmnd_size; ++i) {
2660 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2662 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2667 /* If the medium isn't mounted and the command needs to access
2668 * it, return an error. */
2669 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2670 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2677 fsg->phase_error = 1;
2682 static int do_scsi_command(struct fsg_dev *fsg)
2684 struct fsg_buffhd *bh;
2686 int reply = -EINVAL;
2688 static char unknown[16];
2692 /* Wait for the next buffer to become available for data or status */
2693 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2694 while (bh->state != BUF_STATE_EMPTY) {
2695 if ((rc = sleep_thread(fsg)) != 0)
2698 fsg->phase_error = 0;
2699 fsg->short_packet_received = 0;
2701 down_read(&fsg->filesem); // We're using the backing file
2702 switch (fsg->cmnd[0]) {
2705 fsg->data_size_from_cmnd = fsg->cmnd[4];
2706 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2709 reply = do_inquiry(fsg, bh);
2712 case SC_MODE_SELECT_6:
2713 fsg->data_size_from_cmnd = fsg->cmnd[4];
2714 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2716 "MODE SELECT(6)")) == 0)
2717 reply = do_mode_select(fsg, bh);
2720 case SC_MODE_SELECT_10:
2721 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2722 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2724 "MODE SELECT(10)")) == 0)
2725 reply = do_mode_select(fsg, bh);
2728 case SC_MODE_SENSE_6:
2729 fsg->data_size_from_cmnd = fsg->cmnd[4];
2730 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2731 (1<<1) | (1<<2) | (1<<4), 0,
2732 "MODE SENSE(6)")) == 0)
2733 reply = do_mode_sense(fsg, bh);
2736 case SC_MODE_SENSE_10:
2737 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2738 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2739 (1<<1) | (1<<2) | (3<<7), 0,
2740 "MODE SENSE(10)")) == 0)
2741 reply = do_mode_sense(fsg, bh);
2744 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2745 fsg->data_size_from_cmnd = 0;
2746 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2748 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2749 reply = do_prevent_allow(fsg);
2754 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2755 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2758 reply = do_read(fsg);
2762 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2763 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2764 (1<<1) | (0xf<<2) | (3<<7), 1,
2766 reply = do_read(fsg);
2770 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2771 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2772 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2774 reply = do_read(fsg);
2777 case SC_READ_CAPACITY:
2778 fsg->data_size_from_cmnd = 8;
2779 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2780 (0xf<<2) | (1<<8), 1,
2781 "READ CAPACITY")) == 0)
2782 reply = do_read_capacity(fsg, bh);
2785 case SC_READ_FORMAT_CAPACITIES:
2786 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2787 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2789 "READ FORMAT CAPACITIES")) == 0)
2790 reply = do_read_format_capacities(fsg, bh);
2793 case SC_REQUEST_SENSE:
2794 fsg->data_size_from_cmnd = fsg->cmnd[4];
2795 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2797 "REQUEST SENSE")) == 0)
2798 reply = do_request_sense(fsg, bh);
2801 case SC_START_STOP_UNIT:
2802 fsg->data_size_from_cmnd = 0;
2803 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2805 "START-STOP UNIT")) == 0)
2806 reply = do_start_stop(fsg);
2809 case SC_SYNCHRONIZE_CACHE:
2810 fsg->data_size_from_cmnd = 0;
2811 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2812 (0xf<<2) | (3<<7), 1,
2813 "SYNCHRONIZE CACHE")) == 0)
2814 reply = do_synchronize_cache(fsg);
2817 case SC_TEST_UNIT_READY:
2818 fsg->data_size_from_cmnd = 0;
2819 reply = check_command(fsg, 6, DATA_DIR_NONE,
2824 /* Although optional, this command is used by MS-Windows. We
2825 * support a minimal version: BytChk must be 0. */
2827 fsg->data_size_from_cmnd = 0;
2828 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2829 (1<<1) | (0xf<<2) | (3<<7), 1,
2831 reply = do_verify(fsg);
2836 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2837 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2840 reply = do_write(fsg);
2844 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2845 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2846 (1<<1) | (0xf<<2) | (3<<7), 1,
2848 reply = do_write(fsg);
2852 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2853 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2854 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2856 reply = do_write(fsg);
2859 /* Some mandatory commands that we recognize but don't implement.
2860 * They don't mean much in this setting. It's left as an exercise
2861 * for anyone interested to implement RESERVE and RELEASE in terms
2862 * of Posix locks. */
2863 case SC_FORMAT_UNIT:
2866 case SC_SEND_DIAGNOSTIC:
2870 fsg->data_size_from_cmnd = 0;
2871 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2872 if ((reply = check_command(fsg, fsg->cmnd_size,
2873 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2874 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2879 up_read(&fsg->filesem);
2881 if (reply == -EINTR || signal_pending(current))
2884 /* Set up the single reply buffer for finish_reply() */
2885 if (reply == -EINVAL)
2886 reply = 0; // Error reply length
2887 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2888 reply = min((u32) reply, fsg->data_size_from_cmnd);
2889 bh->inreq->length = reply;
2890 bh->state = BUF_STATE_FULL;
2891 fsg->residue -= reply;
2892 } // Otherwise it's already set
2898 /*-------------------------------------------------------------------------*/
2900 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2902 struct usb_request *req = bh->outreq;
2903 struct bulk_cb_wrap *cbw = (struct bulk_cb_wrap *) req->buf;
2905 /* Was this a real packet? */
2909 /* Is the CBW valid? */
2910 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2911 cbw->Signature != __constant_cpu_to_le32(
2913 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2915 le32_to_cpu(cbw->Signature));
2917 /* The Bulk-only spec says we MUST stall the bulk pipes!
2918 * If we want to avoid stalls, set a flag so that we will
2919 * clear the endpoint halts at the next reset. */
2920 if (!mod_data.can_stall)
2921 set_bit(CLEAR_BULK_HALTS, &fsg->atomic_bitflags);
2922 fsg_set_halt(fsg, fsg->bulk_out);
2923 halt_bulk_in_endpoint(fsg);
2927 /* Is the CBW meaningful? */
2928 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2929 cbw->Length < 6 || cbw->Length > MAX_COMMAND_SIZE) {
2930 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2932 cbw->Lun, cbw->Flags, cbw->Length);
2934 /* We can do anything we want here, so let's stall the
2935 * bulk pipes if we are allowed to. */
2936 if (mod_data.can_stall) {
2937 fsg_set_halt(fsg, fsg->bulk_out);
2938 halt_bulk_in_endpoint(fsg);
2943 /* Save the command for later */
2944 fsg->cmnd_size = cbw->Length;
2945 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2946 if (cbw->Flags & USB_BULK_IN_FLAG)
2947 fsg->data_dir = DATA_DIR_TO_HOST;
2949 fsg->data_dir = DATA_DIR_FROM_HOST;
2950 fsg->data_size = cbw->DataTransferLength;
2951 if (fsg->data_size == 0)
2952 fsg->data_dir = DATA_DIR_NONE;
2953 fsg->lun = cbw->Lun;
2954 fsg->tag = cbw->Tag;
2959 static int get_next_command(struct fsg_dev *fsg)
2961 struct fsg_buffhd *bh;
2964 if (transport_is_bbb()) {
2966 /* Wait for the next buffer to become available */
2967 bh = fsg->next_buffhd_to_fill;
2968 while (bh->state != BUF_STATE_EMPTY) {
2969 if ((rc = sleep_thread(fsg)) != 0)
2973 /* Queue a request to read a Bulk-only CBW */
2974 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2975 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2976 &bh->outreq_busy, &bh->state);
2978 /* We will drain the buffer in software, which means we
2979 * can reuse it for the next filling. No need to advance
2980 * next_buffhd_to_fill. */
2982 /* Wait for the CBW to arrive */
2983 while (bh->state != BUF_STATE_FULL) {
2984 if ((rc = sleep_thread(fsg)) != 0)
2987 rc = received_cbw(fsg, bh);
2988 bh->state = BUF_STATE_EMPTY;
2990 } else { // USB_PR_CB or USB_PR_CBI
2992 /* Wait for the next command to arrive */
2993 while (fsg->cbbuf_cmnd_size == 0) {
2994 if ((rc = sleep_thread(fsg)) != 0)
2998 /* Is the previous status interrupt request still busy?
2999 * The host is allowed to skip reading the status,
3000 * so we must cancel it. */
3001 if (fsg->intreq_busy)
3002 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3004 /* Copy the command and mark the buffer empty */
3005 fsg->data_dir = DATA_DIR_UNKNOWN;
3006 spin_lock_irq(&fsg->lock);
3007 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3008 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3009 fsg->cbbuf_cmnd_size = 0;
3010 spin_unlock_irq(&fsg->lock);
3016 /*-------------------------------------------------------------------------*/
3018 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3019 const struct usb_endpoint_descriptor *d)
3023 ep->driver_data = fsg;
3024 rc = usb_ep_enable(ep, d);
3026 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3030 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3031 struct usb_request **preq)
3033 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3036 ERROR(fsg, "can't allocate request for %s\n", ep->name);
3041 * Reset interface setting and re-init endpoint state (toggle etc).
3042 * Call with altsetting < 0 to disable the interface. The only other
3043 * available altsetting is 0, which enables the interface.
3045 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3049 const struct usb_endpoint_descriptor *d;
3052 DBG(fsg, "reset interface\n");
3055 /* Deallocate the requests */
3056 for (i = 0; i < NUM_BUFFERS; ++i) {
3057 struct fsg_buffhd *bh = &fsg->buffhds[i];
3060 usb_ep_free_request(fsg->bulk_in, bh->inreq);
3064 usb_ep_free_request(fsg->bulk_out, bh->outreq);
3069 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3073 /* Disable the endpoints */
3074 if (fsg->bulk_in_enabled) {
3075 usb_ep_disable(fsg->bulk_in);
3076 fsg->bulk_in_enabled = 0;
3078 if (fsg->bulk_out_enabled) {
3079 usb_ep_disable(fsg->bulk_out);
3080 fsg->bulk_out_enabled = 0;
3082 if (fsg->intr_in_enabled) {
3083 usb_ep_disable(fsg->intr_in);
3084 fsg->intr_in_enabled = 0;
3088 if (altsetting < 0 || rc != 0)
3091 DBG(fsg, "set interface %d\n", altsetting);
3093 /* Enable the endpoints */
3094 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3095 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3097 fsg->bulk_in_enabled = 1;
3099 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3100 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3102 fsg->bulk_out_enabled = 1;
3103 fsg->bulk_out_maxpacket = d->wMaxPacketSize;
3105 if (transport_is_cbi()) {
3106 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3107 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3109 fsg->intr_in_enabled = 1;
3112 /* Allocate the requests */
3113 for (i = 0; i < NUM_BUFFERS; ++i) {
3114 struct fsg_buffhd *bh = &fsg->buffhds[i];
3116 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3118 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3120 bh->inreq->buf = bh->outreq->buf = bh->buf;
3121 bh->inreq->dma = bh->outreq->dma = bh->dma;
3122 bh->inreq->context = bh->outreq->context = bh;
3123 bh->inreq->complete = bulk_in_complete;
3124 bh->outreq->complete = bulk_out_complete;
3126 if (transport_is_cbi()) {
3127 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3129 fsg->intreq->complete = intr_in_complete;
3133 for (i = 0; i < fsg->nluns; ++i)
3134 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3140 * Change our operational configuration. This code must agree with the code
3141 * that returns config descriptors, and with interface altsetting code.
3143 * It's also responsible for power management interactions. Some
3144 * configurations might not work with our current power sources.
3145 * For now we just assume the gadget is always self-powered.
3147 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3151 /* Disable the single interface */
3152 if (fsg->config != 0) {
3153 DBG(fsg, "reset config\n");
3155 rc = do_set_interface(fsg, -1);
3158 /* Enable the interface */
3159 if (new_config != 0) {
3160 fsg->config = new_config;
3161 if ((rc = do_set_interface(fsg, 0)) != 0)
3162 fsg->config = 0; // Reset on errors
3166 switch (fsg->gadget->speed) {
3167 case USB_SPEED_LOW: speed = "low"; break;
3168 case USB_SPEED_FULL: speed = "full"; break;
3169 case USB_SPEED_HIGH: speed = "high"; break;
3170 default: speed = "?"; break;
3172 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3179 /*-------------------------------------------------------------------------*/
3181 static void handle_exception(struct fsg_dev *fsg)
3187 struct fsg_buffhd *bh;
3188 enum fsg_state old_state;
3191 unsigned int exception_req_tag;
3194 /* Clear the existing signals. Anything but SIGUSR1 is converted
3195 * into a high-priority EXIT exception. */
3197 sig = dequeue_signal_lock(current, &fsg->thread_signal_mask,
3201 if (sig != SIGUSR1) {
3202 if (fsg->state < FSG_STATE_EXIT)
3203 DBG(fsg, "Main thread exiting on signal\n");
3204 raise_exception(fsg, FSG_STATE_EXIT);
3208 /* Cancel all the pending transfers */
3209 if (fsg->intreq_busy)
3210 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3211 for (i = 0; i < NUM_BUFFERS; ++i) {
3212 bh = &fsg->buffhds[i];
3214 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3215 if (bh->outreq_busy)
3216 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3219 /* Wait until everything is idle */
3221 num_active = fsg->intreq_busy;
3222 for (i = 0; i < NUM_BUFFERS; ++i) {
3223 bh = &fsg->buffhds[i];
3224 num_active += bh->inreq_busy + bh->outreq_busy;
3226 if (num_active == 0)
3228 if (sleep_thread(fsg))
3232 /* Clear out the controller's fifos */
3233 if (fsg->bulk_in_enabled)
3234 usb_ep_fifo_flush(fsg->bulk_in);
3235 if (fsg->bulk_out_enabled)
3236 usb_ep_fifo_flush(fsg->bulk_out);
3237 if (fsg->intr_in_enabled)
3238 usb_ep_fifo_flush(fsg->intr_in);
3240 /* Reset the I/O buffer states and pointers, the SCSI
3241 * state, and the exception. Then invoke the handler. */
3242 spin_lock_irq(&fsg->lock);
3244 for (i = 0; i < NUM_BUFFERS; ++i) {
3245 bh = &fsg->buffhds[i];
3246 bh->state = BUF_STATE_EMPTY;
3248 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3251 exception_req_tag = fsg->exception_req_tag;
3252 new_config = fsg->new_config;
3253 old_state = fsg->state;
3255 if (old_state == FSG_STATE_ABORT_BULK_OUT)
3256 fsg->state = FSG_STATE_STATUS_PHASE;
3258 for (i = 0; i < fsg->nluns; ++i) {
3259 curlun = &fsg->luns[i];
3260 curlun->prevent_medium_removal = 0;
3261 curlun->sense_data = curlun->unit_attention_data =
3263 curlun->sense_data_info = 0;
3265 fsg->state = FSG_STATE_IDLE;
3267 spin_unlock_irq(&fsg->lock);
3269 /* Carry out any extra actions required for the exception */
3270 switch (old_state) {
3274 case FSG_STATE_ABORT_BULK_OUT:
3276 spin_lock_irq(&fsg->lock);
3277 if (fsg->state == FSG_STATE_STATUS_PHASE)
3278 fsg->state = FSG_STATE_IDLE;
3279 spin_unlock_irq(&fsg->lock);
3282 case FSG_STATE_RESET:
3283 /* In case we were forced against our will to halt a
3284 * bulk endpoint, clear the halt now. (The SuperH UDC
3285 * requires this.) */
3286 if (test_and_clear_bit(CLEAR_BULK_HALTS,
3287 &fsg->atomic_bitflags)) {
3288 usb_ep_clear_halt(fsg->bulk_in);
3289 usb_ep_clear_halt(fsg->bulk_out);
3292 if (transport_is_bbb()) {
3293 if (fsg->ep0_req_tag == exception_req_tag)
3294 ep0_queue(fsg); // Complete the status stage
3296 } else if (transport_is_cbi())
3297 send_status(fsg); // Status by interrupt pipe
3299 /* Technically this should go here, but it would only be
3300 * a waste of time. Ditto for the INTERFACE_CHANGE and
3301 * CONFIG_CHANGE cases. */
3302 // for (i = 0; i < fsg->nluns; ++i)
3303 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3306 case FSG_STATE_INTERFACE_CHANGE:
3307 rc = do_set_interface(fsg, 0);
3308 if (fsg->ep0_req_tag != exception_req_tag)
3310 if (rc != 0) // STALL on errors
3311 fsg_set_halt(fsg, fsg->ep0);
3312 else // Complete the status stage
3316 case FSG_STATE_CONFIG_CHANGE:
3317 rc = do_set_config(fsg, new_config);
3318 if (fsg->ep0_req_tag != exception_req_tag)
3320 if (rc != 0) // STALL on errors
3321 fsg_set_halt(fsg, fsg->ep0);
3322 else // Complete the status stage
3326 case FSG_STATE_DISCONNECT:
3328 do_set_config(fsg, 0); // Unconfigured state
3331 case FSG_STATE_EXIT:
3332 case FSG_STATE_TERMINATED:
3333 do_set_config(fsg, 0); // Free resources
3334 spin_lock_irq(&fsg->lock);
3335 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3336 spin_unlock_irq(&fsg->lock);
3342 /*-------------------------------------------------------------------------*/
3344 static int fsg_main_thread(void *fsg_)
3346 struct fsg_dev *fsg = (struct fsg_dev *) fsg_;
3348 fsg->thread_task = current;
3350 /* Release all our userspace resources */
3351 daemonize("file-storage-gadget");
3353 /* Allow the thread to be killed by a signal, but set the signal mask
3354 * to block everything but INT, TERM, KILL, and USR1. */
3355 siginitsetinv(&fsg->thread_signal_mask, sigmask(SIGINT) |
3356 sigmask(SIGTERM) | sigmask(SIGKILL) |
3358 sigprocmask(SIG_SETMASK, &fsg->thread_signal_mask, NULL);
3360 /* Arrange for userspace references to be interpreted as kernel
3361 * pointers. That way we can pass a kernel pointer to a routine
3362 * that expects a __user pointer and it will work okay. */
3365 /* Wait for the gadget registration to finish up */
3366 wait_for_completion(&fsg->thread_notifier);
3369 while (fsg->state != FSG_STATE_TERMINATED) {
3370 if (exception_in_progress(fsg) || signal_pending(current)) {
3371 handle_exception(fsg);
3375 if (!fsg->running) {
3380 if (get_next_command(fsg))
3383 spin_lock_irq(&fsg->lock);
3384 if (!exception_in_progress(fsg))
3385 fsg->state = FSG_STATE_DATA_PHASE;
3386 spin_unlock_irq(&fsg->lock);
3388 if (do_scsi_command(fsg) || finish_reply(fsg))
3391 spin_lock_irq(&fsg->lock);
3392 if (!exception_in_progress(fsg))
3393 fsg->state = FSG_STATE_STATUS_PHASE;
3394 spin_unlock_irq(&fsg->lock);
3396 if (send_status(fsg))
3399 spin_lock_irq(&fsg->lock);
3400 if (!exception_in_progress(fsg))
3401 fsg->state = FSG_STATE_IDLE;
3402 spin_unlock_irq(&fsg->lock);
3405 fsg->thread_task = NULL;
3406 flush_signals(current);
3408 /* In case we are exiting because of a signal, unregister the
3409 * gadget driver and close the backing file. */
3410 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) {
3411 usb_gadget_unregister_driver(&fsg_driver);
3412 close_all_backing_files(fsg);
3415 /* Let the unbind and cleanup routines know the thread has exited */
3416 complete_and_exit(&fsg->thread_notifier, 0);
3420 /*-------------------------------------------------------------------------*/
3422 /* If the next two routines are called while the gadget is registered,
3423 * the caller must own fsg->filesem for writing. */
3425 static int NORMALLY_INIT open_backing_file(struct lun *curlun,
3426 const char *filename)
3429 struct file *filp = NULL;
3431 struct inode *inode = NULL;
3435 /* R/W if we can, R/O if we must */
3438 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3439 if (-EROFS == PTR_ERR(filp))
3443 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3445 LINFO(curlun, "unable to open backing file: %s\n", filename);
3446 return PTR_ERR(filp);
3449 if (!(filp->f_mode & FMODE_WRITE))
3453 inode = filp->f_dentry->d_inode;
3454 if (inode && S_ISBLK(inode->i_mode)) {
3455 if (bdev_read_only(inode->i_bdev))
3457 } else if (!inode || !S_ISREG(inode->i_mode)) {
3458 LINFO(curlun, "invalid file type: %s\n", filename);
3462 /* If we can't read the file, it's no good.
3463 * If we can't write the file, use it read-only. */
3464 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3465 LINFO(curlun, "file not readable: %s\n", filename);
3468 if (!(filp->f_op->write || filp->f_op->aio_write))
3471 size = i_size_read(inode->i_mapping->host);
3473 LINFO(curlun, "unable to find file size: %s\n", filename);
3477 num_sectors = size >> 9; // File size in 512-byte sectors
3478 if (num_sectors == 0) {
3479 LINFO(curlun, "file too small: %s\n", filename);
3486 curlun->filp = filp;
3487 curlun->file_length = size;
3488 curlun->num_sectors = num_sectors;
3489 LDBG(curlun, "open backing file: %s\n", filename);
3493 filp_close(filp, current->files);
3498 static void close_backing_file(struct lun *curlun)
3501 LDBG(curlun, "close backing file\n");
3503 curlun->filp = NULL;
3507 static void close_all_backing_files(struct fsg_dev *fsg)
3511 for (i = 0; i < fsg->nluns; ++i)
3512 close_backing_file(&fsg->luns[i]);
3516 static ssize_t show_ro(struct device *dev, char *buf)
3518 struct lun *curlun = dev_to_lun(dev);
3520 return sprintf(buf, "%d\n", curlun->ro);
3523 static ssize_t show_file(struct device *dev, char *buf)
3525 struct lun *curlun = dev_to_lun(dev);
3526 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3530 down_read(&fsg->filesem);
3531 if (backing_file_is_open(curlun)) { // Get the complete pathname
3532 p = d_path(curlun->filp->f_dentry, curlun->filp->f_vfsmnt,
3533 buf, PAGE_SIZE - 1);
3538 memmove(buf, p, rc);
3539 buf[rc] = '\n'; // Add a newline
3542 } else { // No file, return 0 bytes
3546 up_read(&fsg->filesem);
3551 ssize_t NORMALLY_INIT store_ro(struct device *dev, const char *buf,
3555 struct lun *curlun = dev_to_lun(dev);
3556 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3559 if (sscanf(buf, "%d", &i) != 1)
3562 /* Allow the write-enable status to change only while the backing file
3564 down_read(&fsg->filesem);
3565 if (backing_file_is_open(curlun)) {
3566 LDBG(curlun, "read-only status change prevented\n");
3570 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3572 up_read(&fsg->filesem);
3576 ssize_t NORMALLY_INIT store_file(struct device *dev, const char *buf,
3579 struct lun *curlun = dev_to_lun(dev);
3580 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3583 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3584 LDBG(curlun, "eject attempt prevented\n");
3585 return -EBUSY; // "Door is locked"
3588 /* Remove a trailing newline */
3589 if (count > 0 && buf[count-1] == '\n')
3590 ((char *) buf)[count-1] = 0; // Ugh!
3592 /* Eject current medium */
3593 down_write(&fsg->filesem);
3594 if (backing_file_is_open(curlun)) {
3595 close_backing_file(curlun);
3596 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3599 /* Load new medium */
3600 if (count > 0 && buf[0]) {
3601 rc = open_backing_file(curlun, buf);
3603 curlun->unit_attention_data =
3604 SS_NOT_READY_TO_READY_TRANSITION;
3606 up_write(&fsg->filesem);
3607 return (rc < 0 ? rc : count);
3611 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3612 static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3613 static DEVICE_ATTR(file, 0444, show_file, NULL);
3616 /*-------------------------------------------------------------------------*/
3618 static void lun_release(struct device *dev)
3620 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3622 complete(&fsg->lun_released);
3625 static void fsg_unbind(struct usb_gadget *gadget)
3627 struct fsg_dev *fsg = get_gadget_data(gadget);
3630 struct usb_request *req = fsg->ep0req;
3632 DBG(fsg, "unbind\n");
3633 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3635 /* Unregister the sysfs attribute files and the LUNs */
3636 init_completion(&fsg->lun_released);
3637 for (i = 0; i < fsg->nluns; ++i) {
3638 curlun = &fsg->luns[i];
3639 if (curlun->registered) {
3640 device_remove_file(&curlun->dev, &dev_attr_ro);
3641 device_remove_file(&curlun->dev, &dev_attr_file);
3642 device_unregister(&curlun->dev);
3643 wait_for_completion(&fsg->lun_released);
3644 curlun->registered = 0;
3648 /* If the thread isn't already dead, tell it to exit now */
3649 if (fsg->state != FSG_STATE_TERMINATED) {
3650 raise_exception(fsg, FSG_STATE_EXIT);
3651 wait_for_completion(&fsg->thread_notifier);
3653 /* The cleanup routine waits for this completion also */
3654 complete(&fsg->thread_notifier);
3657 /* Free the data buffers */
3658 for (i = 0; i < NUM_BUFFERS; ++i) {
3659 struct fsg_buffhd *bh = &fsg->buffhds[i];
3662 usb_ep_free_buffer(fsg->bulk_in, bh->buf, bh->dma,
3666 /* Free the request and buffer for endpoint 0 */
3669 usb_ep_free_buffer(fsg->ep0, req->buf,
3670 req->dma, EP0_BUFSIZE);
3671 usb_ep_free_request(fsg->ep0, req);
3674 set_gadget_data(gadget, 0);
3678 static int __init check_parameters(struct fsg_dev *fsg)
3682 /* Store the default values */
3683 mod_data.transport_type = USB_PR_BULK;
3684 mod_data.transport_name = "Bulk-only";
3685 mod_data.protocol_type = USB_SC_SCSI;
3686 mod_data.protocol_name = "Transparent SCSI";
3688 if (gadget_is_sh(fsg->gadget))
3689 mod_data.can_stall = 0;
3691 if (mod_data.release == 0xffff) { // Parameter wasn't set
3692 if (gadget_is_net2280(fsg->gadget))
3693 mod_data.release = __constant_cpu_to_le16(0x0301);
3694 else if (gadget_is_dummy(fsg->gadget))
3695 mod_data.release = __constant_cpu_to_le16(0x0302);
3696 else if (gadget_is_pxa(fsg->gadget))
3697 mod_data.release = __constant_cpu_to_le16(0x0303);
3698 else if (gadget_is_sh(fsg->gadget))
3699 mod_data.release = __constant_cpu_to_le16(0x0304);
3701 /* The sa1100 controller is not supported */
3703 else if (gadget_is_goku(fsg->gadget))
3704 mod_data.release = __constant_cpu_to_le16(0x0306);
3705 else if (gadget_is_mq11xx(fsg->gadget))
3706 mod_data.release = __constant_cpu_to_le16(0x0307);
3707 else if (gadget_is_omap(fsg->gadget))
3708 mod_data.release = __constant_cpu_to_le16(0x0308);
3710 WARN(fsg, "controller '%s' not recognized\n",
3712 mod_data.release = __constant_cpu_to_le16(0x0399);
3716 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3718 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3719 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3720 ; // Use default setting
3721 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3722 mod_data.transport_type = USB_PR_CB;
3723 mod_data.transport_name = "Control-Bulk";
3724 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3725 mod_data.transport_type = USB_PR_CBI;
3726 mod_data.transport_name = "Control-Bulk-Interrupt";
3728 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3732 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3733 prot == USB_SC_SCSI) {
3734 ; // Use default setting
3735 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3736 prot == USB_SC_RBC) {
3737 mod_data.protocol_type = USB_SC_RBC;
3738 mod_data.protocol_name = "RBC";
3739 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3740 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3741 prot == USB_SC_8020) {
3742 mod_data.protocol_type = USB_SC_8020;
3743 mod_data.protocol_name = "8020i (ATAPI)";
3744 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3745 prot == USB_SC_QIC) {
3746 mod_data.protocol_type = USB_SC_QIC;
3747 mod_data.protocol_name = "QIC-157";
3748 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3749 prot == USB_SC_UFI) {
3750 mod_data.protocol_type = USB_SC_UFI;
3751 mod_data.protocol_name = "UFI";
3752 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3753 prot == USB_SC_8070) {
3754 mod_data.protocol_type = USB_SC_8070;
3755 mod_data.protocol_name = "8070i";
3757 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3761 mod_data.buflen &= PAGE_CACHE_MASK;
3762 if (mod_data.buflen <= 0) {
3763 ERROR(fsg, "invalid buflen\n");
3766 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3772 static int __init fsg_bind(struct usb_gadget *gadget)
3774 struct fsg_dev *fsg = the_fsg;
3779 struct usb_request *req;
3782 fsg->gadget = gadget;
3783 set_gadget_data(gadget, fsg);
3784 fsg->ep0 = gadget->ep0;
3785 fsg->ep0->driver_data = fsg;
3787 if ((rc = check_parameters(fsg)) != 0)
3790 if (mod_data.removable) { // Enable the store_xxx attributes
3791 dev_attr_ro.attr.mode = dev_attr_file.attr.mode = 0644;
3792 dev_attr_ro.store = store_ro;
3793 dev_attr_file.store = store_file;
3796 /* Find out how many LUNs there should be */
3799 i = max(mod_data.num_filenames, 1);
3801 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3806 /* Create the LUNs and open their backing files. We can't register
3807 * the LUN devices until the gadget itself is registered, which
3808 * doesn't happen until after fsg_bind() returns. */
3809 fsg->luns = kmalloc(i * sizeof(struct lun), GFP_KERNEL);
3814 memset(fsg->luns, 0, i * sizeof(struct lun));
3817 for (i = 0; i < fsg->nluns; ++i) {
3818 curlun = &fsg->luns[i];
3820 curlun->dev.parent = &gadget->dev;
3821 curlun->dev.driver = &fsg_driver.driver;
3822 dev_set_drvdata(&curlun->dev, fsg);
3823 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
3824 "%s-lun%d", gadget->dev.bus_id, i);
3826 if (file[i] && *file[i]) {
3827 if ((rc = open_backing_file(curlun, file[i])) != 0)
3829 } else if (!mod_data.removable) {
3830 ERROR(fsg, "no file given for LUN%d\n", i);
3836 /* Find all the endpoints we will use */
3837 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
3840 ep->driver_data = fsg; // claim the endpoint
3843 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
3846 ep->driver_data = fsg; // claim the endpoint
3849 if (transport_is_cbi()) {
3850 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
3853 ep->driver_data = fsg; // claim the endpoint
3857 /* Fix up the descriptors */
3858 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3859 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3860 device_desc.idProduct = cpu_to_le16(mod_data.product);
3861 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3863 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
3864 intf_desc.bNumEndpoints = i;
3865 intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3866 intf_desc.bInterfaceProtocol = mod_data.transport_type;
3867 fs_function[i+1] = NULL;
3869 #ifdef CONFIG_USB_GADGET_DUALSPEED
3870 hs_function[i+1] = NULL;
3872 /* Assume ep0 uses the same maxpacket value for both speeds */
3873 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3875 /* Assume that all endpoint addresses are the same for both speeds */
3876 hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress;
3877 hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress;
3878 hs_intr_in_desc.bEndpointAddress = fs_intr_in_desc.bEndpointAddress;
3883 /* Allocate the request and buffer for endpoint 0 */
3884 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3887 req->buf = usb_ep_alloc_buffer(fsg->ep0, EP0_BUFSIZE,
3888 &req->dma, GFP_KERNEL);
3891 req->complete = ep0_complete;
3893 /* Allocate the data buffers */
3894 for (i = 0; i < NUM_BUFFERS; ++i) {
3895 struct fsg_buffhd *bh = &fsg->buffhds[i];
3897 bh->buf = usb_ep_alloc_buffer(fsg->bulk_in, mod_data.buflen,
3898 &bh->dma, GFP_KERNEL);
3903 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3905 /* This should reflect the actual gadget power source */
3906 usb_gadget_set_selfpowered(gadget);
3908 snprintf(manufacturer, sizeof manufacturer,
3909 UTS_SYSNAME " " UTS_RELEASE " with %s",
3912 /* On a real device, serial[] would be loaded from permanent
3913 * storage. We just encode it from the driver version string. */
3914 for (i = 0; i < sizeof(serial) - 2; i += 2) {
3915 unsigned char c = DRIVER_VERSION[i / 2];
3919 sprintf(&serial[i], "%02X", c);
3922 if ((rc = kernel_thread(fsg_main_thread, fsg, (CLONE_VM | CLONE_FS |
3925 fsg->thread_pid = rc;
3927 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3928 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3930 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3931 for (i = 0; i < fsg->nluns; ++i) {
3932 curlun = &fsg->luns[i];
3933 if (backing_file_is_open(curlun)) {
3936 p = d_path(curlun->filp->f_dentry,
3937 curlun->filp->f_vfsmnt,
3942 LINFO(curlun, "ro=%d, file: %s\n",
3943 curlun->ro, (p ? p : "(error)"));
3948 DBG(fsg, "transport=%s (x%02x)\n",
3949 mod_data.transport_name, mod_data.transport_type);
3950 DBG(fsg, "protocol=%s (x%02x)\n",
3951 mod_data.protocol_name, mod_data.protocol_type);
3952 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3953 mod_data.vendor, mod_data.product, mod_data.release);
3954 DBG(fsg, "removable=%d, stall=%d, buflen=%u\n",
3955 mod_data.removable, mod_data.can_stall,
3957 DBG(fsg, "I/O thread pid: %d\n", fsg->thread_pid);
3961 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3965 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3967 close_all_backing_files(fsg);
3972 /*-------------------------------------------------------------------------*/
3974 static struct usb_gadget_driver fsg_driver = {
3975 #ifdef CONFIG_USB_GADGET_DUALSPEED
3976 .speed = USB_SPEED_HIGH,
3978 .speed = USB_SPEED_FULL,
3980 .function = (char *) longname,
3982 .unbind = fsg_unbind,
3983 .disconnect = fsg_disconnect,
3987 .name = (char *) shortname,
3995 static int __init fsg_alloc(void)
3997 struct fsg_dev *fsg;
3999 fsg = kmalloc(sizeof *fsg, GFP_KERNEL);
4002 memset(fsg, 0, sizeof *fsg);
4003 spin_lock_init(&fsg->lock);
4004 init_rwsem(&fsg->filesem);
4005 init_waitqueue_head(&fsg->thread_wqh);
4006 init_completion(&fsg->thread_notifier);
4013 static void fsg_free(struct fsg_dev *fsg)
4020 static int __init fsg_init(void)
4023 struct fsg_dev *fsg;
4027 if ((rc = fsg_alloc()) != 0)
4030 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0) {
4034 set_bit(REGISTERED, &fsg->atomic_bitflags);
4036 /* Register the LUN devices and their attribute files */
4037 for (i = 0; i < fsg->nluns; ++i) {
4038 curlun = &fsg->luns[i];
4039 if ((rc = device_register(&curlun->dev)) != 0)
4040 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
4042 curlun->registered = 1;
4043 curlun->dev.release = lun_release;
4044 device_create_file(&curlun->dev, &dev_attr_ro);
4045 device_create_file(&curlun->dev, &dev_attr_file);
4049 /* Tell the thread to start working */
4050 complete(&fsg->thread_notifier);
4053 module_init(fsg_init);
4056 static void __exit fsg_cleanup(void)
4058 struct fsg_dev *fsg = the_fsg;
4060 /* Unregister the driver iff the thread hasn't already done so */
4061 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4062 usb_gadget_unregister_driver(&fsg_driver);
4064 /* Wait for the thread to finish up */
4065 wait_for_completion(&fsg->thread_notifier);
4067 close_all_backing_files(fsg);
4070 module_exit(fsg_cleanup);