2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
4 * Copyright (C) 2003, 2004 Alan Stern
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions, and the following disclaimer,
12 * without modification.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The names of the above-listed copyright holders may not be used
17 * to endorse or promote products derived from this software without
18 * specific prior written permission.
20 * ALTERNATIVELY, this software may be distributed under the terms of the
21 * GNU General Public License ("GPL") as published by the Free Software
22 * Foundation, either version 2 of that License or (at your option) any
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * The File-backed Storage Gadget acts as a USB Mass Storage device,
41 * appearing to the host as a disk drive. In addition to providing an
42 * example of a genuinely useful gadget driver for a USB device, it also
43 * illustrates a technique of double-buffering for increased throughput.
44 * Last but not least, it gives an easy way to probe the behavior of the
45 * Mass Storage drivers in a USB host.
47 * Backing storage is provided by a regular file or a block device, specified
48 * by the "file" module parameter. Access can be limited to read-only by
49 * setting the optional "ro" module parameter. The gadget will indicate that
50 * it has removable media if the optional "removable" module parameter is set.
52 * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
53 * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
54 * by the optional "transport" module parameter. It also supports the
55 * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
56 * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
57 * the optional "protocol" module parameter. In addition, the default
58 * Vendor ID, Product ID, and release number can be overridden.
60 * There is support for multiple logical units (LUNs), each of which has
61 * its own backing file. The number of LUNs can be set using the optional
62 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
63 * files are specified using comma-separated lists for "file" and "ro".
64 * The default number of LUNs is taken from the number of "file" elements;
65 * it is 1 if "file" is not given. If "removable" is not set then a backing
66 * file must be specified for each LUN. If it is set, then an unspecified
67 * or empty backing filename means the LUN's medium is not loaded.
69 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
70 * needed (an interrupt-out endpoint is also needed for CBI). The memory
71 * requirement amounts to two 16K buffers, size configurable by a parameter.
72 * Support is included for both full-speed and high-speed operation.
76 * file=filename[,filename...]
77 * Required if "removable" is not set, names of
78 * the files or block devices used for
80 * ro=b[,b...] Default false, booleans for read-only access
81 * removable Default false, boolean for removable media
82 * luns=N Default N = number of filenames, number of
84 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
85 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
86 * ATAPI, QIC, UFI, 8070, or SCSI;
88 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
89 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
90 * release=0xRRRR Override the USB release number (bcdDevice)
91 * buflen=N Default N=16384, buffer size used (will be
92 * rounded down to a multiple of
94 * stall Default determined according to the type of
95 * USB device controller (usually true),
96 * boolean to permit the driver to halt
99 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
100 * "removable", and "luns" options are available; default values are used
101 * for everything else.
103 * The pathnames of the backing files and the ro settings are available in
104 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
105 * gadget's sysfs directory. If the "removable" option is set, writing to
106 * these files will simulate ejecting/loading the medium (writing an empty
107 * line means eject) and adjusting a write-enable tab. Changes to the ro
108 * setting are not allowed when the medium is loaded.
110 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
117 * The FSG driver is fairly straightforward. There is a main kernel
118 * thread that handles most of the work. Interrupt routines field
119 * callbacks from the controller driver: bulk- and interrupt-request
120 * completion notifications, endpoint-0 events, and disconnect events.
121 * Completion events are passed to the main thread by wakeup calls. Many
122 * ep0 requests are handled at interrupt time, but SetInterface,
123 * SetConfiguration, and device reset requests are forwarded to the
124 * thread in the form of "exceptions" using SIGUSR1 signals (since they
125 * should interrupt any ongoing file I/O operations).
127 * The thread's main routine implements the standard command/data/status
128 * parts of a SCSI interaction. It and its subroutines are full of tests
129 * for pending signals/exceptions -- all this polling is necessary since
130 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
131 * indication that the driver really wants to be running in userspace.)
132 * An important point is that so long as the thread is alive it keeps an
133 * open reference to the backing file. This will prevent unmounting
134 * the backing file's underlying filesystem and could cause problems
135 * during system shutdown, for example. To prevent such problems, the
136 * thread catches INT, TERM, and KILL signals and converts them into
139 * In normal operation the main thread is started during the gadget's
140 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
141 * exit when it receives a signal, and there's no point leaving the
142 * gadget running when the thread is dead. So just before the thread
143 * exits, it deregisters the gadget driver. This makes things a little
144 * tricky: The driver is deregistered at two places, and the exiting
145 * thread can indirectly call fsg_unbind() which in turn can tell the
146 * thread to exit. The first problem is resolved through the use of the
147 * REGISTERED atomic bitflag; the driver will only be deregistered once.
148 * The second problem is resolved by having fsg_unbind() check
149 * fsg->state; it won't try to stop the thread if the state is already
150 * FSG_STATE_TERMINATED.
152 * To provide maximum throughput, the driver uses a circular pipeline of
153 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
154 * arbitrarily long; in practice the benefits don't justify having more
155 * than 2 stages (i.e., double buffering). But it helps to think of the
156 * pipeline as being a long one. Each buffer head contains a bulk-in and
157 * a bulk-out request pointer (since the buffer can be used for both
158 * output and input -- directions always are given from the host's
159 * point of view) as well as a pointer to the buffer and various state
162 * Use of the pipeline follows a simple protocol. There is a variable
163 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
164 * At any time that buffer head may still be in use from an earlier
165 * request, so each buffer head has a state variable indicating whether
166 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
167 * buffer head to be EMPTY, filling the buffer either by file I/O or by
168 * USB I/O (during which the buffer head is BUSY), and marking the buffer
169 * head FULL when the I/O is complete. Then the buffer will be emptied
170 * (again possibly by USB I/O, during which it is marked BUSY) and
171 * finally marked EMPTY again (possibly by a completion routine).
173 * A module parameter tells the driver to avoid stalling the bulk
174 * endpoints wherever the transport specification allows. This is
175 * necessary for some UDCs like the SuperH, which cannot reliably clear a
176 * halt on a bulk endpoint. However, under certain circumstances the
177 * Bulk-only specification requires a stall. In such cases the driver
178 * will halt the endpoint and set a flag indicating that it should clear
179 * the halt in software during the next device reset. Hopefully this
180 * will permit everything to work correctly. Furthermore, although the
181 * specification allows the bulk-out endpoint to halt when the host sends
182 * too much data, implementing this would cause an unavoidable race.
183 * The driver will always use the "no-stall" approach for OUT transfers.
185 * One subtle point concerns sending status-stage responses for ep0
186 * requests. Some of these requests, such as device reset, can involve
187 * interrupting an ongoing file I/O operation, which might take an
188 * arbitrarily long time. During that delay the host might give up on
189 * the original ep0 request and issue a new one. When that happens the
190 * driver should not notify the host about completion of the original
191 * request, as the host will no longer be waiting for it. So the driver
192 * assigns to each ep0 request a unique tag, and it keeps track of the
193 * tag value of the request associated with a long-running exception
194 * (device-reset, interface-change, or configuration-change). When the
195 * exception handler is finished, the status-stage response is submitted
196 * only if the current ep0 request tag is equal to the exception request
197 * tag. Thus only the most recently received ep0 request will get a
198 * status-stage response.
200 * Warning: This driver source file is too long. It ought to be split up
201 * into a header file plus about 3 separate .c files, to handle the details
202 * of the Gadget, USB Mass Storage, and SCSI protocols.
210 #include <linux/config.h>
212 #include <asm/system.h>
213 #include <asm/uaccess.h>
215 #include <linux/bitops.h>
216 #include <linux/blkdev.h>
217 #include <linux/compiler.h>
218 #include <linux/completion.h>
219 #include <linux/dcache.h>
220 #include <linux/delay.h>
221 #include <linux/device.h>
222 #include <linux/fcntl.h>
223 #include <linux/file.h>
224 #include <linux/fs.h>
225 #include <linux/init.h>
226 #include <linux/kernel.h>
227 #include <linux/limits.h>
228 #include <linux/list.h>
229 #include <linux/module.h>
230 #include <linux/moduleparam.h>
231 #include <linux/pagemap.h>
232 #include <linux/rwsem.h>
233 #include <linux/sched.h>
234 #include <linux/signal.h>
235 #include <linux/slab.h>
236 #include <linux/spinlock.h>
237 #include <linux/string.h>
238 #include <linux/suspend.h>
239 #include <linux/utsname.h>
240 #include <linux/wait.h>
242 #include <linux/usb_ch9.h>
243 #include <linux/usb_gadget.h>
245 #include "gadget_chips.h"
248 /*-------------------------------------------------------------------------*/
250 #define DRIVER_DESC "File-backed Storage Gadget"
251 #define DRIVER_NAME "g_file_storage"
252 #define DRIVER_VERSION "20 October 2004"
254 static const char longname[] = DRIVER_DESC;
255 static const char shortname[] = DRIVER_NAME;
257 MODULE_DESCRIPTION(DRIVER_DESC);
258 MODULE_AUTHOR("Alan Stern");
259 MODULE_LICENSE("Dual BSD/GPL");
261 /* Thanks to NetChip Technologies for donating this product ID.
263 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
264 * Instead: allocate your own, using normal USB-IF procedures. */
265 #define DRIVER_VENDOR_ID 0x0525 // NetChip
266 #define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
270 * This driver assumes self-powered hardware and has no way for users to
271 * trigger remote wakeup. It uses autoconfiguration to select endpoints
272 * and endpoint addresses.
276 /*-------------------------------------------------------------------------*/
278 #define xprintk(f,level,fmt,args...) \
279 dev_printk(level , &(f)->gadget->dev , fmt , ## args)
280 #define yprintk(l,level,fmt,args...) \
281 dev_printk(level , &(l)->dev , fmt , ## args)
284 #define DBG(fsg,fmt,args...) \
285 xprintk(fsg , KERN_DEBUG , fmt , ## args)
286 #define LDBG(lun,fmt,args...) \
287 yprintk(lun , KERN_DEBUG , fmt , ## args)
288 #define MDBG(fmt,args...) \
289 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
291 #define DBG(fsg,fmt,args...) \
293 #define LDBG(lun,fmt,args...) \
295 #define MDBG(fmt,args...) \
305 #define VDBG(fsg,fmt,args...) \
307 #define VLDBG(lun,fmt,args...) \
311 #define ERROR(fsg,fmt,args...) \
312 xprintk(fsg , KERN_ERR , fmt , ## args)
313 #define LERROR(lun,fmt,args...) \
314 yprintk(lun , KERN_ERR , fmt , ## args)
316 #define WARN(fsg,fmt,args...) \
317 xprintk(fsg , KERN_WARNING , fmt , ## args)
318 #define LWARN(lun,fmt,args...) \
319 yprintk(lun , KERN_WARNING , fmt , ## args)
321 #define INFO(fsg,fmt,args...) \
322 xprintk(fsg , KERN_INFO , fmt , ## args)
323 #define LINFO(lun,fmt,args...) \
324 yprintk(lun , KERN_INFO , fmt , ## args)
326 #define MINFO(fmt,args...) \
327 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
330 /*-------------------------------------------------------------------------*/
332 /* Encapsulate the module parameter settings */
336 /* Arggh! There should be a module_param_array_named macro! */
337 static char *file[MAX_LUNS] = {NULL, };
338 static int ro[MAX_LUNS] = {0, };
345 char *transport_parm;
348 unsigned short vendor;
349 unsigned short product;
350 unsigned short release;
355 char *transport_name;
359 } mod_data = { // Default values
360 .transport_parm = "BBB",
361 .protocol_parm = "SCSI",
363 .vendor = DRIVER_VENDOR_ID,
364 .product = DRIVER_PRODUCT_ID,
365 .release = 0xffff, // Use controller chip type
371 module_param_array(file, charp, &mod_data.num_filenames, S_IRUGO);
372 MODULE_PARM_DESC(file, "names of backing files or devices");
374 module_param_array(ro, bool, &mod_data.num_ros, S_IRUGO);
375 MODULE_PARM_DESC(ro, "true to force read-only");
377 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
378 MODULE_PARM_DESC(luns, "number of LUNs");
380 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
381 MODULE_PARM_DESC(removable, "true to simulate removable media");
384 /* In the non-TEST version, only the module parameters listed above
386 #ifdef CONFIG_USB_FILE_STORAGE_TEST
388 module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
389 MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
391 module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
392 MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
395 module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
396 MODULE_PARM_DESC(vendor, "USB Vendor ID");
398 module_param_named(product, mod_data.product, ushort, S_IRUGO);
399 MODULE_PARM_DESC(product, "USB Product ID");
401 module_param_named(release, mod_data.release, ushort, S_IRUGO);
402 MODULE_PARM_DESC(release, "USB release number");
404 module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
405 MODULE_PARM_DESC(buflen, "I/O buffer size");
407 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
408 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
410 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
413 /*-------------------------------------------------------------------------*/
415 /* USB protocol value = the transport method */
416 #define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
417 #define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
418 #define USB_PR_BULK 0x50 // Bulk-only
420 /* USB subclass value = the protocol encapsulation */
421 #define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
422 #define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
423 #define USB_SC_QIC 0x03 // QIC-157 (tape)
424 #define USB_SC_UFI 0x04 // UFI (floppy)
425 #define USB_SC_8070 0x05 // SFF-8070i (removable)
426 #define USB_SC_SCSI 0x06 // Transparent SCSI
428 /* Bulk-only data structures */
430 /* Command Block Wrapper */
431 struct bulk_cb_wrap {
432 __le32 Signature; // Contains 'USBC'
433 u32 Tag; // Unique per command id
434 __le32 DataTransferLength; // Size of the data
435 u8 Flags; // Direction in bit 7
436 u8 Lun; // LUN (normally 0)
437 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
438 u8 CDB[16]; // Command Data Block
441 #define USB_BULK_CB_WRAP_LEN 31
442 #define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
443 #define USB_BULK_IN_FLAG 0x80
445 /* Command Status Wrapper */
446 struct bulk_cs_wrap {
447 __le32 Signature; // Should = 'USBS'
448 u32 Tag; // Same as original command
449 __le32 Residue; // Amount not transferred
450 u8 Status; // See below
453 #define USB_BULK_CS_WRAP_LEN 13
454 #define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
455 #define USB_STATUS_PASS 0
456 #define USB_STATUS_FAIL 1
457 #define USB_STATUS_PHASE_ERROR 2
459 /* Bulk-only class specific requests */
460 #define USB_BULK_RESET_REQUEST 0xff
461 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
464 /* CBI Interrupt data structure */
465 struct interrupt_data {
470 #define CBI_INTERRUPT_DATA_LEN 2
472 /* CBI Accept Device-Specific Command request */
473 #define USB_CBI_ADSC_REQUEST 0x00
476 #define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
478 /* SCSI commands that we recognize */
479 #define SC_FORMAT_UNIT 0x04
480 #define SC_INQUIRY 0x12
481 #define SC_MODE_SELECT_6 0x15
482 #define SC_MODE_SELECT_10 0x55
483 #define SC_MODE_SENSE_6 0x1a
484 #define SC_MODE_SENSE_10 0x5a
485 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
486 #define SC_READ_6 0x08
487 #define SC_READ_10 0x28
488 #define SC_READ_12 0xa8
489 #define SC_READ_CAPACITY 0x25
490 #define SC_READ_FORMAT_CAPACITIES 0x23
491 #define SC_RELEASE 0x17
492 #define SC_REQUEST_SENSE 0x03
493 #define SC_RESERVE 0x16
494 #define SC_SEND_DIAGNOSTIC 0x1d
495 #define SC_START_STOP_UNIT 0x1b
496 #define SC_SYNCHRONIZE_CACHE 0x35
497 #define SC_TEST_UNIT_READY 0x00
498 #define SC_VERIFY 0x2f
499 #define SC_WRITE_6 0x0a
500 #define SC_WRITE_10 0x2a
501 #define SC_WRITE_12 0xaa
503 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
504 #define SS_NO_SENSE 0
505 #define SS_COMMUNICATION_FAILURE 0x040800
506 #define SS_INVALID_COMMAND 0x052000
507 #define SS_INVALID_FIELD_IN_CDB 0x052400
508 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
509 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
510 #define SS_MEDIUM_NOT_PRESENT 0x023a00
511 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
512 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
513 #define SS_RESET_OCCURRED 0x062900
514 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
515 #define SS_UNRECOVERED_READ_ERROR 0x031100
516 #define SS_WRITE_ERROR 0x030c02
517 #define SS_WRITE_PROTECTED 0x072700
519 #define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
520 #define ASC(x) ((u8) ((x) >> 8))
521 #define ASCQ(x) ((u8) (x))
524 /*-------------------------------------------------------------------------*/
527 * These definitions will permit the compiler to avoid generating code for
528 * parts of the driver that aren't used in the non-TEST version. Even gcc
529 * can recognize when a test of a constant expression yields a dead code
533 #ifdef CONFIG_USB_FILE_STORAGE_TEST
535 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
536 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
537 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
541 #define transport_is_bbb() 1
542 #define transport_is_cbi() 0
543 #define protocol_is_scsi() 1
545 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
554 unsigned int prevent_medium_removal : 1;
555 unsigned int registered : 1;
559 u32 unit_attention_data;
564 #define backing_file_is_open(curlun) ((curlun)->filp != NULL)
566 static inline struct lun *dev_to_lun(struct device *dev)
568 return container_of(dev, struct lun, dev);
572 /* Big enough to hold our biggest descriptor */
573 #define EP0_BUFSIZE 256
574 #define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
576 /* Number of buffers we will use. 2 is enough for double-buffering */
577 #define NUM_BUFFERS 2
579 enum fsg_buffer_state {
588 volatile enum fsg_buffer_state state;
589 struct fsg_buffhd *next;
591 /* The NetChip 2280 is faster, and handles some protocol faults
592 * better, if we don't submit any short bulk-out read requests.
593 * So we will record the intended request length here. */
594 unsigned int bulk_out_intended_length;
596 struct usb_request *inreq;
597 volatile int inreq_busy;
598 struct usb_request *outreq;
599 volatile int outreq_busy;
603 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
604 FSG_STATE_DATA_PHASE,
605 FSG_STATE_STATUS_PHASE,
608 FSG_STATE_ABORT_BULK_OUT,
610 FSG_STATE_INTERFACE_CHANGE,
611 FSG_STATE_CONFIG_CHANGE,
612 FSG_STATE_DISCONNECT,
617 enum data_direction {
618 DATA_DIR_UNKNOWN = 0,
625 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
627 struct usb_gadget *gadget;
629 /* filesem protects: backing files in use */
630 struct rw_semaphore filesem;
632 struct usb_ep *ep0; // Handy copy of gadget->ep0
633 struct usb_request *ep0req; // For control responses
634 volatile unsigned int ep0_req_tag;
635 const char *ep0req_name;
637 struct usb_request *intreq; // For interrupt responses
638 volatile int intreq_busy;
639 struct fsg_buffhd *intr_buffhd;
641 unsigned int bulk_out_maxpacket;
642 enum fsg_state state; // For exception handling
643 unsigned int exception_req_tag;
645 u8 config, new_config;
647 unsigned int running : 1;
648 unsigned int bulk_in_enabled : 1;
649 unsigned int bulk_out_enabled : 1;
650 unsigned int intr_in_enabled : 1;
651 unsigned int phase_error : 1;
652 unsigned int short_packet_received : 1;
653 unsigned int bad_lun_okay : 1;
655 unsigned long atomic_bitflags;
657 #define CLEAR_BULK_HALTS 1
660 struct usb_ep *bulk_in;
661 struct usb_ep *bulk_out;
662 struct usb_ep *intr_in;
664 struct fsg_buffhd *next_buffhd_to_fill;
665 struct fsg_buffhd *next_buffhd_to_drain;
666 struct fsg_buffhd buffhds[NUM_BUFFERS];
668 wait_queue_head_t thread_wqh;
669 int thread_wakeup_needed;
670 struct completion thread_notifier;
672 struct task_struct *thread_task;
673 sigset_t thread_signal_mask;
676 u8 cmnd[MAX_COMMAND_SIZE];
677 enum data_direction data_dir;
679 u32 data_size_from_cmnd;
685 /* The CB protocol offers no way for a host to know when a command
686 * has completed. As a result the next command may arrive early,
687 * and we will still have to handle it. For that reason we need
688 * a buffer to store new commands when using CB (or CBI, which
689 * does not oblige a host to wait for command completion either). */
691 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
696 struct completion lun_released;
699 typedef void (*fsg_routine_t)(struct fsg_dev *);
701 static int inline exception_in_progress(struct fsg_dev *fsg)
703 return (fsg->state > FSG_STATE_IDLE);
706 /* Make bulk-out requests be divisible by the maxpacket size */
707 static void inline set_bulk_out_req_length(struct fsg_dev *fsg,
708 struct fsg_buffhd *bh, unsigned int length)
712 bh->bulk_out_intended_length = length;
713 rem = length % fsg->bulk_out_maxpacket;
715 length += fsg->bulk_out_maxpacket - rem;
716 bh->outreq->length = length;
719 static struct fsg_dev *the_fsg;
720 static struct usb_gadget_driver fsg_driver;
722 static void close_backing_file(struct lun *curlun);
723 static void close_all_backing_files(struct fsg_dev *fsg);
726 /*-------------------------------------------------------------------------*/
730 static void dump_msg(struct fsg_dev *fsg, const char *label,
731 const u8 *buf, unsigned int length)
733 unsigned int start, num, i;
738 DBG(fsg, "%s, length %u:\n", label, length);
742 num = min(length, 16u);
744 for (i = 0; i < num; ++i) {
747 sprintf(p, " %02x", buf[i]);
751 printk(KERN_DEBUG "%6x: %s\n", start, line);
758 static void inline dump_cdb(struct fsg_dev *fsg)
763 static void inline dump_msg(struct fsg_dev *fsg, const char *label,
764 const u8 *buf, unsigned int length)
767 static void inline dump_cdb(struct fsg_dev *fsg)
770 char cmdbuf[3*MAX_COMMAND_SIZE + 1];
772 for (i = 0; i < fsg->cmnd_size; ++i)
773 sprintf(cmdbuf + i*3, " %02x", fsg->cmnd[i]);
774 VDBG(fsg, "SCSI CDB: %s\n", cmdbuf);
777 #endif /* DUMP_MSGS */
780 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
784 if (ep == fsg->bulk_in)
786 else if (ep == fsg->bulk_out)
790 DBG(fsg, "%s set halt\n", name);
791 return usb_ep_set_halt(ep);
795 /*-------------------------------------------------------------------------*/
797 /* Routines for unaligned data access */
799 static u16 inline get_be16(u8 *buf)
801 return ((u16) buf[0] << 8) | ((u16) buf[1]);
804 static u32 inline get_be32(u8 *buf)
806 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
807 ((u32) buf[2] << 8) | ((u32) buf[3]);
810 static void inline put_be16(u8 *buf, u16 val)
816 static void inline put_be32(u8 *buf, u32 val)
825 /*-------------------------------------------------------------------------*/
828 * DESCRIPTORS ... most are static, but strings and (full) configuration
829 * descriptors are built on demand. Also the (static) config and interface
830 * descriptors are adjusted during fsg_bind().
832 #define STRING_MANUFACTURER 1
833 #define STRING_PRODUCT 2
834 #define STRING_SERIAL 3
836 /* There is only one configuration. */
837 #define CONFIG_VALUE 1
839 static struct usb_device_descriptor
841 .bLength = sizeof device_desc,
842 .bDescriptorType = USB_DT_DEVICE,
844 .bcdUSB = __constant_cpu_to_le16(0x0200),
845 .bDeviceClass = USB_CLASS_PER_INTERFACE,
847 /* The next three values can be overridden by module parameters */
848 .idVendor = __constant_cpu_to_le16(DRIVER_VENDOR_ID),
849 .idProduct = __constant_cpu_to_le16(DRIVER_PRODUCT_ID),
850 .bcdDevice = __constant_cpu_to_le16(0xffff),
852 .iManufacturer = STRING_MANUFACTURER,
853 .iProduct = STRING_PRODUCT,
854 .iSerialNumber = STRING_SERIAL,
855 .bNumConfigurations = 1,
858 static struct usb_config_descriptor
860 .bLength = sizeof config_desc,
861 .bDescriptorType = USB_DT_CONFIG,
863 /* wTotalLength computed by usb_gadget_config_buf() */
865 .bConfigurationValue = CONFIG_VALUE,
866 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
867 .bMaxPower = 1, // self-powered
870 static struct usb_otg_descriptor
872 .bLength = sizeof(otg_desc),
873 .bDescriptorType = USB_DT_OTG,
875 .bmAttributes = USB_OTG_SRP,
878 /* There is only one interface. */
880 static struct usb_interface_descriptor
882 .bLength = sizeof intf_desc,
883 .bDescriptorType = USB_DT_INTERFACE,
885 .bNumEndpoints = 2, // Adjusted during fsg_bind()
886 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
887 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
888 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
891 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
892 * and interrupt-in. */
894 static struct usb_endpoint_descriptor
896 .bLength = USB_DT_ENDPOINT_SIZE,
897 .bDescriptorType = USB_DT_ENDPOINT,
899 .bEndpointAddress = USB_DIR_IN,
900 .bmAttributes = USB_ENDPOINT_XFER_BULK,
901 /* wMaxPacketSize set by autoconfiguration */
904 static struct usb_endpoint_descriptor
906 .bLength = USB_DT_ENDPOINT_SIZE,
907 .bDescriptorType = USB_DT_ENDPOINT,
909 .bEndpointAddress = USB_DIR_OUT,
910 .bmAttributes = USB_ENDPOINT_XFER_BULK,
911 /* wMaxPacketSize set by autoconfiguration */
914 static struct usb_endpoint_descriptor
916 .bLength = USB_DT_ENDPOINT_SIZE,
917 .bDescriptorType = USB_DT_ENDPOINT,
919 .bEndpointAddress = USB_DIR_IN,
920 .bmAttributes = USB_ENDPOINT_XFER_INT,
921 .wMaxPacketSize = __constant_cpu_to_le16(2),
922 .bInterval = 32, // frames -> 32 ms
925 static const struct usb_descriptor_header *fs_function[] = {
926 (struct usb_descriptor_header *) &otg_desc,
927 (struct usb_descriptor_header *) &intf_desc,
928 (struct usb_descriptor_header *) &fs_bulk_in_desc,
929 (struct usb_descriptor_header *) &fs_bulk_out_desc,
930 (struct usb_descriptor_header *) &fs_intr_in_desc,
933 #define FS_FUNCTION_PRE_EP_ENTRIES 2
936 #ifdef CONFIG_USB_GADGET_DUALSPEED
939 * USB 2.0 devices need to expose both high speed and full speed
940 * descriptors, unless they only run at full speed.
942 * That means alternate endpoint descriptors (bigger packets)
943 * and a "device qualifier" ... plus more construction options
944 * for the config descriptor.
946 static struct usb_qualifier_descriptor
948 .bLength = sizeof dev_qualifier,
949 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
951 .bcdUSB = __constant_cpu_to_le16(0x0200),
952 .bDeviceClass = USB_CLASS_PER_INTERFACE,
954 .bNumConfigurations = 1,
957 static struct usb_endpoint_descriptor
959 .bLength = USB_DT_ENDPOINT_SIZE,
960 .bDescriptorType = USB_DT_ENDPOINT,
962 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
963 .bmAttributes = USB_ENDPOINT_XFER_BULK,
964 .wMaxPacketSize = __constant_cpu_to_le16(512),
967 static struct usb_endpoint_descriptor
969 .bLength = USB_DT_ENDPOINT_SIZE,
970 .bDescriptorType = USB_DT_ENDPOINT,
972 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
973 .bmAttributes = USB_ENDPOINT_XFER_BULK,
974 .wMaxPacketSize = __constant_cpu_to_le16(512),
975 .bInterval = 1, // NAK every 1 uframe
978 static struct usb_endpoint_descriptor
980 .bLength = USB_DT_ENDPOINT_SIZE,
981 .bDescriptorType = USB_DT_ENDPOINT,
983 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
984 .bmAttributes = USB_ENDPOINT_XFER_INT,
985 .wMaxPacketSize = __constant_cpu_to_le16(2),
986 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
989 static const struct usb_descriptor_header *hs_function[] = {
990 (struct usb_descriptor_header *) &otg_desc,
991 (struct usb_descriptor_header *) &intf_desc,
992 (struct usb_descriptor_header *) &hs_bulk_in_desc,
993 (struct usb_descriptor_header *) &hs_bulk_out_desc,
994 (struct usb_descriptor_header *) &hs_intr_in_desc,
997 #define HS_FUNCTION_PRE_EP_ENTRIES 2
999 /* Maxpacket and other transfer characteristics vary by speed. */
1000 #define ep_desc(g,fs,hs) (((g)->speed==USB_SPEED_HIGH) ? (hs) : (fs))
1004 /* If there's no high speed support, always use the full-speed descriptor. */
1005 #define ep_desc(g,fs,hs) fs
1007 #endif /* !CONFIG_USB_GADGET_DUALSPEED */
1010 /* The CBI specification limits the serial string to 12 uppercase hexadecimal
1012 static char manufacturer[50];
1013 static char serial[13];
1015 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1016 static struct usb_string strings[] = {
1017 {STRING_MANUFACTURER, manufacturer},
1018 {STRING_PRODUCT, longname},
1019 {STRING_SERIAL, serial},
1023 static struct usb_gadget_strings stringtab = {
1024 .language = 0x0409, // en-us
1030 * Config descriptors must agree with the code that sets configurations
1031 * and with code managing interfaces and their altsettings. They must
1032 * also handle different speeds and other-speed requests.
1034 static int populate_config_buf(struct usb_gadget *gadget,
1035 u8 *buf, u8 type, unsigned index)
1037 #ifdef CONFIG_USB_GADGET_DUALSPEED
1038 enum usb_device_speed speed = gadget->speed;
1041 const struct usb_descriptor_header **function;
1046 #ifdef CONFIG_USB_GADGET_DUALSPEED
1047 if (type == USB_DT_OTHER_SPEED_CONFIG)
1048 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
1049 if (speed == USB_SPEED_HIGH)
1050 function = hs_function;
1053 function = fs_function;
1055 /* for now, don't advertise srp-only devices */
1056 if (!gadget->is_otg)
1059 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
1060 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1065 /*-------------------------------------------------------------------------*/
1067 /* These routines may be called in process context or in_irq */
1069 static void wakeup_thread(struct fsg_dev *fsg)
1071 /* Tell the main thread that something has happened */
1072 fsg->thread_wakeup_needed = 1;
1073 wake_up_all(&fsg->thread_wqh);
1077 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
1079 unsigned long flags;
1080 struct task_struct *thread_task;
1082 /* Do nothing if a higher-priority exception is already in progress.
1083 * If a lower-or-equal priority exception is in progress, preempt it
1084 * and notify the main thread by sending it a signal. */
1085 spin_lock_irqsave(&fsg->lock, flags);
1086 if (fsg->state <= new_state) {
1087 fsg->exception_req_tag = fsg->ep0_req_tag;
1088 fsg->state = new_state;
1089 thread_task = fsg->thread_task;
1091 send_sig_info(SIGUSR1, SEND_SIG_FORCED, thread_task);
1093 spin_unlock_irqrestore(&fsg->lock, flags);
1097 /*-------------------------------------------------------------------------*/
1099 /* The disconnect callback and ep0 routines. These always run in_irq,
1100 * except that ep0_queue() is called in the main thread to acknowledge
1101 * completion of various requests: set config, set interface, and
1102 * Bulk-only device reset. */
1104 static void fsg_disconnect(struct usb_gadget *gadget)
1106 struct fsg_dev *fsg = get_gadget_data(gadget);
1108 DBG(fsg, "disconnect or port reset\n");
1109 raise_exception(fsg, FSG_STATE_DISCONNECT);
1113 static int ep0_queue(struct fsg_dev *fsg)
1117 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
1118 if (rc != 0 && rc != -ESHUTDOWN) {
1120 /* We can't do much more than wait for a reset */
1121 WARN(fsg, "error in submission: %s --> %d\n",
1122 fsg->ep0->name, rc);
1127 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
1129 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1131 if (req->actual > 0)
1132 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
1133 if (req->status || req->actual != req->length)
1134 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1135 req->status, req->actual, req->length);
1136 if (req->status == -ECONNRESET) // Request was cancelled
1137 usb_ep_fifo_flush(ep);
1139 if (req->status == 0 && req->context)
1140 ((fsg_routine_t) (req->context))(fsg);
1144 /*-------------------------------------------------------------------------*/
1146 /* Bulk and interrupt endpoint completion handlers.
1147 * These always run in_irq. */
1149 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
1151 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1152 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1154 if (req->status || req->actual != req->length)
1155 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1156 req->status, req->actual, req->length);
1157 if (req->status == -ECONNRESET) // Request was cancelled
1158 usb_ep_fifo_flush(ep);
1160 /* Hold the lock while we update the request and buffer states */
1161 spin_lock(&fsg->lock);
1163 bh->state = BUF_STATE_EMPTY;
1164 spin_unlock(&fsg->lock);
1168 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
1170 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1171 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1173 dump_msg(fsg, "bulk-out", req->buf, req->actual);
1174 if (req->status || req->actual != bh->bulk_out_intended_length)
1175 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1176 req->status, req->actual,
1177 bh->bulk_out_intended_length);
1178 if (req->status == -ECONNRESET) // Request was cancelled
1179 usb_ep_fifo_flush(ep);
1181 /* Hold the lock while we update the request and buffer states */
1182 spin_lock(&fsg->lock);
1183 bh->outreq_busy = 0;
1184 bh->state = BUF_STATE_FULL;
1185 spin_unlock(&fsg->lock);
1190 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1191 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1193 struct fsg_dev *fsg = (struct fsg_dev *) ep->driver_data;
1194 struct fsg_buffhd *bh = (struct fsg_buffhd *) req->context;
1196 if (req->status || req->actual != req->length)
1197 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1198 req->status, req->actual, req->length);
1199 if (req->status == -ECONNRESET) // Request was cancelled
1200 usb_ep_fifo_flush(ep);
1202 /* Hold the lock while we update the request and buffer states */
1203 spin_lock(&fsg->lock);
1204 fsg->intreq_busy = 0;
1205 bh->state = BUF_STATE_EMPTY;
1206 spin_unlock(&fsg->lock);
1211 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1213 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1216 /*-------------------------------------------------------------------------*/
1218 /* Ep0 class-specific handlers. These always run in_irq. */
1220 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1221 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1223 struct usb_request *req = fsg->ep0req;
1224 static u8 cbi_reset_cmnd[6] = {
1225 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
1227 /* Error in command transfer? */
1228 if (req->status || req->length != req->actual ||
1229 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
1231 /* Not all controllers allow a protocol stall after
1232 * receiving control-out data, but we'll try anyway. */
1233 fsg_set_halt(fsg, fsg->ep0);
1234 return; // Wait for reset
1237 /* Is it the special reset command? */
1238 if (req->actual >= sizeof cbi_reset_cmnd &&
1239 memcmp(req->buf, cbi_reset_cmnd,
1240 sizeof cbi_reset_cmnd) == 0) {
1242 /* Raise an exception to stop the current operation
1243 * and reinitialize our state. */
1244 DBG(fsg, "cbi reset request\n");
1245 raise_exception(fsg, FSG_STATE_RESET);
1249 VDBG(fsg, "CB[I] accept device-specific command\n");
1250 spin_lock(&fsg->lock);
1252 /* Save the command for later */
1253 if (fsg->cbbuf_cmnd_size)
1254 WARN(fsg, "CB[I] overwriting previous command\n");
1255 fsg->cbbuf_cmnd_size = req->actual;
1256 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
1258 spin_unlock(&fsg->lock);
1263 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1265 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1268 static int class_setup_req(struct fsg_dev *fsg,
1269 const struct usb_ctrlrequest *ctrl)
1271 struct usb_request *req = fsg->ep0req;
1272 int value = -EOPNOTSUPP;
1277 /* Handle Bulk-only class-specific requests */
1278 if (transport_is_bbb()) {
1279 switch (ctrl->bRequest) {
1281 case USB_BULK_RESET_REQUEST:
1282 if (ctrl->bRequestType != (USB_DIR_OUT |
1283 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1285 if (ctrl->wIndex != 0) {
1290 /* Raise an exception to stop the current operation
1291 * and reinitialize our state. */
1292 DBG(fsg, "bulk reset request\n");
1293 raise_exception(fsg, FSG_STATE_RESET);
1294 value = DELAYED_STATUS;
1297 case USB_BULK_GET_MAX_LUN_REQUEST:
1298 if (ctrl->bRequestType != (USB_DIR_IN |
1299 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1301 if (ctrl->wIndex != 0) {
1305 VDBG(fsg, "get max LUN\n");
1306 *(u8 *) req->buf = fsg->nluns - 1;
1307 value = min(ctrl->wLength, (u16) 1);
1312 /* Handle CBI class-specific requests */
1314 switch (ctrl->bRequest) {
1316 case USB_CBI_ADSC_REQUEST:
1317 if (ctrl->bRequestType != (USB_DIR_OUT |
1318 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1320 if (ctrl->wIndex != 0) {
1324 if (ctrl->wLength > MAX_COMMAND_SIZE) {
1328 value = ctrl->wLength;
1329 fsg->ep0req->context = received_cbi_adsc;
1334 if (value == -EOPNOTSUPP)
1336 "unknown class-specific control req "
1337 "%02x.%02x v%04x i%04x l%u\n",
1338 ctrl->bRequestType, ctrl->bRequest,
1339 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1344 /*-------------------------------------------------------------------------*/
1346 /* Ep0 standard request handlers. These always run in_irq. */
1348 static int standard_setup_req(struct fsg_dev *fsg,
1349 const struct usb_ctrlrequest *ctrl)
1351 struct usb_request *req = fsg->ep0req;
1352 int value = -EOPNOTSUPP;
1354 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1355 * but config change events will also reconfigure hardware. */
1356 switch (ctrl->bRequest) {
1358 case USB_REQ_GET_DESCRIPTOR:
1359 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1362 switch (ctrl->wValue >> 8) {
1365 VDBG(fsg, "get device descriptor\n");
1366 value = min(ctrl->wLength, (u16) sizeof device_desc);
1367 memcpy(req->buf, &device_desc, value);
1369 #ifdef CONFIG_USB_GADGET_DUALSPEED
1370 case USB_DT_DEVICE_QUALIFIER:
1371 VDBG(fsg, "get device qualifier\n");
1372 if (!fsg->gadget->is_dualspeed)
1374 value = min(ctrl->wLength, (u16) sizeof dev_qualifier);
1375 memcpy(req->buf, &dev_qualifier, value);
1378 case USB_DT_OTHER_SPEED_CONFIG:
1379 VDBG(fsg, "get other-speed config descriptor\n");
1380 if (!fsg->gadget->is_dualspeed)
1385 VDBG(fsg, "get configuration descriptor\n");
1386 #ifdef CONFIG_USB_GADGET_DUALSPEED
1389 value = populate_config_buf(fsg->gadget,
1392 ctrl->wValue & 0xff);
1394 value = min(ctrl->wLength, (u16) value);
1398 VDBG(fsg, "get string descriptor\n");
1400 /* wIndex == language code */
1401 value = usb_gadget_get_string(&stringtab,
1402 ctrl->wValue & 0xff, req->buf);
1404 value = min(ctrl->wLength, (u16) value);
1409 /* One config, two speeds */
1410 case USB_REQ_SET_CONFIGURATION:
1411 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
1414 VDBG(fsg, "set configuration\n");
1415 if (ctrl->wValue == CONFIG_VALUE || ctrl->wValue == 0) {
1416 fsg->new_config = ctrl->wValue;
1418 /* Raise an exception to wipe out previous transaction
1419 * state (queued bufs, etc) and set the new config. */
1420 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1421 value = DELAYED_STATUS;
1424 case USB_REQ_GET_CONFIGURATION:
1425 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1428 VDBG(fsg, "get configuration\n");
1429 *(u8 *) req->buf = fsg->config;
1430 value = min(ctrl->wLength, (u16) 1);
1433 case USB_REQ_SET_INTERFACE:
1434 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1435 USB_RECIP_INTERFACE))
1437 if (fsg->config && ctrl->wIndex == 0) {
1439 /* Raise an exception to wipe out previous transaction
1440 * state (queued bufs, etc) and install the new
1441 * interface altsetting. */
1442 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1443 value = DELAYED_STATUS;
1446 case USB_REQ_GET_INTERFACE:
1447 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1448 USB_RECIP_INTERFACE))
1452 if (ctrl->wIndex != 0) {
1456 VDBG(fsg, "get interface\n");
1457 *(u8 *) req->buf = 0;
1458 value = min(ctrl->wLength, (u16) 1);
1463 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1464 ctrl->bRequestType, ctrl->bRequest,
1465 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1472 static int fsg_setup(struct usb_gadget *gadget,
1473 const struct usb_ctrlrequest *ctrl)
1475 struct fsg_dev *fsg = get_gadget_data(gadget);
1478 ++fsg->ep0_req_tag; // Record arrival of a new request
1479 fsg->ep0req->context = NULL;
1480 fsg->ep0req->length = 0;
1481 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1483 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1484 rc = class_setup_req(fsg, ctrl);
1486 rc = standard_setup_req(fsg, ctrl);
1488 /* Respond with data/status or defer until later? */
1489 if (rc >= 0 && rc != DELAYED_STATUS) {
1490 fsg->ep0req->length = rc;
1491 fsg->ep0req->zero = (rc < ctrl->wLength &&
1492 (rc % gadget->ep0->maxpacket) == 0);
1493 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1494 "ep0-in" : "ep0-out");
1495 rc = ep0_queue(fsg);
1498 /* Device either stalls (rc < 0) or reports success */
1503 /*-------------------------------------------------------------------------*/
1505 /* All the following routines run in process context */
1508 /* Use this for bulk or interrupt transfers, not ep0 */
1509 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1510 struct usb_request *req, volatile int *pbusy,
1511 volatile enum fsg_buffer_state *state)
1515 if (ep == fsg->bulk_in)
1516 dump_msg(fsg, "bulk-in", req->buf, req->length);
1517 else if (ep == fsg->intr_in)
1518 dump_msg(fsg, "intr-in", req->buf, req->length);
1520 *state = BUF_STATE_BUSY;
1521 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1524 *state = BUF_STATE_EMPTY;
1526 /* We can't do much more than wait for a reset */
1528 /* Note: currently the net2280 driver fails zero-length
1529 * submissions if DMA is enabled. */
1530 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1532 WARN(fsg, "error in submission: %s --> %d\n",
1538 static int sleep_thread(struct fsg_dev *fsg)
1542 /* Wait until a signal arrives or we are woken up */
1543 rc = wait_event_interruptible(fsg->thread_wqh,
1544 fsg->thread_wakeup_needed);
1545 fsg->thread_wakeup_needed = 0;
1546 if (current->flags & PF_FREEZE)
1547 refrigerator(PF_FREEZE);
1548 return (rc ? -EINTR : 0);
1552 /*-------------------------------------------------------------------------*/
1554 static int do_read(struct fsg_dev *fsg)
1556 struct lun *curlun = fsg->curlun;
1558 struct fsg_buffhd *bh;
1561 loff_t file_offset, file_offset_tmp;
1562 unsigned int amount;
1563 unsigned int partial_page;
1566 /* Get the starting Logical Block Address and check that it's
1568 if (fsg->cmnd[0] == SC_READ_6)
1569 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1571 lba = get_be32(&fsg->cmnd[2]);
1573 /* We allow DPO (Disable Page Out = don't save data in the
1574 * cache) and FUA (Force Unit Access = don't read from the
1575 * cache), but we don't implement them. */
1576 if ((fsg->cmnd[1] & ~0x18) != 0) {
1577 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1581 if (lba >= curlun->num_sectors) {
1582 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1585 file_offset = ((loff_t) lba) << 9;
1587 /* Carry out the file reads */
1588 amount_left = fsg->data_size_from_cmnd;
1589 if (unlikely(amount_left == 0))
1590 return -EIO; // No default reply
1594 /* Figure out how much we need to read:
1595 * Try to read the remaining amount.
1596 * But don't read more than the buffer size.
1597 * And don't try to read past the end of the file.
1598 * Finally, if we're not at a page boundary, don't read past
1600 * If this means reading 0 then we were asked to read past
1601 * the end of file. */
1602 amount = min((unsigned int) amount_left, mod_data.buflen);
1603 amount = min((loff_t) amount,
1604 curlun->file_length - file_offset);
1605 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1606 if (partial_page > 0)
1607 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1610 /* Wait for the next buffer to become available */
1611 bh = fsg->next_buffhd_to_fill;
1612 while (bh->state != BUF_STATE_EMPTY) {
1613 if ((rc = sleep_thread(fsg)) != 0)
1617 /* If we were asked to read past the end of file,
1618 * end with an empty buffer. */
1620 curlun->sense_data =
1621 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1622 curlun->sense_data_info = file_offset >> 9;
1623 bh->inreq->length = 0;
1624 bh->state = BUF_STATE_FULL;
1628 /* Perform the read */
1629 file_offset_tmp = file_offset;
1630 nread = vfs_read(curlun->filp,
1631 (char __user *) bh->buf,
1632 amount, &file_offset_tmp);
1633 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1634 (unsigned long long) file_offset,
1636 if (signal_pending(current))
1640 LDBG(curlun, "error in file read: %d\n",
1643 } else if (nread < amount) {
1644 LDBG(curlun, "partial file read: %d/%u\n",
1645 (int) nread, amount);
1646 nread -= (nread & 511); // Round down to a block
1648 file_offset += nread;
1649 amount_left -= nread;
1650 fsg->residue -= nread;
1651 bh->inreq->length = nread;
1652 bh->state = BUF_STATE_FULL;
1654 /* If an error occurred, report it and its position */
1655 if (nread < amount) {
1656 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1657 curlun->sense_data_info = file_offset >> 9;
1661 if (amount_left == 0)
1662 break; // No more left to read
1664 /* Send this buffer and go read some more */
1665 bh->inreq->zero = 0;
1666 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1667 &bh->inreq_busy, &bh->state);
1668 fsg->next_buffhd_to_fill = bh->next;
1671 return -EIO; // No default reply
1675 /*-------------------------------------------------------------------------*/
1677 static int do_write(struct fsg_dev *fsg)
1679 struct lun *curlun = fsg->curlun;
1681 struct fsg_buffhd *bh;
1683 u32 amount_left_to_req, amount_left_to_write;
1684 loff_t usb_offset, file_offset, file_offset_tmp;
1685 unsigned int amount;
1686 unsigned int partial_page;
1691 curlun->sense_data = SS_WRITE_PROTECTED;
1694 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1696 /* Get the starting Logical Block Address and check that it's
1698 if (fsg->cmnd[0] == SC_WRITE_6)
1699 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1701 lba = get_be32(&fsg->cmnd[2]);
1703 /* We allow DPO (Disable Page Out = don't save data in the
1704 * cache) and FUA (Force Unit Access = write directly to the
1705 * medium). We don't implement DPO; we implement FUA by
1706 * performing synchronous output. */
1707 if ((fsg->cmnd[1] & ~0x18) != 0) {
1708 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1711 if (fsg->cmnd[1] & 0x08) // FUA
1712 curlun->filp->f_flags |= O_SYNC;
1714 if (lba >= curlun->num_sectors) {
1715 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1719 /* Carry out the file writes */
1721 file_offset = usb_offset = ((loff_t) lba) << 9;
1722 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1724 while (amount_left_to_write > 0) {
1726 /* Queue a request for more data from the host */
1727 bh = fsg->next_buffhd_to_fill;
1728 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1730 /* Figure out how much we want to get:
1731 * Try to get the remaining amount.
1732 * But don't get more than the buffer size.
1733 * And don't try to go past the end of the file.
1734 * If we're not at a page boundary,
1735 * don't go past the next page.
1736 * If this means getting 0, then we were asked
1737 * to write past the end of file.
1738 * Finally, round down to a block boundary. */
1739 amount = min(amount_left_to_req, mod_data.buflen);
1740 amount = min((loff_t) amount, curlun->file_length -
1742 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1743 if (partial_page > 0)
1744 amount = min(amount,
1745 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1749 curlun->sense_data =
1750 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1751 curlun->sense_data_info = usb_offset >> 9;
1754 amount -= (amount & 511);
1757 /* Why were we were asked to transfer a
1763 /* Get the next buffer */
1764 usb_offset += amount;
1765 fsg->usb_amount_left -= amount;
1766 amount_left_to_req -= amount;
1767 if (amount_left_to_req == 0)
1770 /* amount is always divisible by 512, hence by
1771 * the bulk-out maxpacket size */
1772 bh->outreq->length = bh->bulk_out_intended_length =
1774 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1775 &bh->outreq_busy, &bh->state);
1776 fsg->next_buffhd_to_fill = bh->next;
1780 /* Write the received data to the backing file */
1781 bh = fsg->next_buffhd_to_drain;
1782 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1783 break; // We stopped early
1784 if (bh->state == BUF_STATE_FULL) {
1785 fsg->next_buffhd_to_drain = bh->next;
1786 bh->state = BUF_STATE_EMPTY;
1788 /* Did something go wrong with the transfer? */
1789 if (bh->outreq->status != 0) {
1790 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1791 curlun->sense_data_info = file_offset >> 9;
1795 amount = bh->outreq->actual;
1796 if (curlun->file_length - file_offset < amount) {
1798 "write %u @ %llu beyond end %llu\n",
1799 amount, (unsigned long long) file_offset,
1800 (unsigned long long) curlun->file_length);
1801 amount = curlun->file_length - file_offset;
1804 /* Perform the write */
1805 file_offset_tmp = file_offset;
1806 nwritten = vfs_write(curlun->filp,
1807 (char __user *) bh->buf,
1808 amount, &file_offset_tmp);
1809 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1810 (unsigned long long) file_offset,
1812 if (signal_pending(current))
1813 return -EINTR; // Interrupted!
1816 LDBG(curlun, "error in file write: %d\n",
1819 } else if (nwritten < amount) {
1820 LDBG(curlun, "partial file write: %d/%u\n",
1821 (int) nwritten, amount);
1822 nwritten -= (nwritten & 511);
1823 // Round down to a block
1825 file_offset += nwritten;
1826 amount_left_to_write -= nwritten;
1827 fsg->residue -= nwritten;
1829 /* If an error occurred, report it and its position */
1830 if (nwritten < amount) {
1831 curlun->sense_data = SS_WRITE_ERROR;
1832 curlun->sense_data_info = file_offset >> 9;
1836 /* Did the host decide to stop early? */
1837 if (bh->outreq->actual != bh->outreq->length) {
1838 fsg->short_packet_received = 1;
1844 /* Wait for something to happen */
1845 if ((rc = sleep_thread(fsg)) != 0)
1849 return -EIO; // No default reply
1853 /*-------------------------------------------------------------------------*/
1855 /* Sync the file data, don't bother with the metadata.
1856 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1857 static int fsync_sub(struct lun *curlun)
1859 struct file *filp = curlun->filp;
1860 struct inode *inode;
1863 if (curlun->ro || !filp)
1865 if (!filp->f_op->fsync)
1868 inode = filp->f_dentry->d_inode;
1869 down(&inode->i_sem);
1870 current->flags |= PF_SYNCWRITE;
1871 rc = filemap_fdatawrite(inode->i_mapping);
1872 err = filp->f_op->fsync(filp, filp->f_dentry, 1);
1875 err = filemap_fdatawait(inode->i_mapping);
1878 current->flags &= ~PF_SYNCWRITE;
1880 VLDBG(curlun, "fdatasync -> %d\n", rc);
1884 static void fsync_all(struct fsg_dev *fsg)
1888 for (i = 0; i < fsg->nluns; ++i)
1889 fsync_sub(&fsg->luns[i]);
1892 static int do_synchronize_cache(struct fsg_dev *fsg)
1894 struct lun *curlun = fsg->curlun;
1897 /* We ignore the requested LBA and write out all file's
1898 * dirty data buffers. */
1899 rc = fsync_sub(curlun);
1901 curlun->sense_data = SS_WRITE_ERROR;
1906 /*-------------------------------------------------------------------------*/
1908 static void invalidate_sub(struct lun *curlun)
1910 struct file *filp = curlun->filp;
1911 struct inode *inode = filp->f_dentry->d_inode;
1914 rc = invalidate_inode_pages(inode->i_mapping);
1915 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1918 static int do_verify(struct fsg_dev *fsg)
1920 struct lun *curlun = fsg->curlun;
1922 u32 verification_length;
1923 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1924 loff_t file_offset, file_offset_tmp;
1926 unsigned int amount;
1929 /* Get the starting Logical Block Address and check that it's
1931 lba = get_be32(&fsg->cmnd[2]);
1932 if (lba >= curlun->num_sectors) {
1933 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1937 /* We allow DPO (Disable Page Out = don't save data in the
1938 * cache) but we don't implement it. */
1939 if ((fsg->cmnd[1] & ~0x10) != 0) {
1940 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1944 verification_length = get_be16(&fsg->cmnd[7]);
1945 if (unlikely(verification_length == 0))
1946 return -EIO; // No default reply
1948 /* Prepare to carry out the file verify */
1949 amount_left = verification_length << 9;
1950 file_offset = ((loff_t) lba) << 9;
1952 /* Write out all the dirty buffers before invalidating them */
1954 if (signal_pending(current))
1957 invalidate_sub(curlun);
1958 if (signal_pending(current))
1961 /* Just try to read the requested blocks */
1962 while (amount_left > 0) {
1964 /* Figure out how much we need to read:
1965 * Try to read the remaining amount, but not more than
1967 * And don't try to read past the end of the file.
1968 * If this means reading 0 then we were asked to read
1969 * past the end of file. */
1970 amount = min((unsigned int) amount_left, mod_data.buflen);
1971 amount = min((loff_t) amount,
1972 curlun->file_length - file_offset);
1974 curlun->sense_data =
1975 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1976 curlun->sense_data_info = file_offset >> 9;
1980 /* Perform the read */
1981 file_offset_tmp = file_offset;
1982 nread = vfs_read(curlun->filp,
1983 (char __user *) bh->buf,
1984 amount, &file_offset_tmp);
1985 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1986 (unsigned long long) file_offset,
1988 if (signal_pending(current))
1992 LDBG(curlun, "error in file verify: %d\n",
1995 } else if (nread < amount) {
1996 LDBG(curlun, "partial file verify: %d/%u\n",
1997 (int) nread, amount);
1998 nread -= (nread & 511); // Round down to a sector
2001 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
2002 curlun->sense_data_info = file_offset >> 9;
2005 file_offset += nread;
2006 amount_left -= nread;
2012 /*-------------------------------------------------------------------------*/
2014 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2016 u8 *buf = (u8 *) bh->buf;
2018 static char vendor_id[] = "Linux ";
2019 static char product_id[] = "File-Stor Gadget";
2021 if (!fsg->curlun) { // Unsupported LUNs are okay
2022 fsg->bad_lun_okay = 1;
2024 buf[0] = 0x7f; // Unsupported, no device-type
2028 memset(buf, 0, 8); // Non-removable, direct-access device
2029 if (mod_data.removable)
2031 buf[2] = 2; // ANSI SCSI level 2
2032 buf[3] = 2; // SCSI-2 INQUIRY data format
2033 buf[4] = 31; // Additional length
2034 // No special options
2035 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id, product_id,
2041 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2043 struct lun *curlun = fsg->curlun;
2044 u8 *buf = (u8 *) bh->buf;
2048 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2050 * If a REQUEST SENSE command is received from an initiator
2051 * with a pending unit attention condition (before the target
2052 * generates the contingent allegiance condition), then the
2053 * target shall either:
2054 * a) report any pending sense data and preserve the unit
2055 * attention condition on the logical unit, or,
2056 * b) report the unit attention condition, may discard any
2057 * pending sense data, and clear the unit attention
2058 * condition on the logical unit for that initiator.
2060 * FSG normally uses option a); enable this code to use option b).
2063 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2064 curlun->sense_data = curlun->unit_attention_data;
2065 curlun->unit_attention_data = SS_NO_SENSE;
2069 if (!curlun) { // Unsupported LUNs are okay
2070 fsg->bad_lun_okay = 1;
2071 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2074 sd = curlun->sense_data;
2075 sdinfo = curlun->sense_data_info;
2076 curlun->sense_data = SS_NO_SENSE;
2077 curlun->sense_data_info = 0;
2081 buf[0] = 0x80 | 0x70; // Valid, current error
2083 put_be32(&buf[3], sdinfo); // Sense information
2084 buf[7] = 18 - 8; // Additional sense length
2091 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2093 struct lun *curlun = fsg->curlun;
2094 u32 lba = get_be32(&fsg->cmnd[2]);
2095 int pmi = fsg->cmnd[8];
2096 u8 *buf = (u8 *) bh->buf;
2098 /* Check the PMI and LBA fields */
2099 if (pmi > 1 || (pmi == 0 && lba != 0)) {
2100 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2104 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block
2105 put_be32(&buf[4], 512); // Block length
2110 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2112 struct lun *curlun = fsg->curlun;
2113 int mscmnd = fsg->cmnd[0];
2114 u8 *buf = (u8 *) bh->buf;
2117 int changeable_values, all_pages;
2121 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
2122 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2125 pc = fsg->cmnd[2] >> 6;
2126 page_code = fsg->cmnd[2] & 0x3f;
2128 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2131 changeable_values = (pc == 1);
2132 all_pages = (page_code == 0x3f);
2134 /* Write the mode parameter header. Fixed values are: default
2135 * medium type, no cache control (DPOFUA), and no block descriptors.
2136 * The only variable value is the WriteProtect bit. We will fill in
2137 * the mode data length later. */
2139 if (mscmnd == SC_MODE_SENSE_6) {
2140 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2143 } else { // SC_MODE_SENSE_10
2144 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2146 limit = 65535; // Should really be mod_data.buflen
2149 /* No block descriptors */
2151 /* The mode pages, in numerical order. The only page we support
2152 * is the Caching page. */
2153 if (page_code == 0x08 || all_pages) {
2155 buf[0] = 0x08; // Page code
2156 buf[1] = 10; // Page length
2157 memset(buf+2, 0, 10); // None of the fields are changeable
2159 if (!changeable_values) {
2160 buf[2] = 0x04; // Write cache enable,
2161 // Read cache not disabled
2162 // No cache retention priorities
2163 put_be16(&buf[4], 0xffff); // Don't disable prefetch
2164 // Minimum prefetch = 0
2165 put_be16(&buf[8], 0xffff); // Maximum prefetch
2166 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2171 /* Check that a valid page was requested and the mode data length
2172 * isn't too long. */
2174 if (!valid_page || len > limit) {
2175 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2179 /* Store the mode data length */
2180 if (mscmnd == SC_MODE_SENSE_6)
2183 put_be16(buf0, len - 2);
2188 static int do_start_stop(struct fsg_dev *fsg)
2190 struct lun *curlun = fsg->curlun;
2193 if (!mod_data.removable) {
2194 curlun->sense_data = SS_INVALID_COMMAND;
2198 // int immed = fsg->cmnd[1] & 0x01;
2199 loej = fsg->cmnd[4] & 0x02;
2200 start = fsg->cmnd[4] & 0x01;
2202 #ifdef CONFIG_USB_FILE_STORAGE_TEST
2203 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
2204 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
2205 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2211 /* Are we allowed to unload the media? */
2212 if (curlun->prevent_medium_removal) {
2213 LDBG(curlun, "unload attempt prevented\n");
2214 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2217 if (loej) { // Simulate an unload/eject
2218 up_read(&fsg->filesem);
2219 down_write(&fsg->filesem);
2220 close_backing_file(curlun);
2221 up_write(&fsg->filesem);
2222 down_read(&fsg->filesem);
2226 /* Our emulation doesn't support mounting; the medium is
2227 * available for use as soon as it is loaded. */
2228 if (!backing_file_is_open(curlun)) {
2229 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2238 static int do_prevent_allow(struct fsg_dev *fsg)
2240 struct lun *curlun = fsg->curlun;
2243 if (!mod_data.removable) {
2244 curlun->sense_data = SS_INVALID_COMMAND;
2248 prevent = fsg->cmnd[4] & 0x01;
2249 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
2250 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2254 if (curlun->prevent_medium_removal && !prevent)
2256 curlun->prevent_medium_removal = prevent;
2261 static int do_read_format_capacities(struct fsg_dev *fsg,
2262 struct fsg_buffhd *bh)
2264 struct lun *curlun = fsg->curlun;
2265 u8 *buf = (u8 *) bh->buf;
2267 buf[0] = buf[1] = buf[2] = 0;
2268 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
2271 put_be32(&buf[0], curlun->num_sectors); // Number of blocks
2272 put_be32(&buf[4], 512); // Block length
2273 buf[4] = 0x02; // Current capacity
2278 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2280 struct lun *curlun = fsg->curlun;
2282 /* We don't support MODE SELECT */
2283 curlun->sense_data = SS_INVALID_COMMAND;
2288 /*-------------------------------------------------------------------------*/
2290 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2294 rc = fsg_set_halt(fsg, fsg->bulk_in);
2296 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2298 if (rc != -EAGAIN) {
2299 WARN(fsg, "usb_ep_set_halt -> %d\n", rc);
2304 /* Wait for a short time and then try again */
2305 if (msleep_interruptible(100) != 0)
2307 rc = usb_ep_set_halt(fsg->bulk_in);
2312 static int pad_with_zeros(struct fsg_dev *fsg)
2314 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2315 u32 nkeep = bh->inreq->length;
2319 bh->state = BUF_STATE_EMPTY; // For the first iteration
2320 fsg->usb_amount_left = nkeep + fsg->residue;
2321 while (fsg->usb_amount_left > 0) {
2323 /* Wait for the next buffer to be free */
2324 while (bh->state != BUF_STATE_EMPTY) {
2325 if ((rc = sleep_thread(fsg)) != 0)
2329 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2330 memset(bh->buf + nkeep, 0, nsend - nkeep);
2331 bh->inreq->length = nsend;
2332 bh->inreq->zero = 0;
2333 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2334 &bh->inreq_busy, &bh->state);
2335 bh = fsg->next_buffhd_to_fill = bh->next;
2336 fsg->usb_amount_left -= nsend;
2342 static int throw_away_data(struct fsg_dev *fsg)
2344 struct fsg_buffhd *bh;
2348 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2349 fsg->usb_amount_left > 0) {
2351 /* Throw away the data in a filled buffer */
2352 if (bh->state == BUF_STATE_FULL) {
2353 bh->state = BUF_STATE_EMPTY;
2354 fsg->next_buffhd_to_drain = bh->next;
2356 /* A short packet or an error ends everything */
2357 if (bh->outreq->actual != bh->outreq->length ||
2358 bh->outreq->status != 0) {
2359 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2365 /* Try to submit another request if we need one */
2366 bh = fsg->next_buffhd_to_fill;
2367 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2368 amount = min(fsg->usb_amount_left,
2369 (u32) mod_data.buflen);
2371 /* amount is always divisible by 512, hence by
2372 * the bulk-out maxpacket size */
2373 bh->outreq->length = bh->bulk_out_intended_length =
2375 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2376 &bh->outreq_busy, &bh->state);
2377 fsg->next_buffhd_to_fill = bh->next;
2378 fsg->usb_amount_left -= amount;
2382 /* Otherwise wait for something to happen */
2383 if ((rc = sleep_thread(fsg)) != 0)
2390 static int finish_reply(struct fsg_dev *fsg)
2392 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2395 switch (fsg->data_dir) {
2397 break; // Nothing to send
2399 /* If we don't know whether the host wants to read or write,
2400 * this must be CB or CBI with an unknown command. We mustn't
2401 * try to send or receive any data. So stall both bulk pipes
2402 * if we can and wait for a reset. */
2403 case DATA_DIR_UNKNOWN:
2404 if (mod_data.can_stall) {
2405 fsg_set_halt(fsg, fsg->bulk_out);
2406 rc = halt_bulk_in_endpoint(fsg);
2410 /* All but the last buffer of data must have already been sent */
2411 case DATA_DIR_TO_HOST:
2412 if (fsg->data_size == 0)
2413 ; // Nothing to send
2415 /* If there's no residue, simply send the last buffer */
2416 else if (fsg->residue == 0) {
2417 bh->inreq->zero = 0;
2418 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2419 &bh->inreq_busy, &bh->state);
2420 fsg->next_buffhd_to_fill = bh->next;
2423 /* There is a residue. For CB and CBI, simply mark the end
2424 * of the data with a short packet. However, if we are
2425 * allowed to stall, there was no data at all (residue ==
2426 * data_size), and the command failed (invalid LUN or
2427 * sense data is set), then halt the bulk-in endpoint
2429 else if (!transport_is_bbb()) {
2430 if (mod_data.can_stall &&
2431 fsg->residue == fsg->data_size &&
2432 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2433 bh->state = BUF_STATE_EMPTY;
2434 rc = halt_bulk_in_endpoint(fsg);
2436 bh->inreq->zero = 1;
2437 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2438 &bh->inreq_busy, &bh->state);
2439 fsg->next_buffhd_to_fill = bh->next;
2443 /* For Bulk-only, if we're allowed to stall then send the
2444 * short packet and halt the bulk-in endpoint. If we can't
2445 * stall, pad out the remaining data with 0's. */
2447 if (mod_data.can_stall) {
2448 bh->inreq->zero = 1;
2449 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2450 &bh->inreq_busy, &bh->state);
2451 fsg->next_buffhd_to_fill = bh->next;
2452 rc = halt_bulk_in_endpoint(fsg);
2454 rc = pad_with_zeros(fsg);
2458 /* We have processed all we want from the data the host has sent.
2459 * There may still be outstanding bulk-out requests. */
2460 case DATA_DIR_FROM_HOST:
2461 if (fsg->residue == 0)
2462 ; // Nothing to receive
2464 /* Did the host stop sending unexpectedly early? */
2465 else if (fsg->short_packet_received) {
2466 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2470 /* We haven't processed all the incoming data. Even though
2471 * we may be allowed to stall, doing so would cause a race.
2472 * The controller may already have ACK'ed all the remaining
2473 * bulk-out packets, in which case the host wouldn't see a
2474 * STALL. Not realizing the endpoint was halted, it wouldn't
2475 * clear the halt -- leading to problems later on. */
2477 else if (mod_data.can_stall) {
2478 fsg_set_halt(fsg, fsg->bulk_out);
2479 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2484 /* We can't stall. Read in the excess data and throw it
2487 rc = throw_away_data(fsg);
2494 static int send_status(struct fsg_dev *fsg)
2496 struct lun *curlun = fsg->curlun;
2497 struct fsg_buffhd *bh;
2499 u8 status = USB_STATUS_PASS;
2502 /* Wait for the next buffer to become available */
2503 bh = fsg->next_buffhd_to_fill;
2504 while (bh->state != BUF_STATE_EMPTY) {
2505 if ((rc = sleep_thread(fsg)) != 0)
2510 sd = curlun->sense_data;
2511 sdinfo = curlun->sense_data_info;
2512 } else if (fsg->bad_lun_okay)
2515 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2517 if (fsg->phase_error) {
2518 DBG(fsg, "sending phase-error status\n");
2519 status = USB_STATUS_PHASE_ERROR;
2520 sd = SS_INVALID_COMMAND;
2521 } else if (sd != SS_NO_SENSE) {
2522 DBG(fsg, "sending command-failure status\n");
2523 status = USB_STATUS_FAIL;
2524 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2526 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2529 if (transport_is_bbb()) {
2530 struct bulk_cs_wrap *csw = (struct bulk_cs_wrap *) bh->buf;
2532 /* Store and send the Bulk-only CSW */
2533 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
2534 csw->Tag = fsg->tag;
2535 csw->Residue = cpu_to_le32(fsg->residue);
2536 csw->Status = status;
2538 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2539 bh->inreq->zero = 0;
2540 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2541 &bh->inreq_busy, &bh->state);
2543 } else if (mod_data.transport_type == USB_PR_CB) {
2545 /* Control-Bulk transport has no status phase! */
2548 } else { // USB_PR_CBI
2549 struct interrupt_data *buf = (struct interrupt_data *)
2552 /* Store and send the Interrupt data. UFI sends the ASC
2553 * and ASCQ bytes. Everything else sends a Type (which
2554 * is always 0) and the status Value. */
2555 if (mod_data.protocol_type == USB_SC_UFI) {
2556 buf->bType = ASC(sd);
2557 buf->bValue = ASCQ(sd);
2560 buf->bValue = status;
2562 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2564 fsg->intr_buffhd = bh; // Point to the right buffhd
2565 fsg->intreq->buf = bh->inreq->buf;
2566 fsg->intreq->dma = bh->inreq->dma;
2567 fsg->intreq->context = bh;
2568 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2569 &fsg->intreq_busy, &bh->state);
2572 fsg->next_buffhd_to_fill = bh->next;
2577 /*-------------------------------------------------------------------------*/
2579 /* Check whether the command is properly formed and whether its data size
2580 * and direction agree with the values we already have. */
2581 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2582 enum data_direction data_dir, unsigned int mask,
2583 int needs_medium, const char *name)
2586 int lun = fsg->cmnd[1] >> 5;
2587 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2591 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2592 * Transparent SCSI doesn't pad. */
2593 if (protocol_is_scsi())
2596 /* There's some disagreement as to whether RBC pads commands or not.
2597 * We'll play it safe and accept either form. */
2598 else if (mod_data.protocol_type == USB_SC_RBC) {
2599 if (fsg->cmnd_size == 12)
2602 /* All the other protocols pad to 12 bytes */
2607 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2608 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2610 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2611 name, cmnd_size, dirletter[(int) data_dir],
2612 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2614 /* We can't reply at all until we know the correct data direction
2616 if (fsg->data_size_from_cmnd == 0)
2617 data_dir = DATA_DIR_NONE;
2618 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2619 fsg->data_dir = data_dir;
2620 fsg->data_size = fsg->data_size_from_cmnd;
2622 } else { // Bulk-only
2623 if (fsg->data_size < fsg->data_size_from_cmnd) {
2625 /* Host data size < Device data size is a phase error.
2626 * Carry out the command, but only transfer as much
2627 * as we are allowed. */
2628 fsg->data_size_from_cmnd = fsg->data_size;
2629 fsg->phase_error = 1;
2632 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2634 /* Conflicting data directions is a phase error */
2635 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2636 fsg->phase_error = 1;
2640 /* Verify the length of the command itself */
2641 if (cmnd_size != fsg->cmnd_size) {
2643 /* Special case workaround: MS-Windows issues REQUEST SENSE
2644 * with cbw->Length == 12 (it should be 6). */
2645 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
2646 cmnd_size = fsg->cmnd_size;
2648 fsg->phase_error = 1;
2653 /* Check that the LUN values are oonsistent */
2654 if (transport_is_bbb()) {
2655 if (fsg->lun != lun)
2656 DBG(fsg, "using LUN %d from CBW, "
2657 "not LUN %d from CDB\n",
2660 fsg->lun = lun; // Use LUN from the command
2663 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2664 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2665 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2666 curlun->sense_data = SS_NO_SENSE;
2667 curlun->sense_data_info = 0;
2670 fsg->curlun = curlun = NULL;
2671 fsg->bad_lun_okay = 0;
2673 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2674 * to use unsupported LUNs; all others may not. */
2675 if (fsg->cmnd[0] != SC_INQUIRY &&
2676 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2677 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2682 /* If a unit attention condition exists, only INQUIRY and
2683 * REQUEST SENSE commands are allowed; anything else must fail. */
2684 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2685 fsg->cmnd[0] != SC_INQUIRY &&
2686 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2687 curlun->sense_data = curlun->unit_attention_data;
2688 curlun->unit_attention_data = SS_NO_SENSE;
2692 /* Check that only command bytes listed in the mask are non-zero */
2693 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2694 for (i = 1; i < cmnd_size; ++i) {
2695 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2697 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2702 /* If the medium isn't mounted and the command needs to access
2703 * it, return an error. */
2704 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2705 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2713 static int do_scsi_command(struct fsg_dev *fsg)
2715 struct fsg_buffhd *bh;
2717 int reply = -EINVAL;
2719 static char unknown[16];
2723 /* Wait for the next buffer to become available for data or status */
2724 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2725 while (bh->state != BUF_STATE_EMPTY) {
2726 if ((rc = sleep_thread(fsg)) != 0)
2729 fsg->phase_error = 0;
2730 fsg->short_packet_received = 0;
2732 down_read(&fsg->filesem); // We're using the backing file
2733 switch (fsg->cmnd[0]) {
2736 fsg->data_size_from_cmnd = fsg->cmnd[4];
2737 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2740 reply = do_inquiry(fsg, bh);
2743 case SC_MODE_SELECT_6:
2744 fsg->data_size_from_cmnd = fsg->cmnd[4];
2745 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2747 "MODE SELECT(6)")) == 0)
2748 reply = do_mode_select(fsg, bh);
2751 case SC_MODE_SELECT_10:
2752 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2753 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2755 "MODE SELECT(10)")) == 0)
2756 reply = do_mode_select(fsg, bh);
2759 case SC_MODE_SENSE_6:
2760 fsg->data_size_from_cmnd = fsg->cmnd[4];
2761 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2762 (1<<1) | (1<<2) | (1<<4), 0,
2763 "MODE SENSE(6)")) == 0)
2764 reply = do_mode_sense(fsg, bh);
2767 case SC_MODE_SENSE_10:
2768 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2769 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2770 (1<<1) | (1<<2) | (3<<7), 0,
2771 "MODE SENSE(10)")) == 0)
2772 reply = do_mode_sense(fsg, bh);
2775 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2776 fsg->data_size_from_cmnd = 0;
2777 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2779 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2780 reply = do_prevent_allow(fsg);
2785 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2786 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2789 reply = do_read(fsg);
2793 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2794 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2795 (1<<1) | (0xf<<2) | (3<<7), 1,
2797 reply = do_read(fsg);
2801 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2802 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2803 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2805 reply = do_read(fsg);
2808 case SC_READ_CAPACITY:
2809 fsg->data_size_from_cmnd = 8;
2810 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2811 (0xf<<2) | (1<<8), 1,
2812 "READ CAPACITY")) == 0)
2813 reply = do_read_capacity(fsg, bh);
2816 case SC_READ_FORMAT_CAPACITIES:
2817 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2818 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2820 "READ FORMAT CAPACITIES")) == 0)
2821 reply = do_read_format_capacities(fsg, bh);
2824 case SC_REQUEST_SENSE:
2825 fsg->data_size_from_cmnd = fsg->cmnd[4];
2826 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2828 "REQUEST SENSE")) == 0)
2829 reply = do_request_sense(fsg, bh);
2832 case SC_START_STOP_UNIT:
2833 fsg->data_size_from_cmnd = 0;
2834 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2836 "START-STOP UNIT")) == 0)
2837 reply = do_start_stop(fsg);
2840 case SC_SYNCHRONIZE_CACHE:
2841 fsg->data_size_from_cmnd = 0;
2842 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2843 (0xf<<2) | (3<<7), 1,
2844 "SYNCHRONIZE CACHE")) == 0)
2845 reply = do_synchronize_cache(fsg);
2848 case SC_TEST_UNIT_READY:
2849 fsg->data_size_from_cmnd = 0;
2850 reply = check_command(fsg, 6, DATA_DIR_NONE,
2855 /* Although optional, this command is used by MS-Windows. We
2856 * support a minimal version: BytChk must be 0. */
2858 fsg->data_size_from_cmnd = 0;
2859 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2860 (1<<1) | (0xf<<2) | (3<<7), 1,
2862 reply = do_verify(fsg);
2867 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2868 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2871 reply = do_write(fsg);
2875 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2876 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2877 (1<<1) | (0xf<<2) | (3<<7), 1,
2879 reply = do_write(fsg);
2883 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2884 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2885 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2887 reply = do_write(fsg);
2890 /* Some mandatory commands that we recognize but don't implement.
2891 * They don't mean much in this setting. It's left as an exercise
2892 * for anyone interested to implement RESERVE and RELEASE in terms
2893 * of Posix locks. */
2894 case SC_FORMAT_UNIT:
2897 case SC_SEND_DIAGNOSTIC:
2901 fsg->data_size_from_cmnd = 0;
2902 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2903 if ((reply = check_command(fsg, fsg->cmnd_size,
2904 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2905 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2910 up_read(&fsg->filesem);
2912 if (reply == -EINTR || signal_pending(current))
2915 /* Set up the single reply buffer for finish_reply() */
2916 if (reply == -EINVAL)
2917 reply = 0; // Error reply length
2918 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2919 reply = min((u32) reply, fsg->data_size_from_cmnd);
2920 bh->inreq->length = reply;
2921 bh->state = BUF_STATE_FULL;
2922 fsg->residue -= reply;
2923 } // Otherwise it's already set
2929 /*-------------------------------------------------------------------------*/
2931 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2933 struct usb_request *req = bh->outreq;
2934 struct bulk_cb_wrap *cbw = (struct bulk_cb_wrap *) req->buf;
2936 /* Was this a real packet? */
2940 /* Is the CBW valid? */
2941 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2942 cbw->Signature != __constant_cpu_to_le32(
2944 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2946 le32_to_cpu(cbw->Signature));
2948 /* The Bulk-only spec says we MUST stall the bulk pipes!
2949 * If we want to avoid stalls, set a flag so that we will
2950 * clear the endpoint halts at the next reset. */
2951 if (!mod_data.can_stall)
2952 set_bit(CLEAR_BULK_HALTS, &fsg->atomic_bitflags);
2953 fsg_set_halt(fsg, fsg->bulk_out);
2954 halt_bulk_in_endpoint(fsg);
2958 /* Is the CBW meaningful? */
2959 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2960 cbw->Length < 6 || cbw->Length > MAX_COMMAND_SIZE) {
2961 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2963 cbw->Lun, cbw->Flags, cbw->Length);
2965 /* We can do anything we want here, so let's stall the
2966 * bulk pipes if we are allowed to. */
2967 if (mod_data.can_stall) {
2968 fsg_set_halt(fsg, fsg->bulk_out);
2969 halt_bulk_in_endpoint(fsg);
2974 /* Save the command for later */
2975 fsg->cmnd_size = cbw->Length;
2976 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2977 if (cbw->Flags & USB_BULK_IN_FLAG)
2978 fsg->data_dir = DATA_DIR_TO_HOST;
2980 fsg->data_dir = DATA_DIR_FROM_HOST;
2981 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2982 if (fsg->data_size == 0)
2983 fsg->data_dir = DATA_DIR_NONE;
2984 fsg->lun = cbw->Lun;
2985 fsg->tag = cbw->Tag;
2990 static int get_next_command(struct fsg_dev *fsg)
2992 struct fsg_buffhd *bh;
2995 if (transport_is_bbb()) {
2997 /* Wait for the next buffer to become available */
2998 bh = fsg->next_buffhd_to_fill;
2999 while (bh->state != BUF_STATE_EMPTY) {
3000 if ((rc = sleep_thread(fsg)) != 0)
3004 /* Queue a request to read a Bulk-only CBW */
3005 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
3006 start_transfer(fsg, fsg->bulk_out, bh->outreq,
3007 &bh->outreq_busy, &bh->state);
3009 /* We will drain the buffer in software, which means we
3010 * can reuse it for the next filling. No need to advance
3011 * next_buffhd_to_fill. */
3013 /* Wait for the CBW to arrive */
3014 while (bh->state != BUF_STATE_FULL) {
3015 if ((rc = sleep_thread(fsg)) != 0)
3018 rc = received_cbw(fsg, bh);
3019 bh->state = BUF_STATE_EMPTY;
3021 } else { // USB_PR_CB or USB_PR_CBI
3023 /* Wait for the next command to arrive */
3024 while (fsg->cbbuf_cmnd_size == 0) {
3025 if ((rc = sleep_thread(fsg)) != 0)
3029 /* Is the previous status interrupt request still busy?
3030 * The host is allowed to skip reading the status,
3031 * so we must cancel it. */
3032 if (fsg->intreq_busy)
3033 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3035 /* Copy the command and mark the buffer empty */
3036 fsg->data_dir = DATA_DIR_UNKNOWN;
3037 spin_lock_irq(&fsg->lock);
3038 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3039 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3040 fsg->cbbuf_cmnd_size = 0;
3041 spin_unlock_irq(&fsg->lock);
3047 /*-------------------------------------------------------------------------*/
3049 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3050 const struct usb_endpoint_descriptor *d)
3054 ep->driver_data = fsg;
3055 rc = usb_ep_enable(ep, d);
3057 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3061 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3062 struct usb_request **preq)
3064 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3067 ERROR(fsg, "can't allocate request for %s\n", ep->name);
3072 * Reset interface setting and re-init endpoint state (toggle etc).
3073 * Call with altsetting < 0 to disable the interface. The only other
3074 * available altsetting is 0, which enables the interface.
3076 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3080 const struct usb_endpoint_descriptor *d;
3083 DBG(fsg, "reset interface\n");
3086 /* Deallocate the requests */
3087 for (i = 0; i < NUM_BUFFERS; ++i) {
3088 struct fsg_buffhd *bh = &fsg->buffhds[i];
3091 usb_ep_free_request(fsg->bulk_in, bh->inreq);
3095 usb_ep_free_request(fsg->bulk_out, bh->outreq);
3100 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3104 /* Disable the endpoints */
3105 if (fsg->bulk_in_enabled) {
3106 usb_ep_disable(fsg->bulk_in);
3107 fsg->bulk_in_enabled = 0;
3109 if (fsg->bulk_out_enabled) {
3110 usb_ep_disable(fsg->bulk_out);
3111 fsg->bulk_out_enabled = 0;
3113 if (fsg->intr_in_enabled) {
3114 usb_ep_disable(fsg->intr_in);
3115 fsg->intr_in_enabled = 0;
3119 if (altsetting < 0 || rc != 0)
3122 DBG(fsg, "set interface %d\n", altsetting);
3124 /* Enable the endpoints */
3125 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3126 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3128 fsg->bulk_in_enabled = 1;
3130 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3131 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3133 fsg->bulk_out_enabled = 1;
3134 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
3136 if (transport_is_cbi()) {
3137 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3138 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3140 fsg->intr_in_enabled = 1;
3143 /* Allocate the requests */
3144 for (i = 0; i < NUM_BUFFERS; ++i) {
3145 struct fsg_buffhd *bh = &fsg->buffhds[i];
3147 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3149 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3151 bh->inreq->buf = bh->outreq->buf = bh->buf;
3152 bh->inreq->dma = bh->outreq->dma = bh->dma;
3153 bh->inreq->context = bh->outreq->context = bh;
3154 bh->inreq->complete = bulk_in_complete;
3155 bh->outreq->complete = bulk_out_complete;
3157 if (transport_is_cbi()) {
3158 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3160 fsg->intreq->complete = intr_in_complete;
3164 for (i = 0; i < fsg->nluns; ++i)
3165 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3171 * Change our operational configuration. This code must agree with the code
3172 * that returns config descriptors, and with interface altsetting code.
3174 * It's also responsible for power management interactions. Some
3175 * configurations might not work with our current power sources.
3176 * For now we just assume the gadget is always self-powered.
3178 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3182 /* Disable the single interface */
3183 if (fsg->config != 0) {
3184 DBG(fsg, "reset config\n");
3186 rc = do_set_interface(fsg, -1);
3189 /* Enable the interface */
3190 if (new_config != 0) {
3191 fsg->config = new_config;
3192 if ((rc = do_set_interface(fsg, 0)) != 0)
3193 fsg->config = 0; // Reset on errors
3197 switch (fsg->gadget->speed) {
3198 case USB_SPEED_LOW: speed = "low"; break;
3199 case USB_SPEED_FULL: speed = "full"; break;
3200 case USB_SPEED_HIGH: speed = "high"; break;
3201 default: speed = "?"; break;
3203 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3210 /*-------------------------------------------------------------------------*/
3212 static void handle_exception(struct fsg_dev *fsg)
3218 struct fsg_buffhd *bh;
3219 enum fsg_state old_state;
3222 unsigned int exception_req_tag;
3225 /* Clear the existing signals. Anything but SIGUSR1 is converted
3226 * into a high-priority EXIT exception. */
3228 sig = dequeue_signal_lock(current, &fsg->thread_signal_mask,
3232 if (sig != SIGUSR1) {
3233 if (fsg->state < FSG_STATE_EXIT)
3234 DBG(fsg, "Main thread exiting on signal\n");
3235 raise_exception(fsg, FSG_STATE_EXIT);
3239 /* Cancel all the pending transfers */
3240 if (fsg->intreq_busy)
3241 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3242 for (i = 0; i < NUM_BUFFERS; ++i) {
3243 bh = &fsg->buffhds[i];
3245 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3246 if (bh->outreq_busy)
3247 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3250 /* Wait until everything is idle */
3252 num_active = fsg->intreq_busy;
3253 for (i = 0; i < NUM_BUFFERS; ++i) {
3254 bh = &fsg->buffhds[i];
3255 num_active += bh->inreq_busy + bh->outreq_busy;
3257 if (num_active == 0)
3259 if (sleep_thread(fsg))
3263 /* Clear out the controller's fifos */
3264 if (fsg->bulk_in_enabled)
3265 usb_ep_fifo_flush(fsg->bulk_in);
3266 if (fsg->bulk_out_enabled)
3267 usb_ep_fifo_flush(fsg->bulk_out);
3268 if (fsg->intr_in_enabled)
3269 usb_ep_fifo_flush(fsg->intr_in);
3271 /* Reset the I/O buffer states and pointers, the SCSI
3272 * state, and the exception. Then invoke the handler. */
3273 spin_lock_irq(&fsg->lock);
3275 for (i = 0; i < NUM_BUFFERS; ++i) {
3276 bh = &fsg->buffhds[i];
3277 bh->state = BUF_STATE_EMPTY;
3279 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3282 exception_req_tag = fsg->exception_req_tag;
3283 new_config = fsg->new_config;
3284 old_state = fsg->state;
3286 if (old_state == FSG_STATE_ABORT_BULK_OUT)
3287 fsg->state = FSG_STATE_STATUS_PHASE;
3289 for (i = 0; i < fsg->nluns; ++i) {
3290 curlun = &fsg->luns[i];
3291 curlun->prevent_medium_removal = 0;
3292 curlun->sense_data = curlun->unit_attention_data =
3294 curlun->sense_data_info = 0;
3296 fsg->state = FSG_STATE_IDLE;
3298 spin_unlock_irq(&fsg->lock);
3300 /* Carry out any extra actions required for the exception */
3301 switch (old_state) {
3305 case FSG_STATE_ABORT_BULK_OUT:
3307 spin_lock_irq(&fsg->lock);
3308 if (fsg->state == FSG_STATE_STATUS_PHASE)
3309 fsg->state = FSG_STATE_IDLE;
3310 spin_unlock_irq(&fsg->lock);
3313 case FSG_STATE_RESET:
3314 /* In case we were forced against our will to halt a
3315 * bulk endpoint, clear the halt now. (The SuperH UDC
3316 * requires this.) */
3317 if (test_and_clear_bit(CLEAR_BULK_HALTS,
3318 &fsg->atomic_bitflags)) {
3319 usb_ep_clear_halt(fsg->bulk_in);
3320 usb_ep_clear_halt(fsg->bulk_out);
3323 if (transport_is_bbb()) {
3324 if (fsg->ep0_req_tag == exception_req_tag)
3325 ep0_queue(fsg); // Complete the status stage
3327 } else if (transport_is_cbi())
3328 send_status(fsg); // Status by interrupt pipe
3330 /* Technically this should go here, but it would only be
3331 * a waste of time. Ditto for the INTERFACE_CHANGE and
3332 * CONFIG_CHANGE cases. */
3333 // for (i = 0; i < fsg->nluns; ++i)
3334 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3337 case FSG_STATE_INTERFACE_CHANGE:
3338 rc = do_set_interface(fsg, 0);
3339 if (fsg->ep0_req_tag != exception_req_tag)
3341 if (rc != 0) // STALL on errors
3342 fsg_set_halt(fsg, fsg->ep0);
3343 else // Complete the status stage
3347 case FSG_STATE_CONFIG_CHANGE:
3348 rc = do_set_config(fsg, new_config);
3349 if (fsg->ep0_req_tag != exception_req_tag)
3351 if (rc != 0) // STALL on errors
3352 fsg_set_halt(fsg, fsg->ep0);
3353 else // Complete the status stage
3357 case FSG_STATE_DISCONNECT:
3359 do_set_config(fsg, 0); // Unconfigured state
3362 case FSG_STATE_EXIT:
3363 case FSG_STATE_TERMINATED:
3364 do_set_config(fsg, 0); // Free resources
3365 spin_lock_irq(&fsg->lock);
3366 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3367 spin_unlock_irq(&fsg->lock);
3373 /*-------------------------------------------------------------------------*/
3375 static int fsg_main_thread(void *fsg_)
3377 struct fsg_dev *fsg = (struct fsg_dev *) fsg_;
3379 fsg->thread_task = current;
3381 /* Release all our userspace resources */
3382 daemonize("file-storage-gadget");
3384 /* Allow the thread to be killed by a signal, but set the signal mask
3385 * to block everything but INT, TERM, KILL, and USR1. */
3386 siginitsetinv(&fsg->thread_signal_mask, sigmask(SIGINT) |
3387 sigmask(SIGTERM) | sigmask(SIGKILL) |
3389 sigprocmask(SIG_SETMASK, &fsg->thread_signal_mask, NULL);
3391 /* Arrange for userspace references to be interpreted as kernel
3392 * pointers. That way we can pass a kernel pointer to a routine
3393 * that expects a __user pointer and it will work okay. */
3396 /* Wait for the gadget registration to finish up */
3397 wait_for_completion(&fsg->thread_notifier);
3400 while (fsg->state != FSG_STATE_TERMINATED) {
3401 if (exception_in_progress(fsg) || signal_pending(current)) {
3402 handle_exception(fsg);
3406 if (!fsg->running) {
3411 if (get_next_command(fsg))
3414 spin_lock_irq(&fsg->lock);
3415 if (!exception_in_progress(fsg))
3416 fsg->state = FSG_STATE_DATA_PHASE;
3417 spin_unlock_irq(&fsg->lock);
3419 if (do_scsi_command(fsg) || finish_reply(fsg))
3422 spin_lock_irq(&fsg->lock);
3423 if (!exception_in_progress(fsg))
3424 fsg->state = FSG_STATE_STATUS_PHASE;
3425 spin_unlock_irq(&fsg->lock);
3427 if (send_status(fsg))
3430 spin_lock_irq(&fsg->lock);
3431 if (!exception_in_progress(fsg))
3432 fsg->state = FSG_STATE_IDLE;
3433 spin_unlock_irq(&fsg->lock);
3436 fsg->thread_task = NULL;
3437 flush_signals(current);
3439 /* In case we are exiting because of a signal, unregister the
3440 * gadget driver and close the backing file. */
3441 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) {
3442 usb_gadget_unregister_driver(&fsg_driver);
3443 close_all_backing_files(fsg);
3446 /* Let the unbind and cleanup routines know the thread has exited */
3447 complete_and_exit(&fsg->thread_notifier, 0);
3451 /*-------------------------------------------------------------------------*/
3453 /* If the next two routines are called while the gadget is registered,
3454 * the caller must own fsg->filesem for writing. */
3456 static int open_backing_file(struct lun *curlun, const char *filename)
3459 struct file *filp = NULL;
3461 struct inode *inode = NULL;
3465 /* R/W if we can, R/O if we must */
3468 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3469 if (-EROFS == PTR_ERR(filp))
3473 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3475 LINFO(curlun, "unable to open backing file: %s\n", filename);
3476 return PTR_ERR(filp);
3479 if (!(filp->f_mode & FMODE_WRITE))
3483 inode = filp->f_dentry->d_inode;
3484 if (inode && S_ISBLK(inode->i_mode)) {
3485 if (bdev_read_only(inode->i_bdev))
3487 } else if (!inode || !S_ISREG(inode->i_mode)) {
3488 LINFO(curlun, "invalid file type: %s\n", filename);
3492 /* If we can't read the file, it's no good.
3493 * If we can't write the file, use it read-only. */
3494 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3495 LINFO(curlun, "file not readable: %s\n", filename);
3498 if (!(filp->f_op->write || filp->f_op->aio_write))
3501 size = i_size_read(inode->i_mapping->host);
3503 LINFO(curlun, "unable to find file size: %s\n", filename);
3507 num_sectors = size >> 9; // File size in 512-byte sectors
3508 if (num_sectors == 0) {
3509 LINFO(curlun, "file too small: %s\n", filename);
3516 curlun->filp = filp;
3517 curlun->file_length = size;
3518 curlun->num_sectors = num_sectors;
3519 LDBG(curlun, "open backing file: %s\n", filename);
3523 filp_close(filp, current->files);
3528 static void close_backing_file(struct lun *curlun)
3531 LDBG(curlun, "close backing file\n");
3533 curlun->filp = NULL;
3537 static void close_all_backing_files(struct fsg_dev *fsg)
3541 for (i = 0; i < fsg->nluns; ++i)
3542 close_backing_file(&fsg->luns[i]);
3546 static ssize_t show_ro(struct device *dev, char *buf)
3548 struct lun *curlun = dev_to_lun(dev);
3550 return sprintf(buf, "%d\n", curlun->ro);
3553 static ssize_t show_file(struct device *dev, char *buf)
3555 struct lun *curlun = dev_to_lun(dev);
3556 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3560 down_read(&fsg->filesem);
3561 if (backing_file_is_open(curlun)) { // Get the complete pathname
3562 p = d_path(curlun->filp->f_dentry, curlun->filp->f_vfsmnt,
3563 buf, PAGE_SIZE - 1);
3568 memmove(buf, p, rc);
3569 buf[rc] = '\n'; // Add a newline
3572 } else { // No file, return 0 bytes
3576 up_read(&fsg->filesem);
3581 static ssize_t store_ro(struct device *dev, const char *buf, size_t count)
3584 struct lun *curlun = dev_to_lun(dev);
3585 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3588 if (sscanf(buf, "%d", &i) != 1)
3591 /* Allow the write-enable status to change only while the backing file
3593 down_read(&fsg->filesem);
3594 if (backing_file_is_open(curlun)) {
3595 LDBG(curlun, "read-only status change prevented\n");
3599 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3601 up_read(&fsg->filesem);
3605 static ssize_t store_file(struct device *dev, const char *buf, size_t count)
3607 struct lun *curlun = dev_to_lun(dev);
3608 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3611 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3612 LDBG(curlun, "eject attempt prevented\n");
3613 return -EBUSY; // "Door is locked"
3616 /* Remove a trailing newline */
3617 if (count > 0 && buf[count-1] == '\n')
3618 ((char *) buf)[count-1] = 0; // Ugh!
3620 /* Eject current medium */
3621 down_write(&fsg->filesem);
3622 if (backing_file_is_open(curlun)) {
3623 close_backing_file(curlun);
3624 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3627 /* Load new medium */
3628 if (count > 0 && buf[0]) {
3629 rc = open_backing_file(curlun, buf);
3631 curlun->unit_attention_data =
3632 SS_NOT_READY_TO_READY_TRANSITION;
3634 up_write(&fsg->filesem);
3635 return (rc < 0 ? rc : count);
3639 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3640 static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3641 static DEVICE_ATTR(file, 0444, show_file, NULL);
3644 /*-------------------------------------------------------------------------*/
3646 static void lun_release(struct device *dev)
3648 struct fsg_dev *fsg = (struct fsg_dev *) dev_get_drvdata(dev);
3650 complete(&fsg->lun_released);
3653 static void fsg_unbind(struct usb_gadget *gadget)
3655 struct fsg_dev *fsg = get_gadget_data(gadget);
3658 struct usb_request *req = fsg->ep0req;
3660 DBG(fsg, "unbind\n");
3661 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3663 /* Unregister the sysfs attribute files and the LUNs */
3664 init_completion(&fsg->lun_released);
3665 for (i = 0; i < fsg->nluns; ++i) {
3666 curlun = &fsg->luns[i];
3667 if (curlun->registered) {
3668 device_remove_file(&curlun->dev, &dev_attr_ro);
3669 device_remove_file(&curlun->dev, &dev_attr_file);
3670 device_unregister(&curlun->dev);
3671 wait_for_completion(&fsg->lun_released);
3672 curlun->registered = 0;
3676 /* If the thread isn't already dead, tell it to exit now */
3677 if (fsg->state != FSG_STATE_TERMINATED) {
3678 raise_exception(fsg, FSG_STATE_EXIT);
3679 wait_for_completion(&fsg->thread_notifier);
3681 /* The cleanup routine waits for this completion also */
3682 complete(&fsg->thread_notifier);
3685 /* Free the data buffers */
3686 for (i = 0; i < NUM_BUFFERS; ++i) {
3687 struct fsg_buffhd *bh = &fsg->buffhds[i];
3690 usb_ep_free_buffer(fsg->bulk_in, bh->buf, bh->dma,
3694 /* Free the request and buffer for endpoint 0 */
3697 usb_ep_free_buffer(fsg->ep0, req->buf,
3698 req->dma, EP0_BUFSIZE);
3699 usb_ep_free_request(fsg->ep0, req);
3702 set_gadget_data(gadget, NULL);
3706 static int __init check_parameters(struct fsg_dev *fsg)
3710 /* Store the default values */
3711 mod_data.transport_type = USB_PR_BULK;
3712 mod_data.transport_name = "Bulk-only";
3713 mod_data.protocol_type = USB_SC_SCSI;
3714 mod_data.protocol_name = "Transparent SCSI";
3716 if (gadget_is_sh(fsg->gadget))
3717 mod_data.can_stall = 0;
3719 if (mod_data.release == 0xffff) { // Parameter wasn't set
3720 if (gadget_is_net2280(fsg->gadget))
3721 mod_data.release = 0x0301;
3722 else if (gadget_is_dummy(fsg->gadget))
3723 mod_data.release = 0x0302;
3724 else if (gadget_is_pxa(fsg->gadget))
3725 mod_data.release = 0x0303;
3726 else if (gadget_is_sh(fsg->gadget))
3727 mod_data.release = 0x0304;
3729 /* The sa1100 controller is not supported */
3731 else if (gadget_is_goku(fsg->gadget))
3732 mod_data.release = 0x0306;
3733 else if (gadget_is_mq11xx(fsg->gadget))
3734 mod_data.release = 0x0307;
3735 else if (gadget_is_omap(fsg->gadget))
3736 mod_data.release = 0x0308;
3737 else if (gadget_is_lh7a40x(fsg->gadget))
3738 mod_data.release = 0x0309;
3739 else if (gadget_is_n9604(fsg->gadget))
3740 mod_data.release = 0x0310;
3741 else if (gadget_is_pxa27x(fsg->gadget))
3742 mod_data.release = 0x0311;
3744 WARN(fsg, "controller '%s' not recognized\n",
3746 mod_data.release = 0x0399;
3750 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3752 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3753 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3754 ; // Use default setting
3755 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3756 mod_data.transport_type = USB_PR_CB;
3757 mod_data.transport_name = "Control-Bulk";
3758 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3759 mod_data.transport_type = USB_PR_CBI;
3760 mod_data.transport_name = "Control-Bulk-Interrupt";
3762 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3766 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3767 prot == USB_SC_SCSI) {
3768 ; // Use default setting
3769 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3770 prot == USB_SC_RBC) {
3771 mod_data.protocol_type = USB_SC_RBC;
3772 mod_data.protocol_name = "RBC";
3773 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3774 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3775 prot == USB_SC_8020) {
3776 mod_data.protocol_type = USB_SC_8020;
3777 mod_data.protocol_name = "8020i (ATAPI)";
3778 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3779 prot == USB_SC_QIC) {
3780 mod_data.protocol_type = USB_SC_QIC;
3781 mod_data.protocol_name = "QIC-157";
3782 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3783 prot == USB_SC_UFI) {
3784 mod_data.protocol_type = USB_SC_UFI;
3785 mod_data.protocol_name = "UFI";
3786 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3787 prot == USB_SC_8070) {
3788 mod_data.protocol_type = USB_SC_8070;
3789 mod_data.protocol_name = "8070i";
3791 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3795 mod_data.buflen &= PAGE_CACHE_MASK;
3796 if (mod_data.buflen <= 0) {
3797 ERROR(fsg, "invalid buflen\n");
3800 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3806 static int __init fsg_bind(struct usb_gadget *gadget)
3808 struct fsg_dev *fsg = the_fsg;
3813 struct usb_request *req;
3816 fsg->gadget = gadget;
3817 set_gadget_data(gadget, fsg);
3818 fsg->ep0 = gadget->ep0;
3819 fsg->ep0->driver_data = fsg;
3821 if ((rc = check_parameters(fsg)) != 0)
3824 if (mod_data.removable) { // Enable the store_xxx attributes
3825 dev_attr_ro.attr.mode = dev_attr_file.attr.mode = 0644;
3826 dev_attr_ro.store = store_ro;
3827 dev_attr_file.store = store_file;
3830 /* Find out how many LUNs there should be */
3833 i = max(mod_data.num_filenames, 1);
3835 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3840 /* Create the LUNs, open their backing files, and register the
3841 * LUN devices in sysfs. */
3842 fsg->luns = kmalloc(i * sizeof(struct lun), GFP_KERNEL);
3847 memset(fsg->luns, 0, i * sizeof(struct lun));
3850 for (i = 0; i < fsg->nluns; ++i) {
3851 curlun = &fsg->luns[i];
3853 curlun->dev.parent = &gadget->dev;
3854 curlun->dev.driver = &fsg_driver.driver;
3855 dev_set_drvdata(&curlun->dev, fsg);
3856 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
3857 "%s-lun%d", gadget->dev.bus_id, i);
3859 if ((rc = device_register(&curlun->dev)) != 0)
3860 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
3862 curlun->registered = 1;
3863 curlun->dev.release = lun_release;
3864 device_create_file(&curlun->dev, &dev_attr_ro);
3865 device_create_file(&curlun->dev, &dev_attr_file);
3868 if (file[i] && *file[i]) {
3869 if ((rc = open_backing_file(curlun, file[i])) != 0)
3871 } else if (!mod_data.removable) {
3872 ERROR(fsg, "no file given for LUN%d\n", i);
3878 /* Find all the endpoints we will use */
3879 usb_ep_autoconfig_reset(gadget);
3880 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
3883 ep->driver_data = fsg; // claim the endpoint
3886 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
3889 ep->driver_data = fsg; // claim the endpoint
3892 if (transport_is_cbi()) {
3893 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
3896 ep->driver_data = fsg; // claim the endpoint
3900 /* Fix up the descriptors */
3901 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3902 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3903 device_desc.idProduct = cpu_to_le16(mod_data.product);
3904 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3906 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
3907 intf_desc.bNumEndpoints = i;
3908 intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3909 intf_desc.bInterfaceProtocol = mod_data.transport_type;
3910 fs_function[i + FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3912 #ifdef CONFIG_USB_GADGET_DUALSPEED
3913 hs_function[i + HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3915 /* Assume ep0 uses the same maxpacket value for both speeds */
3916 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3918 /* Assume that all endpoint addresses are the same for both speeds */
3919 hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress;
3920 hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress;
3921 hs_intr_in_desc.bEndpointAddress = fs_intr_in_desc.bEndpointAddress;
3924 if (gadget->is_otg) {
3925 otg_desc.bmAttributes |= USB_OTG_HNP,
3926 config_desc.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
3931 /* Allocate the request and buffer for endpoint 0 */
3932 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3935 req->buf = usb_ep_alloc_buffer(fsg->ep0, EP0_BUFSIZE,
3936 &req->dma, GFP_KERNEL);
3939 req->complete = ep0_complete;
3941 /* Allocate the data buffers */
3942 for (i = 0; i < NUM_BUFFERS; ++i) {
3943 struct fsg_buffhd *bh = &fsg->buffhds[i];
3945 bh->buf = usb_ep_alloc_buffer(fsg->bulk_in, mod_data.buflen,
3946 &bh->dma, GFP_KERNEL);
3951 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3953 /* This should reflect the actual gadget power source */
3954 usb_gadget_set_selfpowered(gadget);
3956 snprintf(manufacturer, sizeof manufacturer, "%s %s with %s",
3957 system_utsname.sysname, system_utsname.release,
3960 /* On a real device, serial[] would be loaded from permanent
3961 * storage. We just encode it from the driver version string. */
3962 for (i = 0; i < sizeof(serial) - 2; i += 2) {
3963 unsigned char c = DRIVER_VERSION[i / 2];
3967 sprintf(&serial[i], "%02X", c);
3970 if ((rc = kernel_thread(fsg_main_thread, fsg, (CLONE_VM | CLONE_FS |
3973 fsg->thread_pid = rc;
3975 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3976 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3978 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3979 for (i = 0; i < fsg->nluns; ++i) {
3980 curlun = &fsg->luns[i];
3981 if (backing_file_is_open(curlun)) {
3984 p = d_path(curlun->filp->f_dentry,
3985 curlun->filp->f_vfsmnt,
3990 LINFO(curlun, "ro=%d, file: %s\n",
3991 curlun->ro, (p ? p : "(error)"));
3996 DBG(fsg, "transport=%s (x%02x)\n",
3997 mod_data.transport_name, mod_data.transport_type);
3998 DBG(fsg, "protocol=%s (x%02x)\n",
3999 mod_data.protocol_name, mod_data.protocol_type);
4000 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
4001 mod_data.vendor, mod_data.product, mod_data.release);
4002 DBG(fsg, "removable=%d, stall=%d, buflen=%u\n",
4003 mod_data.removable, mod_data.can_stall,
4005 DBG(fsg, "I/O thread pid: %d\n", fsg->thread_pid);
4009 ERROR(fsg, "unable to autoconfigure all endpoints\n");
4013 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
4015 close_all_backing_files(fsg);
4020 /*-------------------------------------------------------------------------*/
4022 static void fsg_suspend(struct usb_gadget *gadget)
4024 struct fsg_dev *fsg = get_gadget_data(gadget);
4026 DBG(fsg, "suspend\n");
4027 set_bit(SUSPENDED, &fsg->atomic_bitflags);
4030 static void fsg_resume(struct usb_gadget *gadget)
4032 struct fsg_dev *fsg = get_gadget_data(gadget);
4034 DBG(fsg, "resume\n");
4035 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
4039 /*-------------------------------------------------------------------------*/
4041 static struct usb_gadget_driver fsg_driver = {
4042 #ifdef CONFIG_USB_GADGET_DUALSPEED
4043 .speed = USB_SPEED_HIGH,
4045 .speed = USB_SPEED_FULL,
4047 .function = (char *) longname,
4049 .unbind = fsg_unbind,
4050 .disconnect = fsg_disconnect,
4052 .suspend = fsg_suspend,
4053 .resume = fsg_resume,
4056 .name = (char *) shortname,
4064 static int __init fsg_alloc(void)
4066 struct fsg_dev *fsg;
4068 fsg = kmalloc(sizeof *fsg, GFP_KERNEL);
4071 memset(fsg, 0, sizeof *fsg);
4072 spin_lock_init(&fsg->lock);
4073 init_rwsem(&fsg->filesem);
4074 init_waitqueue_head(&fsg->thread_wqh);
4075 init_completion(&fsg->thread_notifier);
4082 static void fsg_free(struct fsg_dev *fsg)
4089 static int __init fsg_init(void)
4092 struct fsg_dev *fsg;
4094 if ((rc = fsg_alloc()) != 0)
4097 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0) {
4101 set_bit(REGISTERED, &fsg->atomic_bitflags);
4103 /* Tell the thread to start working */
4104 complete(&fsg->thread_notifier);
4107 module_init(fsg_init);
4110 static void __exit fsg_cleanup(void)
4112 struct fsg_dev *fsg = the_fsg;
4114 /* Unregister the driver iff the thread hasn't already done so */
4115 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4116 usb_gadget_unregister_driver(&fsg_driver);
4118 /* Wait for the thread to finish up */
4119 wait_for_completion(&fsg->thread_notifier);
4121 close_all_backing_files(fsg);
4124 module_exit(fsg_cleanup);