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/device.h>
221 #include <linux/fcntl.h>
222 #include <linux/file.h>
223 #include <linux/fs.h>
224 #include <linux/init.h>
225 #include <linux/kernel.h>
226 #include <linux/limits.h>
227 #include <linux/list.h>
228 #include <linux/module.h>
229 #include <linux/moduleparam.h>
230 #include <linux/pagemap.h>
231 #include <linux/rwsem.h>
232 #include <linux/sched.h>
233 #include <linux/signal.h>
234 #include <linux/slab.h>
235 #include <linux/spinlock.h>
236 #include <linux/string.h>
237 #include <linux/uts.h>
238 #include <linux/version.h>
239 #include <linux/wait.h>
241 #include <linux/usb_ch9.h>
242 #include <linux/usb_gadget.h>
244 #include "gadget_chips.h"
247 /*-------------------------------------------------------------------------*/
249 #define DRIVER_DESC "File-backed Storage Gadget"
250 #define DRIVER_NAME "g_file_storage"
251 #define DRIVER_VERSION "28 July 2004"
253 static const char longname[] = DRIVER_DESC;
254 static const char shortname[] = DRIVER_NAME;
256 MODULE_DESCRIPTION(DRIVER_DESC);
257 MODULE_AUTHOR("Alan Stern");
258 MODULE_LICENSE("Dual BSD/GPL");
260 /* Thanks to NetChip Technologies for donating this product ID.
262 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
263 * Instead: allocate your own, using normal USB-IF procedures. */
264 #define DRIVER_VENDOR_ID 0x0525 // NetChip
265 #define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
269 * This driver assumes self-powered hardware and has no way for users to
270 * trigger remote wakeup. It uses autoconfiguration to select endpoints
271 * and endpoint addresses.
275 /*-------------------------------------------------------------------------*/
277 #define xprintk(f,level,fmt,args...) \
278 dev_printk(level , &(f)->gadget->dev , fmt , ## args)
279 #define yprintk(l,level,fmt,args...) \
280 dev_printk(level , &(l)->dev , fmt , ## args)
283 #define DBG(fsg,fmt,args...) \
284 xprintk(fsg , KERN_DEBUG , fmt , ## args)
285 #define LDBG(lun,fmt,args...) \
286 yprintk(lun , KERN_DEBUG , fmt , ## args)
287 #define MDBG(fmt,args...) \
288 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
290 #define DBG(fsg,fmt,args...) \
292 #define LDBG(lun,fmt,args...) \
294 #define MDBG(fmt,args...) \
304 #define VDBG(fsg,fmt,args...) \
306 #define VLDBG(lun,fmt,args...) \
310 #define ERROR(fsg,fmt,args...) \
311 xprintk(fsg , KERN_ERR , fmt , ## args)
312 #define LERROR(lun,fmt,args...) \
313 yprintk(lun , KERN_ERR , fmt , ## args)
315 #define WARN(fsg,fmt,args...) \
316 xprintk(fsg , KERN_WARNING , fmt , ## args)
317 #define LWARN(lun,fmt,args...) \
318 yprintk(lun , KERN_WARNING , fmt , ## args)
320 #define INFO(fsg,fmt,args...) \
321 xprintk(fsg , KERN_INFO , fmt , ## args)
322 #define LINFO(lun,fmt,args...) \
323 yprintk(lun , KERN_INFO , fmt , ## args)
325 #define MINFO(fmt,args...) \
326 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
329 /*-------------------------------------------------------------------------*/
331 /* Encapsulate the module parameter settings */
335 /* Arggh! There should be a module_param_array_named macro! */
336 static char *file[MAX_LUNS] = {NULL, };
337 static int ro[MAX_LUNS] = {0, };
344 char *transport_parm;
347 unsigned short vendor;
348 unsigned short product;
349 unsigned short release;
354 char *transport_name;
358 } mod_data = { // Default values
359 .transport_parm = "BBB",
360 .protocol_parm = "SCSI",
362 .vendor = DRIVER_VENDOR_ID,
363 .product = DRIVER_PRODUCT_ID,
364 .release = 0xffff, // Use controller chip type
370 module_param_array(file, charp, mod_data.num_filenames, S_IRUGO);
371 MODULE_PARM_DESC(file, "names of backing files or devices");
373 module_param_array(ro, bool, mod_data.num_ros, S_IRUGO);
374 MODULE_PARM_DESC(ro, "true to force read-only");
376 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
377 MODULE_PARM_DESC(luns, "number of LUNs");
379 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
380 MODULE_PARM_DESC(removable, "true to simulate removable media");
383 /* In the non-TEST version, only the module parameters listed above
385 #ifdef CONFIG_USB_FILE_STORAGE_TEST
387 module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
388 MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
390 module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
391 MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
394 module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
395 MODULE_PARM_DESC(vendor, "USB Vendor ID");
397 module_param_named(product, mod_data.product, ushort, S_IRUGO);
398 MODULE_PARM_DESC(product, "USB Product ID");
400 module_param_named(release, mod_data.release, ushort, S_IRUGO);
401 MODULE_PARM_DESC(release, "USB release number");
403 module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
404 MODULE_PARM_DESC(buflen, "I/O buffer size");
406 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
407 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
409 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
412 /*-------------------------------------------------------------------------*/
414 /* USB protocol value = the transport method */
415 #define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
416 #define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
417 #define USB_PR_BULK 0x50 // Bulk-only
419 /* USB subclass value = the protocol encapsulation */
420 #define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
421 #define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
422 #define USB_SC_QIC 0x03 // QIC-157 (tape)
423 #define USB_SC_UFI 0x04 // UFI (floppy)
424 #define USB_SC_8070 0x05 // SFF-8070i (removable)
425 #define USB_SC_SCSI 0x06 // Transparent SCSI
427 /* Bulk-only data structures */
429 /* Command Block Wrapper */
430 struct bulk_cb_wrap {
431 u32 Signature; // Contains 'USBC'
432 u32 Tag; // Unique per command id
433 u32 DataTransferLength; // Size of the data
434 u8 Flags; // Direction in bit 7
435 u8 Lun; // LUN (normally 0)
436 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
437 u8 CDB[16]; // Command Data Block
440 #define USB_BULK_CB_WRAP_LEN 31
441 #define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
442 #define USB_BULK_IN_FLAG 0x80
444 /* Command Status Wrapper */
445 struct bulk_cs_wrap {
446 u32 Signature; // Should = 'USBS'
447 u32 Tag; // Same as original command
448 u32 Residue; // Amount not transferred
449 u8 Status; // See below
452 #define USB_BULK_CS_WRAP_LEN 13
453 #define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
454 #define USB_STATUS_PASS 0
455 #define USB_STATUS_FAIL 1
456 #define USB_STATUS_PHASE_ERROR 2
458 /* Bulk-only class specific requests */
459 #define USB_BULK_RESET_REQUEST 0xff
460 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
463 /* CBI Interrupt data structure */
464 struct interrupt_data {
469 #define CBI_INTERRUPT_DATA_LEN 2
471 /* CBI Accept Device-Specific Command request */
472 #define USB_CBI_ADSC_REQUEST 0x00
475 #define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
477 /* SCSI commands that we recognize */
478 #define SC_FORMAT_UNIT 0x04
479 #define SC_INQUIRY 0x12
480 #define SC_MODE_SELECT_6 0x15
481 #define SC_MODE_SELECT_10 0x55
482 #define SC_MODE_SENSE_6 0x1a
483 #define SC_MODE_SENSE_10 0x5a
484 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
485 #define SC_READ_6 0x08
486 #define SC_READ_10 0x28
487 #define SC_READ_12 0xa8
488 #define SC_READ_CAPACITY 0x25
489 #define SC_READ_FORMAT_CAPACITIES 0x23
490 #define SC_RELEASE 0x17
491 #define SC_REQUEST_SENSE 0x03
492 #define SC_RESERVE 0x16
493 #define SC_SEND_DIAGNOSTIC 0x1d
494 #define SC_START_STOP_UNIT 0x1b
495 #define SC_SYNCHRONIZE_CACHE 0x35
496 #define SC_TEST_UNIT_READY 0x00
497 #define SC_VERIFY 0x2f
498 #define SC_WRITE_6 0x0a
499 #define SC_WRITE_10 0x2a
500 #define SC_WRITE_12 0xaa
502 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
503 #define SS_NO_SENSE 0
504 #define SS_COMMUNICATION_FAILURE 0x040800
505 #define SS_INVALID_COMMAND 0x052000
506 #define SS_INVALID_FIELD_IN_CDB 0x052400
507 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
508 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
509 #define SS_MEDIUM_NOT_PRESENT 0x023a00
510 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
511 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
512 #define SS_RESET_OCCURRED 0x062900
513 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
514 #define SS_UNRECOVERED_READ_ERROR 0x031100
515 #define SS_WRITE_ERROR 0x030c02
516 #define SS_WRITE_PROTECTED 0x072700
518 #define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
519 #define ASC(x) ((u8) ((x) >> 8))
520 #define ASCQ(x) ((u8) (x))
523 /*-------------------------------------------------------------------------*/
526 * These definitions will permit the compiler to avoid generating code for
527 * parts of the driver that aren't used in the non-TEST version. Even gcc
528 * can recognize when a test of a constant expression yields a dead code
532 #ifdef CONFIG_USB_FILE_STORAGE_TEST
534 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
535 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
536 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
540 #define transport_is_bbb() 1
541 #define transport_is_cbi() 0
542 #define protocol_is_scsi() 1
544 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
553 unsigned int prevent_medium_removal : 1;
554 unsigned int registered : 1;
558 u32 unit_attention_data;
563 #define backing_file_is_open(curlun) ((curlun)->filp != NULL)
565 static inline struct lun *dev_to_lun(struct device *dev)
567 return container_of(dev, struct lun, dev);
571 /* Big enough to hold our biggest descriptor */
572 #define EP0_BUFSIZE 256
573 #define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
575 /* Number of buffers we will use. 2 is enough for double-buffering */
576 #define NUM_BUFFERS 2
578 enum fsg_buffer_state {
587 volatile enum fsg_buffer_state state;
588 struct fsg_buffhd *next;
590 /* The NetChip 2280 is faster, and handles some protocol faults
591 * better, if we don't submit any short bulk-out read requests.
592 * So we will record the intended request length here. */
593 unsigned int bulk_out_intended_length;
595 struct usb_request *inreq;
596 volatile int inreq_busy;
597 struct usb_request *outreq;
598 volatile int outreq_busy;
602 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
603 FSG_STATE_DATA_PHASE,
604 FSG_STATE_STATUS_PHASE,
607 FSG_STATE_ABORT_BULK_OUT,
609 FSG_STATE_INTERFACE_CHANGE,
610 FSG_STATE_CONFIG_CHANGE,
611 FSG_STATE_DISCONNECT,
616 enum data_direction {
617 DATA_DIR_UNKNOWN = 0,
624 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
626 struct usb_gadget *gadget;
628 /* filesem protects: backing files in use */
629 struct rw_semaphore filesem;
631 struct usb_ep *ep0; // Handy copy of gadget->ep0
632 struct usb_request *ep0req; // For control responses
633 volatile unsigned int ep0_req_tag;
634 const char *ep0req_name;
636 struct usb_request *intreq; // For interrupt responses
637 volatile int intreq_busy;
638 struct fsg_buffhd *intr_buffhd;
640 unsigned int bulk_out_maxpacket;
641 enum fsg_state state; // For exception handling
642 unsigned int exception_req_tag;
644 u8 config, new_config;
646 unsigned int running : 1;
647 unsigned int bulk_in_enabled : 1;
648 unsigned int bulk_out_enabled : 1;
649 unsigned int intr_in_enabled : 1;
650 unsigned int phase_error : 1;
651 unsigned int short_packet_received : 1;
652 unsigned int bad_lun_okay : 1;
654 unsigned long atomic_bitflags;
656 #define CLEAR_BULK_HALTS 1
659 struct usb_ep *bulk_in;
660 struct usb_ep *bulk_out;
661 struct usb_ep *intr_in;
663 struct fsg_buffhd *next_buffhd_to_fill;
664 struct fsg_buffhd *next_buffhd_to_drain;
665 struct fsg_buffhd buffhds[NUM_BUFFERS];
667 wait_queue_head_t thread_wqh;
668 int thread_wakeup_needed;
669 struct completion thread_notifier;
671 struct task_struct *thread_task;
672 sigset_t thread_signal_mask;
675 u8 cmnd[MAX_COMMAND_SIZE];
676 enum data_direction data_dir;
678 u32 data_size_from_cmnd;
684 /* The CB protocol offers no way for a host to know when a command
685 * has completed. As a result the next command may arrive early,
686 * and we will still have to handle it. For that reason we need
687 * a buffer to store new commands when using CB (or CBI, which
688 * does not oblige a host to wait for command completion either). */
690 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
695 struct completion lun_released;
698 typedef void (*fsg_routine_t)(struct fsg_dev *);
700 static int inline exception_in_progress(struct fsg_dev *fsg)
702 return (fsg->state > FSG_STATE_IDLE);
705 /* Make bulk-out requests be divisible by the maxpacket size */
706 static void inline set_bulk_out_req_length(struct fsg_dev *fsg,
707 struct fsg_buffhd *bh, unsigned int length)
711 bh->bulk_out_intended_length = length;
712 rem = length % fsg->bulk_out_maxpacket;
714 length += fsg->bulk_out_maxpacket - rem;
715 bh->outreq->length = length;
718 static struct fsg_dev *the_fsg;
719 static struct usb_gadget_driver fsg_driver;
721 static void close_backing_file(struct lun *curlun);
722 static void close_all_backing_files(struct fsg_dev *fsg);
725 /*-------------------------------------------------------------------------*/
729 static void dump_msg(struct fsg_dev *fsg, const char *label,
730 const u8 *buf, unsigned int length)
732 unsigned int start, num, i;
737 DBG(fsg, "%s, length %u:\n", label, length);
741 num = min(length, 16u);
743 for (i = 0; i < num; ++i) {
746 sprintf(p, " %02x", buf[i]);
750 printk(KERN_DEBUG "%6x: %s\n", start, line);
757 static void inline dump_cdb(struct fsg_dev *fsg)
762 static void inline dump_msg(struct fsg_dev *fsg, const char *label,
763 const u8 *buf, unsigned int length)
766 static void inline dump_cdb(struct fsg_dev *fsg)
769 char cmdbuf[3*MAX_COMMAND_SIZE + 1];
771 for (i = 0; i < fsg->cmnd_size; ++i)
772 sprintf(cmdbuf + i*3, " %02x", fsg->cmnd[i]);
773 VDBG(fsg, "SCSI CDB: %s\n", cmdbuf);
776 #endif /* DUMP_MSGS */
779 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
783 if (ep == fsg->bulk_in)
785 else if (ep == fsg->bulk_out)
789 DBG(fsg, "%s set halt\n", name);
790 return usb_ep_set_halt(ep);
794 /*-------------------------------------------------------------------------*/
796 /* Routines for unaligned data access */
798 static u16 inline get_be16(u8 *buf)
800 return ((u16) buf[0] << 8) | ((u16) buf[1]);
803 static u32 inline get_be32(u8 *buf)
805 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
806 ((u32) buf[2] << 8) | ((u32) buf[3]);
809 static void inline put_be16(u8 *buf, u16 val)
815 static void inline put_be32(u8 *buf, u32 val)
824 /*-------------------------------------------------------------------------*/
827 * DESCRIPTORS ... most are static, but strings and (full) configuration
828 * descriptors are built on demand. Also the (static) config and interface
829 * descriptors are adjusted during fsg_bind().
831 #define STRING_MANUFACTURER 1
832 #define STRING_PRODUCT 2
833 #define STRING_SERIAL 3
835 /* There is only one configuration. */
836 #define CONFIG_VALUE 1
838 static struct usb_device_descriptor
840 .bLength = sizeof device_desc,
841 .bDescriptorType = USB_DT_DEVICE,
843 .bcdUSB = __constant_cpu_to_le16(0x0200),
844 .bDeviceClass = USB_CLASS_PER_INTERFACE,
846 /* The next three values can be overridden by module parameters */
847 .idVendor = __constant_cpu_to_le16(DRIVER_VENDOR_ID),
848 .idProduct = __constant_cpu_to_le16(DRIVER_PRODUCT_ID),
849 .bcdDevice = __constant_cpu_to_le16(0xffff),
851 .iManufacturer = STRING_MANUFACTURER,
852 .iProduct = STRING_PRODUCT,
853 .iSerialNumber = STRING_SERIAL,
854 .bNumConfigurations = 1,
857 static struct usb_config_descriptor
859 .bLength = sizeof config_desc,
860 .bDescriptorType = USB_DT_CONFIG,
862 /* wTotalLength computed by usb_gadget_config_buf() */
864 .bConfigurationValue = CONFIG_VALUE,
865 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
866 .bMaxPower = 1, // self-powered
869 /* There is only one interface. */
871 static struct usb_interface_descriptor
873 .bLength = sizeof intf_desc,
874 .bDescriptorType = USB_DT_INTERFACE,
876 .bNumEndpoints = 2, // Adjusted during fsg_bind()
877 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
878 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
879 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
882 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
883 * and interrupt-in. */
885 static struct usb_endpoint_descriptor
887 .bLength = USB_DT_ENDPOINT_SIZE,
888 .bDescriptorType = USB_DT_ENDPOINT,
890 .bEndpointAddress = USB_DIR_IN,
891 .bmAttributes = USB_ENDPOINT_XFER_BULK,
892 /* wMaxPacketSize set by autoconfiguration */
895 static struct usb_endpoint_descriptor
897 .bLength = USB_DT_ENDPOINT_SIZE,
898 .bDescriptorType = USB_DT_ENDPOINT,
900 .bEndpointAddress = USB_DIR_OUT,
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_IN,
911 .bmAttributes = USB_ENDPOINT_XFER_INT,
912 .wMaxPacketSize = __constant_cpu_to_le16(2),
913 .bInterval = 32, // frames -> 32 ms
916 static const struct usb_descriptor_header *fs_function[] = {
917 (struct usb_descriptor_header *) &intf_desc,
918 (struct usb_descriptor_header *) &fs_bulk_in_desc,
919 (struct usb_descriptor_header *) &fs_bulk_out_desc,
920 (struct usb_descriptor_header *) &fs_intr_in_desc,
925 #ifdef CONFIG_USB_GADGET_DUALSPEED
928 * USB 2.0 devices need to expose both high speed and full speed
929 * descriptors, unless they only run at full speed.
931 * That means alternate endpoint descriptors (bigger packets)
932 * and a "device qualifier" ... plus more construction options
933 * for the config descriptor.
935 static struct usb_qualifier_descriptor
937 .bLength = sizeof dev_qualifier,
938 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
940 .bcdUSB = __constant_cpu_to_le16(0x0200),
941 .bDeviceClass = USB_CLASS_PER_INTERFACE,
943 .bNumConfigurations = 1,
946 static struct usb_endpoint_descriptor
948 .bLength = USB_DT_ENDPOINT_SIZE,
949 .bDescriptorType = USB_DT_ENDPOINT,
951 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
952 .bmAttributes = USB_ENDPOINT_XFER_BULK,
953 .wMaxPacketSize = __constant_cpu_to_le16(512),
956 static struct usb_endpoint_descriptor
958 .bLength = USB_DT_ENDPOINT_SIZE,
959 .bDescriptorType = USB_DT_ENDPOINT,
961 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
962 .bmAttributes = USB_ENDPOINT_XFER_BULK,
963 .wMaxPacketSize = __constant_cpu_to_le16(512),
964 .bInterval = 1, // NAK every 1 uframe
967 static struct usb_endpoint_descriptor
969 .bLength = USB_DT_ENDPOINT_SIZE,
970 .bDescriptorType = USB_DT_ENDPOINT,
972 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
973 .bmAttributes = USB_ENDPOINT_XFER_INT,
974 .wMaxPacketSize = __constant_cpu_to_le16(2),
975 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
978 static const struct usb_descriptor_header *hs_function[] = {
979 (struct usb_descriptor_header *) &intf_desc,
980 (struct usb_descriptor_header *) &hs_bulk_in_desc,
981 (struct usb_descriptor_header *) &hs_bulk_out_desc,
982 (struct usb_descriptor_header *) &hs_intr_in_desc,
986 /* Maxpacket and other transfer characteristics vary by speed. */
987 #define ep_desc(g,fs,hs) (((g)->speed==USB_SPEED_HIGH) ? (hs) : (fs))
991 /* If there's no high speed support, always use the full-speed descriptor. */
992 #define ep_desc(g,fs,hs) fs
994 #endif /* !CONFIG_USB_GADGET_DUALSPEED */
997 /* The CBI specification limits the serial string to 12 uppercase hexadecimal
999 static char manufacturer[40];
1000 static char serial[13];
1002 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1003 static struct usb_string strings[] = {
1004 {STRING_MANUFACTURER, manufacturer},
1005 {STRING_PRODUCT, longname},
1006 {STRING_SERIAL, serial},
1010 static struct usb_gadget_strings stringtab = {
1011 .language = 0x0409, // en-us
1017 * Config descriptors must agree with the code that sets configurations
1018 * and with code managing interfaces and their altsettings. They must
1019 * also handle different speeds and other-speed requests.
1021 static int populate_config_buf(enum usb_device_speed speed,
1022 u8 *buf, u8 type, unsigned index)
1025 const struct usb_descriptor_header **function;
1030 #ifdef CONFIG_USB_GADGET_DUALSPEED
1031 if (type == USB_DT_OTHER_SPEED_CONFIG)
1032 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
1033 if (speed == USB_SPEED_HIGH)
1034 function = hs_function;
1037 function = fs_function;
1039 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
1040 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1045 /*-------------------------------------------------------------------------*/
1047 /* These routines may be called in process context or in_irq */
1049 static void wakeup_thread(struct fsg_dev *fsg)
1051 /* Tell the main thread that something has happened */
1052 fsg->thread_wakeup_needed = 1;
1053 wake_up_all(&fsg->thread_wqh);
1057 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
1059 unsigned long flags;
1060 struct task_struct *thread_task;
1062 /* Do nothing if a higher-priority exception is already in progress.
1063 * If a lower-or-equal priority exception is in progress, preempt it
1064 * and notify the main thread by sending it a signal. */
1065 spin_lock_irqsave(&fsg->lock, flags);
1066 if (fsg->state <= new_state) {
1067 fsg->exception_req_tag = fsg->ep0_req_tag;
1068 fsg->state = new_state;
1069 thread_task = fsg->thread_task;
1071 send_sig_info(SIGUSR1, SEND_SIG_FORCED, thread_task);
1073 spin_unlock_irqrestore(&fsg->lock, flags);
1077 /*-------------------------------------------------------------------------*/
1079 /* The disconnect callback and ep0 routines. These always run in_irq,
1080 * except that ep0_queue() is called in the main thread to acknowledge
1081 * completion of various requests: set config, set interface, and
1082 * Bulk-only device reset. */
1084 static void fsg_disconnect(struct usb_gadget *gadget)
1086 struct fsg_dev *fsg = get_gadget_data(gadget);
1088 DBG(fsg, "disconnect or port reset\n");
1089 raise_exception(fsg, FSG_STATE_DISCONNECT);
1093 static int ep0_queue(struct fsg_dev *fsg)
1097 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
1098 if (rc != 0 && rc != -ESHUTDOWN) {
1100 /* We can't do much more than wait for a reset */
1101 WARN(fsg, "error in submission: %s --> %d\n",
1102 fsg->ep0->name, rc);
1107 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
1109 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1111 if (req->actual > 0)
1112 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
1113 if (req->status || req->actual != req->length)
1114 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1115 req->status, req->actual, req->length);
1116 if (req->status == -ECONNRESET) // Request was cancelled
1117 usb_ep_fifo_flush(ep);
1119 if (req->status == 0 && req->context)
1120 ((fsg_routine_t) (req->context))(fsg);
1124 /*-------------------------------------------------------------------------*/
1126 /* Bulk and interrupt endpoint completion handlers.
1127 * These always run in_irq. */
1129 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
1131 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1132 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
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 /* Hold the lock while we update the request and buffer states */
1141 spin_lock(&fsg->lock);
1143 bh->state = BUF_STATE_EMPTY;
1144 spin_unlock(&fsg->lock);
1148 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
1150 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1151 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1153 dump_msg(fsg, "bulk-out", req->buf, req->actual);
1154 if (req->status || req->actual != bh->bulk_out_intended_length)
1155 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1156 req->status, req->actual,
1157 bh->bulk_out_intended_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);
1163 bh->outreq_busy = 0;
1164 bh->state = BUF_STATE_FULL;
1165 spin_unlock(&fsg->lock);
1170 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1171 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1173 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1174 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1176 if (req->status || req->actual != req->length)
1177 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1178 req->status, req->actual, req->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 fsg->intreq_busy = 0;
1185 bh->state = BUF_STATE_EMPTY;
1186 spin_unlock(&fsg->lock);
1191 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1193 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1196 /*-------------------------------------------------------------------------*/
1198 /* Ep0 class-specific handlers. These always run in_irq. */
1200 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1201 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1203 struct usb_request *req = fsg->ep0req;
1204 static u8 cbi_reset_cmnd[6] = {
1205 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
1207 /* Error in command transfer? */
1208 if (req->status || req->length != req->actual ||
1209 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
1211 /* Not all controllers allow a protocol stall after
1212 * receiving control-out data, but we'll try anyway. */
1213 fsg_set_halt(fsg, fsg->ep0);
1214 return; // Wait for reset
1217 /* Is it the special reset command? */
1218 if (req->actual >= sizeof cbi_reset_cmnd &&
1219 memcmp(req->buf, cbi_reset_cmnd,
1220 sizeof cbi_reset_cmnd) == 0) {
1222 /* Raise an exception to stop the current operation
1223 * and reinitialize our state. */
1224 DBG(fsg, "cbi reset request\n");
1225 raise_exception(fsg, FSG_STATE_RESET);
1229 VDBG(fsg, "CB[I] accept device-specific command\n");
1230 spin_lock(&fsg->lock);
1232 /* Save the command for later */
1233 if (fsg->cbbuf_cmnd_size)
1234 WARN(fsg, "CB[I] overwriting previous command\n");
1235 fsg->cbbuf_cmnd_size = req->actual;
1236 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
1238 spin_unlock(&fsg->lock);
1243 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1245 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1248 static int class_setup_req(struct fsg_dev *fsg,
1249 const struct usb_ctrlrequest *ctrl)
1251 struct usb_request *req = fsg->ep0req;
1252 int value = -EOPNOTSUPP;
1257 /* Handle Bulk-only class-specific requests */
1258 if (transport_is_bbb()) {
1259 switch (ctrl->bRequest) {
1261 case USB_BULK_RESET_REQUEST:
1262 if (ctrl->bRequestType != (USB_DIR_OUT |
1263 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1265 if (ctrl->wIndex != 0) {
1270 /* Raise an exception to stop the current operation
1271 * and reinitialize our state. */
1272 DBG(fsg, "bulk reset request\n");
1273 raise_exception(fsg, FSG_STATE_RESET);
1274 value = DELAYED_STATUS;
1277 case USB_BULK_GET_MAX_LUN_REQUEST:
1278 if (ctrl->bRequestType != (USB_DIR_IN |
1279 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1281 if (ctrl->wIndex != 0) {
1285 VDBG(fsg, "get max LUN\n");
1286 *(u8 *) req->buf = fsg->nluns - 1;
1287 value = min(ctrl->wLength, (u16) 1);
1292 /* Handle CBI class-specific requests */
1294 switch (ctrl->bRequest) {
1296 case USB_CBI_ADSC_REQUEST:
1297 if (ctrl->bRequestType != (USB_DIR_OUT |
1298 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1300 if (ctrl->wIndex != 0) {
1304 if (ctrl->wLength > MAX_COMMAND_SIZE) {
1308 value = ctrl->wLength;
1309 fsg->ep0req->context = received_cbi_adsc;
1314 if (value == -EOPNOTSUPP)
1316 "unknown class-specific control req "
1317 "%02x.%02x v%04x i%04x l%u\n",
1318 ctrl->bRequestType, ctrl->bRequest,
1319 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1324 /*-------------------------------------------------------------------------*/
1326 /* Ep0 standard request handlers. These always run in_irq. */
1328 static int standard_setup_req(struct fsg_dev *fsg,
1329 const struct usb_ctrlrequest *ctrl)
1331 struct usb_request *req = fsg->ep0req;
1332 int value = -EOPNOTSUPP;
1334 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1335 * but config change events will also reconfigure hardware. */
1336 switch (ctrl->bRequest) {
1338 case USB_REQ_GET_DESCRIPTOR:
1339 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1342 switch (ctrl->wValue >> 8) {
1345 VDBG(fsg, "get device descriptor\n");
1346 value = min(ctrl->wLength, (u16) sizeof device_desc);
1347 memcpy(req->buf, &device_desc, value);
1349 #ifdef CONFIG_USB_GADGET_DUALSPEED
1350 case USB_DT_DEVICE_QUALIFIER:
1351 VDBG(fsg, "get device qualifier\n");
1352 if (!fsg->gadget->is_dualspeed)
1354 value = min(ctrl->wLength, (u16) sizeof dev_qualifier);
1355 memcpy(req->buf, &dev_qualifier, value);
1358 case USB_DT_OTHER_SPEED_CONFIG:
1359 VDBG(fsg, "get other-speed config descriptor\n");
1360 if (!fsg->gadget->is_dualspeed)
1365 VDBG(fsg, "get configuration descriptor\n");
1366 #ifdef CONFIG_USB_GADGET_DUALSPEED
1369 value = populate_config_buf(fsg->gadget->speed,
1372 ctrl->wValue & 0xff);
1374 value = min(ctrl->wLength, (u16) value);
1378 VDBG(fsg, "get string descriptor\n");
1380 /* wIndex == language code */
1381 value = usb_gadget_get_string(&stringtab,
1382 ctrl->wValue & 0xff, req->buf);
1384 value = min(ctrl->wLength, (u16) value);
1389 /* One config, two speeds */
1390 case USB_REQ_SET_CONFIGURATION:
1391 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
1394 VDBG(fsg, "set configuration\n");
1395 if (ctrl->wValue == CONFIG_VALUE || ctrl->wValue == 0) {
1396 fsg->new_config = ctrl->wValue;
1398 /* Raise an exception to wipe out previous transaction
1399 * state (queued bufs, etc) and set the new config. */
1400 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1401 value = DELAYED_STATUS;
1404 case USB_REQ_GET_CONFIGURATION:
1405 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1408 VDBG(fsg, "get configuration\n");
1409 *(u8 *) req->buf = fsg->config;
1410 value = min(ctrl->wLength, (u16) 1);
1413 case USB_REQ_SET_INTERFACE:
1414 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1415 USB_RECIP_INTERFACE))
1417 if (fsg->config && ctrl->wIndex == 0) {
1419 /* Raise an exception to wipe out previous transaction
1420 * state (queued bufs, etc) and install the new
1421 * interface altsetting. */
1422 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1423 value = DELAYED_STATUS;
1426 case USB_REQ_GET_INTERFACE:
1427 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1428 USB_RECIP_INTERFACE))
1432 if (ctrl->wIndex != 0) {
1436 VDBG(fsg, "get interface\n");
1437 *(u8 *) req->buf = 0;
1438 value = min(ctrl->wLength, (u16) 1);
1443 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1444 ctrl->bRequestType, ctrl->bRequest,
1445 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1452 static int fsg_setup(struct usb_gadget *gadget,
1453 const struct usb_ctrlrequest *ctrl)
1455 struct fsg_dev *fsg = get_gadget_data(gadget);
1458 ++fsg->ep0_req_tag; // Record arrival of a new request
1459 fsg->ep0req->context = NULL;
1460 fsg->ep0req->length = 0;
1461 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1463 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1464 rc = class_setup_req(fsg, ctrl);
1466 rc = standard_setup_req(fsg, ctrl);
1468 /* Respond with data/status or defer until later? */
1469 if (rc >= 0 && rc != DELAYED_STATUS) {
1470 fsg->ep0req->length = rc;
1471 fsg->ep0req->zero = (rc < ctrl->wLength &&
1472 (rc % gadget->ep0->maxpacket) == 0);
1473 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1474 "ep0-in" : "ep0-out");
1475 rc = ep0_queue(fsg);
1478 /* Device either stalls (rc < 0) or reports success */
1483 /*-------------------------------------------------------------------------*/
1485 /* All the following routines run in process context */
1488 /* Use this for bulk or interrupt transfers, not ep0 */
1489 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1490 struct usb_request *req, volatile int *pbusy,
1491 volatile enum fsg_buffer_state *state)
1495 if (ep == fsg->bulk_in)
1496 dump_msg(fsg, "bulk-in", req->buf, req->length);
1497 else if (ep == fsg->intr_in)
1498 dump_msg(fsg, "intr-in", req->buf, req->length);
1500 *state = BUF_STATE_BUSY;
1501 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1504 *state = BUF_STATE_EMPTY;
1506 /* We can't do much more than wait for a reset */
1508 /* Note: currently the net2280 driver fails zero-length
1509 * submissions if DMA is enabled. */
1510 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1512 WARN(fsg, "error in submission: %s --> %d\n",
1518 static int sleep_thread(struct fsg_dev *fsg)
1522 /* Wait until a signal arrives or we are woken up */
1523 rc = wait_event_interruptible(fsg->thread_wqh,
1524 fsg->thread_wakeup_needed);
1525 fsg->thread_wakeup_needed = 0;
1526 return (rc ? -EINTR : 0);
1530 /*-------------------------------------------------------------------------*/
1532 static int do_read(struct fsg_dev *fsg)
1534 struct lun *curlun = fsg->curlun;
1536 struct fsg_buffhd *bh;
1539 loff_t file_offset, file_offset_tmp;
1540 unsigned int amount;
1541 unsigned int partial_page;
1544 /* Get the starting Logical Block Address and check that it's
1546 if (fsg->cmnd[0] == SC_READ_6)
1547 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1549 lba = get_be32(&fsg->cmnd[2]);
1551 /* We allow DPO (Disable Page Out = don't save data in the
1552 * cache) and FUA (Force Unit Access = don't read from the
1553 * cache), but we don't implement them. */
1554 if ((fsg->cmnd[1] & ~0x18) != 0) {
1555 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1559 if (lba >= curlun->num_sectors) {
1560 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1563 file_offset = ((loff_t) lba) << 9;
1565 /* Carry out the file reads */
1566 amount_left = fsg->data_size_from_cmnd;
1567 if (unlikely(amount_left == 0))
1568 return -EIO; // No default reply
1572 /* Figure out how much we need to read:
1573 * Try to read the remaining amount.
1574 * But don't read more than the buffer size.
1575 * And don't try to read past the end of the file.
1576 * Finally, if we're not at a page boundary, don't read past
1578 * If this means reading 0 then we were asked to read past
1579 * the end of file. */
1580 amount = min((unsigned int) amount_left, mod_data.buflen);
1581 amount = min((loff_t) amount,
1582 curlun->file_length - file_offset);
1583 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1584 if (partial_page > 0)
1585 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1588 /* Wait for the next buffer to become available */
1589 bh = fsg->next_buffhd_to_fill;
1590 while (bh->state != BUF_STATE_EMPTY) {
1591 if ((rc = sleep_thread(fsg)) != 0)
1595 /* If we were asked to read past the end of file,
1596 * end with an empty buffer. */
1598 curlun->sense_data =
1599 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1600 curlun->sense_data_info = file_offset >> 9;
1601 bh->inreq->length = 0;
1602 bh->state = BUF_STATE_FULL;
1606 /* Perform the read */
1607 file_offset_tmp = file_offset;
1608 nread = vfs_read(curlun->filp,
1609 (char __user *) bh->buf,
1610 amount, &file_offset_tmp);
1611 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1612 (unsigned long long) file_offset,
1614 if (signal_pending(current))
1618 LDBG(curlun, "error in file read: %d\n",
1621 } else if (nread < amount) {
1622 LDBG(curlun, "partial file read: %d/%u\n",
1623 (int) nread, amount);
1624 nread -= (nread & 511); // Round down to a block
1626 file_offset += nread;
1627 amount_left -= nread;
1628 fsg->residue -= nread;
1629 bh->inreq->length = nread;
1630 bh->state = BUF_STATE_FULL;
1632 /* If an error occurred, report it and its position */
1633 if (nread < amount) {
1634 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1635 curlun->sense_data_info = file_offset >> 9;
1639 if (amount_left == 0)
1640 break; // No more left to read
1642 /* Send this buffer and go read some more */
1643 bh->inreq->zero = 0;
1644 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1645 &bh->inreq_busy, &bh->state);
1646 fsg->next_buffhd_to_fill = bh->next;
1649 return -EIO; // No default reply
1653 /*-------------------------------------------------------------------------*/
1655 static int do_write(struct fsg_dev *fsg)
1657 struct lun *curlun = fsg->curlun;
1659 struct fsg_buffhd *bh;
1661 u32 amount_left_to_req, amount_left_to_write;
1662 loff_t usb_offset, file_offset, file_offset_tmp;
1663 unsigned int amount;
1664 unsigned int partial_page;
1669 curlun->sense_data = SS_WRITE_PROTECTED;
1672 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1674 /* Get the starting Logical Block Address and check that it's
1676 if (fsg->cmnd[0] == SC_WRITE_6)
1677 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1679 lba = get_be32(&fsg->cmnd[2]);
1681 /* We allow DPO (Disable Page Out = don't save data in the
1682 * cache) and FUA (Force Unit Access = write directly to the
1683 * medium). We don't implement DPO; we implement FUA by
1684 * performing synchronous output. */
1685 if ((fsg->cmnd[1] & ~0x18) != 0) {
1686 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1689 if (fsg->cmnd[1] & 0x08) // FUA
1690 curlun->filp->f_flags |= O_SYNC;
1692 if (lba >= curlun->num_sectors) {
1693 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1697 /* Carry out the file writes */
1699 file_offset = usb_offset = ((loff_t) lba) << 9;
1700 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1702 while (amount_left_to_write > 0) {
1704 /* Queue a request for more data from the host */
1705 bh = fsg->next_buffhd_to_fill;
1706 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1708 /* Figure out how much we want to get:
1709 * Try to get the remaining amount.
1710 * But don't get more than the buffer size.
1711 * And don't try to go past the end of the file.
1712 * If we're not at a page boundary,
1713 * don't go past the next page.
1714 * If this means getting 0, then we were asked
1715 * to write past the end of file.
1716 * Finally, round down to a block boundary. */
1717 amount = min(amount_left_to_req, mod_data.buflen);
1718 amount = min((loff_t) amount, curlun->file_length -
1720 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1721 if (partial_page > 0)
1722 amount = min(amount,
1723 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1727 curlun->sense_data =
1728 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1729 curlun->sense_data_info = usb_offset >> 9;
1732 amount -= (amount & 511);
1735 /* Why were we were asked to transfer a
1741 /* Get the next buffer */
1742 usb_offset += amount;
1743 fsg->usb_amount_left -= amount;
1744 amount_left_to_req -= amount;
1745 if (amount_left_to_req == 0)
1748 /* amount is always divisible by 512, hence by
1749 * the bulk-out maxpacket size */
1750 bh->outreq->length = bh->bulk_out_intended_length =
1752 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1753 &bh->outreq_busy, &bh->state);
1754 fsg->next_buffhd_to_fill = bh->next;
1758 /* Write the received data to the backing file */
1759 bh = fsg->next_buffhd_to_drain;
1760 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1761 break; // We stopped early
1762 if (bh->state == BUF_STATE_FULL) {
1763 fsg->next_buffhd_to_drain = bh->next;
1764 bh->state = BUF_STATE_EMPTY;
1766 /* Did something go wrong with the transfer? */
1767 if (bh->outreq->status != 0) {
1768 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1769 curlun->sense_data_info = file_offset >> 9;
1773 amount = bh->outreq->actual;
1774 if (curlun->file_length - file_offset < amount) {
1776 "write %u @ %llu beyond end %llu\n",
1777 amount, (unsigned long long) file_offset,
1778 (unsigned long long) curlun->file_length);
1779 amount = curlun->file_length - file_offset;
1782 /* Perform the write */
1783 file_offset_tmp = file_offset;
1784 nwritten = vfs_write(curlun->filp,
1785 (char __user *) bh->buf,
1786 amount, &file_offset_tmp);
1787 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1788 (unsigned long long) file_offset,
1790 if (signal_pending(current))
1791 return -EINTR; // Interrupted!
1794 LDBG(curlun, "error in file write: %d\n",
1797 } else if (nwritten < amount) {
1798 LDBG(curlun, "partial file write: %d/%u\n",
1799 (int) nwritten, amount);
1800 nwritten -= (nwritten & 511);
1801 // Round down to a block
1803 file_offset += nwritten;
1804 amount_left_to_write -= nwritten;
1805 fsg->residue -= nwritten;
1807 /* If an error occurred, report it and its position */
1808 if (nwritten < amount) {
1809 curlun->sense_data = SS_WRITE_ERROR;
1810 curlun->sense_data_info = file_offset >> 9;
1814 /* Did the host decide to stop early? */
1815 if (bh->outreq->actual != bh->outreq->length) {
1816 fsg->short_packet_received = 1;
1822 /* Wait for something to happen */
1823 if ((rc = sleep_thread(fsg)) != 0)
1827 return -EIO; // No default reply
1831 /*-------------------------------------------------------------------------*/
1833 /* Sync the file data, don't bother with the metadata.
1834 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1835 static int fsync_sub(struct lun *curlun)
1837 struct file *filp = curlun->filp;
1838 struct inode *inode;
1841 if (curlun->ro || !filp)
1843 if (!filp->f_op->fsync)
1846 inode = filp->f_dentry->d_inode;
1847 down(&inode->i_sem);
1848 current->flags |= PF_SYNCWRITE;
1849 rc = filemap_fdatawrite(inode->i_mapping);
1850 err = filp->f_op->fsync(filp, filp->f_dentry, 1);
1853 err = filemap_fdatawait(inode->i_mapping);
1856 current->flags &= ~PF_SYNCWRITE;
1858 VLDBG(curlun, "fdatasync -> %d\n", rc);
1862 static void fsync_all(struct fsg_dev *fsg)
1866 for (i = 0; i < fsg->nluns; ++i)
1867 fsync_sub(&fsg->luns[i]);
1870 static int do_synchronize_cache(struct fsg_dev *fsg)
1872 struct lun *curlun = fsg->curlun;
1875 /* We ignore the requested LBA and write out all file's
1876 * dirty data buffers. */
1877 rc = fsync_sub(curlun);
1879 curlun->sense_data = SS_WRITE_ERROR;
1884 /*-------------------------------------------------------------------------*/
1886 static void invalidate_sub(struct lun *curlun)
1888 struct file *filp = curlun->filp;
1889 struct inode *inode = filp->f_dentry->d_inode;
1892 rc = invalidate_inode_pages(inode->i_mapping);
1893 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1896 static int do_verify(struct fsg_dev *fsg)
1898 struct lun *curlun = fsg->curlun;
1900 u32 verification_length;
1901 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1902 loff_t file_offset, file_offset_tmp;
1904 unsigned int amount;
1907 /* Get the starting Logical Block Address and check that it's
1909 lba = get_be32(&fsg->cmnd[2]);
1910 if (lba >= curlun->num_sectors) {
1911 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1915 /* We allow DPO (Disable Page Out = don't save data in the
1916 * cache) but we don't implement it. */
1917 if ((fsg->cmnd[1] & ~0x10) != 0) {
1918 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1922 verification_length = get_be16(&fsg->cmnd[7]);
1923 if (unlikely(verification_length == 0))
1924 return -EIO; // No default reply
1926 /* Prepare to carry out the file verify */
1927 amount_left = verification_length << 9;
1928 file_offset = ((loff_t) lba) << 9;
1930 /* Write out all the dirty buffers before invalidating them */
1932 if (signal_pending(current))
1935 invalidate_sub(curlun);
1936 if (signal_pending(current))
1939 /* Just try to read the requested blocks */
1940 while (amount_left > 0) {
1942 /* Figure out how much we need to read:
1943 * Try to read the remaining amount, but not more than
1945 * And don't try to read past the end of the file.
1946 * If this means reading 0 then we were asked to read
1947 * past the end of file. */
1948 amount = min((unsigned int) amount_left, mod_data.buflen);
1949 amount = min((loff_t) amount,
1950 curlun->file_length - file_offset);
1952 curlun->sense_data =
1953 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1954 curlun->sense_data_info = file_offset >> 9;
1958 /* Perform the read */
1959 file_offset_tmp = file_offset;
1960 nread = vfs_read(curlun->filp,
1961 (char __user *) bh->buf,
1962 amount, &file_offset_tmp);
1963 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1964 (unsigned long long) file_offset,
1966 if (signal_pending(current))
1970 LDBG(curlun, "error in file verify: %d\n",
1973 } else if (nread < amount) {
1974 LDBG(curlun, "partial file verify: %d/%u\n",
1975 (int) nread, amount);
1976 nread -= (nread & 511); // Round down to a sector
1979 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1980 curlun->sense_data_info = file_offset >> 9;
1983 file_offset += nread;
1984 amount_left -= nread;
1990 /*-------------------------------------------------------------------------*/
1992 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1994 u8 *buf = (u8 *) bh->buf;
1996 static char vendor_id[] = "Linux ";
1997 static char product_id[] = "File-Stor Gadget";
1999 if (!fsg->curlun) { // Unsupported LUNs are okay
2000 fsg->bad_lun_okay = 1;
2002 buf[0] = 0x7f; // Unsupported, no device-type
2006 memset(buf, 0, 8); // Non-removable, direct-access device
2007 if (mod_data.removable)
2009 buf[2] = 2; // ANSI SCSI level 2
2010 buf[3] = 2; // SCSI-2 INQUIRY data format
2011 buf[4] = 31; // Additional length
2012 // No special options
2013 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id, product_id,
2019 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2021 struct lun *curlun = fsg->curlun;
2022 u8 *buf = (u8 *) bh->buf;
2026 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2028 * If a REQUEST SENSE command is received from an initiator
2029 * with a pending unit attention condition (before the target
2030 * generates the contingent allegiance condition), then the
2031 * target shall either:
2032 * a) report any pending sense data and preserve the unit
2033 * attention condition on the logical unit, or,
2034 * b) report the unit attention condition, may discard any
2035 * pending sense data, and clear the unit attention
2036 * condition on the logical unit for that initiator.
2038 * FSG normally uses option a); enable this code to use option b).
2041 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2042 curlun->sense_data = curlun->unit_attention_data;
2043 curlun->unit_attention_data = SS_NO_SENSE;
2047 if (!curlun) { // Unsupported LUNs are okay
2048 fsg->bad_lun_okay = 1;
2049 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2052 sd = curlun->sense_data;
2053 sdinfo = curlun->sense_data_info;
2054 curlun->sense_data = SS_NO_SENSE;
2055 curlun->sense_data_info = 0;
2059 buf[0] = 0x80 | 0x70; // Valid, current error
2061 put_be32(&buf[3], sdinfo); // Sense information
2062 buf[7] = 18 - 8; // Additional sense length
2069 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2071 struct lun *curlun = fsg->curlun;
2072 u32 lba = get_be32(&fsg->cmnd[2]);
2073 int pmi = fsg->cmnd[8];
2074 u8 *buf = (u8 *) bh->buf;
2076 /* Check the PMI and LBA fields */
2077 if (pmi > 1 || (pmi == 0 && lba != 0)) {
2078 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2082 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block
2083 put_be32(&buf[4], 512); // Block length
2088 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2090 struct lun *curlun = fsg->curlun;
2091 int mscmnd = fsg->cmnd[0];
2092 u8 *buf = (u8 *) bh->buf;
2095 int changeable_values, all_pages;
2099 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
2100 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2103 pc = fsg->cmnd[2] >> 6;
2104 page_code = fsg->cmnd[2] & 0x3f;
2106 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2109 changeable_values = (pc == 1);
2110 all_pages = (page_code == 0x3f);
2112 /* Write the mode parameter header. Fixed values are: default
2113 * medium type, no cache control (DPOFUA), and no block descriptors.
2114 * The only variable value is the WriteProtect bit. We will fill in
2115 * the mode data length later. */
2117 if (mscmnd == SC_MODE_SENSE_6) {
2118 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2121 } else { // SC_MODE_SENSE_10
2122 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2124 limit = 65535; // Should really be mod_data.buflen
2127 /* No block descriptors */
2129 /* The mode pages, in numerical order. The only page we support
2130 * is the Caching page. */
2131 if (page_code == 0x08 || all_pages) {
2133 buf[0] = 0x08; // Page code
2134 buf[1] = 10; // Page length
2135 memset(buf+2, 0, 10); // None of the fields are changeable
2137 if (!changeable_values) {
2138 buf[2] = 0x04; // Write cache enable,
2139 // Read cache not disabled
2140 // No cache retention priorities
2141 put_be16(&buf[4], 0xffff); // Don't disable prefetch
2142 // Minimum prefetch = 0
2143 put_be16(&buf[8], 0xffff); // Maximum prefetch
2144 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2149 /* Check that a valid page was requested and the mode data length
2150 * isn't too long. */
2152 if (!valid_page || len > limit) {
2153 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2157 /* Store the mode data length */
2158 if (mscmnd == SC_MODE_SENSE_6)
2161 put_be16(buf0, len - 2);
2166 static int do_start_stop(struct fsg_dev *fsg)
2168 struct lun *curlun = fsg->curlun;
2171 if (!mod_data.removable) {
2172 curlun->sense_data = SS_INVALID_COMMAND;
2176 // int immed = fsg->cmnd[1] & 0x01;
2177 loej = fsg->cmnd[4] & 0x02;
2178 start = fsg->cmnd[4] & 0x01;
2180 #ifdef CONFIG_USB_FILE_STORAGE_TEST
2181 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
2182 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
2183 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2189 /* Are we allowed to unload the media? */
2190 if (curlun->prevent_medium_removal) {
2191 LDBG(curlun, "unload attempt prevented\n");
2192 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2195 if (loej) { // Simulate an unload/eject
2196 up_read(&fsg->filesem);
2197 down_write(&fsg->filesem);
2198 close_backing_file(curlun);
2199 up_write(&fsg->filesem);
2200 down_read(&fsg->filesem);
2204 /* Our emulation doesn't support mounting; the medium is
2205 * available for use as soon as it is loaded. */
2206 if (!backing_file_is_open(curlun)) {
2207 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2216 static int do_prevent_allow(struct fsg_dev *fsg)
2218 struct lun *curlun = fsg->curlun;
2221 if (!mod_data.removable) {
2222 curlun->sense_data = SS_INVALID_COMMAND;
2226 prevent = fsg->cmnd[4] & 0x01;
2227 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
2228 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2232 if (curlun->prevent_medium_removal && !prevent)
2234 curlun->prevent_medium_removal = prevent;
2239 static int do_read_format_capacities(struct fsg_dev *fsg,
2240 struct fsg_buffhd *bh)
2242 struct lun *curlun = fsg->curlun;
2243 u8 *buf = (u8 *) bh->buf;
2245 buf[0] = buf[1] = buf[2] = 0;
2246 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
2249 put_be32(&buf[0], curlun->num_sectors); // Number of blocks
2250 put_be32(&buf[4], 512); // Block length
2251 buf[4] = 0x02; // Current capacity
2256 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2258 struct lun *curlun = fsg->curlun;
2260 /* We don't support MODE SELECT */
2261 curlun->sense_data = SS_INVALID_COMMAND;
2266 /*-------------------------------------------------------------------------*/
2268 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2272 rc = fsg_set_halt(fsg, fsg->bulk_in);
2274 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2276 if (rc != -EAGAIN) {
2277 WARN(fsg, "usb_ep_set_halt -> %d\n", rc);
2282 /* Wait for a short time and then try again */
2283 set_current_state(TASK_INTERRUPTIBLE);
2284 if (schedule_timeout(HZ / 10) != 0)
2286 rc = usb_ep_set_halt(fsg->bulk_in);
2291 static int pad_with_zeros(struct fsg_dev *fsg)
2293 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2294 u32 nkeep = bh->inreq->length;
2298 bh->state = BUF_STATE_EMPTY; // For the first iteration
2299 fsg->usb_amount_left = nkeep + fsg->residue;
2300 while (fsg->usb_amount_left > 0) {
2302 /* Wait for the next buffer to be free */
2303 while (bh->state != BUF_STATE_EMPTY) {
2304 if ((rc = sleep_thread(fsg)) != 0)
2308 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2309 memset(bh->buf + nkeep, 0, nsend - nkeep);
2310 bh->inreq->length = nsend;
2311 bh->inreq->zero = 0;
2312 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2313 &bh->inreq_busy, &bh->state);
2314 bh = fsg->next_buffhd_to_fill = bh->next;
2315 fsg->usb_amount_left -= nsend;
2321 static int throw_away_data(struct fsg_dev *fsg)
2323 struct fsg_buffhd *bh;
2327 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2328 fsg->usb_amount_left > 0) {
2330 /* Throw away the data in a filled buffer */
2331 if (bh->state == BUF_STATE_FULL) {
2332 bh->state = BUF_STATE_EMPTY;
2333 fsg->next_buffhd_to_drain = bh->next;
2335 /* A short packet or an error ends everything */
2336 if (bh->outreq->actual != bh->outreq->length ||
2337 bh->outreq->status != 0) {
2338 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2344 /* Try to submit another request if we need one */
2345 bh = fsg->next_buffhd_to_fill;
2346 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2347 amount = min(fsg->usb_amount_left,
2348 (u32) mod_data.buflen);
2350 /* amount is always divisible by 512, hence by
2351 * the bulk-out maxpacket size */
2352 bh->outreq->length = bh->bulk_out_intended_length =
2354 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2355 &bh->outreq_busy, &bh->state);
2356 fsg->next_buffhd_to_fill = bh->next;
2357 fsg->usb_amount_left -= amount;
2361 /* Otherwise wait for something to happen */
2362 if ((rc = sleep_thread(fsg)) != 0)
2369 static int finish_reply(struct fsg_dev *fsg)
2371 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2374 switch (fsg->data_dir) {
2376 break; // Nothing to send
2378 /* If we don't know whether the host wants to read or write,
2379 * this must be CB or CBI with an unknown command. We mustn't
2380 * try to send or receive any data. So stall both bulk pipes
2381 * if we can and wait for a reset. */
2382 case DATA_DIR_UNKNOWN:
2383 if (mod_data.can_stall) {
2384 fsg_set_halt(fsg, fsg->bulk_out);
2385 rc = halt_bulk_in_endpoint(fsg);
2389 /* All but the last buffer of data must have already been sent */
2390 case DATA_DIR_TO_HOST:
2391 if (fsg->data_size == 0)
2392 ; // Nothing to send
2394 /* If there's no residue, simply send the last buffer */
2395 else if (fsg->residue == 0) {
2396 bh->inreq->zero = 0;
2397 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2398 &bh->inreq_busy, &bh->state);
2399 fsg->next_buffhd_to_fill = bh->next;
2402 /* There is a residue. For CB and CBI, simply mark the end
2403 * of the data with a short packet. However, if we are
2404 * allowed to stall, there was no data at all (residue ==
2405 * data_size), and the command failed (invalid LUN or
2406 * sense data is set), then halt the bulk-in endpoint
2408 else if (!transport_is_bbb()) {
2409 if (mod_data.can_stall &&
2410 fsg->residue == fsg->data_size &&
2411 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2412 bh->state = BUF_STATE_EMPTY;
2413 rc = halt_bulk_in_endpoint(fsg);
2415 bh->inreq->zero = 1;
2416 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2417 &bh->inreq_busy, &bh->state);
2418 fsg->next_buffhd_to_fill = bh->next;
2422 /* For Bulk-only, if we're allowed to stall then send the
2423 * short packet and halt the bulk-in endpoint. If we can't
2424 * stall, pad out the remaining data with 0's. */
2426 if (mod_data.can_stall) {
2427 bh->inreq->zero = 1;
2428 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2429 &bh->inreq_busy, &bh->state);
2430 fsg->next_buffhd_to_fill = bh->next;
2431 rc = halt_bulk_in_endpoint(fsg);
2433 rc = pad_with_zeros(fsg);
2437 /* We have processed all we want from the data the host has sent.
2438 * There may still be outstanding bulk-out requests. */
2439 case DATA_DIR_FROM_HOST:
2440 if (fsg->residue == 0)
2441 ; // Nothing to receive
2443 /* Did the host stop sending unexpectedly early? */
2444 else if (fsg->short_packet_received) {
2445 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2449 /* We haven't processed all the incoming data. Even though
2450 * we may be allowed to stall, doing so would cause a race.
2451 * The controller may already have ACK'ed all the remaining
2452 * bulk-out packets, in which case the host wouldn't see a
2453 * STALL. Not realizing the endpoint was halted, it wouldn't
2454 * clear the halt -- leading to problems later on. */
2456 else if (mod_data.can_stall) {
2457 fsg_set_halt(fsg, fsg->bulk_out);
2458 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2463 /* We can't stall. Read in the excess data and throw it
2466 rc = throw_away_data(fsg);
2473 static int send_status(struct fsg_dev *fsg)
2475 struct lun *curlun = fsg->curlun;
2476 struct fsg_buffhd *bh;
2478 u8 status = USB_STATUS_PASS;
2481 /* Wait for the next buffer to become available */
2482 bh = fsg->next_buffhd_to_fill;
2483 while (bh->state != BUF_STATE_EMPTY) {
2484 if ((rc = sleep_thread(fsg)) != 0)
2489 sd = curlun->sense_data;
2490 sdinfo = curlun->sense_data_info;
2491 } else if (fsg->bad_lun_okay)
2494 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2496 if (fsg->phase_error) {
2497 DBG(fsg, "sending phase-error status\n");
2498 status = USB_STATUS_PHASE_ERROR;
2499 sd = SS_INVALID_COMMAND;
2500 } else if (sd != SS_NO_SENSE) {
2501 DBG(fsg, "sending command-failure status\n");
2502 status = USB_STATUS_FAIL;
2503 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2505 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2508 if (transport_is_bbb()) {
2509 struct bulk_cs_wrap *csw = (struct bulk_cs_wrap *) bh->buf;
2511 /* Store and send the Bulk-only CSW */
2512 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
2513 csw->Tag = fsg->tag;
2514 csw->Residue = cpu_to_le32(fsg->residue);
2515 csw->Status = status;
2517 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2518 bh->inreq->zero = 0;
2519 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2520 &bh->inreq_busy, &bh->state);
2522 } else if (mod_data.transport_type == USB_PR_CB) {
2524 /* Control-Bulk transport has no status phase! */
2527 } else { // USB_PR_CBI
2528 struct interrupt_data *buf = (struct interrupt_data *)
2531 /* Store and send the Interrupt data. UFI sends the ASC
2532 * and ASCQ bytes. Everything else sends a Type (which
2533 * is always 0) and the status Value. */
2534 if (mod_data.protocol_type == USB_SC_UFI) {
2535 buf->bType = ASC(sd);
2536 buf->bValue = ASCQ(sd);
2539 buf->bValue = status;
2541 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2543 fsg->intr_buffhd = bh; // Point to the right buffhd
2544 fsg->intreq->buf = bh->inreq->buf;
2545 fsg->intreq->dma = bh->inreq->dma;
2546 fsg->intreq->context = bh;
2547 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2548 &fsg->intreq_busy, &bh->state);
2551 fsg->next_buffhd_to_fill = bh->next;
2556 /*-------------------------------------------------------------------------*/
2558 /* Check whether the command is properly formed and whether its data size
2559 * and direction agree with the values we already have. */
2560 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2561 enum data_direction data_dir, unsigned int mask,
2562 int needs_medium, const char *name)
2565 int lun = fsg->cmnd[1] >> 5;
2566 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2570 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2571 * Transparent SCSI doesn't pad. */
2572 if (protocol_is_scsi())
2575 /* There's some disagreement as to whether RBC pads commands or not.
2576 * We'll play it safe and accept either form. */
2577 else if (mod_data.protocol_type == USB_SC_RBC) {
2578 if (fsg->cmnd_size == 12)
2581 /* All the other protocols pad to 12 bytes */
2586 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2587 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2589 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2590 name, cmnd_size, dirletter[(int) data_dir],
2591 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2593 /* We can't reply at all until we know the correct data direction
2595 if (fsg->data_size_from_cmnd == 0)
2596 data_dir = DATA_DIR_NONE;
2597 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2598 fsg->data_dir = data_dir;
2599 fsg->data_size = fsg->data_size_from_cmnd;
2601 } else { // Bulk-only
2602 if (fsg->data_size < fsg->data_size_from_cmnd) {
2604 /* Host data size < Device data size is a phase error.
2605 * Carry out the command, but only transfer as much
2606 * as we are allowed. */
2607 fsg->data_size_from_cmnd = fsg->data_size;
2608 fsg->phase_error = 1;
2611 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2613 /* Conflicting data directions is a phase error */
2614 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2615 fsg->phase_error = 1;
2619 /* Verify the length of the command itself */
2620 if (cmnd_size != fsg->cmnd_size) {
2622 /* Special case workaround: MS-Windows issues REQUEST SENSE
2623 * with cbw->Length == 12 (it should be 6). */
2624 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
2625 cmnd_size = fsg->cmnd_size;
2627 fsg->phase_error = 1;
2632 /* Check that the LUN values are oonsistent */
2633 if (transport_is_bbb()) {
2634 if (fsg->lun != lun)
2635 DBG(fsg, "using LUN %d from CBW, "
2636 "not LUN %d from CDB\n",
2639 fsg->lun = lun; // Use LUN from the command
2642 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2643 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2644 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2645 curlun->sense_data = SS_NO_SENSE;
2646 curlun->sense_data_info = 0;
2649 fsg->curlun = curlun = NULL;
2650 fsg->bad_lun_okay = 0;
2652 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2653 * to use unsupported LUNs; all others may not. */
2654 if (fsg->cmnd[0] != SC_INQUIRY &&
2655 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2656 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2661 /* If a unit attention condition exists, only INQUIRY and
2662 * REQUEST SENSE commands are allowed; anything else must fail. */
2663 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2664 fsg->cmnd[0] != SC_INQUIRY &&
2665 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2666 curlun->sense_data = curlun->unit_attention_data;
2667 curlun->unit_attention_data = SS_NO_SENSE;
2671 /* Check that only command bytes listed in the mask are non-zero */
2672 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2673 for (i = 1; i < cmnd_size; ++i) {
2674 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2676 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2681 /* If the medium isn't mounted and the command needs to access
2682 * it, return an error. */
2683 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2684 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2692 static int do_scsi_command(struct fsg_dev *fsg)
2694 struct fsg_buffhd *bh;
2696 int reply = -EINVAL;
2698 static char unknown[16];
2702 /* Wait for the next buffer to become available for data or status */
2703 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2704 while (bh->state != BUF_STATE_EMPTY) {
2705 if ((rc = sleep_thread(fsg)) != 0)
2708 fsg->phase_error = 0;
2709 fsg->short_packet_received = 0;
2711 down_read(&fsg->filesem); // We're using the backing file
2712 switch (fsg->cmnd[0]) {
2715 fsg->data_size_from_cmnd = fsg->cmnd[4];
2716 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2719 reply = do_inquiry(fsg, bh);
2722 case SC_MODE_SELECT_6:
2723 fsg->data_size_from_cmnd = fsg->cmnd[4];
2724 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2726 "MODE SELECT(6)")) == 0)
2727 reply = do_mode_select(fsg, bh);
2730 case SC_MODE_SELECT_10:
2731 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2732 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2734 "MODE SELECT(10)")) == 0)
2735 reply = do_mode_select(fsg, bh);
2738 case SC_MODE_SENSE_6:
2739 fsg->data_size_from_cmnd = fsg->cmnd[4];
2740 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2741 (1<<1) | (1<<2) | (1<<4), 0,
2742 "MODE SENSE(6)")) == 0)
2743 reply = do_mode_sense(fsg, bh);
2746 case SC_MODE_SENSE_10:
2747 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2748 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2749 (1<<1) | (1<<2) | (3<<7), 0,
2750 "MODE SENSE(10)")) == 0)
2751 reply = do_mode_sense(fsg, bh);
2754 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2755 fsg->data_size_from_cmnd = 0;
2756 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2758 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2759 reply = do_prevent_allow(fsg);
2764 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2765 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2768 reply = do_read(fsg);
2772 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2773 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2774 (1<<1) | (0xf<<2) | (3<<7), 1,
2776 reply = do_read(fsg);
2780 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2781 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2782 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2784 reply = do_read(fsg);
2787 case SC_READ_CAPACITY:
2788 fsg->data_size_from_cmnd = 8;
2789 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2790 (0xf<<2) | (1<<8), 1,
2791 "READ CAPACITY")) == 0)
2792 reply = do_read_capacity(fsg, bh);
2795 case SC_READ_FORMAT_CAPACITIES:
2796 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2797 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2799 "READ FORMAT CAPACITIES")) == 0)
2800 reply = do_read_format_capacities(fsg, bh);
2803 case SC_REQUEST_SENSE:
2804 fsg->data_size_from_cmnd = fsg->cmnd[4];
2805 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2807 "REQUEST SENSE")) == 0)
2808 reply = do_request_sense(fsg, bh);
2811 case SC_START_STOP_UNIT:
2812 fsg->data_size_from_cmnd = 0;
2813 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2815 "START-STOP UNIT")) == 0)
2816 reply = do_start_stop(fsg);
2819 case SC_SYNCHRONIZE_CACHE:
2820 fsg->data_size_from_cmnd = 0;
2821 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2822 (0xf<<2) | (3<<7), 1,
2823 "SYNCHRONIZE CACHE")) == 0)
2824 reply = do_synchronize_cache(fsg);
2827 case SC_TEST_UNIT_READY:
2828 fsg->data_size_from_cmnd = 0;
2829 reply = check_command(fsg, 6, DATA_DIR_NONE,
2834 /* Although optional, this command is used by MS-Windows. We
2835 * support a minimal version: BytChk must be 0. */
2837 fsg->data_size_from_cmnd = 0;
2838 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2839 (1<<1) | (0xf<<2) | (3<<7), 1,
2841 reply = do_verify(fsg);
2846 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2847 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2850 reply = do_write(fsg);
2854 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2855 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2856 (1<<1) | (0xf<<2) | (3<<7), 1,
2858 reply = do_write(fsg);
2862 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2863 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2864 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2866 reply = do_write(fsg);
2869 /* Some mandatory commands that we recognize but don't implement.
2870 * They don't mean much in this setting. It's left as an exercise
2871 * for anyone interested to implement RESERVE and RELEASE in terms
2872 * of Posix locks. */
2873 case SC_FORMAT_UNIT:
2876 case SC_SEND_DIAGNOSTIC:
2880 fsg->data_size_from_cmnd = 0;
2881 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2882 if ((reply = check_command(fsg, fsg->cmnd_size,
2883 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2884 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2889 up_read(&fsg->filesem);
2891 if (reply == -EINTR || signal_pending(current))
2894 /* Set up the single reply buffer for finish_reply() */
2895 if (reply == -EINVAL)
2896 reply = 0; // Error reply length
2897 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2898 reply = min((u32) reply, fsg->data_size_from_cmnd);
2899 bh->inreq->length = reply;
2900 bh->state = BUF_STATE_FULL;
2901 fsg->residue -= reply;
2902 } // Otherwise it's already set
2908 /*-------------------------------------------------------------------------*/
2910 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2912 struct usb_request *req = bh->outreq;
2913 struct bulk_cb_wrap *cbw = (struct bulk_cb_wrap *) req->buf;
2915 /* Was this a real packet? */
2919 /* Is the CBW valid? */
2920 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2921 cbw->Signature != __constant_cpu_to_le32(
2923 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2925 le32_to_cpu(cbw->Signature));
2927 /* The Bulk-only spec says we MUST stall the bulk pipes!
2928 * If we want to avoid stalls, set a flag so that we will
2929 * clear the endpoint halts at the next reset. */
2930 if (!mod_data.can_stall)
2931 set_bit(CLEAR_BULK_HALTS, &fsg->atomic_bitflags);
2932 fsg_set_halt(fsg, fsg->bulk_out);
2933 halt_bulk_in_endpoint(fsg);
2937 /* Is the CBW meaningful? */
2938 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2939 cbw->Length < 6 || cbw->Length > MAX_COMMAND_SIZE) {
2940 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2942 cbw->Lun, cbw->Flags, cbw->Length);
2944 /* We can do anything we want here, so let's stall the
2945 * bulk pipes if we are allowed to. */
2946 if (mod_data.can_stall) {
2947 fsg_set_halt(fsg, fsg->bulk_out);
2948 halt_bulk_in_endpoint(fsg);
2953 /* Save the command for later */
2954 fsg->cmnd_size = cbw->Length;
2955 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2956 if (cbw->Flags & USB_BULK_IN_FLAG)
2957 fsg->data_dir = DATA_DIR_TO_HOST;
2959 fsg->data_dir = DATA_DIR_FROM_HOST;
2960 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2961 if (fsg->data_size == 0)
2962 fsg->data_dir = DATA_DIR_NONE;
2963 fsg->lun = cbw->Lun;
2964 fsg->tag = cbw->Tag;
2969 static int get_next_command(struct fsg_dev *fsg)
2971 struct fsg_buffhd *bh;
2974 if (transport_is_bbb()) {
2976 /* Wait for the next buffer to become available */
2977 bh = fsg->next_buffhd_to_fill;
2978 while (bh->state != BUF_STATE_EMPTY) {
2979 if ((rc = sleep_thread(fsg)) != 0)
2983 /* Queue a request to read a Bulk-only CBW */
2984 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2985 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2986 &bh->outreq_busy, &bh->state);
2988 /* We will drain the buffer in software, which means we
2989 * can reuse it for the next filling. No need to advance
2990 * next_buffhd_to_fill. */
2992 /* Wait for the CBW to arrive */
2993 while (bh->state != BUF_STATE_FULL) {
2994 if ((rc = sleep_thread(fsg)) != 0)
2997 rc = received_cbw(fsg, bh);
2998 bh->state = BUF_STATE_EMPTY;
3000 } else { // USB_PR_CB or USB_PR_CBI
3002 /* Wait for the next command to arrive */
3003 while (fsg->cbbuf_cmnd_size == 0) {
3004 if ((rc = sleep_thread(fsg)) != 0)
3008 /* Is the previous status interrupt request still busy?
3009 * The host is allowed to skip reading the status,
3010 * so we must cancel it. */
3011 if (fsg->intreq_busy)
3012 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3014 /* Copy the command and mark the buffer empty */
3015 fsg->data_dir = DATA_DIR_UNKNOWN;
3016 spin_lock_irq(&fsg->lock);
3017 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3018 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3019 fsg->cbbuf_cmnd_size = 0;
3020 spin_unlock_irq(&fsg->lock);
3026 /*-------------------------------------------------------------------------*/
3028 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3029 const struct usb_endpoint_descriptor *d)
3033 ep->driver_data = fsg;
3034 rc = usb_ep_enable(ep, d);
3036 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3040 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3041 struct usb_request **preq)
3043 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3046 ERROR(fsg, "can't allocate request for %s\n", ep->name);
3051 * Reset interface setting and re-init endpoint state (toggle etc).
3052 * Call with altsetting < 0 to disable the interface. The only other
3053 * available altsetting is 0, which enables the interface.
3055 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3059 const struct usb_endpoint_descriptor *d;
3062 DBG(fsg, "reset interface\n");
3065 /* Deallocate the requests */
3066 for (i = 0; i < NUM_BUFFERS; ++i) {
3067 struct fsg_buffhd *bh = &fsg->buffhds[i];
3070 usb_ep_free_request(fsg->bulk_in, bh->inreq);
3074 usb_ep_free_request(fsg->bulk_out, bh->outreq);
3079 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3083 /* Disable the endpoints */
3084 if (fsg->bulk_in_enabled) {
3085 usb_ep_disable(fsg->bulk_in);
3086 fsg->bulk_in_enabled = 0;
3088 if (fsg->bulk_out_enabled) {
3089 usb_ep_disable(fsg->bulk_out);
3090 fsg->bulk_out_enabled = 0;
3092 if (fsg->intr_in_enabled) {
3093 usb_ep_disable(fsg->intr_in);
3094 fsg->intr_in_enabled = 0;
3098 if (altsetting < 0 || rc != 0)
3101 DBG(fsg, "set interface %d\n", altsetting);
3103 /* Enable the endpoints */
3104 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3105 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3107 fsg->bulk_in_enabled = 1;
3109 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3110 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3112 fsg->bulk_out_enabled = 1;
3113 fsg->bulk_out_maxpacket = d->wMaxPacketSize;
3115 if (transport_is_cbi()) {
3116 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3117 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3119 fsg->intr_in_enabled = 1;
3122 /* Allocate the requests */
3123 for (i = 0; i < NUM_BUFFERS; ++i) {
3124 struct fsg_buffhd *bh = &fsg->buffhds[i];
3126 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3128 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3130 bh->inreq->buf = bh->outreq->buf = bh->buf;
3131 bh->inreq->dma = bh->outreq->dma = bh->dma;
3132 bh->inreq->context = bh->outreq->context = bh;
3133 bh->inreq->complete = bulk_in_complete;
3134 bh->outreq->complete = bulk_out_complete;
3136 if (transport_is_cbi()) {
3137 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3139 fsg->intreq->complete = intr_in_complete;
3143 for (i = 0; i < fsg->nluns; ++i)
3144 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3150 * Change our operational configuration. This code must agree with the code
3151 * that returns config descriptors, and with interface altsetting code.
3153 * It's also responsible for power management interactions. Some
3154 * configurations might not work with our current power sources.
3155 * For now we just assume the gadget is always self-powered.
3157 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3161 /* Disable the single interface */
3162 if (fsg->config != 0) {
3163 DBG(fsg, "reset config\n");
3165 rc = do_set_interface(fsg, -1);
3168 /* Enable the interface */
3169 if (new_config != 0) {
3170 fsg->config = new_config;
3171 if ((rc = do_set_interface(fsg, 0)) != 0)
3172 fsg->config = 0; // Reset on errors
3176 switch (fsg->gadget->speed) {
3177 case USB_SPEED_LOW: speed = "low"; break;
3178 case USB_SPEED_FULL: speed = "full"; break;
3179 case USB_SPEED_HIGH: speed = "high"; break;
3180 default: speed = "?"; break;
3182 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3189 /*-------------------------------------------------------------------------*/
3191 static void handle_exception(struct fsg_dev *fsg)
3197 struct fsg_buffhd *bh;
3198 enum fsg_state old_state;
3201 unsigned int exception_req_tag;
3204 /* Clear the existing signals. Anything but SIGUSR1 is converted
3205 * into a high-priority EXIT exception. */
3207 sig = dequeue_signal_lock(current, &fsg->thread_signal_mask,
3211 if (sig != SIGUSR1) {
3212 if (fsg->state < FSG_STATE_EXIT)
3213 DBG(fsg, "Main thread exiting on signal\n");
3214 raise_exception(fsg, FSG_STATE_EXIT);
3218 /* Cancel all the pending transfers */
3219 if (fsg->intreq_busy)
3220 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3221 for (i = 0; i < NUM_BUFFERS; ++i) {
3222 bh = &fsg->buffhds[i];
3224 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3225 if (bh->outreq_busy)
3226 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3229 /* Wait until everything is idle */
3231 num_active = fsg->intreq_busy;
3232 for (i = 0; i < NUM_BUFFERS; ++i) {
3233 bh = &fsg->buffhds[i];
3234 num_active += bh->inreq_busy + bh->outreq_busy;
3236 if (num_active == 0)
3238 if (sleep_thread(fsg))
3242 /* Clear out the controller's fifos */
3243 if (fsg->bulk_in_enabled)
3244 usb_ep_fifo_flush(fsg->bulk_in);
3245 if (fsg->bulk_out_enabled)
3246 usb_ep_fifo_flush(fsg->bulk_out);
3247 if (fsg->intr_in_enabled)
3248 usb_ep_fifo_flush(fsg->intr_in);
3250 /* Reset the I/O buffer states and pointers, the SCSI
3251 * state, and the exception. Then invoke the handler. */
3252 spin_lock_irq(&fsg->lock);
3254 for (i = 0; i < NUM_BUFFERS; ++i) {
3255 bh = &fsg->buffhds[i];
3256 bh->state = BUF_STATE_EMPTY;
3258 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3261 exception_req_tag = fsg->exception_req_tag;
3262 new_config = fsg->new_config;
3263 old_state = fsg->state;
3265 if (old_state == FSG_STATE_ABORT_BULK_OUT)
3266 fsg->state = FSG_STATE_STATUS_PHASE;
3268 for (i = 0; i < fsg->nluns; ++i) {
3269 curlun = &fsg->luns[i];
3270 curlun->prevent_medium_removal = 0;
3271 curlun->sense_data = curlun->unit_attention_data =
3273 curlun->sense_data_info = 0;
3275 fsg->state = FSG_STATE_IDLE;
3277 spin_unlock_irq(&fsg->lock);
3279 /* Carry out any extra actions required for the exception */
3280 switch (old_state) {
3284 case FSG_STATE_ABORT_BULK_OUT:
3286 spin_lock_irq(&fsg->lock);
3287 if (fsg->state == FSG_STATE_STATUS_PHASE)
3288 fsg->state = FSG_STATE_IDLE;
3289 spin_unlock_irq(&fsg->lock);
3292 case FSG_STATE_RESET:
3293 /* In case we were forced against our will to halt a
3294 * bulk endpoint, clear the halt now. (The SuperH UDC
3295 * requires this.) */
3296 if (test_and_clear_bit(CLEAR_BULK_HALTS,
3297 &fsg->atomic_bitflags)) {
3298 usb_ep_clear_halt(fsg->bulk_in);
3299 usb_ep_clear_halt(fsg->bulk_out);
3302 if (transport_is_bbb()) {
3303 if (fsg->ep0_req_tag == exception_req_tag)
3304 ep0_queue(fsg); // Complete the status stage
3306 } else if (transport_is_cbi())
3307 send_status(fsg); // Status by interrupt pipe
3309 /* Technically this should go here, but it would only be
3310 * a waste of time. Ditto for the INTERFACE_CHANGE and
3311 * CONFIG_CHANGE cases. */
3312 // for (i = 0; i < fsg->nluns; ++i)
3313 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3316 case FSG_STATE_INTERFACE_CHANGE:
3317 rc = do_set_interface(fsg, 0);
3318 if (fsg->ep0_req_tag != exception_req_tag)
3320 if (rc != 0) // STALL on errors
3321 fsg_set_halt(fsg, fsg->ep0);
3322 else // Complete the status stage
3326 case FSG_STATE_CONFIG_CHANGE:
3327 rc = do_set_config(fsg, new_config);
3328 if (fsg->ep0_req_tag != exception_req_tag)
3330 if (rc != 0) // STALL on errors
3331 fsg_set_halt(fsg, fsg->ep0);
3332 else // Complete the status stage
3336 case FSG_STATE_DISCONNECT:
3338 do_set_config(fsg, 0); // Unconfigured state
3341 case FSG_STATE_EXIT:
3342 case FSG_STATE_TERMINATED:
3343 do_set_config(fsg, 0); // Free resources
3344 spin_lock_irq(&fsg->lock);
3345 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3346 spin_unlock_irq(&fsg->lock);
3352 /*-------------------------------------------------------------------------*/
3354 static int fsg_main_thread(void *fsg_)
3356 struct fsg_dev *fsg = (struct fsg_dev *) fsg_;
3358 fsg->thread_task = current;
3360 /* Release all our userspace resources */
3361 daemonize("file-storage-gadget");
3363 /* Allow the thread to be killed by a signal, but set the signal mask
3364 * to block everything but INT, TERM, KILL, and USR1. */
3365 siginitsetinv(&fsg->thread_signal_mask, sigmask(SIGINT) |
3366 sigmask(SIGTERM) | sigmask(SIGKILL) |
3368 sigprocmask(SIG_SETMASK, &fsg->thread_signal_mask, NULL);
3370 /* Arrange for userspace references to be interpreted as kernel
3371 * pointers. That way we can pass a kernel pointer to a routine
3372 * that expects a __user pointer and it will work okay. */
3375 /* Wait for the gadget registration to finish up */
3376 wait_for_completion(&fsg->thread_notifier);
3379 while (fsg->state != FSG_STATE_TERMINATED) {
3380 if (exception_in_progress(fsg) || signal_pending(current)) {
3381 handle_exception(fsg);
3385 if (!fsg->running) {
3390 if (get_next_command(fsg))
3393 spin_lock_irq(&fsg->lock);
3394 if (!exception_in_progress(fsg))
3395 fsg->state = FSG_STATE_DATA_PHASE;
3396 spin_unlock_irq(&fsg->lock);
3398 if (do_scsi_command(fsg) || finish_reply(fsg))
3401 spin_lock_irq(&fsg->lock);
3402 if (!exception_in_progress(fsg))
3403 fsg->state = FSG_STATE_STATUS_PHASE;
3404 spin_unlock_irq(&fsg->lock);
3406 if (send_status(fsg))
3409 spin_lock_irq(&fsg->lock);
3410 if (!exception_in_progress(fsg))
3411 fsg->state = FSG_STATE_IDLE;
3412 spin_unlock_irq(&fsg->lock);
3415 fsg->thread_task = NULL;
3416 flush_signals(current);
3418 /* In case we are exiting because of a signal, unregister the
3419 * gadget driver and close the backing file. */
3420 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) {
3421 usb_gadget_unregister_driver(&fsg_driver);
3422 close_all_backing_files(fsg);
3425 /* Let the unbind and cleanup routines know the thread has exited */
3426 complete_and_exit(&fsg->thread_notifier, 0);
3430 /*-------------------------------------------------------------------------*/
3432 /* If the next two routines are called while the gadget is registered,
3433 * the caller must own fsg->filesem for writing. */
3435 static int open_backing_file(struct lun *curlun, const char *filename)
3438 struct file *filp = NULL;
3440 struct inode *inode = NULL;
3444 /* R/W if we can, R/O if we must */
3447 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3448 if (-EROFS == PTR_ERR(filp))
3452 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3454 LINFO(curlun, "unable to open backing file: %s\n", filename);
3455 return PTR_ERR(filp);
3458 if (!(filp->f_mode & FMODE_WRITE))
3462 inode = filp->f_dentry->d_inode;
3463 if (inode && S_ISBLK(inode->i_mode)) {
3464 if (bdev_read_only(inode->i_bdev))
3466 } else if (!inode || !S_ISREG(inode->i_mode)) {
3467 LINFO(curlun, "invalid file type: %s\n", filename);
3471 /* If we can't read the file, it's no good.
3472 * If we can't write the file, use it read-only. */
3473 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3474 LINFO(curlun, "file not readable: %s\n", filename);
3477 if (!(filp->f_op->write || filp->f_op->aio_write))
3480 size = i_size_read(inode->i_mapping->host);
3482 LINFO(curlun, "unable to find file size: %s\n", filename);
3486 num_sectors = size >> 9; // File size in 512-byte sectors
3487 if (num_sectors == 0) {
3488 LINFO(curlun, "file too small: %s\n", filename);
3495 curlun->filp = filp;
3496 curlun->file_length = size;
3497 curlun->num_sectors = num_sectors;
3498 LDBG(curlun, "open backing file: %s\n", filename);
3502 filp_close(filp, current->files);
3507 static void close_backing_file(struct lun *curlun)
3510 LDBG(curlun, "close backing file\n");
3512 curlun->filp = NULL;
3516 static void close_all_backing_files(struct fsg_dev *fsg)
3520 for (i = 0; i < fsg->nluns; ++i)
3521 close_backing_file(&fsg->luns[i]);
3525 static ssize_t show_ro(struct device *dev, char *buf)
3527 struct lun *curlun = dev_to_lun(dev);
3529 return sprintf(buf, "%d\n", curlun->ro);
3532 static ssize_t show_file(struct device *dev, char *buf)
3534 struct lun *curlun = dev_to_lun(dev);
3535 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3539 down_read(&fsg->filesem);
3540 if (backing_file_is_open(curlun)) { // Get the complete pathname
3541 p = d_path(curlun->filp->f_dentry, curlun->filp->f_vfsmnt,
3542 buf, PAGE_SIZE - 1);
3547 memmove(buf, p, rc);
3548 buf[rc] = '\n'; // Add a newline
3551 } else { // No file, return 0 bytes
3555 up_read(&fsg->filesem);
3560 ssize_t store_ro(struct device *dev, const char *buf, size_t count)
3563 struct lun *curlun = dev_to_lun(dev);
3564 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3567 if (sscanf(buf, "%d", &i) != 1)
3570 /* Allow the write-enable status to change only while the backing file
3572 down_read(&fsg->filesem);
3573 if (backing_file_is_open(curlun)) {
3574 LDBG(curlun, "read-only status change prevented\n");
3578 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3580 up_read(&fsg->filesem);
3584 ssize_t store_file(struct device *dev, const char *buf, size_t count)
3586 struct lun *curlun = dev_to_lun(dev);
3587 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3590 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3591 LDBG(curlun, "eject attempt prevented\n");
3592 return -EBUSY; // "Door is locked"
3595 /* Remove a trailing newline */
3596 if (count > 0 && buf[count-1] == '\n')
3597 ((char *) buf)[count-1] = 0; // Ugh!
3599 /* Eject current medium */
3600 down_write(&fsg->filesem);
3601 if (backing_file_is_open(curlun)) {
3602 close_backing_file(curlun);
3603 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3606 /* Load new medium */
3607 if (count > 0 && buf[0]) {
3608 rc = open_backing_file(curlun, buf);
3610 curlun->unit_attention_data =
3611 SS_NOT_READY_TO_READY_TRANSITION;
3613 up_write(&fsg->filesem);
3614 return (rc < 0 ? rc : count);
3618 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3619 static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3620 static DEVICE_ATTR(file, 0444, show_file, NULL);
3623 /*-------------------------------------------------------------------------*/
3625 static void lun_release(struct device *dev)
3627 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3629 complete(&fsg->lun_released);
3632 static void fsg_unbind(struct usb_gadget *gadget)
3634 struct fsg_dev *fsg = get_gadget_data(gadget);
3637 struct usb_request *req = fsg->ep0req;
3639 DBG(fsg, "unbind\n");
3640 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3642 /* Unregister the sysfs attribute files and the LUNs */
3643 init_completion(&fsg->lun_released);
3644 for (i = 0; i < fsg->nluns; ++i) {
3645 curlun = &fsg->luns[i];
3646 if (curlun->registered) {
3647 device_remove_file(&curlun->dev, &dev_attr_ro);
3648 device_remove_file(&curlun->dev, &dev_attr_file);
3649 device_unregister(&curlun->dev);
3650 wait_for_completion(&fsg->lun_released);
3651 curlun->registered = 0;
3655 /* If the thread isn't already dead, tell it to exit now */
3656 if (fsg->state != FSG_STATE_TERMINATED) {
3657 raise_exception(fsg, FSG_STATE_EXIT);
3658 wait_for_completion(&fsg->thread_notifier);
3660 /* The cleanup routine waits for this completion also */
3661 complete(&fsg->thread_notifier);
3664 /* Free the data buffers */
3665 for (i = 0; i < NUM_BUFFERS; ++i) {
3666 struct fsg_buffhd *bh = &fsg->buffhds[i];
3669 usb_ep_free_buffer(fsg->bulk_in, bh->buf, bh->dma,
3673 /* Free the request and buffer for endpoint 0 */
3676 usb_ep_free_buffer(fsg->ep0, req->buf,
3677 req->dma, EP0_BUFSIZE);
3678 usb_ep_free_request(fsg->ep0, req);
3681 set_gadget_data(gadget, NULL);
3685 static int __init check_parameters(struct fsg_dev *fsg)
3689 /* Store the default values */
3690 mod_data.transport_type = USB_PR_BULK;
3691 mod_data.transport_name = "Bulk-only";
3692 mod_data.protocol_type = USB_SC_SCSI;
3693 mod_data.protocol_name = "Transparent SCSI";
3695 if (gadget_is_sh(fsg->gadget))
3696 mod_data.can_stall = 0;
3698 if (mod_data.release == 0xffff) { // Parameter wasn't set
3699 if (gadget_is_net2280(fsg->gadget))
3700 mod_data.release = __constant_cpu_to_le16(0x0301);
3701 else if (gadget_is_dummy(fsg->gadget))
3702 mod_data.release = __constant_cpu_to_le16(0x0302);
3703 else if (gadget_is_pxa(fsg->gadget))
3704 mod_data.release = __constant_cpu_to_le16(0x0303);
3705 else if (gadget_is_sh(fsg->gadget))
3706 mod_data.release = __constant_cpu_to_le16(0x0304);
3708 /* The sa1100 controller is not supported */
3710 else if (gadget_is_goku(fsg->gadget))
3711 mod_data.release = __constant_cpu_to_le16(0x0306);
3712 else if (gadget_is_mq11xx(fsg->gadget))
3713 mod_data.release = __constant_cpu_to_le16(0x0307);
3714 else if (gadget_is_omap(fsg->gadget))
3715 mod_data.release = __constant_cpu_to_le16(0x0308);
3716 else if (gadget_is_lh7a40x(gadget))
3717 mod_data.release = __constant_cpu_to_le16 (0x0309);
3719 WARN(fsg, "controller '%s' not recognized\n",
3721 mod_data.release = __constant_cpu_to_le16(0x0399);
3725 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3727 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3728 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3729 ; // Use default setting
3730 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3731 mod_data.transport_type = USB_PR_CB;
3732 mod_data.transport_name = "Control-Bulk";
3733 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3734 mod_data.transport_type = USB_PR_CBI;
3735 mod_data.transport_name = "Control-Bulk-Interrupt";
3737 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3741 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3742 prot == USB_SC_SCSI) {
3743 ; // Use default setting
3744 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3745 prot == USB_SC_RBC) {
3746 mod_data.protocol_type = USB_SC_RBC;
3747 mod_data.protocol_name = "RBC";
3748 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3749 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3750 prot == USB_SC_8020) {
3751 mod_data.protocol_type = USB_SC_8020;
3752 mod_data.protocol_name = "8020i (ATAPI)";
3753 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3754 prot == USB_SC_QIC) {
3755 mod_data.protocol_type = USB_SC_QIC;
3756 mod_data.protocol_name = "QIC-157";
3757 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3758 prot == USB_SC_UFI) {
3759 mod_data.protocol_type = USB_SC_UFI;
3760 mod_data.protocol_name = "UFI";
3761 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3762 prot == USB_SC_8070) {
3763 mod_data.protocol_type = USB_SC_8070;
3764 mod_data.protocol_name = "8070i";
3766 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3770 mod_data.buflen &= PAGE_CACHE_MASK;
3771 if (mod_data.buflen <= 0) {
3772 ERROR(fsg, "invalid buflen\n");
3775 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3781 static int __init fsg_bind(struct usb_gadget *gadget)
3783 struct fsg_dev *fsg = the_fsg;
3788 struct usb_request *req;
3791 fsg->gadget = gadget;
3792 set_gadget_data(gadget, fsg);
3793 fsg->ep0 = gadget->ep0;
3794 fsg->ep0->driver_data = fsg;
3796 if ((rc = check_parameters(fsg)) != 0)
3799 if (mod_data.removable) { // Enable the store_xxx attributes
3800 dev_attr_ro.attr.mode = dev_attr_file.attr.mode = 0644;
3801 dev_attr_ro.store = store_ro;
3802 dev_attr_file.store = store_file;
3805 /* Find out how many LUNs there should be */
3808 i = max(mod_data.num_filenames, 1);
3810 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3815 /* Create the LUNs, open their backing files, and register the
3816 * LUN devices in sysfs. */
3817 fsg->luns = kmalloc(i * sizeof(struct lun), GFP_KERNEL);
3822 memset(fsg->luns, 0, i * sizeof(struct lun));
3825 for (i = 0; i < fsg->nluns; ++i) {
3826 curlun = &fsg->luns[i];
3828 curlun->dev.parent = &gadget->dev;
3829 curlun->dev.driver = &fsg_driver.driver;
3830 dev_set_drvdata(&curlun->dev, fsg);
3831 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
3832 "%s-lun%d", gadget->dev.bus_id, i);
3834 if ((rc = device_register(&curlun->dev)) != 0)
3835 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
3837 curlun->registered = 1;
3838 curlun->dev.release = lun_release;
3839 device_create_file(&curlun->dev, &dev_attr_ro);
3840 device_create_file(&curlun->dev, &dev_attr_file);
3843 if (file[i] && *file[i]) {
3844 if ((rc = open_backing_file(curlun, file[i])) != 0)
3846 } else if (!mod_data.removable) {
3847 ERROR(fsg, "no file given for LUN%d\n", i);
3853 /* Find all the endpoints we will use */
3854 usb_ep_autoconfig_reset(gadget);
3855 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
3858 ep->driver_data = fsg; // claim the endpoint
3861 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
3864 ep->driver_data = fsg; // claim the endpoint
3867 if (transport_is_cbi()) {
3868 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
3871 ep->driver_data = fsg; // claim the endpoint
3875 /* Fix up the descriptors */
3876 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3877 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3878 device_desc.idProduct = cpu_to_le16(mod_data.product);
3879 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3881 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
3882 intf_desc.bNumEndpoints = i;
3883 intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3884 intf_desc.bInterfaceProtocol = mod_data.transport_type;
3885 fs_function[i+1] = NULL;
3887 #ifdef CONFIG_USB_GADGET_DUALSPEED
3888 hs_function[i+1] = NULL;
3890 /* Assume ep0 uses the same maxpacket value for both speeds */
3891 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3893 /* Assume that all endpoint addresses are the same for both speeds */
3894 hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress;
3895 hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress;
3896 hs_intr_in_desc.bEndpointAddress = fs_intr_in_desc.bEndpointAddress;
3901 /* Allocate the request and buffer for endpoint 0 */
3902 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3905 req->buf = usb_ep_alloc_buffer(fsg->ep0, EP0_BUFSIZE,
3906 &req->dma, GFP_KERNEL);
3909 req->complete = ep0_complete;
3911 /* Allocate the data buffers */
3912 for (i = 0; i < NUM_BUFFERS; ++i) {
3913 struct fsg_buffhd *bh = &fsg->buffhds[i];
3915 bh->buf = usb_ep_alloc_buffer(fsg->bulk_in, mod_data.buflen,
3916 &bh->dma, GFP_KERNEL);
3921 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3923 /* This should reflect the actual gadget power source */
3924 usb_gadget_set_selfpowered(gadget);
3926 snprintf(manufacturer, sizeof manufacturer,
3927 UTS_SYSNAME " " UTS_RELEASE " with %s",
3930 /* On a real device, serial[] would be loaded from permanent
3931 * storage. We just encode it from the driver version string. */
3932 for (i = 0; i < sizeof(serial) - 2; i += 2) {
3933 unsigned char c = DRIVER_VERSION[i / 2];
3937 sprintf(&serial[i], "%02X", c);
3940 if ((rc = kernel_thread(fsg_main_thread, fsg, (CLONE_VM | CLONE_FS |
3943 fsg->thread_pid = rc;
3945 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3946 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3948 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3949 for (i = 0; i < fsg->nluns; ++i) {
3950 curlun = &fsg->luns[i];
3951 if (backing_file_is_open(curlun)) {
3954 p = d_path(curlun->filp->f_dentry,
3955 curlun->filp->f_vfsmnt,
3960 LINFO(curlun, "ro=%d, file: %s\n",
3961 curlun->ro, (p ? p : "(error)"));
3966 DBG(fsg, "transport=%s (x%02x)\n",
3967 mod_data.transport_name, mod_data.transport_type);
3968 DBG(fsg, "protocol=%s (x%02x)\n",
3969 mod_data.protocol_name, mod_data.protocol_type);
3970 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3971 mod_data.vendor, mod_data.product, mod_data.release);
3972 DBG(fsg, "removable=%d, stall=%d, buflen=%u\n",
3973 mod_data.removable, mod_data.can_stall,
3975 DBG(fsg, "I/O thread pid: %d\n", fsg->thread_pid);
3979 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3983 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3985 close_all_backing_files(fsg);
3990 /*-------------------------------------------------------------------------*/
3992 static void fsg_suspend(struct usb_gadget *gadget)
3994 struct fsg_dev *fsg = get_gadget_data(gadget);
3996 DBG(fsg, "suspend\n");
3997 set_bit(SUSPENDED, &fsg->atomic_bitflags);
4000 static void fsg_resume(struct usb_gadget *gadget)
4002 struct fsg_dev *fsg = get_gadget_data(gadget);
4004 DBG(fsg, "resume\n");
4005 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
4009 /*-------------------------------------------------------------------------*/
4011 static struct usb_gadget_driver fsg_driver = {
4012 #ifdef CONFIG_USB_GADGET_DUALSPEED
4013 .speed = USB_SPEED_HIGH,
4015 .speed = USB_SPEED_FULL,
4017 .function = (char *) longname,
4019 .unbind = fsg_unbind,
4020 .disconnect = fsg_disconnect,
4022 .suspend = fsg_suspend,
4023 .resume = fsg_resume,
4026 .name = (char *) shortname,
4034 static int __init fsg_alloc(void)
4036 struct fsg_dev *fsg;
4038 fsg = kmalloc(sizeof *fsg, GFP_KERNEL);
4041 memset(fsg, 0, sizeof *fsg);
4042 spin_lock_init(&fsg->lock);
4043 init_rwsem(&fsg->filesem);
4044 init_waitqueue_head(&fsg->thread_wqh);
4045 init_completion(&fsg->thread_notifier);
4052 static void fsg_free(struct fsg_dev *fsg)
4059 static int __init fsg_init(void)
4062 struct fsg_dev *fsg;
4064 if ((rc = fsg_alloc()) != 0)
4067 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0) {
4071 set_bit(REGISTERED, &fsg->atomic_bitflags);
4073 /* Tell the thread to start working */
4074 complete(&fsg->thread_notifier);
4077 module_init(fsg_init);
4080 static void __exit fsg_cleanup(void)
4082 struct fsg_dev *fsg = the_fsg;
4084 /* Unregister the driver iff the thread hasn't already done so */
4085 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4086 usb_gadget_unregister_driver(&fsg_driver);
4088 /* Wait for the thread to finish up */
4089 wait_for_completion(&fsg->thread_notifier);
4091 close_all_backing_files(fsg);
4094 module_exit(fsg_cleanup);