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. The gadget will indicate that
50 * it has removable media if the optional "removable" module parameter is set.
52 * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
53 * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
54 * by the optional "transport" module parameter. It also supports the
55 * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
56 * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
57 * the optional "protocol" module parameter. In addition, the default
58 * Vendor ID, Product ID, and release number can be overridden.
60 * There is support for multiple logical units (LUNs), each of which has
61 * its own backing file. The number of LUNs can be set using the optional
62 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
63 * files are specified using comma-separated lists for "file" and "ro".
64 * The default number of LUNs is taken from the number of "file" elements;
65 * it is 1 if "file" is not given. If "removable" is not set then a backing
66 * file must be specified for each LUN. If it is set, then an unspecified
67 * or empty backing filename means the LUN's medium is not loaded.
69 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
70 * needed (an interrupt-out endpoint is also needed for CBI). The memory
71 * requirement amounts to two 16K buffers, size configurable by a parameter.
72 * Support is included for both full-speed and high-speed operation.
76 * file=filename[,filename...]
77 * Required if "removable" is not set, names of
78 * the files or block devices used for
80 * ro=b[,b...] Default false, booleans for read-only access
81 * removable Default false, boolean for removable media
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 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
89 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
90 * release=0xRRRR Override the USB release number (bcdDevice)
91 * buflen=N Default N=16384, buffer size used (will be
92 * rounded down to a multiple of
94 * stall Default determined according to the type of
95 * USB device controller (usually true),
96 * boolean to permit the driver to halt
99 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
100 * "removable", and "luns" options are available; default values are used
101 * 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 the "removable" option is set, writing to
106 * these files will simulate ejecting/loading the medium (writing an empty
107 * line means eject) and adjusting a write-enable tab. Changes to the ro
108 * setting are not allowed when the medium is loaded.
110 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
117 * The FSG driver is fairly straightforward. There is a main kernel
118 * thread that handles most of the work. Interrupt routines field
119 * callbacks from the controller driver: bulk- and interrupt-request
120 * completion notifications, endpoint-0 events, and disconnect events.
121 * Completion events are passed to the main thread by wakeup calls. Many
122 * ep0 requests are handled at interrupt time, but SetInterface,
123 * SetConfiguration, and device reset requests are forwarded to the
124 * thread in the form of "exceptions" using SIGUSR1 signals (since they
125 * should interrupt any ongoing file I/O operations).
127 * The thread's main routine implements the standard command/data/status
128 * parts of a SCSI interaction. It and its subroutines are full of tests
129 * for pending signals/exceptions -- all this polling is necessary since
130 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
131 * indication that the driver really wants to be running in userspace.)
132 * An important point is that so long as the thread is alive it keeps an
133 * open reference to the backing file. This will prevent unmounting
134 * the backing file's underlying filesystem and could cause problems
135 * during system shutdown, for example. To prevent such problems, the
136 * thread catches INT, TERM, and KILL signals and converts them into
139 * In normal operation the main thread is started during the gadget's
140 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
141 * exit when it receives a signal, and there's no point leaving the
142 * gadget running when the thread is dead. So just before the thread
143 * exits, it deregisters the gadget driver. This makes things a little
144 * tricky: The driver is deregistered at two places, and the exiting
145 * thread can indirectly call fsg_unbind() which in turn can tell the
146 * thread to exit. The first problem is resolved through the use of the
147 * REGISTERED atomic bitflag; the driver will only be deregistered once.
148 * The second problem is resolved by having fsg_unbind() check
149 * fsg->state; it won't try to stop the thread if the state is already
150 * FSG_STATE_TERMINATED.
152 * To provide maximum throughput, the driver uses a circular pipeline of
153 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
154 * arbitrarily long; in practice the benefits don't justify having more
155 * than 2 stages (i.e., double buffering). But it helps to think of the
156 * pipeline as being a long one. Each buffer head contains a bulk-in and
157 * a bulk-out request pointer (since the buffer can be used for both
158 * output and input -- directions always are given from the host's
159 * point of view) as well as a pointer to the buffer and various state
162 * Use of the pipeline follows a simple protocol. There is a variable
163 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
164 * At any time that buffer head may still be in use from an earlier
165 * request, so each buffer head has a state variable indicating whether
166 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
167 * buffer head to be EMPTY, filling the buffer either by file I/O or by
168 * USB I/O (during which the buffer head is BUSY), and marking the buffer
169 * head FULL when the I/O is complete. Then the buffer will be emptied
170 * (again possibly by USB I/O, during which it is marked BUSY) and
171 * finally marked EMPTY again (possibly by a completion routine).
173 * A module parameter tells the driver to avoid stalling the bulk
174 * endpoints wherever the transport specification allows. This is
175 * necessary for some UDCs like the SuperH, which cannot reliably clear a
176 * halt on a bulk endpoint. However, under certain circumstances the
177 * Bulk-only specification requires a stall. In such cases the driver
178 * will halt the endpoint and set a flag indicating that it should clear
179 * the halt in software during the next device reset. Hopefully this
180 * will permit everything to work correctly. Furthermore, although the
181 * specification allows the bulk-out endpoint to halt when the host sends
182 * too much data, implementing this would cause an unavoidable race.
183 * The driver will always use the "no-stall" approach for OUT transfers.
185 * One subtle point concerns sending status-stage responses for ep0
186 * requests. Some of these requests, such as device reset, can involve
187 * interrupting an ongoing file I/O operation, which might take an
188 * arbitrarily long time. During that delay the host might give up on
189 * the original ep0 request and issue a new one. When that happens the
190 * driver should not notify the host about completion of the original
191 * request, as the host will no longer be waiting for it. So the driver
192 * assigns to each ep0 request a unique tag, and it keeps track of the
193 * tag value of the request associated with a long-running exception
194 * (device-reset, interface-change, or configuration-change). When the
195 * exception handler is finished, the status-stage response is submitted
196 * only if the current ep0 request tag is equal to the exception request
197 * tag. Thus only the most recently received ep0 request will get a
198 * status-stage response.
200 * Warning: This driver source file is too long. It ought to be split up
201 * into a header file plus about 3 separate .c files, to handle the details
202 * of the Gadget, USB Mass Storage, and SCSI protocols.
210 #include <linux/config.h>
212 #include <asm/system.h>
213 #include <asm/uaccess.h>
215 #include <linux/bitops.h>
216 #include <linux/blkdev.h>
217 #include <linux/compiler.h>
218 #include <linux/completion.h>
219 #include <linux/dcache.h>
220 #include <linux/delay.h>
221 #include <linux/device.h>
222 #include <linux/fcntl.h>
223 #include <linux/file.h>
224 #include <linux/fs.h>
225 #include <linux/init.h>
226 #include <linux/kernel.h>
227 #include <linux/limits.h>
228 #include <linux/list.h>
229 #include <linux/module.h>
230 #include <linux/moduleparam.h>
231 #include <linux/pagemap.h>
232 #include <linux/rwsem.h>
233 #include <linux/sched.h>
234 #include <linux/signal.h>
235 #include <linux/slab.h>
236 #include <linux/spinlock.h>
237 #include <linux/string.h>
238 #include <linux/suspend.h>
239 #include <linux/uts.h>
240 #include <linux/version.h>
241 #include <linux/wait.h>
243 #include <linux/usb_ch9.h>
244 #include <linux/usb_gadget.h>
246 #include "gadget_chips.h"
249 /*-------------------------------------------------------------------------*/
251 #define DRIVER_DESC "File-backed Storage Gadget"
252 #define DRIVER_NAME "g_file_storage"
253 #define DRIVER_VERSION "20 October 2004"
255 static const char longname[] = DRIVER_DESC;
256 static const char shortname[] = DRIVER_NAME;
258 MODULE_DESCRIPTION(DRIVER_DESC);
259 MODULE_AUTHOR("Alan Stern");
260 MODULE_LICENSE("Dual BSD/GPL");
262 /* Thanks to NetChip Technologies for donating this product ID.
264 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
265 * Instead: allocate your own, using normal USB-IF procedures. */
266 #define DRIVER_VENDOR_ID 0x0525 // NetChip
267 #define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
271 * This driver assumes self-powered hardware and has no way for users to
272 * trigger remote wakeup. It uses autoconfiguration to select endpoints
273 * and endpoint addresses.
277 /*-------------------------------------------------------------------------*/
279 #define xprintk(f,level,fmt,args...) \
280 dev_printk(level , &(f)->gadget->dev , fmt , ## args)
281 #define yprintk(l,level,fmt,args...) \
282 dev_printk(level , &(l)->dev , fmt , ## args)
285 #define DBG(fsg,fmt,args...) \
286 xprintk(fsg , KERN_DEBUG , fmt , ## args)
287 #define LDBG(lun,fmt,args...) \
288 yprintk(lun , KERN_DEBUG , fmt , ## args)
289 #define MDBG(fmt,args...) \
290 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
292 #define DBG(fsg,fmt,args...) \
294 #define LDBG(lun,fmt,args...) \
296 #define MDBG(fmt,args...) \
306 #define VDBG(fsg,fmt,args...) \
308 #define VLDBG(lun,fmt,args...) \
312 #define ERROR(fsg,fmt,args...) \
313 xprintk(fsg , KERN_ERR , fmt , ## args)
314 #define LERROR(lun,fmt,args...) \
315 yprintk(lun , KERN_ERR , fmt , ## args)
317 #define WARN(fsg,fmt,args...) \
318 xprintk(fsg , KERN_WARNING , fmt , ## args)
319 #define LWARN(lun,fmt,args...) \
320 yprintk(lun , KERN_WARNING , fmt , ## args)
322 #define INFO(fsg,fmt,args...) \
323 xprintk(fsg , KERN_INFO , fmt , ## args)
324 #define LINFO(lun,fmt,args...) \
325 yprintk(lun , KERN_INFO , fmt , ## args)
327 #define MINFO(fmt,args...) \
328 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
331 /*-------------------------------------------------------------------------*/
333 /* Encapsulate the module parameter settings */
337 /* Arggh! There should be a module_param_array_named macro! */
338 static char *file[MAX_LUNS] = {NULL, };
339 static int ro[MAX_LUNS] = {0, };
346 char *transport_parm;
349 unsigned short vendor;
350 unsigned short product;
351 unsigned short release;
356 char *transport_name;
360 } mod_data = { // Default values
361 .transport_parm = "BBB",
362 .protocol_parm = "SCSI",
364 .vendor = DRIVER_VENDOR_ID,
365 .product = DRIVER_PRODUCT_ID,
366 .release = 0xffff, // Use controller chip type
372 module_param_array(file, charp, &mod_data.num_filenames, S_IRUGO);
373 MODULE_PARM_DESC(file, "names of backing files or devices");
375 module_param_array(ro, bool, &mod_data.num_ros, S_IRUGO);
376 MODULE_PARM_DESC(ro, "true to force read-only");
378 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
379 MODULE_PARM_DESC(luns, "number of LUNs");
381 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
382 MODULE_PARM_DESC(removable, "true to simulate removable media");
385 /* In the non-TEST version, only the module parameters listed above
387 #ifdef CONFIG_USB_FILE_STORAGE_TEST
389 module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
390 MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
392 module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
393 MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
396 module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
397 MODULE_PARM_DESC(vendor, "USB Vendor ID");
399 module_param_named(product, mod_data.product, ushort, S_IRUGO);
400 MODULE_PARM_DESC(product, "USB Product ID");
402 module_param_named(release, mod_data.release, ushort, S_IRUGO);
403 MODULE_PARM_DESC(release, "USB release number");
405 module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
406 MODULE_PARM_DESC(buflen, "I/O buffer size");
408 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
409 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
411 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
414 /*-------------------------------------------------------------------------*/
416 /* USB protocol value = the transport method */
417 #define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
418 #define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
419 #define USB_PR_BULK 0x50 // Bulk-only
421 /* USB subclass value = the protocol encapsulation */
422 #define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
423 #define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
424 #define USB_SC_QIC 0x03 // QIC-157 (tape)
425 #define USB_SC_UFI 0x04 // UFI (floppy)
426 #define USB_SC_8070 0x05 // SFF-8070i (removable)
427 #define USB_SC_SCSI 0x06 // Transparent SCSI
429 /* Bulk-only data structures */
431 /* Command Block Wrapper */
432 struct bulk_cb_wrap {
433 __le32 Signature; // Contains 'USBC'
434 u32 Tag; // Unique per command id
435 __le32 DataTransferLength; // Size of the data
436 u8 Flags; // Direction in bit 7
437 u8 Lun; // LUN (normally 0)
438 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
439 u8 CDB[16]; // Command Data Block
442 #define USB_BULK_CB_WRAP_LEN 31
443 #define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
444 #define USB_BULK_IN_FLAG 0x80
446 /* Command Status Wrapper */
447 struct bulk_cs_wrap {
448 __le32 Signature; // Should = 'USBS'
449 u32 Tag; // Same as original command
450 __le32 Residue; // Amount not transferred
451 u8 Status; // See below
454 #define USB_BULK_CS_WRAP_LEN 13
455 #define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
456 #define USB_STATUS_PASS 0
457 #define USB_STATUS_FAIL 1
458 #define USB_STATUS_PHASE_ERROR 2
460 /* Bulk-only class specific requests */
461 #define USB_BULK_RESET_REQUEST 0xff
462 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
465 /* CBI Interrupt data structure */
466 struct interrupt_data {
471 #define CBI_INTERRUPT_DATA_LEN 2
473 /* CBI Accept Device-Specific Command request */
474 #define USB_CBI_ADSC_REQUEST 0x00
477 #define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
479 /* SCSI commands that we recognize */
480 #define SC_FORMAT_UNIT 0x04
481 #define SC_INQUIRY 0x12
482 #define SC_MODE_SELECT_6 0x15
483 #define SC_MODE_SELECT_10 0x55
484 #define SC_MODE_SENSE_6 0x1a
485 #define SC_MODE_SENSE_10 0x5a
486 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
487 #define SC_READ_6 0x08
488 #define SC_READ_10 0x28
489 #define SC_READ_12 0xa8
490 #define SC_READ_CAPACITY 0x25
491 #define SC_READ_FORMAT_CAPACITIES 0x23
492 #define SC_RELEASE 0x17
493 #define SC_REQUEST_SENSE 0x03
494 #define SC_RESERVE 0x16
495 #define SC_SEND_DIAGNOSTIC 0x1d
496 #define SC_START_STOP_UNIT 0x1b
497 #define SC_SYNCHRONIZE_CACHE 0x35
498 #define SC_TEST_UNIT_READY 0x00
499 #define SC_VERIFY 0x2f
500 #define SC_WRITE_6 0x0a
501 #define SC_WRITE_10 0x2a
502 #define SC_WRITE_12 0xaa
504 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
505 #define SS_NO_SENSE 0
506 #define SS_COMMUNICATION_FAILURE 0x040800
507 #define SS_INVALID_COMMAND 0x052000
508 #define SS_INVALID_FIELD_IN_CDB 0x052400
509 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
510 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
511 #define SS_MEDIUM_NOT_PRESENT 0x023a00
512 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
513 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
514 #define SS_RESET_OCCURRED 0x062900
515 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
516 #define SS_UNRECOVERED_READ_ERROR 0x031100
517 #define SS_WRITE_ERROR 0x030c02
518 #define SS_WRITE_PROTECTED 0x072700
520 #define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
521 #define ASC(x) ((u8) ((x) >> 8))
522 #define ASCQ(x) ((u8) (x))
525 /*-------------------------------------------------------------------------*/
528 * These definitions will permit the compiler to avoid generating code for
529 * parts of the driver that aren't used in the non-TEST version. Even gcc
530 * can recognize when a test of a constant expression yields a dead code
534 #ifdef CONFIG_USB_FILE_STORAGE_TEST
536 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
537 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
538 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
542 #define transport_is_bbb() 1
543 #define transport_is_cbi() 0
544 #define protocol_is_scsi() 1
546 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
555 unsigned int prevent_medium_removal : 1;
556 unsigned int registered : 1;
560 u32 unit_attention_data;
565 #define backing_file_is_open(curlun) ((curlun)->filp != NULL)
567 static inline struct lun *dev_to_lun(struct device *dev)
569 return container_of(dev, struct lun, dev);
573 /* Big enough to hold our biggest descriptor */
574 #define EP0_BUFSIZE 256
575 #define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
577 /* Number of buffers we will use. 2 is enough for double-buffering */
578 #define NUM_BUFFERS 2
580 enum fsg_buffer_state {
589 volatile enum fsg_buffer_state state;
590 struct fsg_buffhd *next;
592 /* The NetChip 2280 is faster, and handles some protocol faults
593 * better, if we don't submit any short bulk-out read requests.
594 * So we will record the intended request length here. */
595 unsigned int bulk_out_intended_length;
597 struct usb_request *inreq;
598 volatile int inreq_busy;
599 struct usb_request *outreq;
600 volatile int outreq_busy;
604 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
605 FSG_STATE_DATA_PHASE,
606 FSG_STATE_STATUS_PHASE,
609 FSG_STATE_ABORT_BULK_OUT,
611 FSG_STATE_INTERFACE_CHANGE,
612 FSG_STATE_CONFIG_CHANGE,
613 FSG_STATE_DISCONNECT,
618 enum data_direction {
619 DATA_DIR_UNKNOWN = 0,
626 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
628 struct usb_gadget *gadget;
630 /* filesem protects: backing files in use */
631 struct rw_semaphore filesem;
633 struct usb_ep *ep0; // Handy copy of gadget->ep0
634 struct usb_request *ep0req; // For control responses
635 volatile unsigned int ep0_req_tag;
636 const char *ep0req_name;
638 struct usb_request *intreq; // For interrupt responses
639 volatile int intreq_busy;
640 struct fsg_buffhd *intr_buffhd;
642 unsigned int bulk_out_maxpacket;
643 enum fsg_state state; // For exception handling
644 unsigned int exception_req_tag;
646 u8 config, new_config;
648 unsigned int running : 1;
649 unsigned int bulk_in_enabled : 1;
650 unsigned int bulk_out_enabled : 1;
651 unsigned int intr_in_enabled : 1;
652 unsigned int phase_error : 1;
653 unsigned int short_packet_received : 1;
654 unsigned int bad_lun_okay : 1;
656 unsigned long atomic_bitflags;
658 #define CLEAR_BULK_HALTS 1
661 struct usb_ep *bulk_in;
662 struct usb_ep *bulk_out;
663 struct usb_ep *intr_in;
665 struct fsg_buffhd *next_buffhd_to_fill;
666 struct fsg_buffhd *next_buffhd_to_drain;
667 struct fsg_buffhd buffhds[NUM_BUFFERS];
669 wait_queue_head_t thread_wqh;
670 int thread_wakeup_needed;
671 struct completion thread_notifier;
673 struct task_struct *thread_task;
674 sigset_t thread_signal_mask;
677 u8 cmnd[MAX_COMMAND_SIZE];
678 enum data_direction data_dir;
680 u32 data_size_from_cmnd;
686 /* The CB protocol offers no way for a host to know when a command
687 * has completed. As a result the next command may arrive early,
688 * and we will still have to handle it. For that reason we need
689 * a buffer to store new commands when using CB (or CBI, which
690 * does not oblige a host to wait for command completion either). */
692 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
697 struct completion lun_released;
700 typedef void (*fsg_routine_t)(struct fsg_dev *);
702 static int inline exception_in_progress(struct fsg_dev *fsg)
704 return (fsg->state > FSG_STATE_IDLE);
707 /* Make bulk-out requests be divisible by the maxpacket size */
708 static void inline set_bulk_out_req_length(struct fsg_dev *fsg,
709 struct fsg_buffhd *bh, unsigned int length)
713 bh->bulk_out_intended_length = length;
714 rem = length % fsg->bulk_out_maxpacket;
716 length += fsg->bulk_out_maxpacket - rem;
717 bh->outreq->length = length;
720 static struct fsg_dev *the_fsg;
721 static struct usb_gadget_driver fsg_driver;
723 static void close_backing_file(struct lun *curlun);
724 static void close_all_backing_files(struct fsg_dev *fsg);
727 /*-------------------------------------------------------------------------*/
731 static void dump_msg(struct fsg_dev *fsg, const char *label,
732 const u8 *buf, unsigned int length)
734 unsigned int start, num, i;
739 DBG(fsg, "%s, length %u:\n", label, length);
743 num = min(length, 16u);
745 for (i = 0; i < num; ++i) {
748 sprintf(p, " %02x", buf[i]);
752 printk(KERN_DEBUG "%6x: %s\n", start, line);
759 static void inline dump_cdb(struct fsg_dev *fsg)
764 static void inline dump_msg(struct fsg_dev *fsg, const char *label,
765 const u8 *buf, unsigned int length)
768 static void inline dump_cdb(struct fsg_dev *fsg)
771 char cmdbuf[3*MAX_COMMAND_SIZE + 1];
773 for (i = 0; i < fsg->cmnd_size; ++i)
774 sprintf(cmdbuf + i*3, " %02x", fsg->cmnd[i]);
775 VDBG(fsg, "SCSI CDB: %s\n", cmdbuf);
778 #endif /* DUMP_MSGS */
781 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
785 if (ep == fsg->bulk_in)
787 else if (ep == fsg->bulk_out)
791 DBG(fsg, "%s set halt\n", name);
792 return usb_ep_set_halt(ep);
796 /*-------------------------------------------------------------------------*/
798 /* Routines for unaligned data access */
800 static u16 inline get_be16(u8 *buf)
802 return ((u16) buf[0] << 8) | ((u16) buf[1]);
805 static u32 inline get_be32(u8 *buf)
807 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
808 ((u32) buf[2] << 8) | ((u32) buf[3]);
811 static void inline put_be16(u8 *buf, u16 val)
817 static void inline put_be32(u8 *buf, u32 val)
826 /*-------------------------------------------------------------------------*/
829 * DESCRIPTORS ... most are static, but strings and (full) configuration
830 * descriptors are built on demand. Also the (static) config and interface
831 * descriptors are adjusted during fsg_bind().
833 #define STRING_MANUFACTURER 1
834 #define STRING_PRODUCT 2
835 #define STRING_SERIAL 3
837 /* There is only one configuration. */
838 #define CONFIG_VALUE 1
840 static struct usb_device_descriptor
842 .bLength = sizeof device_desc,
843 .bDescriptorType = USB_DT_DEVICE,
845 .bcdUSB = __constant_cpu_to_le16(0x0200),
846 .bDeviceClass = USB_CLASS_PER_INTERFACE,
848 /* The next three values can be overridden by module parameters */
849 .idVendor = __constant_cpu_to_le16(DRIVER_VENDOR_ID),
850 .idProduct = __constant_cpu_to_le16(DRIVER_PRODUCT_ID),
851 .bcdDevice = __constant_cpu_to_le16(0xffff),
853 .iManufacturer = STRING_MANUFACTURER,
854 .iProduct = STRING_PRODUCT,
855 .iSerialNumber = STRING_SERIAL,
856 .bNumConfigurations = 1,
859 static struct usb_config_descriptor
861 .bLength = sizeof config_desc,
862 .bDescriptorType = USB_DT_CONFIG,
864 /* wTotalLength computed by usb_gadget_config_buf() */
866 .bConfigurationValue = CONFIG_VALUE,
867 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
868 .bMaxPower = 1, // self-powered
871 static struct usb_otg_descriptor
873 .bLength = sizeof(otg_desc),
874 .bDescriptorType = USB_DT_OTG,
876 .bmAttributes = USB_OTG_SRP,
879 /* There is only one interface. */
881 static struct usb_interface_descriptor
883 .bLength = sizeof intf_desc,
884 .bDescriptorType = USB_DT_INTERFACE,
886 .bNumEndpoints = 2, // Adjusted during fsg_bind()
887 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
888 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
889 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
892 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
893 * and interrupt-in. */
895 static struct usb_endpoint_descriptor
897 .bLength = USB_DT_ENDPOINT_SIZE,
898 .bDescriptorType = USB_DT_ENDPOINT,
900 .bEndpointAddress = USB_DIR_IN,
901 .bmAttributes = USB_ENDPOINT_XFER_BULK,
902 /* wMaxPacketSize set by autoconfiguration */
905 static struct usb_endpoint_descriptor
907 .bLength = USB_DT_ENDPOINT_SIZE,
908 .bDescriptorType = USB_DT_ENDPOINT,
910 .bEndpointAddress = USB_DIR_OUT,
911 .bmAttributes = USB_ENDPOINT_XFER_BULK,
912 /* wMaxPacketSize set by autoconfiguration */
915 static struct usb_endpoint_descriptor
917 .bLength = USB_DT_ENDPOINT_SIZE,
918 .bDescriptorType = USB_DT_ENDPOINT,
920 .bEndpointAddress = USB_DIR_IN,
921 .bmAttributes = USB_ENDPOINT_XFER_INT,
922 .wMaxPacketSize = __constant_cpu_to_le16(2),
923 .bInterval = 32, // frames -> 32 ms
926 static const struct usb_descriptor_header *fs_function[] = {
927 (struct usb_descriptor_header *) &otg_desc,
928 (struct usb_descriptor_header *) &intf_desc,
929 (struct usb_descriptor_header *) &fs_bulk_in_desc,
930 (struct usb_descriptor_header *) &fs_bulk_out_desc,
931 (struct usb_descriptor_header *) &fs_intr_in_desc,
934 #define FS_FUNCTION_PRE_EP_ENTRIES 2
937 #ifdef CONFIG_USB_GADGET_DUALSPEED
940 * USB 2.0 devices need to expose both high speed and full speed
941 * descriptors, unless they only run at full speed.
943 * That means alternate endpoint descriptors (bigger packets)
944 * and a "device qualifier" ... plus more construction options
945 * for the config descriptor.
947 static struct usb_qualifier_descriptor
949 .bLength = sizeof dev_qualifier,
950 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
952 .bcdUSB = __constant_cpu_to_le16(0x0200),
953 .bDeviceClass = USB_CLASS_PER_INTERFACE,
955 .bNumConfigurations = 1,
958 static struct usb_endpoint_descriptor
960 .bLength = USB_DT_ENDPOINT_SIZE,
961 .bDescriptorType = USB_DT_ENDPOINT,
963 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
964 .bmAttributes = USB_ENDPOINT_XFER_BULK,
965 .wMaxPacketSize = __constant_cpu_to_le16(512),
968 static struct usb_endpoint_descriptor
970 .bLength = USB_DT_ENDPOINT_SIZE,
971 .bDescriptorType = USB_DT_ENDPOINT,
973 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
974 .bmAttributes = USB_ENDPOINT_XFER_BULK,
975 .wMaxPacketSize = __constant_cpu_to_le16(512),
976 .bInterval = 1, // NAK every 1 uframe
979 static struct usb_endpoint_descriptor
981 .bLength = USB_DT_ENDPOINT_SIZE,
982 .bDescriptorType = USB_DT_ENDPOINT,
984 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
985 .bmAttributes = USB_ENDPOINT_XFER_INT,
986 .wMaxPacketSize = __constant_cpu_to_le16(2),
987 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
990 static const struct usb_descriptor_header *hs_function[] = {
991 (struct usb_descriptor_header *) &otg_desc,
992 (struct usb_descriptor_header *) &intf_desc,
993 (struct usb_descriptor_header *) &hs_bulk_in_desc,
994 (struct usb_descriptor_header *) &hs_bulk_out_desc,
995 (struct usb_descriptor_header *) &hs_intr_in_desc,
998 #define HS_FUNCTION_PRE_EP_ENTRIES 2
1000 /* Maxpacket and other transfer characteristics vary by speed. */
1001 #define ep_desc(g,fs,hs) (((g)->speed==USB_SPEED_HIGH) ? (hs) : (fs))
1005 /* If there's no high speed support, always use the full-speed descriptor. */
1006 #define ep_desc(g,fs,hs) fs
1008 #endif /* !CONFIG_USB_GADGET_DUALSPEED */
1011 /* The CBI specification limits the serial string to 12 uppercase hexadecimal
1013 static char manufacturer[50];
1014 static char serial[13];
1016 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1017 static struct usb_string strings[] = {
1018 {STRING_MANUFACTURER, manufacturer},
1019 {STRING_PRODUCT, longname},
1020 {STRING_SERIAL, serial},
1024 static struct usb_gadget_strings stringtab = {
1025 .language = 0x0409, // en-us
1031 * Config descriptors must agree with the code that sets configurations
1032 * and with code managing interfaces and their altsettings. They must
1033 * also handle different speeds and other-speed requests.
1035 static int populate_config_buf(struct usb_gadget *gadget,
1036 u8 *buf, u8 type, unsigned index)
1038 #ifdef CONFIG_USB_GADGET_DUALSPEED
1039 enum usb_device_speed speed = gadget->speed;
1042 const struct usb_descriptor_header **function;
1047 #ifdef CONFIG_USB_GADGET_DUALSPEED
1048 if (type == USB_DT_OTHER_SPEED_CONFIG)
1049 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
1050 if (speed == USB_SPEED_HIGH)
1051 function = hs_function;
1054 function = fs_function;
1056 /* for now, don't advertise srp-only devices */
1057 if (!gadget->is_otg)
1060 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
1061 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1066 /*-------------------------------------------------------------------------*/
1068 /* These routines may be called in process context or in_irq */
1070 static void wakeup_thread(struct fsg_dev *fsg)
1072 /* Tell the main thread that something has happened */
1073 fsg->thread_wakeup_needed = 1;
1074 wake_up_all(&fsg->thread_wqh);
1078 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
1080 unsigned long flags;
1081 struct task_struct *thread_task;
1083 /* Do nothing if a higher-priority exception is already in progress.
1084 * If a lower-or-equal priority exception is in progress, preempt it
1085 * and notify the main thread by sending it a signal. */
1086 spin_lock_irqsave(&fsg->lock, flags);
1087 if (fsg->state <= new_state) {
1088 fsg->exception_req_tag = fsg->ep0_req_tag;
1089 fsg->state = new_state;
1090 thread_task = fsg->thread_task;
1092 send_sig_info(SIGUSR1, SEND_SIG_FORCED, thread_task);
1094 spin_unlock_irqrestore(&fsg->lock, flags);
1098 /*-------------------------------------------------------------------------*/
1100 /* The disconnect callback and ep0 routines. These always run in_irq,
1101 * except that ep0_queue() is called in the main thread to acknowledge
1102 * completion of various requests: set config, set interface, and
1103 * Bulk-only device reset. */
1105 static void fsg_disconnect(struct usb_gadget *gadget)
1107 struct fsg_dev *fsg = get_gadget_data(gadget);
1109 DBG(fsg, "disconnect or port reset\n");
1110 raise_exception(fsg, FSG_STATE_DISCONNECT);
1114 static int ep0_queue(struct fsg_dev *fsg)
1118 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
1119 if (rc != 0 && rc != -ESHUTDOWN) {
1121 /* We can't do much more than wait for a reset */
1122 WARN(fsg, "error in submission: %s --> %d\n",
1123 fsg->ep0->name, rc);
1128 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
1130 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1132 if (req->actual > 0)
1133 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
1134 if (req->status || req->actual != req->length)
1135 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1136 req->status, req->actual, req->length);
1137 if (req->status == -ECONNRESET) // Request was cancelled
1138 usb_ep_fifo_flush(ep);
1140 if (req->status == 0 && req->context)
1141 ((fsg_routine_t) (req->context))(fsg);
1145 /*-------------------------------------------------------------------------*/
1147 /* Bulk and interrupt endpoint completion handlers.
1148 * These always run in_irq. */
1150 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
1152 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1153 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1155 if (req->status || req->actual != req->length)
1156 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1157 req->status, req->actual, req->length);
1158 if (req->status == -ECONNRESET) // Request was cancelled
1159 usb_ep_fifo_flush(ep);
1161 /* Hold the lock while we update the request and buffer states */
1162 spin_lock(&fsg->lock);
1164 bh->state = BUF_STATE_EMPTY;
1165 spin_unlock(&fsg->lock);
1169 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
1171 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1172 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1174 dump_msg(fsg, "bulk-out", req->buf, req->actual);
1175 if (req->status || req->actual != bh->bulk_out_intended_length)
1176 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1177 req->status, req->actual,
1178 bh->bulk_out_intended_length);
1179 if (req->status == -ECONNRESET) // Request was cancelled
1180 usb_ep_fifo_flush(ep);
1182 /* Hold the lock while we update the request and buffer states */
1183 spin_lock(&fsg->lock);
1184 bh->outreq_busy = 0;
1185 bh->state = BUF_STATE_FULL;
1186 spin_unlock(&fsg->lock);
1191 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1192 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1194 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1195 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1197 if (req->status || req->actual != req->length)
1198 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1199 req->status, req->actual, req->length);
1200 if (req->status == -ECONNRESET) // Request was cancelled
1201 usb_ep_fifo_flush(ep);
1203 /* Hold the lock while we update the request and buffer states */
1204 spin_lock(&fsg->lock);
1205 fsg->intreq_busy = 0;
1206 bh->state = BUF_STATE_EMPTY;
1207 spin_unlock(&fsg->lock);
1212 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1214 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1217 /*-------------------------------------------------------------------------*/
1219 /* Ep0 class-specific handlers. These always run in_irq. */
1221 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1222 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1224 struct usb_request *req = fsg->ep0req;
1225 static u8 cbi_reset_cmnd[6] = {
1226 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
1228 /* Error in command transfer? */
1229 if (req->status || req->length != req->actual ||
1230 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
1232 /* Not all controllers allow a protocol stall after
1233 * receiving control-out data, but we'll try anyway. */
1234 fsg_set_halt(fsg, fsg->ep0);
1235 return; // Wait for reset
1238 /* Is it the special reset command? */
1239 if (req->actual >= sizeof cbi_reset_cmnd &&
1240 memcmp(req->buf, cbi_reset_cmnd,
1241 sizeof cbi_reset_cmnd) == 0) {
1243 /* Raise an exception to stop the current operation
1244 * and reinitialize our state. */
1245 DBG(fsg, "cbi reset request\n");
1246 raise_exception(fsg, FSG_STATE_RESET);
1250 VDBG(fsg, "CB[I] accept device-specific command\n");
1251 spin_lock(&fsg->lock);
1253 /* Save the command for later */
1254 if (fsg->cbbuf_cmnd_size)
1255 WARN(fsg, "CB[I] overwriting previous command\n");
1256 fsg->cbbuf_cmnd_size = req->actual;
1257 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
1259 spin_unlock(&fsg->lock);
1264 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1266 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1269 static int class_setup_req(struct fsg_dev *fsg,
1270 const struct usb_ctrlrequest *ctrl)
1272 struct usb_request *req = fsg->ep0req;
1273 int value = -EOPNOTSUPP;
1278 /* Handle Bulk-only class-specific requests */
1279 if (transport_is_bbb()) {
1280 switch (ctrl->bRequest) {
1282 case USB_BULK_RESET_REQUEST:
1283 if (ctrl->bRequestType != (USB_DIR_OUT |
1284 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1286 if (ctrl->wIndex != 0) {
1291 /* Raise an exception to stop the current operation
1292 * and reinitialize our state. */
1293 DBG(fsg, "bulk reset request\n");
1294 raise_exception(fsg, FSG_STATE_RESET);
1295 value = DELAYED_STATUS;
1298 case USB_BULK_GET_MAX_LUN_REQUEST:
1299 if (ctrl->bRequestType != (USB_DIR_IN |
1300 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1302 if (ctrl->wIndex != 0) {
1306 VDBG(fsg, "get max LUN\n");
1307 *(u8 *) req->buf = fsg->nluns - 1;
1308 value = min(ctrl->wLength, (u16) 1);
1313 /* Handle CBI class-specific requests */
1315 switch (ctrl->bRequest) {
1317 case USB_CBI_ADSC_REQUEST:
1318 if (ctrl->bRequestType != (USB_DIR_OUT |
1319 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1321 if (ctrl->wIndex != 0) {
1325 if (ctrl->wLength > MAX_COMMAND_SIZE) {
1329 value = ctrl->wLength;
1330 fsg->ep0req->context = received_cbi_adsc;
1335 if (value == -EOPNOTSUPP)
1337 "unknown class-specific control req "
1338 "%02x.%02x v%04x i%04x l%u\n",
1339 ctrl->bRequestType, ctrl->bRequest,
1340 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1345 /*-------------------------------------------------------------------------*/
1347 /* Ep0 standard request handlers. These always run in_irq. */
1349 static int standard_setup_req(struct fsg_dev *fsg,
1350 const struct usb_ctrlrequest *ctrl)
1352 struct usb_request *req = fsg->ep0req;
1353 int value = -EOPNOTSUPP;
1355 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1356 * but config change events will also reconfigure hardware. */
1357 switch (ctrl->bRequest) {
1359 case USB_REQ_GET_DESCRIPTOR:
1360 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1363 switch (ctrl->wValue >> 8) {
1366 VDBG(fsg, "get device descriptor\n");
1367 value = min(ctrl->wLength, (u16) sizeof device_desc);
1368 memcpy(req->buf, &device_desc, value);
1370 #ifdef CONFIG_USB_GADGET_DUALSPEED
1371 case USB_DT_DEVICE_QUALIFIER:
1372 VDBG(fsg, "get device qualifier\n");
1373 if (!fsg->gadget->is_dualspeed)
1375 value = min(ctrl->wLength, (u16) sizeof dev_qualifier);
1376 memcpy(req->buf, &dev_qualifier, value);
1379 case USB_DT_OTHER_SPEED_CONFIG:
1380 VDBG(fsg, "get other-speed config descriptor\n");
1381 if (!fsg->gadget->is_dualspeed)
1386 VDBG(fsg, "get configuration descriptor\n");
1387 #ifdef CONFIG_USB_GADGET_DUALSPEED
1390 value = populate_config_buf(fsg->gadget,
1393 ctrl->wValue & 0xff);
1395 value = min(ctrl->wLength, (u16) value);
1399 VDBG(fsg, "get string descriptor\n");
1401 /* wIndex == language code */
1402 value = usb_gadget_get_string(&stringtab,
1403 ctrl->wValue & 0xff, req->buf);
1405 value = min(ctrl->wLength, (u16) value);
1410 /* One config, two speeds */
1411 case USB_REQ_SET_CONFIGURATION:
1412 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
1415 VDBG(fsg, "set configuration\n");
1416 if (ctrl->wValue == CONFIG_VALUE || ctrl->wValue == 0) {
1417 fsg->new_config = ctrl->wValue;
1419 /* Raise an exception to wipe out previous transaction
1420 * state (queued bufs, etc) and set the new config. */
1421 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1422 value = DELAYED_STATUS;
1425 case USB_REQ_GET_CONFIGURATION:
1426 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1429 VDBG(fsg, "get configuration\n");
1430 *(u8 *) req->buf = fsg->config;
1431 value = min(ctrl->wLength, (u16) 1);
1434 case USB_REQ_SET_INTERFACE:
1435 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1436 USB_RECIP_INTERFACE))
1438 if (fsg->config && ctrl->wIndex == 0) {
1440 /* Raise an exception to wipe out previous transaction
1441 * state (queued bufs, etc) and install the new
1442 * interface altsetting. */
1443 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1444 value = DELAYED_STATUS;
1447 case USB_REQ_GET_INTERFACE:
1448 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1449 USB_RECIP_INTERFACE))
1453 if (ctrl->wIndex != 0) {
1457 VDBG(fsg, "get interface\n");
1458 *(u8 *) req->buf = 0;
1459 value = min(ctrl->wLength, (u16) 1);
1464 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1465 ctrl->bRequestType, ctrl->bRequest,
1466 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1473 static int fsg_setup(struct usb_gadget *gadget,
1474 const struct usb_ctrlrequest *ctrl)
1476 struct fsg_dev *fsg = get_gadget_data(gadget);
1479 ++fsg->ep0_req_tag; // Record arrival of a new request
1480 fsg->ep0req->context = NULL;
1481 fsg->ep0req->length = 0;
1482 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1484 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1485 rc = class_setup_req(fsg, ctrl);
1487 rc = standard_setup_req(fsg, ctrl);
1489 /* Respond with data/status or defer until later? */
1490 if (rc >= 0 && rc != DELAYED_STATUS) {
1491 fsg->ep0req->length = rc;
1492 fsg->ep0req->zero = (rc < ctrl->wLength &&
1493 (rc % gadget->ep0->maxpacket) == 0);
1494 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1495 "ep0-in" : "ep0-out");
1496 rc = ep0_queue(fsg);
1499 /* Device either stalls (rc < 0) or reports success */
1504 /*-------------------------------------------------------------------------*/
1506 /* All the following routines run in process context */
1509 /* Use this for bulk or interrupt transfers, not ep0 */
1510 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1511 struct usb_request *req, volatile int *pbusy,
1512 volatile enum fsg_buffer_state *state)
1516 if (ep == fsg->bulk_in)
1517 dump_msg(fsg, "bulk-in", req->buf, req->length);
1518 else if (ep == fsg->intr_in)
1519 dump_msg(fsg, "intr-in", req->buf, req->length);
1521 *state = BUF_STATE_BUSY;
1522 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1525 *state = BUF_STATE_EMPTY;
1527 /* We can't do much more than wait for a reset */
1529 /* Note: currently the net2280 driver fails zero-length
1530 * submissions if DMA is enabled. */
1531 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1533 WARN(fsg, "error in submission: %s --> %d\n",
1539 static int sleep_thread(struct fsg_dev *fsg)
1543 /* Wait until a signal arrives or we are woken up */
1544 rc = wait_event_interruptible(fsg->thread_wqh,
1545 fsg->thread_wakeup_needed);
1546 fsg->thread_wakeup_needed = 0;
1547 if (current->flags & PF_FREEZE)
1548 refrigerator(PF_FREEZE);
1549 return (rc ? -EINTR : 0);
1553 /*-------------------------------------------------------------------------*/
1555 static int do_read(struct fsg_dev *fsg)
1557 struct lun *curlun = fsg->curlun;
1559 struct fsg_buffhd *bh;
1562 loff_t file_offset, file_offset_tmp;
1563 unsigned int amount;
1564 unsigned int partial_page;
1567 /* Get the starting Logical Block Address and check that it's
1569 if (fsg->cmnd[0] == SC_READ_6)
1570 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1572 lba = get_be32(&fsg->cmnd[2]);
1574 /* We allow DPO (Disable Page Out = don't save data in the
1575 * cache) and FUA (Force Unit Access = don't read from the
1576 * cache), but we don't implement them. */
1577 if ((fsg->cmnd[1] & ~0x18) != 0) {
1578 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1582 if (lba >= curlun->num_sectors) {
1583 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1586 file_offset = ((loff_t) lba) << 9;
1588 /* Carry out the file reads */
1589 amount_left = fsg->data_size_from_cmnd;
1590 if (unlikely(amount_left == 0))
1591 return -EIO; // No default reply
1595 /* Figure out how much we need to read:
1596 * Try to read the remaining amount.
1597 * But don't read more than the buffer size.
1598 * And don't try to read past the end of the file.
1599 * Finally, if we're not at a page boundary, don't read past
1601 * If this means reading 0 then we were asked to read past
1602 * the end of file. */
1603 amount = min((unsigned int) amount_left, mod_data.buflen);
1604 amount = min((loff_t) amount,
1605 curlun->file_length - file_offset);
1606 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1607 if (partial_page > 0)
1608 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1611 /* Wait for the next buffer to become available */
1612 bh = fsg->next_buffhd_to_fill;
1613 while (bh->state != BUF_STATE_EMPTY) {
1614 if ((rc = sleep_thread(fsg)) != 0)
1618 /* If we were asked to read past the end of file,
1619 * end with an empty buffer. */
1621 curlun->sense_data =
1622 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1623 curlun->sense_data_info = file_offset >> 9;
1624 bh->inreq->length = 0;
1625 bh->state = BUF_STATE_FULL;
1629 /* Perform the read */
1630 file_offset_tmp = file_offset;
1631 nread = vfs_read(curlun->filp,
1632 (char __user *) bh->buf,
1633 amount, &file_offset_tmp);
1634 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1635 (unsigned long long) file_offset,
1637 if (signal_pending(current))
1641 LDBG(curlun, "error in file read: %d\n",
1644 } else if (nread < amount) {
1645 LDBG(curlun, "partial file read: %d/%u\n",
1646 (int) nread, amount);
1647 nread -= (nread & 511); // Round down to a block
1649 file_offset += nread;
1650 amount_left -= nread;
1651 fsg->residue -= nread;
1652 bh->inreq->length = nread;
1653 bh->state = BUF_STATE_FULL;
1655 /* If an error occurred, report it and its position */
1656 if (nread < amount) {
1657 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1658 curlun->sense_data_info = file_offset >> 9;
1662 if (amount_left == 0)
1663 break; // No more left to read
1665 /* Send this buffer and go read some more */
1666 bh->inreq->zero = 0;
1667 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1668 &bh->inreq_busy, &bh->state);
1669 fsg->next_buffhd_to_fill = bh->next;
1672 return -EIO; // No default reply
1676 /*-------------------------------------------------------------------------*/
1678 static int do_write(struct fsg_dev *fsg)
1680 struct lun *curlun = fsg->curlun;
1682 struct fsg_buffhd *bh;
1684 u32 amount_left_to_req, amount_left_to_write;
1685 loff_t usb_offset, file_offset, file_offset_tmp;
1686 unsigned int amount;
1687 unsigned int partial_page;
1692 curlun->sense_data = SS_WRITE_PROTECTED;
1695 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1697 /* Get the starting Logical Block Address and check that it's
1699 if (fsg->cmnd[0] == SC_WRITE_6)
1700 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1702 lba = get_be32(&fsg->cmnd[2]);
1704 /* We allow DPO (Disable Page Out = don't save data in the
1705 * cache) and FUA (Force Unit Access = write directly to the
1706 * medium). We don't implement DPO; we implement FUA by
1707 * performing synchronous output. */
1708 if ((fsg->cmnd[1] & ~0x18) != 0) {
1709 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1712 if (fsg->cmnd[1] & 0x08) // FUA
1713 curlun->filp->f_flags |= O_SYNC;
1715 if (lba >= curlun->num_sectors) {
1716 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1720 /* Carry out the file writes */
1722 file_offset = usb_offset = ((loff_t) lba) << 9;
1723 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1725 while (amount_left_to_write > 0) {
1727 /* Queue a request for more data from the host */
1728 bh = fsg->next_buffhd_to_fill;
1729 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1731 /* Figure out how much we want to get:
1732 * Try to get the remaining amount.
1733 * But don't get more than the buffer size.
1734 * And don't try to go past the end of the file.
1735 * If we're not at a page boundary,
1736 * don't go past the next page.
1737 * If this means getting 0, then we were asked
1738 * to write past the end of file.
1739 * Finally, round down to a block boundary. */
1740 amount = min(amount_left_to_req, mod_data.buflen);
1741 amount = min((loff_t) amount, curlun->file_length -
1743 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1744 if (partial_page > 0)
1745 amount = min(amount,
1746 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1750 curlun->sense_data =
1751 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1752 curlun->sense_data_info = usb_offset >> 9;
1755 amount -= (amount & 511);
1758 /* Why were we were asked to transfer a
1764 /* Get the next buffer */
1765 usb_offset += amount;
1766 fsg->usb_amount_left -= amount;
1767 amount_left_to_req -= amount;
1768 if (amount_left_to_req == 0)
1771 /* amount is always divisible by 512, hence by
1772 * the bulk-out maxpacket size */
1773 bh->outreq->length = bh->bulk_out_intended_length =
1775 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1776 &bh->outreq_busy, &bh->state);
1777 fsg->next_buffhd_to_fill = bh->next;
1781 /* Write the received data to the backing file */
1782 bh = fsg->next_buffhd_to_drain;
1783 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1784 break; // We stopped early
1785 if (bh->state == BUF_STATE_FULL) {
1786 fsg->next_buffhd_to_drain = bh->next;
1787 bh->state = BUF_STATE_EMPTY;
1789 /* Did something go wrong with the transfer? */
1790 if (bh->outreq->status != 0) {
1791 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1792 curlun->sense_data_info = file_offset >> 9;
1796 amount = bh->outreq->actual;
1797 if (curlun->file_length - file_offset < amount) {
1799 "write %u @ %llu beyond end %llu\n",
1800 amount, (unsigned long long) file_offset,
1801 (unsigned long long) curlun->file_length);
1802 amount = curlun->file_length - file_offset;
1805 /* Perform the write */
1806 file_offset_tmp = file_offset;
1807 nwritten = vfs_write(curlun->filp,
1808 (char __user *) bh->buf,
1809 amount, &file_offset_tmp);
1810 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1811 (unsigned long long) file_offset,
1813 if (signal_pending(current))
1814 return -EINTR; // Interrupted!
1817 LDBG(curlun, "error in file write: %d\n",
1820 } else if (nwritten < amount) {
1821 LDBG(curlun, "partial file write: %d/%u\n",
1822 (int) nwritten, amount);
1823 nwritten -= (nwritten & 511);
1824 // Round down to a block
1826 file_offset += nwritten;
1827 amount_left_to_write -= nwritten;
1828 fsg->residue -= nwritten;
1830 /* If an error occurred, report it and its position */
1831 if (nwritten < amount) {
1832 curlun->sense_data = SS_WRITE_ERROR;
1833 curlun->sense_data_info = file_offset >> 9;
1837 /* Did the host decide to stop early? */
1838 if (bh->outreq->actual != bh->outreq->length) {
1839 fsg->short_packet_received = 1;
1845 /* Wait for something to happen */
1846 if ((rc = sleep_thread(fsg)) != 0)
1850 return -EIO; // No default reply
1854 /*-------------------------------------------------------------------------*/
1856 /* Sync the file data, don't bother with the metadata.
1857 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1858 static int fsync_sub(struct lun *curlun)
1860 struct file *filp = curlun->filp;
1861 struct inode *inode;
1864 if (curlun->ro || !filp)
1866 if (!filp->f_op->fsync)
1869 inode = filp->f_dentry->d_inode;
1870 down(&inode->i_sem);
1871 current->flags |= PF_SYNCWRITE;
1872 rc = filemap_fdatawrite(inode->i_mapping);
1873 err = filp->f_op->fsync(filp, filp->f_dentry, 1);
1876 err = filemap_fdatawait(inode->i_mapping);
1879 current->flags &= ~PF_SYNCWRITE;
1881 VLDBG(curlun, "fdatasync -> %d\n", rc);
1885 static void fsync_all(struct fsg_dev *fsg)
1889 for (i = 0; i < fsg->nluns; ++i)
1890 fsync_sub(&fsg->luns[i]);
1893 static int do_synchronize_cache(struct fsg_dev *fsg)
1895 struct lun *curlun = fsg->curlun;
1898 /* We ignore the requested LBA and write out all file's
1899 * dirty data buffers. */
1900 rc = fsync_sub(curlun);
1902 curlun->sense_data = SS_WRITE_ERROR;
1907 /*-------------------------------------------------------------------------*/
1909 static void invalidate_sub(struct lun *curlun)
1911 struct file *filp = curlun->filp;
1912 struct inode *inode = filp->f_dentry->d_inode;
1915 rc = invalidate_inode_pages(inode->i_mapping);
1916 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1919 static int do_verify(struct fsg_dev *fsg)
1921 struct lun *curlun = fsg->curlun;
1923 u32 verification_length;
1924 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1925 loff_t file_offset, file_offset_tmp;
1927 unsigned int amount;
1930 /* Get the starting Logical Block Address and check that it's
1932 lba = get_be32(&fsg->cmnd[2]);
1933 if (lba >= curlun->num_sectors) {
1934 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1938 /* We allow DPO (Disable Page Out = don't save data in the
1939 * cache) but we don't implement it. */
1940 if ((fsg->cmnd[1] & ~0x10) != 0) {
1941 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1945 verification_length = get_be16(&fsg->cmnd[7]);
1946 if (unlikely(verification_length == 0))
1947 return -EIO; // No default reply
1949 /* Prepare to carry out the file verify */
1950 amount_left = verification_length << 9;
1951 file_offset = ((loff_t) lba) << 9;
1953 /* Write out all the dirty buffers before invalidating them */
1955 if (signal_pending(current))
1958 invalidate_sub(curlun);
1959 if (signal_pending(current))
1962 /* Just try to read the requested blocks */
1963 while (amount_left > 0) {
1965 /* Figure out how much we need to read:
1966 * Try to read the remaining amount, but not more than
1968 * And don't try to read past the end of the file.
1969 * If this means reading 0 then we were asked to read
1970 * past the end of file. */
1971 amount = min((unsigned int) amount_left, mod_data.buflen);
1972 amount = min((loff_t) amount,
1973 curlun->file_length - file_offset);
1975 curlun->sense_data =
1976 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1977 curlun->sense_data_info = file_offset >> 9;
1981 /* Perform the read */
1982 file_offset_tmp = file_offset;
1983 nread = vfs_read(curlun->filp,
1984 (char __user *) bh->buf,
1985 amount, &file_offset_tmp);
1986 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1987 (unsigned long long) file_offset,
1989 if (signal_pending(current))
1993 LDBG(curlun, "error in file verify: %d\n",
1996 } else if (nread < amount) {
1997 LDBG(curlun, "partial file verify: %d/%u\n",
1998 (int) nread, amount);
1999 nread -= (nread & 511); // Round down to a sector
2002 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
2003 curlun->sense_data_info = file_offset >> 9;
2006 file_offset += nread;
2007 amount_left -= nread;
2013 /*-------------------------------------------------------------------------*/
2015 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2017 u8 *buf = (u8 *) bh->buf;
2019 static char vendor_id[] = "Linux ";
2020 static char product_id[] = "File-Stor Gadget";
2022 if (!fsg->curlun) { // Unsupported LUNs are okay
2023 fsg->bad_lun_okay = 1;
2025 buf[0] = 0x7f; // Unsupported, no device-type
2029 memset(buf, 0, 8); // Non-removable, direct-access device
2030 if (mod_data.removable)
2032 buf[2] = 2; // ANSI SCSI level 2
2033 buf[3] = 2; // SCSI-2 INQUIRY data format
2034 buf[4] = 31; // Additional length
2035 // No special options
2036 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id, product_id,
2042 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2044 struct lun *curlun = fsg->curlun;
2045 u8 *buf = (u8 *) bh->buf;
2049 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2051 * If a REQUEST SENSE command is received from an initiator
2052 * with a pending unit attention condition (before the target
2053 * generates the contingent allegiance condition), then the
2054 * target shall either:
2055 * a) report any pending sense data and preserve the unit
2056 * attention condition on the logical unit, or,
2057 * b) report the unit attention condition, may discard any
2058 * pending sense data, and clear the unit attention
2059 * condition on the logical unit for that initiator.
2061 * FSG normally uses option a); enable this code to use option b).
2064 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2065 curlun->sense_data = curlun->unit_attention_data;
2066 curlun->unit_attention_data = SS_NO_SENSE;
2070 if (!curlun) { // Unsupported LUNs are okay
2071 fsg->bad_lun_okay = 1;
2072 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2075 sd = curlun->sense_data;
2076 sdinfo = curlun->sense_data_info;
2077 curlun->sense_data = SS_NO_SENSE;
2078 curlun->sense_data_info = 0;
2082 buf[0] = 0x80 | 0x70; // Valid, current error
2084 put_be32(&buf[3], sdinfo); // Sense information
2085 buf[7] = 18 - 8; // Additional sense length
2092 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2094 struct lun *curlun = fsg->curlun;
2095 u32 lba = get_be32(&fsg->cmnd[2]);
2096 int pmi = fsg->cmnd[8];
2097 u8 *buf = (u8 *) bh->buf;
2099 /* Check the PMI and LBA fields */
2100 if (pmi > 1 || (pmi == 0 && lba != 0)) {
2101 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2105 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block
2106 put_be32(&buf[4], 512); // Block length
2111 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2113 struct lun *curlun = fsg->curlun;
2114 int mscmnd = fsg->cmnd[0];
2115 u8 *buf = (u8 *) bh->buf;
2118 int changeable_values, all_pages;
2122 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
2123 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2126 pc = fsg->cmnd[2] >> 6;
2127 page_code = fsg->cmnd[2] & 0x3f;
2129 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2132 changeable_values = (pc == 1);
2133 all_pages = (page_code == 0x3f);
2135 /* Write the mode parameter header. Fixed values are: default
2136 * medium type, no cache control (DPOFUA), and no block descriptors.
2137 * The only variable value is the WriteProtect bit. We will fill in
2138 * the mode data length later. */
2140 if (mscmnd == SC_MODE_SENSE_6) {
2141 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2144 } else { // SC_MODE_SENSE_10
2145 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2147 limit = 65535; // Should really be mod_data.buflen
2150 /* No block descriptors */
2152 /* The mode pages, in numerical order. The only page we support
2153 * is the Caching page. */
2154 if (page_code == 0x08 || all_pages) {
2156 buf[0] = 0x08; // Page code
2157 buf[1] = 10; // Page length
2158 memset(buf+2, 0, 10); // None of the fields are changeable
2160 if (!changeable_values) {
2161 buf[2] = 0x04; // Write cache enable,
2162 // Read cache not disabled
2163 // No cache retention priorities
2164 put_be16(&buf[4], 0xffff); // Don't disable prefetch
2165 // Minimum prefetch = 0
2166 put_be16(&buf[8], 0xffff); // Maximum prefetch
2167 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2172 /* Check that a valid page was requested and the mode data length
2173 * isn't too long. */
2175 if (!valid_page || len > limit) {
2176 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2180 /* Store the mode data length */
2181 if (mscmnd == SC_MODE_SENSE_6)
2184 put_be16(buf0, len - 2);
2189 static int do_start_stop(struct fsg_dev *fsg)
2191 struct lun *curlun = fsg->curlun;
2194 if (!mod_data.removable) {
2195 curlun->sense_data = SS_INVALID_COMMAND;
2199 // int immed = fsg->cmnd[1] & 0x01;
2200 loej = fsg->cmnd[4] & 0x02;
2201 start = fsg->cmnd[4] & 0x01;
2203 #ifdef CONFIG_USB_FILE_STORAGE_TEST
2204 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
2205 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
2206 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2212 /* Are we allowed to unload the media? */
2213 if (curlun->prevent_medium_removal) {
2214 LDBG(curlun, "unload attempt prevented\n");
2215 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2218 if (loej) { // Simulate an unload/eject
2219 up_read(&fsg->filesem);
2220 down_write(&fsg->filesem);
2221 close_backing_file(curlun);
2222 up_write(&fsg->filesem);
2223 down_read(&fsg->filesem);
2227 /* Our emulation doesn't support mounting; the medium is
2228 * available for use as soon as it is loaded. */
2229 if (!backing_file_is_open(curlun)) {
2230 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2239 static int do_prevent_allow(struct fsg_dev *fsg)
2241 struct lun *curlun = fsg->curlun;
2244 if (!mod_data.removable) {
2245 curlun->sense_data = SS_INVALID_COMMAND;
2249 prevent = fsg->cmnd[4] & 0x01;
2250 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
2251 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2255 if (curlun->prevent_medium_removal && !prevent)
2257 curlun->prevent_medium_removal = prevent;
2262 static int do_read_format_capacities(struct fsg_dev *fsg,
2263 struct fsg_buffhd *bh)
2265 struct lun *curlun = fsg->curlun;
2266 u8 *buf = (u8 *) bh->buf;
2268 buf[0] = buf[1] = buf[2] = 0;
2269 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
2272 put_be32(&buf[0], curlun->num_sectors); // Number of blocks
2273 put_be32(&buf[4], 512); // Block length
2274 buf[4] = 0x02; // Current capacity
2279 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2281 struct lun *curlun = fsg->curlun;
2283 /* We don't support MODE SELECT */
2284 curlun->sense_data = SS_INVALID_COMMAND;
2289 /*-------------------------------------------------------------------------*/
2291 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2295 rc = fsg_set_halt(fsg, fsg->bulk_in);
2297 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2299 if (rc != -EAGAIN) {
2300 WARN(fsg, "usb_ep_set_halt -> %d\n", rc);
2305 /* Wait for a short time and then try again */
2306 if (msleep_interruptible(100) != 0)
2308 rc = usb_ep_set_halt(fsg->bulk_in);
2313 static int pad_with_zeros(struct fsg_dev *fsg)
2315 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2316 u32 nkeep = bh->inreq->length;
2320 bh->state = BUF_STATE_EMPTY; // For the first iteration
2321 fsg->usb_amount_left = nkeep + fsg->residue;
2322 while (fsg->usb_amount_left > 0) {
2324 /* Wait for the next buffer to be free */
2325 while (bh->state != BUF_STATE_EMPTY) {
2326 if ((rc = sleep_thread(fsg)) != 0)
2330 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2331 memset(bh->buf + nkeep, 0, nsend - nkeep);
2332 bh->inreq->length = nsend;
2333 bh->inreq->zero = 0;
2334 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2335 &bh->inreq_busy, &bh->state);
2336 bh = fsg->next_buffhd_to_fill = bh->next;
2337 fsg->usb_amount_left -= nsend;
2343 static int throw_away_data(struct fsg_dev *fsg)
2345 struct fsg_buffhd *bh;
2349 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2350 fsg->usb_amount_left > 0) {
2352 /* Throw away the data in a filled buffer */
2353 if (bh->state == BUF_STATE_FULL) {
2354 bh->state = BUF_STATE_EMPTY;
2355 fsg->next_buffhd_to_drain = bh->next;
2357 /* A short packet or an error ends everything */
2358 if (bh->outreq->actual != bh->outreq->length ||
2359 bh->outreq->status != 0) {
2360 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2366 /* Try to submit another request if we need one */
2367 bh = fsg->next_buffhd_to_fill;
2368 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2369 amount = min(fsg->usb_amount_left,
2370 (u32) mod_data.buflen);
2372 /* amount is always divisible by 512, hence by
2373 * the bulk-out maxpacket size */
2374 bh->outreq->length = bh->bulk_out_intended_length =
2376 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2377 &bh->outreq_busy, &bh->state);
2378 fsg->next_buffhd_to_fill = bh->next;
2379 fsg->usb_amount_left -= amount;
2383 /* Otherwise wait for something to happen */
2384 if ((rc = sleep_thread(fsg)) != 0)
2391 static int finish_reply(struct fsg_dev *fsg)
2393 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2396 switch (fsg->data_dir) {
2398 break; // Nothing to send
2400 /* If we don't know whether the host wants to read or write,
2401 * this must be CB or CBI with an unknown command. We mustn't
2402 * try to send or receive any data. So stall both bulk pipes
2403 * if we can and wait for a reset. */
2404 case DATA_DIR_UNKNOWN:
2405 if (mod_data.can_stall) {
2406 fsg_set_halt(fsg, fsg->bulk_out);
2407 rc = halt_bulk_in_endpoint(fsg);
2411 /* All but the last buffer of data must have already been sent */
2412 case DATA_DIR_TO_HOST:
2413 if (fsg->data_size == 0)
2414 ; // Nothing to send
2416 /* If there's no residue, simply send the last buffer */
2417 else if (fsg->residue == 0) {
2418 bh->inreq->zero = 0;
2419 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2420 &bh->inreq_busy, &bh->state);
2421 fsg->next_buffhd_to_fill = bh->next;
2424 /* There is a residue. For CB and CBI, simply mark the end
2425 * of the data with a short packet. However, if we are
2426 * allowed to stall, there was no data at all (residue ==
2427 * data_size), and the command failed (invalid LUN or
2428 * sense data is set), then halt the bulk-in endpoint
2430 else if (!transport_is_bbb()) {
2431 if (mod_data.can_stall &&
2432 fsg->residue == fsg->data_size &&
2433 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2434 bh->state = BUF_STATE_EMPTY;
2435 rc = halt_bulk_in_endpoint(fsg);
2437 bh->inreq->zero = 1;
2438 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2439 &bh->inreq_busy, &bh->state);
2440 fsg->next_buffhd_to_fill = bh->next;
2444 /* For Bulk-only, if we're allowed to stall then send the
2445 * short packet and halt the bulk-in endpoint. If we can't
2446 * stall, pad out the remaining data with 0's. */
2448 if (mod_data.can_stall) {
2449 bh->inreq->zero = 1;
2450 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2451 &bh->inreq_busy, &bh->state);
2452 fsg->next_buffhd_to_fill = bh->next;
2453 rc = halt_bulk_in_endpoint(fsg);
2455 rc = pad_with_zeros(fsg);
2459 /* We have processed all we want from the data the host has sent.
2460 * There may still be outstanding bulk-out requests. */
2461 case DATA_DIR_FROM_HOST:
2462 if (fsg->residue == 0)
2463 ; // Nothing to receive
2465 /* Did the host stop sending unexpectedly early? */
2466 else if (fsg->short_packet_received) {
2467 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2471 /* We haven't processed all the incoming data. Even though
2472 * we may be allowed to stall, doing so would cause a race.
2473 * The controller may already have ACK'ed all the remaining
2474 * bulk-out packets, in which case the host wouldn't see a
2475 * STALL. Not realizing the endpoint was halted, it wouldn't
2476 * clear the halt -- leading to problems later on. */
2478 else if (mod_data.can_stall) {
2479 fsg_set_halt(fsg, fsg->bulk_out);
2480 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2485 /* We can't stall. Read in the excess data and throw it
2488 rc = throw_away_data(fsg);
2495 static int send_status(struct fsg_dev *fsg)
2497 struct lun *curlun = fsg->curlun;
2498 struct fsg_buffhd *bh;
2500 u8 status = USB_STATUS_PASS;
2503 /* Wait for the next buffer to become available */
2504 bh = fsg->next_buffhd_to_fill;
2505 while (bh->state != BUF_STATE_EMPTY) {
2506 if ((rc = sleep_thread(fsg)) != 0)
2511 sd = curlun->sense_data;
2512 sdinfo = curlun->sense_data_info;
2513 } else if (fsg->bad_lun_okay)
2516 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2518 if (fsg->phase_error) {
2519 DBG(fsg, "sending phase-error status\n");
2520 status = USB_STATUS_PHASE_ERROR;
2521 sd = SS_INVALID_COMMAND;
2522 } else if (sd != SS_NO_SENSE) {
2523 DBG(fsg, "sending command-failure status\n");
2524 status = USB_STATUS_FAIL;
2525 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2527 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2530 if (transport_is_bbb()) {
2531 struct bulk_cs_wrap *csw = (struct bulk_cs_wrap *) bh->buf;
2533 /* Store and send the Bulk-only CSW */
2534 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
2535 csw->Tag = fsg->tag;
2536 csw->Residue = cpu_to_le32(fsg->residue);
2537 csw->Status = status;
2539 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2540 bh->inreq->zero = 0;
2541 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2542 &bh->inreq_busy, &bh->state);
2544 } else if (mod_data.transport_type == USB_PR_CB) {
2546 /* Control-Bulk transport has no status phase! */
2549 } else { // USB_PR_CBI
2550 struct interrupt_data *buf = (struct interrupt_data *)
2553 /* Store and send the Interrupt data. UFI sends the ASC
2554 * and ASCQ bytes. Everything else sends a Type (which
2555 * is always 0) and the status Value. */
2556 if (mod_data.protocol_type == USB_SC_UFI) {
2557 buf->bType = ASC(sd);
2558 buf->bValue = ASCQ(sd);
2561 buf->bValue = status;
2563 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2565 fsg->intr_buffhd = bh; // Point to the right buffhd
2566 fsg->intreq->buf = bh->inreq->buf;
2567 fsg->intreq->dma = bh->inreq->dma;
2568 fsg->intreq->context = bh;
2569 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2570 &fsg->intreq_busy, &bh->state);
2573 fsg->next_buffhd_to_fill = bh->next;
2578 /*-------------------------------------------------------------------------*/
2580 /* Check whether the command is properly formed and whether its data size
2581 * and direction agree with the values we already have. */
2582 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2583 enum data_direction data_dir, unsigned int mask,
2584 int needs_medium, const char *name)
2587 int lun = fsg->cmnd[1] >> 5;
2588 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2592 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2593 * Transparent SCSI doesn't pad. */
2594 if (protocol_is_scsi())
2597 /* There's some disagreement as to whether RBC pads commands or not.
2598 * We'll play it safe and accept either form. */
2599 else if (mod_data.protocol_type == USB_SC_RBC) {
2600 if (fsg->cmnd_size == 12)
2603 /* All the other protocols pad to 12 bytes */
2608 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2609 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2611 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2612 name, cmnd_size, dirletter[(int) data_dir],
2613 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2615 /* We can't reply at all until we know the correct data direction
2617 if (fsg->data_size_from_cmnd == 0)
2618 data_dir = DATA_DIR_NONE;
2619 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2620 fsg->data_dir = data_dir;
2621 fsg->data_size = fsg->data_size_from_cmnd;
2623 } else { // Bulk-only
2624 if (fsg->data_size < fsg->data_size_from_cmnd) {
2626 /* Host data size < Device data size is a phase error.
2627 * Carry out the command, but only transfer as much
2628 * as we are allowed. */
2629 fsg->data_size_from_cmnd = fsg->data_size;
2630 fsg->phase_error = 1;
2633 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2635 /* Conflicting data directions is a phase error */
2636 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2637 fsg->phase_error = 1;
2641 /* Verify the length of the command itself */
2642 if (cmnd_size != fsg->cmnd_size) {
2644 /* Special case workaround: MS-Windows issues REQUEST SENSE
2645 * with cbw->Length == 12 (it should be 6). */
2646 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
2647 cmnd_size = fsg->cmnd_size;
2649 fsg->phase_error = 1;
2654 /* Check that the LUN values are oonsistent */
2655 if (transport_is_bbb()) {
2656 if (fsg->lun != lun)
2657 DBG(fsg, "using LUN %d from CBW, "
2658 "not LUN %d from CDB\n",
2661 fsg->lun = lun; // Use LUN from the command
2664 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2665 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2666 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2667 curlun->sense_data = SS_NO_SENSE;
2668 curlun->sense_data_info = 0;
2671 fsg->curlun = curlun = NULL;
2672 fsg->bad_lun_okay = 0;
2674 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2675 * to use unsupported LUNs; all others may not. */
2676 if (fsg->cmnd[0] != SC_INQUIRY &&
2677 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2678 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2683 /* If a unit attention condition exists, only INQUIRY and
2684 * REQUEST SENSE commands are allowed; anything else must fail. */
2685 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2686 fsg->cmnd[0] != SC_INQUIRY &&
2687 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2688 curlun->sense_data = curlun->unit_attention_data;
2689 curlun->unit_attention_data = SS_NO_SENSE;
2693 /* Check that only command bytes listed in the mask are non-zero */
2694 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2695 for (i = 1; i < cmnd_size; ++i) {
2696 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2698 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2703 /* If the medium isn't mounted and the command needs to access
2704 * it, return an error. */
2705 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2706 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2714 static int do_scsi_command(struct fsg_dev *fsg)
2716 struct fsg_buffhd *bh;
2718 int reply = -EINVAL;
2720 static char unknown[16];
2724 /* Wait for the next buffer to become available for data or status */
2725 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2726 while (bh->state != BUF_STATE_EMPTY) {
2727 if ((rc = sleep_thread(fsg)) != 0)
2730 fsg->phase_error = 0;
2731 fsg->short_packet_received = 0;
2733 down_read(&fsg->filesem); // We're using the backing file
2734 switch (fsg->cmnd[0]) {
2737 fsg->data_size_from_cmnd = fsg->cmnd[4];
2738 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2741 reply = do_inquiry(fsg, bh);
2744 case SC_MODE_SELECT_6:
2745 fsg->data_size_from_cmnd = fsg->cmnd[4];
2746 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2748 "MODE SELECT(6)")) == 0)
2749 reply = do_mode_select(fsg, bh);
2752 case SC_MODE_SELECT_10:
2753 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2754 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2756 "MODE SELECT(10)")) == 0)
2757 reply = do_mode_select(fsg, bh);
2760 case SC_MODE_SENSE_6:
2761 fsg->data_size_from_cmnd = fsg->cmnd[4];
2762 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2763 (1<<1) | (1<<2) | (1<<4), 0,
2764 "MODE SENSE(6)")) == 0)
2765 reply = do_mode_sense(fsg, bh);
2768 case SC_MODE_SENSE_10:
2769 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2770 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2771 (1<<1) | (1<<2) | (3<<7), 0,
2772 "MODE SENSE(10)")) == 0)
2773 reply = do_mode_sense(fsg, bh);
2776 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2777 fsg->data_size_from_cmnd = 0;
2778 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2780 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2781 reply = do_prevent_allow(fsg);
2786 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2787 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2790 reply = do_read(fsg);
2794 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2795 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2796 (1<<1) | (0xf<<2) | (3<<7), 1,
2798 reply = do_read(fsg);
2802 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2803 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2804 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2806 reply = do_read(fsg);
2809 case SC_READ_CAPACITY:
2810 fsg->data_size_from_cmnd = 8;
2811 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2812 (0xf<<2) | (1<<8), 1,
2813 "READ CAPACITY")) == 0)
2814 reply = do_read_capacity(fsg, bh);
2817 case SC_READ_FORMAT_CAPACITIES:
2818 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2819 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2821 "READ FORMAT CAPACITIES")) == 0)
2822 reply = do_read_format_capacities(fsg, bh);
2825 case SC_REQUEST_SENSE:
2826 fsg->data_size_from_cmnd = fsg->cmnd[4];
2827 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2829 "REQUEST SENSE")) == 0)
2830 reply = do_request_sense(fsg, bh);
2833 case SC_START_STOP_UNIT:
2834 fsg->data_size_from_cmnd = 0;
2835 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2837 "START-STOP UNIT")) == 0)
2838 reply = do_start_stop(fsg);
2841 case SC_SYNCHRONIZE_CACHE:
2842 fsg->data_size_from_cmnd = 0;
2843 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2844 (0xf<<2) | (3<<7), 1,
2845 "SYNCHRONIZE CACHE")) == 0)
2846 reply = do_synchronize_cache(fsg);
2849 case SC_TEST_UNIT_READY:
2850 fsg->data_size_from_cmnd = 0;
2851 reply = check_command(fsg, 6, DATA_DIR_NONE,
2856 /* Although optional, this command is used by MS-Windows. We
2857 * support a minimal version: BytChk must be 0. */
2859 fsg->data_size_from_cmnd = 0;
2860 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2861 (1<<1) | (0xf<<2) | (3<<7), 1,
2863 reply = do_verify(fsg);
2868 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2869 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2872 reply = do_write(fsg);
2876 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2877 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2878 (1<<1) | (0xf<<2) | (3<<7), 1,
2880 reply = do_write(fsg);
2884 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2885 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2886 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2888 reply = do_write(fsg);
2891 /* Some mandatory commands that we recognize but don't implement.
2892 * They don't mean much in this setting. It's left as an exercise
2893 * for anyone interested to implement RESERVE and RELEASE in terms
2894 * of Posix locks. */
2895 case SC_FORMAT_UNIT:
2898 case SC_SEND_DIAGNOSTIC:
2902 fsg->data_size_from_cmnd = 0;
2903 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2904 if ((reply = check_command(fsg, fsg->cmnd_size,
2905 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2906 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2911 up_read(&fsg->filesem);
2913 if (reply == -EINTR || signal_pending(current))
2916 /* Set up the single reply buffer for finish_reply() */
2917 if (reply == -EINVAL)
2918 reply = 0; // Error reply length
2919 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2920 reply = min((u32) reply, fsg->data_size_from_cmnd);
2921 bh->inreq->length = reply;
2922 bh->state = BUF_STATE_FULL;
2923 fsg->residue -= reply;
2924 } // Otherwise it's already set
2930 /*-------------------------------------------------------------------------*/
2932 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2934 struct usb_request *req = bh->outreq;
2935 struct bulk_cb_wrap *cbw = (struct bulk_cb_wrap *) req->buf;
2937 /* Was this a real packet? */
2941 /* Is the CBW valid? */
2942 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2943 cbw->Signature != __constant_cpu_to_le32(
2945 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2947 le32_to_cpu(cbw->Signature));
2949 /* The Bulk-only spec says we MUST stall the bulk pipes!
2950 * If we want to avoid stalls, set a flag so that we will
2951 * clear the endpoint halts at the next reset. */
2952 if (!mod_data.can_stall)
2953 set_bit(CLEAR_BULK_HALTS, &fsg->atomic_bitflags);
2954 fsg_set_halt(fsg, fsg->bulk_out);
2955 halt_bulk_in_endpoint(fsg);
2959 /* Is the CBW meaningful? */
2960 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2961 cbw->Length < 6 || cbw->Length > MAX_COMMAND_SIZE) {
2962 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2964 cbw->Lun, cbw->Flags, cbw->Length);
2966 /* We can do anything we want here, so let's stall the
2967 * bulk pipes if we are allowed to. */
2968 if (mod_data.can_stall) {
2969 fsg_set_halt(fsg, fsg->bulk_out);
2970 halt_bulk_in_endpoint(fsg);
2975 /* Save the command for later */
2976 fsg->cmnd_size = cbw->Length;
2977 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2978 if (cbw->Flags & USB_BULK_IN_FLAG)
2979 fsg->data_dir = DATA_DIR_TO_HOST;
2981 fsg->data_dir = DATA_DIR_FROM_HOST;
2982 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2983 if (fsg->data_size == 0)
2984 fsg->data_dir = DATA_DIR_NONE;
2985 fsg->lun = cbw->Lun;
2986 fsg->tag = cbw->Tag;
2991 static int get_next_command(struct fsg_dev *fsg)
2993 struct fsg_buffhd *bh;
2996 if (transport_is_bbb()) {
2998 /* Wait for the next buffer to become available */
2999 bh = fsg->next_buffhd_to_fill;
3000 while (bh->state != BUF_STATE_EMPTY) {
3001 if ((rc = sleep_thread(fsg)) != 0)
3005 /* Queue a request to read a Bulk-only CBW */
3006 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
3007 start_transfer(fsg, fsg->bulk_out, bh->outreq,
3008 &bh->outreq_busy, &bh->state);
3010 /* We will drain the buffer in software, which means we
3011 * can reuse it for the next filling. No need to advance
3012 * next_buffhd_to_fill. */
3014 /* Wait for the CBW to arrive */
3015 while (bh->state != BUF_STATE_FULL) {
3016 if ((rc = sleep_thread(fsg)) != 0)
3019 rc = received_cbw(fsg, bh);
3020 bh->state = BUF_STATE_EMPTY;
3022 } else { // USB_PR_CB or USB_PR_CBI
3024 /* Wait for the next command to arrive */
3025 while (fsg->cbbuf_cmnd_size == 0) {
3026 if ((rc = sleep_thread(fsg)) != 0)
3030 /* Is the previous status interrupt request still busy?
3031 * The host is allowed to skip reading the status,
3032 * so we must cancel it. */
3033 if (fsg->intreq_busy)
3034 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3036 /* Copy the command and mark the buffer empty */
3037 fsg->data_dir = DATA_DIR_UNKNOWN;
3038 spin_lock_irq(&fsg->lock);
3039 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3040 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3041 fsg->cbbuf_cmnd_size = 0;
3042 spin_unlock_irq(&fsg->lock);
3048 /*-------------------------------------------------------------------------*/
3050 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3051 const struct usb_endpoint_descriptor *d)
3055 ep->driver_data = fsg;
3056 rc = usb_ep_enable(ep, d);
3058 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3062 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3063 struct usb_request **preq)
3065 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3068 ERROR(fsg, "can't allocate request for %s\n", ep->name);
3073 * Reset interface setting and re-init endpoint state (toggle etc).
3074 * Call with altsetting < 0 to disable the interface. The only other
3075 * available altsetting is 0, which enables the interface.
3077 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3081 const struct usb_endpoint_descriptor *d;
3084 DBG(fsg, "reset interface\n");
3087 /* Deallocate the requests */
3088 for (i = 0; i < NUM_BUFFERS; ++i) {
3089 struct fsg_buffhd *bh = &fsg->buffhds[i];
3092 usb_ep_free_request(fsg->bulk_in, bh->inreq);
3096 usb_ep_free_request(fsg->bulk_out, bh->outreq);
3101 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3105 /* Disable the endpoints */
3106 if (fsg->bulk_in_enabled) {
3107 usb_ep_disable(fsg->bulk_in);
3108 fsg->bulk_in_enabled = 0;
3110 if (fsg->bulk_out_enabled) {
3111 usb_ep_disable(fsg->bulk_out);
3112 fsg->bulk_out_enabled = 0;
3114 if (fsg->intr_in_enabled) {
3115 usb_ep_disable(fsg->intr_in);
3116 fsg->intr_in_enabled = 0;
3120 if (altsetting < 0 || rc != 0)
3123 DBG(fsg, "set interface %d\n", altsetting);
3125 /* Enable the endpoints */
3126 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3127 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3129 fsg->bulk_in_enabled = 1;
3131 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3132 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3134 fsg->bulk_out_enabled = 1;
3135 fsg->bulk_out_maxpacket = d->wMaxPacketSize;
3137 if (transport_is_cbi()) {
3138 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3139 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3141 fsg->intr_in_enabled = 1;
3144 /* Allocate the requests */
3145 for (i = 0; i < NUM_BUFFERS; ++i) {
3146 struct fsg_buffhd *bh = &fsg->buffhds[i];
3148 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3150 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3152 bh->inreq->buf = bh->outreq->buf = bh->buf;
3153 bh->inreq->dma = bh->outreq->dma = bh->dma;
3154 bh->inreq->context = bh->outreq->context = bh;
3155 bh->inreq->complete = bulk_in_complete;
3156 bh->outreq->complete = bulk_out_complete;
3158 if (transport_is_cbi()) {
3159 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3161 fsg->intreq->complete = intr_in_complete;
3165 for (i = 0; i < fsg->nluns; ++i)
3166 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3172 * Change our operational configuration. This code must agree with the code
3173 * that returns config descriptors, and with interface altsetting code.
3175 * It's also responsible for power management interactions. Some
3176 * configurations might not work with our current power sources.
3177 * For now we just assume the gadget is always self-powered.
3179 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3183 /* Disable the single interface */
3184 if (fsg->config != 0) {
3185 DBG(fsg, "reset config\n");
3187 rc = do_set_interface(fsg, -1);
3190 /* Enable the interface */
3191 if (new_config != 0) {
3192 fsg->config = new_config;
3193 if ((rc = do_set_interface(fsg, 0)) != 0)
3194 fsg->config = 0; // Reset on errors
3198 switch (fsg->gadget->speed) {
3199 case USB_SPEED_LOW: speed = "low"; break;
3200 case USB_SPEED_FULL: speed = "full"; break;
3201 case USB_SPEED_HIGH: speed = "high"; break;
3202 default: speed = "?"; break;
3204 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3211 /*-------------------------------------------------------------------------*/
3213 static void handle_exception(struct fsg_dev *fsg)
3219 struct fsg_buffhd *bh;
3220 enum fsg_state old_state;
3223 unsigned int exception_req_tag;
3226 /* Clear the existing signals. Anything but SIGUSR1 is converted
3227 * into a high-priority EXIT exception. */
3229 sig = dequeue_signal_lock(current, &fsg->thread_signal_mask,
3233 if (sig != SIGUSR1) {
3234 if (fsg->state < FSG_STATE_EXIT)
3235 DBG(fsg, "Main thread exiting on signal\n");
3236 raise_exception(fsg, FSG_STATE_EXIT);
3240 /* Cancel all the pending transfers */
3241 if (fsg->intreq_busy)
3242 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3243 for (i = 0; i < NUM_BUFFERS; ++i) {
3244 bh = &fsg->buffhds[i];
3246 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3247 if (bh->outreq_busy)
3248 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3251 /* Wait until everything is idle */
3253 num_active = fsg->intreq_busy;
3254 for (i = 0; i < NUM_BUFFERS; ++i) {
3255 bh = &fsg->buffhds[i];
3256 num_active += bh->inreq_busy + bh->outreq_busy;
3258 if (num_active == 0)
3260 if (sleep_thread(fsg))
3264 /* Clear out the controller's fifos */
3265 if (fsg->bulk_in_enabled)
3266 usb_ep_fifo_flush(fsg->bulk_in);
3267 if (fsg->bulk_out_enabled)
3268 usb_ep_fifo_flush(fsg->bulk_out);
3269 if (fsg->intr_in_enabled)
3270 usb_ep_fifo_flush(fsg->intr_in);
3272 /* Reset the I/O buffer states and pointers, the SCSI
3273 * state, and the exception. Then invoke the handler. */
3274 spin_lock_irq(&fsg->lock);
3276 for (i = 0; i < NUM_BUFFERS; ++i) {
3277 bh = &fsg->buffhds[i];
3278 bh->state = BUF_STATE_EMPTY;
3280 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3283 exception_req_tag = fsg->exception_req_tag;
3284 new_config = fsg->new_config;
3285 old_state = fsg->state;
3287 if (old_state == FSG_STATE_ABORT_BULK_OUT)
3288 fsg->state = FSG_STATE_STATUS_PHASE;
3290 for (i = 0; i < fsg->nluns; ++i) {
3291 curlun = &fsg->luns[i];
3292 curlun->prevent_medium_removal = 0;
3293 curlun->sense_data = curlun->unit_attention_data =
3295 curlun->sense_data_info = 0;
3297 fsg->state = FSG_STATE_IDLE;
3299 spin_unlock_irq(&fsg->lock);
3301 /* Carry out any extra actions required for the exception */
3302 switch (old_state) {
3306 case FSG_STATE_ABORT_BULK_OUT:
3308 spin_lock_irq(&fsg->lock);
3309 if (fsg->state == FSG_STATE_STATUS_PHASE)
3310 fsg->state = FSG_STATE_IDLE;
3311 spin_unlock_irq(&fsg->lock);
3314 case FSG_STATE_RESET:
3315 /* In case we were forced against our will to halt a
3316 * bulk endpoint, clear the halt now. (The SuperH UDC
3317 * requires this.) */
3318 if (test_and_clear_bit(CLEAR_BULK_HALTS,
3319 &fsg->atomic_bitflags)) {
3320 usb_ep_clear_halt(fsg->bulk_in);
3321 usb_ep_clear_halt(fsg->bulk_out);
3324 if (transport_is_bbb()) {
3325 if (fsg->ep0_req_tag == exception_req_tag)
3326 ep0_queue(fsg); // Complete the status stage
3328 } else if (transport_is_cbi())
3329 send_status(fsg); // Status by interrupt pipe
3331 /* Technically this should go here, but it would only be
3332 * a waste of time. Ditto for the INTERFACE_CHANGE and
3333 * CONFIG_CHANGE cases. */
3334 // for (i = 0; i < fsg->nluns; ++i)
3335 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3338 case FSG_STATE_INTERFACE_CHANGE:
3339 rc = do_set_interface(fsg, 0);
3340 if (fsg->ep0_req_tag != exception_req_tag)
3342 if (rc != 0) // STALL on errors
3343 fsg_set_halt(fsg, fsg->ep0);
3344 else // Complete the status stage
3348 case FSG_STATE_CONFIG_CHANGE:
3349 rc = do_set_config(fsg, new_config);
3350 if (fsg->ep0_req_tag != exception_req_tag)
3352 if (rc != 0) // STALL on errors
3353 fsg_set_halt(fsg, fsg->ep0);
3354 else // Complete the status stage
3358 case FSG_STATE_DISCONNECT:
3360 do_set_config(fsg, 0); // Unconfigured state
3363 case FSG_STATE_EXIT:
3364 case FSG_STATE_TERMINATED:
3365 do_set_config(fsg, 0); // Free resources
3366 spin_lock_irq(&fsg->lock);
3367 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3368 spin_unlock_irq(&fsg->lock);
3374 /*-------------------------------------------------------------------------*/
3376 static int fsg_main_thread(void *fsg_)
3378 struct fsg_dev *fsg = (struct fsg_dev *) fsg_;
3380 fsg->thread_task = current;
3382 /* Release all our userspace resources */
3383 daemonize("file-storage-gadget");
3385 /* Allow the thread to be killed by a signal, but set the signal mask
3386 * to block everything but INT, TERM, KILL, and USR1. */
3387 siginitsetinv(&fsg->thread_signal_mask, sigmask(SIGINT) |
3388 sigmask(SIGTERM) | sigmask(SIGKILL) |
3390 sigprocmask(SIG_SETMASK, &fsg->thread_signal_mask, NULL);
3392 /* Arrange for userspace references to be interpreted as kernel
3393 * pointers. That way we can pass a kernel pointer to a routine
3394 * that expects a __user pointer and it will work okay. */
3397 /* Wait for the gadget registration to finish up */
3398 wait_for_completion(&fsg->thread_notifier);
3401 while (fsg->state != FSG_STATE_TERMINATED) {
3402 if (exception_in_progress(fsg) || signal_pending(current)) {
3403 handle_exception(fsg);
3407 if (!fsg->running) {
3412 if (get_next_command(fsg))
3415 spin_lock_irq(&fsg->lock);
3416 if (!exception_in_progress(fsg))
3417 fsg->state = FSG_STATE_DATA_PHASE;
3418 spin_unlock_irq(&fsg->lock);
3420 if (do_scsi_command(fsg) || finish_reply(fsg))
3423 spin_lock_irq(&fsg->lock);
3424 if (!exception_in_progress(fsg))
3425 fsg->state = FSG_STATE_STATUS_PHASE;
3426 spin_unlock_irq(&fsg->lock);
3428 if (send_status(fsg))
3431 spin_lock_irq(&fsg->lock);
3432 if (!exception_in_progress(fsg))
3433 fsg->state = FSG_STATE_IDLE;
3434 spin_unlock_irq(&fsg->lock);
3437 fsg->thread_task = NULL;
3438 flush_signals(current);
3440 /* In case we are exiting because of a signal, unregister the
3441 * gadget driver and close the backing file. */
3442 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) {
3443 usb_gadget_unregister_driver(&fsg_driver);
3444 close_all_backing_files(fsg);
3447 /* Let the unbind and cleanup routines know the thread has exited */
3448 complete_and_exit(&fsg->thread_notifier, 0);
3452 /*-------------------------------------------------------------------------*/
3454 /* If the next two routines are called while the gadget is registered,
3455 * the caller must own fsg->filesem for writing. */
3457 static int open_backing_file(struct lun *curlun, const char *filename)
3460 struct file *filp = NULL;
3462 struct inode *inode = NULL;
3466 /* R/W if we can, R/O if we must */
3469 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3470 if (-EROFS == PTR_ERR(filp))
3474 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3476 LINFO(curlun, "unable to open backing file: %s\n", filename);
3477 return PTR_ERR(filp);
3480 if (!(filp->f_mode & FMODE_WRITE))
3484 inode = filp->f_dentry->d_inode;
3485 if (inode && S_ISBLK(inode->i_mode)) {
3486 if (bdev_read_only(inode->i_bdev))
3488 } else if (!inode || !S_ISREG(inode->i_mode)) {
3489 LINFO(curlun, "invalid file type: %s\n", filename);
3493 /* If we can't read the file, it's no good.
3494 * If we can't write the file, use it read-only. */
3495 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3496 LINFO(curlun, "file not readable: %s\n", filename);
3499 if (!(filp->f_op->write || filp->f_op->aio_write))
3502 size = i_size_read(inode->i_mapping->host);
3504 LINFO(curlun, "unable to find file size: %s\n", filename);
3508 num_sectors = size >> 9; // File size in 512-byte sectors
3509 if (num_sectors == 0) {
3510 LINFO(curlun, "file too small: %s\n", filename);
3517 curlun->filp = filp;
3518 curlun->file_length = size;
3519 curlun->num_sectors = num_sectors;
3520 LDBG(curlun, "open backing file: %s\n", filename);
3524 filp_close(filp, current->files);
3529 static void close_backing_file(struct lun *curlun)
3532 LDBG(curlun, "close backing file\n");
3534 curlun->filp = NULL;
3538 static void close_all_backing_files(struct fsg_dev *fsg)
3542 for (i = 0; i < fsg->nluns; ++i)
3543 close_backing_file(&fsg->luns[i]);
3547 static ssize_t show_ro(struct device *dev, char *buf)
3549 struct lun *curlun = dev_to_lun(dev);
3551 return sprintf(buf, "%d\n", curlun->ro);
3554 static ssize_t show_file(struct device *dev, char *buf)
3556 struct lun *curlun = dev_to_lun(dev);
3557 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3561 down_read(&fsg->filesem);
3562 if (backing_file_is_open(curlun)) { // Get the complete pathname
3563 p = d_path(curlun->filp->f_dentry, curlun->filp->f_vfsmnt,
3564 buf, PAGE_SIZE - 1);
3569 memmove(buf, p, rc);
3570 buf[rc] = '\n'; // Add a newline
3573 } else { // No file, return 0 bytes
3577 up_read(&fsg->filesem);
3582 static ssize_t store_ro(struct device *dev, const char *buf, size_t count)
3585 struct lun *curlun = dev_to_lun(dev);
3586 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3589 if (sscanf(buf, "%d", &i) != 1)
3592 /* Allow the write-enable status to change only while the backing file
3594 down_read(&fsg->filesem);
3595 if (backing_file_is_open(curlun)) {
3596 LDBG(curlun, "read-only status change prevented\n");
3600 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3602 up_read(&fsg->filesem);
3606 static ssize_t store_file(struct device *dev, const char *buf, size_t count)
3608 struct lun *curlun = dev_to_lun(dev);
3609 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3612 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3613 LDBG(curlun, "eject attempt prevented\n");
3614 return -EBUSY; // "Door is locked"
3617 /* Remove a trailing newline */
3618 if (count > 0 && buf[count-1] == '\n')
3619 ((char *) buf)[count-1] = 0; // Ugh!
3621 /* Eject current medium */
3622 down_write(&fsg->filesem);
3623 if (backing_file_is_open(curlun)) {
3624 close_backing_file(curlun);
3625 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3628 /* Load new medium */
3629 if (count > 0 && buf[0]) {
3630 rc = open_backing_file(curlun, buf);
3632 curlun->unit_attention_data =
3633 SS_NOT_READY_TO_READY_TRANSITION;
3635 up_write(&fsg->filesem);
3636 return (rc < 0 ? rc : count);
3640 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3641 static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3642 static DEVICE_ATTR(file, 0444, show_file, NULL);
3645 /*-------------------------------------------------------------------------*/
3647 static void lun_release(struct device *dev)
3649 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3651 complete(&fsg->lun_released);
3654 static void fsg_unbind(struct usb_gadget *gadget)
3656 struct fsg_dev *fsg = get_gadget_data(gadget);
3659 struct usb_request *req = fsg->ep0req;
3661 DBG(fsg, "unbind\n");
3662 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3664 /* Unregister the sysfs attribute files and the LUNs */
3665 init_completion(&fsg->lun_released);
3666 for (i = 0; i < fsg->nluns; ++i) {
3667 curlun = &fsg->luns[i];
3668 if (curlun->registered) {
3669 device_remove_file(&curlun->dev, &dev_attr_ro);
3670 device_remove_file(&curlun->dev, &dev_attr_file);
3671 device_unregister(&curlun->dev);
3672 wait_for_completion(&fsg->lun_released);
3673 curlun->registered = 0;
3677 /* If the thread isn't already dead, tell it to exit now */
3678 if (fsg->state != FSG_STATE_TERMINATED) {
3679 raise_exception(fsg, FSG_STATE_EXIT);
3680 wait_for_completion(&fsg->thread_notifier);
3682 /* The cleanup routine waits for this completion also */
3683 complete(&fsg->thread_notifier);
3686 /* Free the data buffers */
3687 for (i = 0; i < NUM_BUFFERS; ++i) {
3688 struct fsg_buffhd *bh = &fsg->buffhds[i];
3691 usb_ep_free_buffer(fsg->bulk_in, bh->buf, bh->dma,
3695 /* Free the request and buffer for endpoint 0 */
3698 usb_ep_free_buffer(fsg->ep0, req->buf,
3699 req->dma, EP0_BUFSIZE);
3700 usb_ep_free_request(fsg->ep0, req);
3703 set_gadget_data(gadget, NULL);
3707 static int __init check_parameters(struct fsg_dev *fsg)
3711 /* Store the default values */
3712 mod_data.transport_type = USB_PR_BULK;
3713 mod_data.transport_name = "Bulk-only";
3714 mod_data.protocol_type = USB_SC_SCSI;
3715 mod_data.protocol_name = "Transparent SCSI";
3717 if (gadget_is_sh(fsg->gadget))
3718 mod_data.can_stall = 0;
3720 if (mod_data.release == 0xffff) { // Parameter wasn't set
3721 if (gadget_is_net2280(fsg->gadget))
3722 mod_data.release = 0x0301;
3723 else if (gadget_is_dummy(fsg->gadget))
3724 mod_data.release = 0x0302;
3725 else if (gadget_is_pxa(fsg->gadget))
3726 mod_data.release = 0x0303;
3727 else if (gadget_is_sh(fsg->gadget))
3728 mod_data.release = 0x0304;
3730 /* The sa1100 controller is not supported */
3732 else if (gadget_is_goku(fsg->gadget))
3733 mod_data.release = 0x0306;
3734 else if (gadget_is_mq11xx(fsg->gadget))
3735 mod_data.release = 0x0307;
3736 else if (gadget_is_omap(fsg->gadget))
3737 mod_data.release = 0x0308;
3738 else if (gadget_is_lh7a40x(fsg->gadget))
3739 mod_data.release = 0x0309;
3740 else if (gadget_is_n9604(fsg->gadget))
3741 mod_data.release = 0x0310;
3742 else if (gadget_is_pxa27x(fsg->gadget))
3743 mod_data.release = 0x0311;
3745 WARN(fsg, "controller '%s' not recognized\n",
3747 mod_data.release = 0x0399;
3751 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3753 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3754 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3755 ; // Use default setting
3756 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3757 mod_data.transport_type = USB_PR_CB;
3758 mod_data.transport_name = "Control-Bulk";
3759 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3760 mod_data.transport_type = USB_PR_CBI;
3761 mod_data.transport_name = "Control-Bulk-Interrupt";
3763 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3767 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3768 prot == USB_SC_SCSI) {
3769 ; // Use default setting
3770 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3771 prot == USB_SC_RBC) {
3772 mod_data.protocol_type = USB_SC_RBC;
3773 mod_data.protocol_name = "RBC";
3774 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3775 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3776 prot == USB_SC_8020) {
3777 mod_data.protocol_type = USB_SC_8020;
3778 mod_data.protocol_name = "8020i (ATAPI)";
3779 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3780 prot == USB_SC_QIC) {
3781 mod_data.protocol_type = USB_SC_QIC;
3782 mod_data.protocol_name = "QIC-157";
3783 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3784 prot == USB_SC_UFI) {
3785 mod_data.protocol_type = USB_SC_UFI;
3786 mod_data.protocol_name = "UFI";
3787 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3788 prot == USB_SC_8070) {
3789 mod_data.protocol_type = USB_SC_8070;
3790 mod_data.protocol_name = "8070i";
3792 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3796 mod_data.buflen &= PAGE_CACHE_MASK;
3797 if (mod_data.buflen <= 0) {
3798 ERROR(fsg, "invalid buflen\n");
3801 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3807 static int __init fsg_bind(struct usb_gadget *gadget)
3809 struct fsg_dev *fsg = the_fsg;
3814 struct usb_request *req;
3817 fsg->gadget = gadget;
3818 set_gadget_data(gadget, fsg);
3819 fsg->ep0 = gadget->ep0;
3820 fsg->ep0->driver_data = fsg;
3822 if ((rc = check_parameters(fsg)) != 0)
3825 if (mod_data.removable) { // Enable the store_xxx attributes
3826 dev_attr_ro.attr.mode = dev_attr_file.attr.mode = 0644;
3827 dev_attr_ro.store = store_ro;
3828 dev_attr_file.store = store_file;
3831 /* Find out how many LUNs there should be */
3834 i = max(mod_data.num_filenames, 1);
3836 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3841 /* Create the LUNs, open their backing files, and register the
3842 * LUN devices in sysfs. */
3843 fsg->luns = kmalloc(i * sizeof(struct lun), GFP_KERNEL);
3848 memset(fsg->luns, 0, i * sizeof(struct lun));
3851 for (i = 0; i < fsg->nluns; ++i) {
3852 curlun = &fsg->luns[i];
3854 curlun->dev.parent = &gadget->dev;
3855 curlun->dev.driver = &fsg_driver.driver;
3856 dev_set_drvdata(&curlun->dev, fsg);
3857 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
3858 "%s-lun%d", gadget->dev.bus_id, i);
3860 if ((rc = device_register(&curlun->dev)) != 0)
3861 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
3863 curlun->registered = 1;
3864 curlun->dev.release = lun_release;
3865 device_create_file(&curlun->dev, &dev_attr_ro);
3866 device_create_file(&curlun->dev, &dev_attr_file);
3869 if (file[i] && *file[i]) {
3870 if ((rc = open_backing_file(curlun, file[i])) != 0)
3872 } else if (!mod_data.removable) {
3873 ERROR(fsg, "no file given for LUN%d\n", i);
3879 /* Find all the endpoints we will use */
3880 usb_ep_autoconfig_reset(gadget);
3881 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
3884 ep->driver_data = fsg; // claim the endpoint
3887 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
3890 ep->driver_data = fsg; // claim the endpoint
3893 if (transport_is_cbi()) {
3894 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
3897 ep->driver_data = fsg; // claim the endpoint
3901 /* Fix up the descriptors */
3902 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3903 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3904 device_desc.idProduct = cpu_to_le16(mod_data.product);
3905 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3907 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
3908 intf_desc.bNumEndpoints = i;
3909 intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3910 intf_desc.bInterfaceProtocol = mod_data.transport_type;
3911 fs_function[i + FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3913 #ifdef CONFIG_USB_GADGET_DUALSPEED
3914 hs_function[i + HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3916 /* Assume ep0 uses the same maxpacket value for both speeds */
3917 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3919 /* Assume that all endpoint addresses are the same for both speeds */
3920 hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress;
3921 hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress;
3922 hs_intr_in_desc.bEndpointAddress = fs_intr_in_desc.bEndpointAddress;
3925 if (gadget->is_otg) {
3926 otg_desc.bmAttributes |= USB_OTG_HNP,
3927 config_desc.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
3932 /* Allocate the request and buffer for endpoint 0 */
3933 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3936 req->buf = usb_ep_alloc_buffer(fsg->ep0, EP0_BUFSIZE,
3937 &req->dma, GFP_KERNEL);
3940 req->complete = ep0_complete;
3942 /* Allocate the data buffers */
3943 for (i = 0; i < NUM_BUFFERS; ++i) {
3944 struct fsg_buffhd *bh = &fsg->buffhds[i];
3946 bh->buf = usb_ep_alloc_buffer(fsg->bulk_in, mod_data.buflen,
3947 &bh->dma, GFP_KERNEL);
3952 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3954 /* This should reflect the actual gadget power source */
3955 usb_gadget_set_selfpowered(gadget);
3957 snprintf(manufacturer, sizeof manufacturer,
3958 UTS_SYSNAME " " UTS_RELEASE " with %s",
3961 /* On a real device, serial[] would be loaded from permanent
3962 * storage. We just encode it from the driver version string. */
3963 for (i = 0; i < sizeof(serial) - 2; i += 2) {
3964 unsigned char c = DRIVER_VERSION[i / 2];
3968 sprintf(&serial[i], "%02X", c);
3971 if ((rc = kernel_thread(fsg_main_thread, fsg, (CLONE_VM | CLONE_FS |
3974 fsg->thread_pid = rc;
3976 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3977 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3979 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3980 for (i = 0; i < fsg->nluns; ++i) {
3981 curlun = &fsg->luns[i];
3982 if (backing_file_is_open(curlun)) {
3985 p = d_path(curlun->filp->f_dentry,
3986 curlun->filp->f_vfsmnt,
3991 LINFO(curlun, "ro=%d, file: %s\n",
3992 curlun->ro, (p ? p : "(error)"));
3997 DBG(fsg, "transport=%s (x%02x)\n",
3998 mod_data.transport_name, mod_data.transport_type);
3999 DBG(fsg, "protocol=%s (x%02x)\n",
4000 mod_data.protocol_name, mod_data.protocol_type);
4001 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
4002 mod_data.vendor, mod_data.product, mod_data.release);
4003 DBG(fsg, "removable=%d, stall=%d, buflen=%u\n",
4004 mod_data.removable, mod_data.can_stall,
4006 DBG(fsg, "I/O thread pid: %d\n", fsg->thread_pid);
4010 ERROR(fsg, "unable to autoconfigure all endpoints\n");
4014 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
4016 close_all_backing_files(fsg);
4021 /*-------------------------------------------------------------------------*/
4023 static void fsg_suspend(struct usb_gadget *gadget)
4025 struct fsg_dev *fsg = get_gadget_data(gadget);
4027 DBG(fsg, "suspend\n");
4028 set_bit(SUSPENDED, &fsg->atomic_bitflags);
4031 static void fsg_resume(struct usb_gadget *gadget)
4033 struct fsg_dev *fsg = get_gadget_data(gadget);
4035 DBG(fsg, "resume\n");
4036 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
4040 /*-------------------------------------------------------------------------*/
4042 static struct usb_gadget_driver fsg_driver = {
4043 #ifdef CONFIG_USB_GADGET_DUALSPEED
4044 .speed = USB_SPEED_HIGH,
4046 .speed = USB_SPEED_FULL,
4048 .function = (char *) longname,
4050 .unbind = fsg_unbind,
4051 .disconnect = fsg_disconnect,
4053 .suspend = fsg_suspend,
4054 .resume = fsg_resume,
4057 .name = (char *) shortname,
4065 static int __init fsg_alloc(void)
4067 struct fsg_dev *fsg;
4069 fsg = kmalloc(sizeof *fsg, GFP_KERNEL);
4072 memset(fsg, 0, sizeof *fsg);
4073 spin_lock_init(&fsg->lock);
4074 init_rwsem(&fsg->filesem);
4075 init_waitqueue_head(&fsg->thread_wqh);
4076 init_completion(&fsg->thread_notifier);
4083 static void fsg_free(struct fsg_dev *fsg)
4090 static int __init fsg_init(void)
4093 struct fsg_dev *fsg;
4095 if ((rc = fsg_alloc()) != 0)
4098 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0) {
4102 set_bit(REGISTERED, &fsg->atomic_bitflags);
4104 /* Tell the thread to start working */
4105 complete(&fsg->thread_notifier);
4108 module_init(fsg_init);
4111 static void __exit fsg_cleanup(void)
4113 struct fsg_dev *fsg = the_fsg;
4115 /* Unregister the driver iff the thread hasn't already done so */
4116 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4117 usb_gadget_unregister_driver(&fsg_driver);
4119 /* Wait for the thread to finish up */
4120 wait_for_completion(&fsg->thread_notifier);
4122 close_all_backing_files(fsg);
4125 module_exit(fsg_cleanup);