2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
4 * Copyright (C) 2003-2008 Alan Stern
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions, and the following disclaimer,
12 * without modification.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The names of the above-listed copyright holders may not be used
17 * to endorse or promote products derived from this software without
18 * specific prior written permission.
20 * ALTERNATIVELY, this software may be distributed under the terms of the
21 * GNU General Public License ("GPL") as published by the Free Software
22 * Foundation, either version 2 of that License or (at your option) any
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * The File-backed Storage Gadget acts as a USB Mass Storage device,
41 * appearing to the host as a disk drive or as a CD-ROM drive. In addition
42 * to providing an example of a genuinely useful gadget driver for a USB
43 * device, it also illustrates a technique of double-buffering for increased
44 * throughput. Last but not least, it gives an easy way to probe the
45 * behavior of the Mass Storage drivers in a USB host.
47 * Backing storage is provided by a regular file or a block device, specified
48 * by the "file" module parameter. Access can be limited to read-only by
49 * setting the optional "ro" module parameter. (For CD-ROM emulation,
50 * access is always read-only.) The gadget will indicate that it has
51 * removable media if the optional "removable" module parameter is set.
53 * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
54 * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
55 * by the optional "transport" module parameter. It also supports the
56 * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
57 * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
58 * the optional "protocol" module parameter. In addition, the default
59 * Vendor ID, Product ID, release number and serial number can be overridden.
61 * There is support for multiple logical units (LUNs), each of which has
62 * its own backing file. The number of LUNs can be set using the optional
63 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
64 * files are specified using comma-separated lists for "file" and "ro".
65 * The default number of LUNs is taken from the number of "file" elements;
66 * it is 1 if "file" is not given. If "removable" is not set then a backing
67 * file must be specified for each LUN. If it is set, then an unspecified
68 * or empty backing filename means the LUN's medium is not loaded. Ideally
69 * each LUN would be settable independently as a disk drive or a CD-ROM
70 * drive, but currently all LUNs have to be the same type. The CD-ROM
71 * emulation includes a single data track and no audio tracks; hence there
72 * need be only one backing file per LUN. Note also that the CD-ROM block
73 * length is set to 512 rather than the more common value 2048.
75 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
76 * needed (an interrupt-out endpoint is also needed for CBI). The memory
77 * requirement amounts to two 16K buffers, size configurable by a parameter.
78 * Support is included for both full-speed and high-speed operation.
80 * Note that the driver is slightly non-portable in that it assumes a
81 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
82 * interrupt-in endpoints. With most device controllers this isn't an
83 * issue, but there may be some with hardware restrictions that prevent
84 * a buffer from being used by more than one endpoint.
88 * file=filename[,filename...]
89 * Required if "removable" is not set, names of
90 * the files or block devices used for
92 * serial=HHHH... Required serial number (string of hex chars)
93 * ro=b[,b...] Default false, booleans for read-only access
94 * removable Default false, boolean for removable media
95 * luns=N Default N = number of filenames, number of
97 * nofua=b[,b...] Default false, booleans for ignore FUA flag
98 * in SCSI WRITE(10,12) commands
99 * stall Default determined according to the type of
100 * USB device controller (usually true),
101 * boolean to permit the driver to halt
103 * cdrom Default false, boolean for whether to emulate
105 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
106 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
107 * ATAPI, QIC, UFI, 8070, or SCSI;
109 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
110 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
111 * release=0xRRRR Override the USB release number (bcdDevice)
112 * buflen=N Default N=16384, buffer size used (will be
113 * rounded down to a multiple of
116 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "serial", "ro",
117 * "removable", "luns", "nofua", "stall", and "cdrom" options are available;
118 * default values are used for everything else.
120 * The pathnames of the backing files and the ro settings are available in
121 * the attribute files "file", "nofua", and "ro" in the lun<n> subdirectory of
122 * the gadget's sysfs directory. If the "removable" option is set, writing to
123 * these files will simulate ejecting/loading the medium (writing an empty
124 * line means eject) and adjusting a write-enable tab. Changes to the ro
125 * setting are not allowed when the medium is loaded or if CD-ROM emulation
128 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
129 * The driver's SCSI command interface was based on the "Information
130 * technology - Small Computer System Interface - 2" document from
131 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
132 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
133 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
134 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
135 * document, Revision 1.0, December 14, 1998, available at
136 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
143 * The FSG driver is fairly straightforward. There is a main kernel
144 * thread that handles most of the work. Interrupt routines field
145 * callbacks from the controller driver: bulk- and interrupt-request
146 * completion notifications, endpoint-0 events, and disconnect events.
147 * Completion events are passed to the main thread by wakeup calls. Many
148 * ep0 requests are handled at interrupt time, but SetInterface,
149 * SetConfiguration, and device reset requests are forwarded to the
150 * thread in the form of "exceptions" using SIGUSR1 signals (since they
151 * should interrupt any ongoing file I/O operations).
153 * The thread's main routine implements the standard command/data/status
154 * parts of a SCSI interaction. It and its subroutines are full of tests
155 * for pending signals/exceptions -- all this polling is necessary since
156 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
157 * indication that the driver really wants to be running in userspace.)
158 * An important point is that so long as the thread is alive it keeps an
159 * open reference to the backing file. This will prevent unmounting
160 * the backing file's underlying filesystem and could cause problems
161 * during system shutdown, for example. To prevent such problems, the
162 * thread catches INT, TERM, and KILL signals and converts them into
165 * In normal operation the main thread is started during the gadget's
166 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
167 * exit when it receives a signal, and there's no point leaving the
168 * gadget running when the thread is dead. So just before the thread
169 * exits, it deregisters the gadget driver. This makes things a little
170 * tricky: The driver is deregistered at two places, and the exiting
171 * thread can indirectly call fsg_unbind() which in turn can tell the
172 * thread to exit. The first problem is resolved through the use of the
173 * REGISTERED atomic bitflag; the driver will only be deregistered once.
174 * The second problem is resolved by having fsg_unbind() check
175 * fsg->state; it won't try to stop the thread if the state is already
176 * FSG_STATE_TERMINATED.
178 * To provide maximum throughput, the driver uses a circular pipeline of
179 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
180 * arbitrarily long; in practice the benefits don't justify having more
181 * than 2 stages (i.e., double buffering). But it helps to think of the
182 * pipeline as being a long one. Each buffer head contains a bulk-in and
183 * a bulk-out request pointer (since the buffer can be used for both
184 * output and input -- directions always are given from the host's
185 * point of view) as well as a pointer to the buffer and various state
188 * Use of the pipeline follows a simple protocol. There is a variable
189 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
190 * At any time that buffer head may still be in use from an earlier
191 * request, so each buffer head has a state variable indicating whether
192 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
193 * buffer head to be EMPTY, filling the buffer either by file I/O or by
194 * USB I/O (during which the buffer head is BUSY), and marking the buffer
195 * head FULL when the I/O is complete. Then the buffer will be emptied
196 * (again possibly by USB I/O, during which it is marked BUSY) and
197 * finally marked EMPTY again (possibly by a completion routine).
199 * A module parameter tells the driver to avoid stalling the bulk
200 * endpoints wherever the transport specification allows. This is
201 * necessary for some UDCs like the SuperH, which cannot reliably clear a
202 * halt on a bulk endpoint. However, under certain circumstances the
203 * Bulk-only specification requires a stall. In such cases the driver
204 * will halt the endpoint and set a flag indicating that it should clear
205 * the halt in software during the next device reset. Hopefully this
206 * will permit everything to work correctly. Furthermore, although the
207 * specification allows the bulk-out endpoint to halt when the host sends
208 * too much data, implementing this would cause an unavoidable race.
209 * The driver will always use the "no-stall" approach for OUT transfers.
211 * One subtle point concerns sending status-stage responses for ep0
212 * requests. Some of these requests, such as device reset, can involve
213 * interrupting an ongoing file I/O operation, which might take an
214 * arbitrarily long time. During that delay the host might give up on
215 * the original ep0 request and issue a new one. When that happens the
216 * driver should not notify the host about completion of the original
217 * request, as the host will no longer be waiting for it. So the driver
218 * assigns to each ep0 request a unique tag, and it keeps track of the
219 * tag value of the request associated with a long-running exception
220 * (device-reset, interface-change, or configuration-change). When the
221 * exception handler is finished, the status-stage response is submitted
222 * only if the current ep0 request tag is equal to the exception request
223 * tag. Thus only the most recently received ep0 request will get a
224 * status-stage response.
226 * Warning: This driver source file is too long. It ought to be split up
227 * into a header file plus about 3 separate .c files, to handle the details
228 * of the Gadget, USB Mass Storage, and SCSI protocols.
232 /* #define VERBOSE_DEBUG */
233 /* #define DUMP_MSGS */
236 #include <linux/blkdev.h>
237 #include <linux/completion.h>
238 #include <linux/dcache.h>
239 #include <linux/delay.h>
240 #include <linux/device.h>
241 #include <linux/fcntl.h>
242 #include <linux/file.h>
243 #include <linux/fs.h>
244 #include <linux/kref.h>
245 #include <linux/kthread.h>
246 #include <linux/limits.h>
247 #include <linux/module.h>
248 #include <linux/rwsem.h>
249 #include <linux/slab.h>
250 #include <linux/spinlock.h>
251 #include <linux/string.h>
252 #include <linux/freezer.h>
253 #include <linux/utsname.h>
255 #include <linux/usb/ch9.h>
256 #include <linux/usb/gadget.h>
258 #include "gadget_chips.h"
263 * Kbuild is not very cooperative with respect to linking separately
264 * compiled library objects into one module. So for now we won't use
265 * separate compilation ... ensuring init/exit sections work to shrink
266 * the runtime footprint, and giving us at least some parts of what
267 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
269 #include "usbstring.c"
271 #include "epautoconf.c"
273 /*-------------------------------------------------------------------------*/
275 #define DRIVER_DESC "File-backed Storage Gadget"
276 #define DRIVER_NAME "g_file_storage"
277 #define DRIVER_VERSION "1 September 2010"
279 static char fsg_string_manufacturer
[64];
280 static const char fsg_string_product
[] = DRIVER_DESC
;
281 static const char fsg_string_config
[] = "Self-powered";
282 static const char fsg_string_interface
[] = "Mass Storage";
285 #include "storage_common.c"
288 MODULE_DESCRIPTION(DRIVER_DESC
);
289 MODULE_AUTHOR("Alan Stern");
290 MODULE_LICENSE("Dual BSD/GPL");
293 * This driver assumes self-powered hardware and has no way for users to
294 * trigger remote wakeup. It uses autoconfiguration to select endpoints
295 * and endpoint addresses.
299 /*-------------------------------------------------------------------------*/
302 /* Encapsulate the module parameter settings */
305 char *file
[FSG_MAX_LUNS
];
307 int ro
[FSG_MAX_LUNS
];
308 int nofua
[FSG_MAX_LUNS
];
309 unsigned int num_filenames
;
310 unsigned int num_ros
;
311 unsigned int num_nofuas
;
318 char *transport_parm
;
320 unsigned short vendor
;
321 unsigned short product
;
322 unsigned short release
;
326 char *transport_name
;
330 } mod_data
= { // Default values
331 .transport_parm
= "BBB",
332 .protocol_parm
= "SCSI",
336 .vendor
= FSG_VENDOR_ID
,
337 .product
= FSG_PRODUCT_ID
,
338 .release
= 0xffff, // Use controller chip type
343 module_param_array_named(file
, mod_data
.file
, charp
, &mod_data
.num_filenames
,
345 MODULE_PARM_DESC(file
, "names of backing files or devices");
347 module_param_named(serial
, mod_data
.serial
, charp
, S_IRUGO
);
348 MODULE_PARM_DESC(serial
, "USB serial number");
350 module_param_array_named(ro
, mod_data
.ro
, bool, &mod_data
.num_ros
, S_IRUGO
);
351 MODULE_PARM_DESC(ro
, "true to force read-only");
353 module_param_array_named(nofua
, mod_data
.nofua
, bool, &mod_data
.num_nofuas
,
355 MODULE_PARM_DESC(nofua
, "true to ignore SCSI WRITE(10,12) FUA bit");
357 module_param_named(luns
, mod_data
.nluns
, uint
, S_IRUGO
);
358 MODULE_PARM_DESC(luns
, "number of LUNs");
360 module_param_named(removable
, mod_data
.removable
, bool, S_IRUGO
);
361 MODULE_PARM_DESC(removable
, "true to simulate removable media");
363 module_param_named(stall
, mod_data
.can_stall
, bool, S_IRUGO
);
364 MODULE_PARM_DESC(stall
, "false to prevent bulk stalls");
366 module_param_named(cdrom
, mod_data
.cdrom
, bool, S_IRUGO
);
367 MODULE_PARM_DESC(cdrom
, "true to emulate cdrom instead of disk");
369 /* In the non-TEST version, only the module parameters listed above
371 #ifdef CONFIG_USB_FILE_STORAGE_TEST
373 module_param_named(transport
, mod_data
.transport_parm
, charp
, S_IRUGO
);
374 MODULE_PARM_DESC(transport
, "type of transport (BBB, CBI, or CB)");
376 module_param_named(protocol
, mod_data
.protocol_parm
, charp
, S_IRUGO
);
377 MODULE_PARM_DESC(protocol
, "type of protocol (RBC, 8020, QIC, UFI, "
380 module_param_named(vendor
, mod_data
.vendor
, ushort
, S_IRUGO
);
381 MODULE_PARM_DESC(vendor
, "USB Vendor ID");
383 module_param_named(product
, mod_data
.product
, ushort
, S_IRUGO
);
384 MODULE_PARM_DESC(product
, "USB Product ID");
386 module_param_named(release
, mod_data
.release
, ushort
, S_IRUGO
);
387 MODULE_PARM_DESC(release
, "USB release number");
389 module_param_named(buflen
, mod_data
.buflen
, uint
, S_IRUGO
);
390 MODULE_PARM_DESC(buflen
, "I/O buffer size");
392 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
396 * These definitions will permit the compiler to avoid generating code for
397 * parts of the driver that aren't used in the non-TEST version. Even gcc
398 * can recognize when a test of a constant expression yields a dead code
402 #ifdef CONFIG_USB_FILE_STORAGE_TEST
404 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
405 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
406 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
410 #define transport_is_bbb() 1
411 #define transport_is_cbi() 0
412 #define protocol_is_scsi() 1
414 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
417 /*-------------------------------------------------------------------------*/
421 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
423 struct usb_gadget
*gadget
;
425 /* filesem protects: backing files in use */
426 struct rw_semaphore filesem
;
428 /* reference counting: wait until all LUNs are released */
431 struct usb_ep
*ep0
; // Handy copy of gadget->ep0
432 struct usb_request
*ep0req
; // For control responses
433 unsigned int ep0_req_tag
;
434 const char *ep0req_name
;
436 struct usb_request
*intreq
; // For interrupt responses
438 struct fsg_buffhd
*intr_buffhd
;
440 unsigned int bulk_out_maxpacket
;
441 enum fsg_state state
; // For exception handling
442 unsigned int exception_req_tag
;
444 u8 config
, new_config
;
446 unsigned int running
: 1;
447 unsigned int bulk_in_enabled
: 1;
448 unsigned int bulk_out_enabled
: 1;
449 unsigned int intr_in_enabled
: 1;
450 unsigned int phase_error
: 1;
451 unsigned int short_packet_received
: 1;
452 unsigned int bad_lun_okay
: 1;
454 unsigned long atomic_bitflags
;
456 #define IGNORE_BULK_OUT 1
459 struct usb_ep
*bulk_in
;
460 struct usb_ep
*bulk_out
;
461 struct usb_ep
*intr_in
;
463 struct fsg_buffhd
*next_buffhd_to_fill
;
464 struct fsg_buffhd
*next_buffhd_to_drain
;
465 struct fsg_buffhd buffhds
[FSG_NUM_BUFFERS
];
467 int thread_wakeup_needed
;
468 struct completion thread_notifier
;
469 struct task_struct
*thread_task
;
472 u8 cmnd
[MAX_COMMAND_SIZE
];
473 enum data_direction data_dir
;
475 u32 data_size_from_cmnd
;
481 /* The CB protocol offers no way for a host to know when a command
482 * has completed. As a result the next command may arrive early,
483 * and we will still have to handle it. For that reason we need
484 * a buffer to store new commands when using CB (or CBI, which
485 * does not oblige a host to wait for command completion either). */
487 u8 cbbuf_cmnd
[MAX_COMMAND_SIZE
];
490 struct fsg_lun
*luns
;
491 struct fsg_lun
*curlun
;
494 typedef void (*fsg_routine_t
)(struct fsg_dev
*);
496 static int exception_in_progress(struct fsg_dev
*fsg
)
498 return (fsg
->state
> FSG_STATE_IDLE
);
501 /* Make bulk-out requests be divisible by the maxpacket size */
502 static void set_bulk_out_req_length(struct fsg_dev
*fsg
,
503 struct fsg_buffhd
*bh
, unsigned int length
)
507 bh
->bulk_out_intended_length
= length
;
508 rem
= length
% fsg
->bulk_out_maxpacket
;
510 length
+= fsg
->bulk_out_maxpacket
- rem
;
511 bh
->outreq
->length
= length
;
514 static struct fsg_dev
*the_fsg
;
515 static struct usb_gadget_driver fsg_driver
;
518 /*-------------------------------------------------------------------------*/
520 static int fsg_set_halt(struct fsg_dev
*fsg
, struct usb_ep
*ep
)
524 if (ep
== fsg
->bulk_in
)
526 else if (ep
== fsg
->bulk_out
)
530 DBG(fsg
, "%s set halt\n", name
);
531 return usb_ep_set_halt(ep
);
535 /*-------------------------------------------------------------------------*/
538 * DESCRIPTORS ... most are static, but strings and (full) configuration
539 * descriptors are built on demand. Also the (static) config and interface
540 * descriptors are adjusted during fsg_bind().
543 /* There is only one configuration. */
544 #define CONFIG_VALUE 1
546 static struct usb_device_descriptor
548 .bLength
= sizeof device_desc
,
549 .bDescriptorType
= USB_DT_DEVICE
,
551 .bcdUSB
= cpu_to_le16(0x0200),
552 .bDeviceClass
= USB_CLASS_PER_INTERFACE
,
554 /* The next three values can be overridden by module parameters */
555 .idVendor
= cpu_to_le16(FSG_VENDOR_ID
),
556 .idProduct
= cpu_to_le16(FSG_PRODUCT_ID
),
557 .bcdDevice
= cpu_to_le16(0xffff),
559 .iManufacturer
= FSG_STRING_MANUFACTURER
,
560 .iProduct
= FSG_STRING_PRODUCT
,
561 .iSerialNumber
= FSG_STRING_SERIAL
,
562 .bNumConfigurations
= 1,
565 static struct usb_config_descriptor
567 .bLength
= sizeof config_desc
,
568 .bDescriptorType
= USB_DT_CONFIG
,
570 /* wTotalLength computed by usb_gadget_config_buf() */
572 .bConfigurationValue
= CONFIG_VALUE
,
573 .iConfiguration
= FSG_STRING_CONFIG
,
574 .bmAttributes
= USB_CONFIG_ATT_ONE
| USB_CONFIG_ATT_SELFPOWER
,
575 .bMaxPower
= CONFIG_USB_GADGET_VBUS_DRAW
/ 2,
579 static struct usb_qualifier_descriptor
581 .bLength
= sizeof dev_qualifier
,
582 .bDescriptorType
= USB_DT_DEVICE_QUALIFIER
,
584 .bcdUSB
= cpu_to_le16(0x0200),
585 .bDeviceClass
= USB_CLASS_PER_INTERFACE
,
587 .bNumConfigurations
= 1,
593 * Config descriptors must agree with the code that sets configurations
594 * and with code managing interfaces and their altsettings. They must
595 * also handle different speeds and other-speed requests.
597 static int populate_config_buf(struct usb_gadget
*gadget
,
598 u8
*buf
, u8 type
, unsigned index
)
600 enum usb_device_speed speed
= gadget
->speed
;
602 const struct usb_descriptor_header
**function
;
607 if (gadget_is_dualspeed(gadget
) && type
== USB_DT_OTHER_SPEED_CONFIG
)
608 speed
= (USB_SPEED_FULL
+ USB_SPEED_HIGH
) - speed
;
609 function
= gadget_is_dualspeed(gadget
) && speed
== USB_SPEED_HIGH
610 ? (const struct usb_descriptor_header
**)fsg_hs_function
611 : (const struct usb_descriptor_header
**)fsg_fs_function
;
613 /* for now, don't advertise srp-only devices */
614 if (!gadget_is_otg(gadget
))
617 len
= usb_gadget_config_buf(&config_desc
, buf
, EP0_BUFSIZE
, function
);
618 ((struct usb_config_descriptor
*) buf
)->bDescriptorType
= type
;
623 /*-------------------------------------------------------------------------*/
625 /* These routines may be called in process context or in_irq */
627 /* Caller must hold fsg->lock */
628 static void wakeup_thread(struct fsg_dev
*fsg
)
630 /* Tell the main thread that something has happened */
631 fsg
->thread_wakeup_needed
= 1;
632 if (fsg
->thread_task
)
633 wake_up_process(fsg
->thread_task
);
637 static void raise_exception(struct fsg_dev
*fsg
, enum fsg_state new_state
)
641 /* Do nothing if a higher-priority exception is already in progress.
642 * If a lower-or-equal priority exception is in progress, preempt it
643 * and notify the main thread by sending it a signal. */
644 spin_lock_irqsave(&fsg
->lock
, flags
);
645 if (fsg
->state
<= new_state
) {
646 fsg
->exception_req_tag
= fsg
->ep0_req_tag
;
647 fsg
->state
= new_state
;
648 if (fsg
->thread_task
)
649 send_sig_info(SIGUSR1
, SEND_SIG_FORCED
,
652 spin_unlock_irqrestore(&fsg
->lock
, flags
);
656 /*-------------------------------------------------------------------------*/
658 /* The disconnect callback and ep0 routines. These always run in_irq,
659 * except that ep0_queue() is called in the main thread to acknowledge
660 * completion of various requests: set config, set interface, and
661 * Bulk-only device reset. */
663 static void fsg_disconnect(struct usb_gadget
*gadget
)
665 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
667 DBG(fsg
, "disconnect or port reset\n");
668 raise_exception(fsg
, FSG_STATE_DISCONNECT
);
672 static int ep0_queue(struct fsg_dev
*fsg
)
676 rc
= usb_ep_queue(fsg
->ep0
, fsg
->ep0req
, GFP_ATOMIC
);
677 if (rc
!= 0 && rc
!= -ESHUTDOWN
) {
679 /* We can't do much more than wait for a reset */
680 WARNING(fsg
, "error in submission: %s --> %d\n",
686 static void ep0_complete(struct usb_ep
*ep
, struct usb_request
*req
)
688 struct fsg_dev
*fsg
= ep
->driver_data
;
691 dump_msg(fsg
, fsg
->ep0req_name
, req
->buf
, req
->actual
);
692 if (req
->status
|| req
->actual
!= req
->length
)
693 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
694 req
->status
, req
->actual
, req
->length
);
695 if (req
->status
== -ECONNRESET
) // Request was cancelled
696 usb_ep_fifo_flush(ep
);
698 if (req
->status
== 0 && req
->context
)
699 ((fsg_routine_t
) (req
->context
))(fsg
);
703 /*-------------------------------------------------------------------------*/
705 /* Bulk and interrupt endpoint completion handlers.
706 * These always run in_irq. */
708 static void bulk_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
710 struct fsg_dev
*fsg
= ep
->driver_data
;
711 struct fsg_buffhd
*bh
= req
->context
;
713 if (req
->status
|| req
->actual
!= req
->length
)
714 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
715 req
->status
, req
->actual
, req
->length
);
716 if (req
->status
== -ECONNRESET
) // Request was cancelled
717 usb_ep_fifo_flush(ep
);
719 /* Hold the lock while we update the request and buffer states */
721 spin_lock(&fsg
->lock
);
723 bh
->state
= BUF_STATE_EMPTY
;
725 spin_unlock(&fsg
->lock
);
728 static void bulk_out_complete(struct usb_ep
*ep
, struct usb_request
*req
)
730 struct fsg_dev
*fsg
= ep
->driver_data
;
731 struct fsg_buffhd
*bh
= req
->context
;
733 dump_msg(fsg
, "bulk-out", req
->buf
, req
->actual
);
734 if (req
->status
|| req
->actual
!= bh
->bulk_out_intended_length
)
735 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
736 req
->status
, req
->actual
,
737 bh
->bulk_out_intended_length
);
738 if (req
->status
== -ECONNRESET
) // Request was cancelled
739 usb_ep_fifo_flush(ep
);
741 /* Hold the lock while we update the request and buffer states */
743 spin_lock(&fsg
->lock
);
745 bh
->state
= BUF_STATE_FULL
;
747 spin_unlock(&fsg
->lock
);
751 #ifdef CONFIG_USB_FILE_STORAGE_TEST
752 static void intr_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
754 struct fsg_dev
*fsg
= ep
->driver_data
;
755 struct fsg_buffhd
*bh
= req
->context
;
757 if (req
->status
|| req
->actual
!= req
->length
)
758 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
759 req
->status
, req
->actual
, req
->length
);
760 if (req
->status
== -ECONNRESET
) // Request was cancelled
761 usb_ep_fifo_flush(ep
);
763 /* Hold the lock while we update the request and buffer states */
765 spin_lock(&fsg
->lock
);
766 fsg
->intreq_busy
= 0;
767 bh
->state
= BUF_STATE_EMPTY
;
769 spin_unlock(&fsg
->lock
);
773 static void intr_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
775 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
778 /*-------------------------------------------------------------------------*/
780 /* Ep0 class-specific handlers. These always run in_irq. */
782 #ifdef CONFIG_USB_FILE_STORAGE_TEST
783 static void received_cbi_adsc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
785 struct usb_request
*req
= fsg
->ep0req
;
786 static u8 cbi_reset_cmnd
[6] = {
787 SEND_DIAGNOSTIC
, 4, 0xff, 0xff, 0xff, 0xff};
789 /* Error in command transfer? */
790 if (req
->status
|| req
->length
!= req
->actual
||
791 req
->actual
< 6 || req
->actual
> MAX_COMMAND_SIZE
) {
793 /* Not all controllers allow a protocol stall after
794 * receiving control-out data, but we'll try anyway. */
795 fsg_set_halt(fsg
, fsg
->ep0
);
796 return; // Wait for reset
799 /* Is it the special reset command? */
800 if (req
->actual
>= sizeof cbi_reset_cmnd
&&
801 memcmp(req
->buf
, cbi_reset_cmnd
,
802 sizeof cbi_reset_cmnd
) == 0) {
804 /* Raise an exception to stop the current operation
805 * and reinitialize our state. */
806 DBG(fsg
, "cbi reset request\n");
807 raise_exception(fsg
, FSG_STATE_RESET
);
811 VDBG(fsg
, "CB[I] accept device-specific command\n");
812 spin_lock(&fsg
->lock
);
814 /* Save the command for later */
815 if (fsg
->cbbuf_cmnd_size
)
816 WARNING(fsg
, "CB[I] overwriting previous command\n");
817 fsg
->cbbuf_cmnd_size
= req
->actual
;
818 memcpy(fsg
->cbbuf_cmnd
, req
->buf
, fsg
->cbbuf_cmnd_size
);
821 spin_unlock(&fsg
->lock
);
825 static void received_cbi_adsc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
827 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
830 static int class_setup_req(struct fsg_dev
*fsg
,
831 const struct usb_ctrlrequest
*ctrl
)
833 struct usb_request
*req
= fsg
->ep0req
;
834 int value
= -EOPNOTSUPP
;
835 u16 w_index
= le16_to_cpu(ctrl
->wIndex
);
836 u16 w_value
= le16_to_cpu(ctrl
->wValue
);
837 u16 w_length
= le16_to_cpu(ctrl
->wLength
);
842 /* Handle Bulk-only class-specific requests */
843 if (transport_is_bbb()) {
844 switch (ctrl
->bRequest
) {
846 case USB_BULK_RESET_REQUEST
:
847 if (ctrl
->bRequestType
!= (USB_DIR_OUT
|
848 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
850 if (w_index
!= 0 || w_value
!= 0) {
855 /* Raise an exception to stop the current operation
856 * and reinitialize our state. */
857 DBG(fsg
, "bulk reset request\n");
858 raise_exception(fsg
, FSG_STATE_RESET
);
859 value
= DELAYED_STATUS
;
862 case USB_BULK_GET_MAX_LUN_REQUEST
:
863 if (ctrl
->bRequestType
!= (USB_DIR_IN
|
864 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
866 if (w_index
!= 0 || w_value
!= 0) {
870 VDBG(fsg
, "get max LUN\n");
871 *(u8
*) req
->buf
= fsg
->nluns
- 1;
877 /* Handle CBI class-specific requests */
879 switch (ctrl
->bRequest
) {
881 case USB_CBI_ADSC_REQUEST
:
882 if (ctrl
->bRequestType
!= (USB_DIR_OUT
|
883 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
885 if (w_index
!= 0 || w_value
!= 0) {
889 if (w_length
> MAX_COMMAND_SIZE
) {
894 fsg
->ep0req
->context
= received_cbi_adsc
;
899 if (value
== -EOPNOTSUPP
)
901 "unknown class-specific control req "
902 "%02x.%02x v%04x i%04x l%u\n",
903 ctrl
->bRequestType
, ctrl
->bRequest
,
904 le16_to_cpu(ctrl
->wValue
), w_index
, w_length
);
909 /*-------------------------------------------------------------------------*/
911 /* Ep0 standard request handlers. These always run in_irq. */
913 static int standard_setup_req(struct fsg_dev
*fsg
,
914 const struct usb_ctrlrequest
*ctrl
)
916 struct usb_request
*req
= fsg
->ep0req
;
917 int value
= -EOPNOTSUPP
;
918 u16 w_index
= le16_to_cpu(ctrl
->wIndex
);
919 u16 w_value
= le16_to_cpu(ctrl
->wValue
);
921 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
922 * but config change events will also reconfigure hardware. */
923 switch (ctrl
->bRequest
) {
925 case USB_REQ_GET_DESCRIPTOR
:
926 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
929 switch (w_value
>> 8) {
932 VDBG(fsg
, "get device descriptor\n");
933 device_desc
.bMaxPacketSize0
= fsg
->ep0
->maxpacket
;
934 value
= sizeof device_desc
;
935 memcpy(req
->buf
, &device_desc
, value
);
937 case USB_DT_DEVICE_QUALIFIER
:
938 VDBG(fsg
, "get device qualifier\n");
939 if (!gadget_is_dualspeed(fsg
->gadget
))
942 * Assume ep0 uses the same maxpacket value for both
945 dev_qualifier
.bMaxPacketSize0
= fsg
->ep0
->maxpacket
;
946 value
= sizeof dev_qualifier
;
947 memcpy(req
->buf
, &dev_qualifier
, value
);
950 case USB_DT_OTHER_SPEED_CONFIG
:
951 VDBG(fsg
, "get other-speed config descriptor\n");
952 if (!gadget_is_dualspeed(fsg
->gadget
))
956 VDBG(fsg
, "get configuration descriptor\n");
958 value
= populate_config_buf(fsg
->gadget
,
965 VDBG(fsg
, "get string descriptor\n");
967 /* wIndex == language code */
968 value
= usb_gadget_get_string(&fsg_stringtab
,
969 w_value
& 0xff, req
->buf
);
974 /* One config, two speeds */
975 case USB_REQ_SET_CONFIGURATION
:
976 if (ctrl
->bRequestType
!= (USB_DIR_OUT
| USB_TYPE_STANDARD
|
979 VDBG(fsg
, "set configuration\n");
980 if (w_value
== CONFIG_VALUE
|| w_value
== 0) {
981 fsg
->new_config
= w_value
;
983 /* Raise an exception to wipe out previous transaction
984 * state (queued bufs, etc) and set the new config. */
985 raise_exception(fsg
, FSG_STATE_CONFIG_CHANGE
);
986 value
= DELAYED_STATUS
;
989 case USB_REQ_GET_CONFIGURATION
:
990 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
993 VDBG(fsg
, "get configuration\n");
994 *(u8
*) req
->buf
= fsg
->config
;
998 case USB_REQ_SET_INTERFACE
:
999 if (ctrl
->bRequestType
!= (USB_DIR_OUT
| USB_TYPE_STANDARD
|
1000 USB_RECIP_INTERFACE
))
1002 if (fsg
->config
&& w_index
== 0) {
1004 /* Raise an exception to wipe out previous transaction
1005 * state (queued bufs, etc) and install the new
1006 * interface altsetting. */
1007 raise_exception(fsg
, FSG_STATE_INTERFACE_CHANGE
);
1008 value
= DELAYED_STATUS
;
1011 case USB_REQ_GET_INTERFACE
:
1012 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
1013 USB_RECIP_INTERFACE
))
1021 VDBG(fsg
, "get interface\n");
1022 *(u8
*) req
->buf
= 0;
1028 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1029 ctrl
->bRequestType
, ctrl
->bRequest
,
1030 w_value
, w_index
, le16_to_cpu(ctrl
->wLength
));
1037 static int fsg_setup(struct usb_gadget
*gadget
,
1038 const struct usb_ctrlrequest
*ctrl
)
1040 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
1042 int w_length
= le16_to_cpu(ctrl
->wLength
);
1044 ++fsg
->ep0_req_tag
; // Record arrival of a new request
1045 fsg
->ep0req
->context
= NULL
;
1046 fsg
->ep0req
->length
= 0;
1047 dump_msg(fsg
, "ep0-setup", (u8
*) ctrl
, sizeof(*ctrl
));
1049 if ((ctrl
->bRequestType
& USB_TYPE_MASK
) == USB_TYPE_CLASS
)
1050 rc
= class_setup_req(fsg
, ctrl
);
1052 rc
= standard_setup_req(fsg
, ctrl
);
1054 /* Respond with data/status or defer until later? */
1055 if (rc
>= 0 && rc
!= DELAYED_STATUS
) {
1056 rc
= min(rc
, w_length
);
1057 fsg
->ep0req
->length
= rc
;
1058 fsg
->ep0req
->zero
= rc
< w_length
;
1059 fsg
->ep0req_name
= (ctrl
->bRequestType
& USB_DIR_IN
?
1060 "ep0-in" : "ep0-out");
1061 rc
= ep0_queue(fsg
);
1064 /* Device either stalls (rc < 0) or reports success */
1069 /*-------------------------------------------------------------------------*/
1071 /* All the following routines run in process context */
1074 /* Use this for bulk or interrupt transfers, not ep0 */
1075 static void start_transfer(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
1076 struct usb_request
*req
, int *pbusy
,
1077 enum fsg_buffer_state
*state
)
1081 if (ep
== fsg
->bulk_in
)
1082 dump_msg(fsg
, "bulk-in", req
->buf
, req
->length
);
1083 else if (ep
== fsg
->intr_in
)
1084 dump_msg(fsg
, "intr-in", req
->buf
, req
->length
);
1086 spin_lock_irq(&fsg
->lock
);
1088 *state
= BUF_STATE_BUSY
;
1089 spin_unlock_irq(&fsg
->lock
);
1090 rc
= usb_ep_queue(ep
, req
, GFP_KERNEL
);
1093 *state
= BUF_STATE_EMPTY
;
1095 /* We can't do much more than wait for a reset */
1097 /* Note: currently the net2280 driver fails zero-length
1098 * submissions if DMA is enabled. */
1099 if (rc
!= -ESHUTDOWN
&& !(rc
== -EOPNOTSUPP
&&
1101 WARNING(fsg
, "error in submission: %s --> %d\n",
1107 static int sleep_thread(struct fsg_dev
*fsg
)
1111 /* Wait until a signal arrives or we are woken up */
1114 set_current_state(TASK_INTERRUPTIBLE
);
1115 if (signal_pending(current
)) {
1119 if (fsg
->thread_wakeup_needed
)
1123 __set_current_state(TASK_RUNNING
);
1124 fsg
->thread_wakeup_needed
= 0;
1129 /*-------------------------------------------------------------------------*/
1131 static int do_read(struct fsg_dev
*fsg
)
1133 struct fsg_lun
*curlun
= fsg
->curlun
;
1135 struct fsg_buffhd
*bh
;
1138 loff_t file_offset
, file_offset_tmp
;
1139 unsigned int amount
;
1140 unsigned int partial_page
;
1143 /* Get the starting Logical Block Address and check that it's
1145 if (fsg
->cmnd
[0] == READ_6
)
1146 lba
= get_unaligned_be24(&fsg
->cmnd
[1]);
1148 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1150 /* We allow DPO (Disable Page Out = don't save data in the
1151 * cache) and FUA (Force Unit Access = don't read from the
1152 * cache), but we don't implement them. */
1153 if ((fsg
->cmnd
[1] & ~0x18) != 0) {
1154 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1158 if (lba
>= curlun
->num_sectors
) {
1159 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1162 file_offset
= ((loff_t
) lba
) << 9;
1164 /* Carry out the file reads */
1165 amount_left
= fsg
->data_size_from_cmnd
;
1166 if (unlikely(amount_left
== 0))
1167 return -EIO
; // No default reply
1171 /* Figure out how much we need to read:
1172 * Try to read the remaining amount.
1173 * But don't read more than the buffer size.
1174 * And don't try to read past the end of the file.
1175 * Finally, if we're not at a page boundary, don't read past
1177 * If this means reading 0 then we were asked to read past
1178 * the end of file. */
1179 amount
= min((unsigned int) amount_left
, mod_data
.buflen
);
1180 amount
= min((loff_t
) amount
,
1181 curlun
->file_length
- file_offset
);
1182 partial_page
= file_offset
& (PAGE_CACHE_SIZE
- 1);
1183 if (partial_page
> 0)
1184 amount
= min(amount
, (unsigned int) PAGE_CACHE_SIZE
-
1187 /* Wait for the next buffer to become available */
1188 bh
= fsg
->next_buffhd_to_fill
;
1189 while (bh
->state
!= BUF_STATE_EMPTY
) {
1190 rc
= sleep_thread(fsg
);
1195 /* If we were asked to read past the end of file,
1196 * end with an empty buffer. */
1198 curlun
->sense_data
=
1199 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1200 curlun
->sense_data_info
= file_offset
>> 9;
1201 curlun
->info_valid
= 1;
1202 bh
->inreq
->length
= 0;
1203 bh
->state
= BUF_STATE_FULL
;
1207 /* Perform the read */
1208 file_offset_tmp
= file_offset
;
1209 nread
= vfs_read(curlun
->filp
,
1210 (char __user
*) bh
->buf
,
1211 amount
, &file_offset_tmp
);
1212 VLDBG(curlun
, "file read %u @ %llu -> %d\n", amount
,
1213 (unsigned long long) file_offset
,
1215 if (signal_pending(current
))
1219 LDBG(curlun
, "error in file read: %d\n",
1222 } else if (nread
< amount
) {
1223 LDBG(curlun
, "partial file read: %d/%u\n",
1224 (int) nread
, amount
);
1225 nread
-= (nread
& 511); // Round down to a block
1227 file_offset
+= nread
;
1228 amount_left
-= nread
;
1229 fsg
->residue
-= nread
;
1230 bh
->inreq
->length
= nread
;
1231 bh
->state
= BUF_STATE_FULL
;
1233 /* If an error occurred, report it and its position */
1234 if (nread
< amount
) {
1235 curlun
->sense_data
= SS_UNRECOVERED_READ_ERROR
;
1236 curlun
->sense_data_info
= file_offset
>> 9;
1237 curlun
->info_valid
= 1;
1241 if (amount_left
== 0)
1242 break; // No more left to read
1244 /* Send this buffer and go read some more */
1245 bh
->inreq
->zero
= 0;
1246 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
1247 &bh
->inreq_busy
, &bh
->state
);
1248 fsg
->next_buffhd_to_fill
= bh
->next
;
1251 return -EIO
; // No default reply
1255 /*-------------------------------------------------------------------------*/
1257 static int do_write(struct fsg_dev
*fsg
)
1259 struct fsg_lun
*curlun
= fsg
->curlun
;
1261 struct fsg_buffhd
*bh
;
1263 u32 amount_left_to_req
, amount_left_to_write
;
1264 loff_t usb_offset
, file_offset
, file_offset_tmp
;
1265 unsigned int amount
;
1266 unsigned int partial_page
;
1271 curlun
->sense_data
= SS_WRITE_PROTECTED
;
1274 spin_lock(&curlun
->filp
->f_lock
);
1275 curlun
->filp
->f_flags
&= ~O_SYNC
; // Default is not to wait
1276 spin_unlock(&curlun
->filp
->f_lock
);
1278 /* Get the starting Logical Block Address and check that it's
1280 if (fsg
->cmnd
[0] == WRITE_6
)
1281 lba
= get_unaligned_be24(&fsg
->cmnd
[1]);
1283 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1285 /* We allow DPO (Disable Page Out = don't save data in the
1286 * cache) and FUA (Force Unit Access = write directly to the
1287 * medium). We don't implement DPO; we implement FUA by
1288 * performing synchronous output. */
1289 if ((fsg
->cmnd
[1] & ~0x18) != 0) {
1290 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1294 if (!curlun
->nofua
&& (fsg
->cmnd
[1] & 0x08)) {
1295 spin_lock(&curlun
->filp
->f_lock
);
1296 curlun
->filp
->f_flags
|= O_DSYNC
;
1297 spin_unlock(&curlun
->filp
->f_lock
);
1300 if (lba
>= curlun
->num_sectors
) {
1301 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1305 /* Carry out the file writes */
1307 file_offset
= usb_offset
= ((loff_t
) lba
) << 9;
1308 amount_left_to_req
= amount_left_to_write
= fsg
->data_size_from_cmnd
;
1310 while (amount_left_to_write
> 0) {
1312 /* Queue a request for more data from the host */
1313 bh
= fsg
->next_buffhd_to_fill
;
1314 if (bh
->state
== BUF_STATE_EMPTY
&& get_some_more
) {
1316 /* Figure out how much we want to get:
1317 * Try to get the remaining amount.
1318 * But don't get more than the buffer size.
1319 * And don't try to go past the end of the file.
1320 * If we're not at a page boundary,
1321 * don't go past the next page.
1322 * If this means getting 0, then we were asked
1323 * to write past the end of file.
1324 * Finally, round down to a block boundary. */
1325 amount
= min(amount_left_to_req
, mod_data
.buflen
);
1326 amount
= min((loff_t
) amount
, curlun
->file_length
-
1328 partial_page
= usb_offset
& (PAGE_CACHE_SIZE
- 1);
1329 if (partial_page
> 0)
1330 amount
= min(amount
,
1331 (unsigned int) PAGE_CACHE_SIZE
- partial_page
);
1335 curlun
->sense_data
=
1336 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1337 curlun
->sense_data_info
= usb_offset
>> 9;
1338 curlun
->info_valid
= 1;
1341 amount
-= (amount
& 511);
1344 /* Why were we were asked to transfer a
1350 /* Get the next buffer */
1351 usb_offset
+= amount
;
1352 fsg
->usb_amount_left
-= amount
;
1353 amount_left_to_req
-= amount
;
1354 if (amount_left_to_req
== 0)
1357 /* amount is always divisible by 512, hence by
1358 * the bulk-out maxpacket size */
1359 bh
->outreq
->length
= bh
->bulk_out_intended_length
=
1361 bh
->outreq
->short_not_ok
= 1;
1362 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
1363 &bh
->outreq_busy
, &bh
->state
);
1364 fsg
->next_buffhd_to_fill
= bh
->next
;
1368 /* Write the received data to the backing file */
1369 bh
= fsg
->next_buffhd_to_drain
;
1370 if (bh
->state
== BUF_STATE_EMPTY
&& !get_some_more
)
1371 break; // We stopped early
1372 if (bh
->state
== BUF_STATE_FULL
) {
1374 fsg
->next_buffhd_to_drain
= bh
->next
;
1375 bh
->state
= BUF_STATE_EMPTY
;
1377 /* Did something go wrong with the transfer? */
1378 if (bh
->outreq
->status
!= 0) {
1379 curlun
->sense_data
= SS_COMMUNICATION_FAILURE
;
1380 curlun
->sense_data_info
= file_offset
>> 9;
1381 curlun
->info_valid
= 1;
1385 amount
= bh
->outreq
->actual
;
1386 if (curlun
->file_length
- file_offset
< amount
) {
1388 "write %u @ %llu beyond end %llu\n",
1389 amount
, (unsigned long long) file_offset
,
1390 (unsigned long long) curlun
->file_length
);
1391 amount
= curlun
->file_length
- file_offset
;
1394 /* Perform the write */
1395 file_offset_tmp
= file_offset
;
1396 nwritten
= vfs_write(curlun
->filp
,
1397 (char __user
*) bh
->buf
,
1398 amount
, &file_offset_tmp
);
1399 VLDBG(curlun
, "file write %u @ %llu -> %d\n", amount
,
1400 (unsigned long long) file_offset
,
1402 if (signal_pending(current
))
1403 return -EINTR
; // Interrupted!
1406 LDBG(curlun
, "error in file write: %d\n",
1409 } else if (nwritten
< amount
) {
1410 LDBG(curlun
, "partial file write: %d/%u\n",
1411 (int) nwritten
, amount
);
1412 nwritten
-= (nwritten
& 511);
1413 // Round down to a block
1415 file_offset
+= nwritten
;
1416 amount_left_to_write
-= nwritten
;
1417 fsg
->residue
-= nwritten
;
1419 /* If an error occurred, report it and its position */
1420 if (nwritten
< amount
) {
1421 curlun
->sense_data
= SS_WRITE_ERROR
;
1422 curlun
->sense_data_info
= file_offset
>> 9;
1423 curlun
->info_valid
= 1;
1427 /* Did the host decide to stop early? */
1428 if (bh
->outreq
->actual
!= bh
->outreq
->length
) {
1429 fsg
->short_packet_received
= 1;
1435 /* Wait for something to happen */
1436 rc
= sleep_thread(fsg
);
1441 return -EIO
; // No default reply
1445 /*-------------------------------------------------------------------------*/
1447 static int do_synchronize_cache(struct fsg_dev
*fsg
)
1449 struct fsg_lun
*curlun
= fsg
->curlun
;
1452 /* We ignore the requested LBA and write out all file's
1453 * dirty data buffers. */
1454 rc
= fsg_lun_fsync_sub(curlun
);
1456 curlun
->sense_data
= SS_WRITE_ERROR
;
1461 /*-------------------------------------------------------------------------*/
1463 static void invalidate_sub(struct fsg_lun
*curlun
)
1465 struct file
*filp
= curlun
->filp
;
1466 struct inode
*inode
= filp
->f_path
.dentry
->d_inode
;
1469 rc
= invalidate_mapping_pages(inode
->i_mapping
, 0, -1);
1470 VLDBG(curlun
, "invalidate_mapping_pages -> %ld\n", rc
);
1473 static int do_verify(struct fsg_dev
*fsg
)
1475 struct fsg_lun
*curlun
= fsg
->curlun
;
1477 u32 verification_length
;
1478 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
1479 loff_t file_offset
, file_offset_tmp
;
1481 unsigned int amount
;
1484 /* Get the starting Logical Block Address and check that it's
1486 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1487 if (lba
>= curlun
->num_sectors
) {
1488 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1492 /* We allow DPO (Disable Page Out = don't save data in the
1493 * cache) but we don't implement it. */
1494 if ((fsg
->cmnd
[1] & ~0x10) != 0) {
1495 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1499 verification_length
= get_unaligned_be16(&fsg
->cmnd
[7]);
1500 if (unlikely(verification_length
== 0))
1501 return -EIO
; // No default reply
1503 /* Prepare to carry out the file verify */
1504 amount_left
= verification_length
<< 9;
1505 file_offset
= ((loff_t
) lba
) << 9;
1507 /* Write out all the dirty buffers before invalidating them */
1508 fsg_lun_fsync_sub(curlun
);
1509 if (signal_pending(current
))
1512 invalidate_sub(curlun
);
1513 if (signal_pending(current
))
1516 /* Just try to read the requested blocks */
1517 while (amount_left
> 0) {
1519 /* Figure out how much we need to read:
1520 * Try to read the remaining amount, but not more than
1522 * And don't try to read past the end of the file.
1523 * If this means reading 0 then we were asked to read
1524 * past the end of file. */
1525 amount
= min((unsigned int) amount_left
, mod_data
.buflen
);
1526 amount
= min((loff_t
) amount
,
1527 curlun
->file_length
- file_offset
);
1529 curlun
->sense_data
=
1530 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1531 curlun
->sense_data_info
= file_offset
>> 9;
1532 curlun
->info_valid
= 1;
1536 /* Perform the read */
1537 file_offset_tmp
= file_offset
;
1538 nread
= vfs_read(curlun
->filp
,
1539 (char __user
*) bh
->buf
,
1540 amount
, &file_offset_tmp
);
1541 VLDBG(curlun
, "file read %u @ %llu -> %d\n", amount
,
1542 (unsigned long long) file_offset
,
1544 if (signal_pending(current
))
1548 LDBG(curlun
, "error in file verify: %d\n",
1551 } else if (nread
< amount
) {
1552 LDBG(curlun
, "partial file verify: %d/%u\n",
1553 (int) nread
, amount
);
1554 nread
-= (nread
& 511); // Round down to a sector
1557 curlun
->sense_data
= SS_UNRECOVERED_READ_ERROR
;
1558 curlun
->sense_data_info
= file_offset
>> 9;
1559 curlun
->info_valid
= 1;
1562 file_offset
+= nread
;
1563 amount_left
-= nread
;
1569 /*-------------------------------------------------------------------------*/
1571 static int do_inquiry(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1573 u8
*buf
= (u8
*) bh
->buf
;
1575 static char vendor_id
[] = "Linux ";
1576 static char product_disk_id
[] = "File-Stor Gadget";
1577 static char product_cdrom_id
[] = "File-CD Gadget ";
1579 if (!fsg
->curlun
) { // Unsupported LUNs are okay
1580 fsg
->bad_lun_okay
= 1;
1582 buf
[0] = 0x7f; // Unsupported, no device-type
1583 buf
[4] = 31; // Additional length
1588 buf
[0] = (mod_data
.cdrom
? TYPE_ROM
: TYPE_DISK
);
1589 if (mod_data
.removable
)
1591 buf
[2] = 2; // ANSI SCSI level 2
1592 buf
[3] = 2; // SCSI-2 INQUIRY data format
1593 buf
[4] = 31; // Additional length
1594 // No special options
1595 sprintf(buf
+ 8, "%-8s%-16s%04x", vendor_id
,
1596 (mod_data
.cdrom
? product_cdrom_id
:
1603 static int do_request_sense(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1605 struct fsg_lun
*curlun
= fsg
->curlun
;
1606 u8
*buf
= (u8
*) bh
->buf
;
1611 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1613 * If a REQUEST SENSE command is received from an initiator
1614 * with a pending unit attention condition (before the target
1615 * generates the contingent allegiance condition), then the
1616 * target shall either:
1617 * a) report any pending sense data and preserve the unit
1618 * attention condition on the logical unit, or,
1619 * b) report the unit attention condition, may discard any
1620 * pending sense data, and clear the unit attention
1621 * condition on the logical unit for that initiator.
1623 * FSG normally uses option a); enable this code to use option b).
1626 if (curlun
&& curlun
->unit_attention_data
!= SS_NO_SENSE
) {
1627 curlun
->sense_data
= curlun
->unit_attention_data
;
1628 curlun
->unit_attention_data
= SS_NO_SENSE
;
1632 if (!curlun
) { // Unsupported LUNs are okay
1633 fsg
->bad_lun_okay
= 1;
1634 sd
= SS_LOGICAL_UNIT_NOT_SUPPORTED
;
1638 sd
= curlun
->sense_data
;
1639 sdinfo
= curlun
->sense_data_info
;
1640 valid
= curlun
->info_valid
<< 7;
1641 curlun
->sense_data
= SS_NO_SENSE
;
1642 curlun
->sense_data_info
= 0;
1643 curlun
->info_valid
= 0;
1647 buf
[0] = valid
| 0x70; // Valid, current error
1649 put_unaligned_be32(sdinfo
, &buf
[3]); /* Sense information */
1650 buf
[7] = 18 - 8; // Additional sense length
1657 static int do_read_capacity(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1659 struct fsg_lun
*curlun
= fsg
->curlun
;
1660 u32 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1661 int pmi
= fsg
->cmnd
[8];
1662 u8
*buf
= (u8
*) bh
->buf
;
1664 /* Check the PMI and LBA fields */
1665 if (pmi
> 1 || (pmi
== 0 && lba
!= 0)) {
1666 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1670 put_unaligned_be32(curlun
->num_sectors
- 1, &buf
[0]);
1671 /* Max logical block */
1672 put_unaligned_be32(512, &buf
[4]); /* Block length */
1677 static int do_read_header(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1679 struct fsg_lun
*curlun
= fsg
->curlun
;
1680 int msf
= fsg
->cmnd
[1] & 0x02;
1681 u32 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1682 u8
*buf
= (u8
*) bh
->buf
;
1684 if ((fsg
->cmnd
[1] & ~0x02) != 0) { /* Mask away MSF */
1685 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1688 if (lba
>= curlun
->num_sectors
) {
1689 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1694 buf
[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1695 store_cdrom_address(&buf
[4], msf
, lba
);
1700 static int do_read_toc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1702 struct fsg_lun
*curlun
= fsg
->curlun
;
1703 int msf
= fsg
->cmnd
[1] & 0x02;
1704 int start_track
= fsg
->cmnd
[6];
1705 u8
*buf
= (u8
*) bh
->buf
;
1707 if ((fsg
->cmnd
[1] & ~0x02) != 0 || /* Mask away MSF */
1709 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1714 buf
[1] = (20-2); /* TOC data length */
1715 buf
[2] = 1; /* First track number */
1716 buf
[3] = 1; /* Last track number */
1717 buf
[5] = 0x16; /* Data track, copying allowed */
1718 buf
[6] = 0x01; /* Only track is number 1 */
1719 store_cdrom_address(&buf
[8], msf
, 0);
1721 buf
[13] = 0x16; /* Lead-out track is data */
1722 buf
[14] = 0xAA; /* Lead-out track number */
1723 store_cdrom_address(&buf
[16], msf
, curlun
->num_sectors
);
1728 static int do_mode_sense(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1730 struct fsg_lun
*curlun
= fsg
->curlun
;
1731 int mscmnd
= fsg
->cmnd
[0];
1732 u8
*buf
= (u8
*) bh
->buf
;
1735 int changeable_values
, all_pages
;
1739 if ((fsg
->cmnd
[1] & ~0x08) != 0) { // Mask away DBD
1740 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1743 pc
= fsg
->cmnd
[2] >> 6;
1744 page_code
= fsg
->cmnd
[2] & 0x3f;
1746 curlun
->sense_data
= SS_SAVING_PARAMETERS_NOT_SUPPORTED
;
1749 changeable_values
= (pc
== 1);
1750 all_pages
= (page_code
== 0x3f);
1752 /* Write the mode parameter header. Fixed values are: default
1753 * medium type, no cache control (DPOFUA), and no block descriptors.
1754 * The only variable value is the WriteProtect bit. We will fill in
1755 * the mode data length later. */
1757 if (mscmnd
== MODE_SENSE
) {
1758 buf
[2] = (curlun
->ro
? 0x80 : 0x00); // WP, DPOFUA
1761 } else { // MODE_SENSE_10
1762 buf
[3] = (curlun
->ro
? 0x80 : 0x00); // WP, DPOFUA
1764 limit
= 65535; // Should really be mod_data.buflen
1767 /* No block descriptors */
1769 /* The mode pages, in numerical order. The only page we support
1770 * is the Caching page. */
1771 if (page_code
== 0x08 || all_pages
) {
1773 buf
[0] = 0x08; // Page code
1774 buf
[1] = 10; // Page length
1775 memset(buf
+2, 0, 10); // None of the fields are changeable
1777 if (!changeable_values
) {
1778 buf
[2] = 0x04; // Write cache enable,
1779 // Read cache not disabled
1780 // No cache retention priorities
1781 put_unaligned_be16(0xffff, &buf
[4]);
1782 /* Don't disable prefetch */
1783 /* Minimum prefetch = 0 */
1784 put_unaligned_be16(0xffff, &buf
[8]);
1785 /* Maximum prefetch */
1786 put_unaligned_be16(0xffff, &buf
[10]);
1787 /* Maximum prefetch ceiling */
1792 /* Check that a valid page was requested and the mode data length
1793 * isn't too long. */
1795 if (!valid_page
|| len
> limit
) {
1796 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1800 /* Store the mode data length */
1801 if (mscmnd
== MODE_SENSE
)
1804 put_unaligned_be16(len
- 2, buf0
);
1809 static int do_start_stop(struct fsg_dev
*fsg
)
1811 struct fsg_lun
*curlun
= fsg
->curlun
;
1814 if (!mod_data
.removable
) {
1815 curlun
->sense_data
= SS_INVALID_COMMAND
;
1819 // int immed = fsg->cmnd[1] & 0x01;
1820 loej
= fsg
->cmnd
[4] & 0x02;
1821 start
= fsg
->cmnd
[4] & 0x01;
1823 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1824 if ((fsg
->cmnd
[1] & ~0x01) != 0 || // Mask away Immed
1825 (fsg
->cmnd
[4] & ~0x03) != 0) { // Mask LoEj, Start
1826 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1832 /* Are we allowed to unload the media? */
1833 if (curlun
->prevent_medium_removal
) {
1834 LDBG(curlun
, "unload attempt prevented\n");
1835 curlun
->sense_data
= SS_MEDIUM_REMOVAL_PREVENTED
;
1838 if (loej
) { // Simulate an unload/eject
1839 up_read(&fsg
->filesem
);
1840 down_write(&fsg
->filesem
);
1841 fsg_lun_close(curlun
);
1842 up_write(&fsg
->filesem
);
1843 down_read(&fsg
->filesem
);
1847 /* Our emulation doesn't support mounting; the medium is
1848 * available for use as soon as it is loaded. */
1849 if (!fsg_lun_is_open(curlun
)) {
1850 curlun
->sense_data
= SS_MEDIUM_NOT_PRESENT
;
1859 static int do_prevent_allow(struct fsg_dev
*fsg
)
1861 struct fsg_lun
*curlun
= fsg
->curlun
;
1864 if (!mod_data
.removable
) {
1865 curlun
->sense_data
= SS_INVALID_COMMAND
;
1869 prevent
= fsg
->cmnd
[4] & 0x01;
1870 if ((fsg
->cmnd
[4] & ~0x01) != 0) { // Mask away Prevent
1871 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1875 if (curlun
->prevent_medium_removal
&& !prevent
)
1876 fsg_lun_fsync_sub(curlun
);
1877 curlun
->prevent_medium_removal
= prevent
;
1882 static int do_read_format_capacities(struct fsg_dev
*fsg
,
1883 struct fsg_buffhd
*bh
)
1885 struct fsg_lun
*curlun
= fsg
->curlun
;
1886 u8
*buf
= (u8
*) bh
->buf
;
1888 buf
[0] = buf
[1] = buf
[2] = 0;
1889 buf
[3] = 8; // Only the Current/Maximum Capacity Descriptor
1892 put_unaligned_be32(curlun
->num_sectors
, &buf
[0]);
1893 /* Number of blocks */
1894 put_unaligned_be32(512, &buf
[4]); /* Block length */
1895 buf
[4] = 0x02; /* Current capacity */
1900 static int do_mode_select(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1902 struct fsg_lun
*curlun
= fsg
->curlun
;
1904 /* We don't support MODE SELECT */
1905 curlun
->sense_data
= SS_INVALID_COMMAND
;
1910 /*-------------------------------------------------------------------------*/
1912 static int halt_bulk_in_endpoint(struct fsg_dev
*fsg
)
1916 rc
= fsg_set_halt(fsg
, fsg
->bulk_in
);
1918 VDBG(fsg
, "delayed bulk-in endpoint halt\n");
1920 if (rc
!= -EAGAIN
) {
1921 WARNING(fsg
, "usb_ep_set_halt -> %d\n", rc
);
1926 /* Wait for a short time and then try again */
1927 if (msleep_interruptible(100) != 0)
1929 rc
= usb_ep_set_halt(fsg
->bulk_in
);
1934 static int wedge_bulk_in_endpoint(struct fsg_dev
*fsg
)
1938 DBG(fsg
, "bulk-in set wedge\n");
1939 rc
= usb_ep_set_wedge(fsg
->bulk_in
);
1941 VDBG(fsg
, "delayed bulk-in endpoint wedge\n");
1943 if (rc
!= -EAGAIN
) {
1944 WARNING(fsg
, "usb_ep_set_wedge -> %d\n", rc
);
1949 /* Wait for a short time and then try again */
1950 if (msleep_interruptible(100) != 0)
1952 rc
= usb_ep_set_wedge(fsg
->bulk_in
);
1957 static int throw_away_data(struct fsg_dev
*fsg
)
1959 struct fsg_buffhd
*bh
;
1963 while ((bh
= fsg
->next_buffhd_to_drain
)->state
!= BUF_STATE_EMPTY
||
1964 fsg
->usb_amount_left
> 0) {
1966 /* Throw away the data in a filled buffer */
1967 if (bh
->state
== BUF_STATE_FULL
) {
1969 bh
->state
= BUF_STATE_EMPTY
;
1970 fsg
->next_buffhd_to_drain
= bh
->next
;
1972 /* A short packet or an error ends everything */
1973 if (bh
->outreq
->actual
!= bh
->outreq
->length
||
1974 bh
->outreq
->status
!= 0) {
1975 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
1981 /* Try to submit another request if we need one */
1982 bh
= fsg
->next_buffhd_to_fill
;
1983 if (bh
->state
== BUF_STATE_EMPTY
&& fsg
->usb_amount_left
> 0) {
1984 amount
= min(fsg
->usb_amount_left
,
1985 (u32
) mod_data
.buflen
);
1987 /* amount is always divisible by 512, hence by
1988 * the bulk-out maxpacket size */
1989 bh
->outreq
->length
= bh
->bulk_out_intended_length
=
1991 bh
->outreq
->short_not_ok
= 1;
1992 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
1993 &bh
->outreq_busy
, &bh
->state
);
1994 fsg
->next_buffhd_to_fill
= bh
->next
;
1995 fsg
->usb_amount_left
-= amount
;
1999 /* Otherwise wait for something to happen */
2000 rc
= sleep_thread(fsg
);
2008 static int finish_reply(struct fsg_dev
*fsg
)
2010 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
2013 switch (fsg
->data_dir
) {
2015 break; // Nothing to send
2017 /* If we don't know whether the host wants to read or write,
2018 * this must be CB or CBI with an unknown command. We mustn't
2019 * try to send or receive any data. So stall both bulk pipes
2020 * if we can and wait for a reset. */
2021 case DATA_DIR_UNKNOWN
:
2022 if (mod_data
.can_stall
) {
2023 fsg_set_halt(fsg
, fsg
->bulk_out
);
2024 rc
= halt_bulk_in_endpoint(fsg
);
2028 /* All but the last buffer of data must have already been sent */
2029 case DATA_DIR_TO_HOST
:
2030 if (fsg
->data_size
== 0)
2031 ; // Nothing to send
2033 /* If there's no residue, simply send the last buffer */
2034 else if (fsg
->residue
== 0) {
2035 bh
->inreq
->zero
= 0;
2036 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2037 &bh
->inreq_busy
, &bh
->state
);
2038 fsg
->next_buffhd_to_fill
= bh
->next
;
2041 /* There is a residue. For CB and CBI, simply mark the end
2042 * of the data with a short packet. However, if we are
2043 * allowed to stall, there was no data at all (residue ==
2044 * data_size), and the command failed (invalid LUN or
2045 * sense data is set), then halt the bulk-in endpoint
2047 else if (!transport_is_bbb()) {
2048 if (mod_data
.can_stall
&&
2049 fsg
->residue
== fsg
->data_size
&&
2050 (!fsg
->curlun
|| fsg
->curlun
->sense_data
!= SS_NO_SENSE
)) {
2051 bh
->state
= BUF_STATE_EMPTY
;
2052 rc
= halt_bulk_in_endpoint(fsg
);
2054 bh
->inreq
->zero
= 1;
2055 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2056 &bh
->inreq_busy
, &bh
->state
);
2057 fsg
->next_buffhd_to_fill
= bh
->next
;
2062 * For Bulk-only, mark the end of the data with a short
2063 * packet. If we are allowed to stall, halt the bulk-in
2064 * endpoint. (Note: This violates the Bulk-Only Transport
2065 * specification, which requires us to pad the data if we
2066 * don't halt the endpoint. Presumably nobody will mind.)
2069 bh
->inreq
->zero
= 1;
2070 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2071 &bh
->inreq_busy
, &bh
->state
);
2072 fsg
->next_buffhd_to_fill
= bh
->next
;
2073 if (mod_data
.can_stall
)
2074 rc
= halt_bulk_in_endpoint(fsg
);
2078 /* We have processed all we want from the data the host has sent.
2079 * There may still be outstanding bulk-out requests. */
2080 case DATA_DIR_FROM_HOST
:
2081 if (fsg
->residue
== 0)
2082 ; // Nothing to receive
2084 /* Did the host stop sending unexpectedly early? */
2085 else if (fsg
->short_packet_received
) {
2086 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2090 /* We haven't processed all the incoming data. Even though
2091 * we may be allowed to stall, doing so would cause a race.
2092 * The controller may already have ACK'ed all the remaining
2093 * bulk-out packets, in which case the host wouldn't see a
2094 * STALL. Not realizing the endpoint was halted, it wouldn't
2095 * clear the halt -- leading to problems later on. */
2097 else if (mod_data
.can_stall
) {
2098 fsg_set_halt(fsg
, fsg
->bulk_out
);
2099 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2104 /* We can't stall. Read in the excess data and throw it
2107 rc
= throw_away_data(fsg
);
2114 static int send_status(struct fsg_dev
*fsg
)
2116 struct fsg_lun
*curlun
= fsg
->curlun
;
2117 struct fsg_buffhd
*bh
;
2119 u8 status
= USB_STATUS_PASS
;
2122 /* Wait for the next buffer to become available */
2123 bh
= fsg
->next_buffhd_to_fill
;
2124 while (bh
->state
!= BUF_STATE_EMPTY
) {
2125 rc
= sleep_thread(fsg
);
2131 sd
= curlun
->sense_data
;
2132 sdinfo
= curlun
->sense_data_info
;
2133 } else if (fsg
->bad_lun_okay
)
2136 sd
= SS_LOGICAL_UNIT_NOT_SUPPORTED
;
2138 if (fsg
->phase_error
) {
2139 DBG(fsg
, "sending phase-error status\n");
2140 status
= USB_STATUS_PHASE_ERROR
;
2141 sd
= SS_INVALID_COMMAND
;
2142 } else if (sd
!= SS_NO_SENSE
) {
2143 DBG(fsg
, "sending command-failure status\n");
2144 status
= USB_STATUS_FAIL
;
2145 VDBG(fsg
, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2147 SK(sd
), ASC(sd
), ASCQ(sd
), sdinfo
);
2150 if (transport_is_bbb()) {
2151 struct bulk_cs_wrap
*csw
= bh
->buf
;
2153 /* Store and send the Bulk-only CSW */
2154 csw
->Signature
= cpu_to_le32(USB_BULK_CS_SIG
);
2155 csw
->Tag
= fsg
->tag
;
2156 csw
->Residue
= cpu_to_le32(fsg
->residue
);
2157 csw
->Status
= status
;
2159 bh
->inreq
->length
= USB_BULK_CS_WRAP_LEN
;
2160 bh
->inreq
->zero
= 0;
2161 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2162 &bh
->inreq_busy
, &bh
->state
);
2164 } else if (mod_data
.transport_type
== USB_PR_CB
) {
2166 /* Control-Bulk transport has no status phase! */
2169 } else { // USB_PR_CBI
2170 struct interrupt_data
*buf
= bh
->buf
;
2172 /* Store and send the Interrupt data. UFI sends the ASC
2173 * and ASCQ bytes. Everything else sends a Type (which
2174 * is always 0) and the status Value. */
2175 if (mod_data
.protocol_type
== USB_SC_UFI
) {
2176 buf
->bType
= ASC(sd
);
2177 buf
->bValue
= ASCQ(sd
);
2180 buf
->bValue
= status
;
2182 fsg
->intreq
->length
= CBI_INTERRUPT_DATA_LEN
;
2184 fsg
->intr_buffhd
= bh
; // Point to the right buffhd
2185 fsg
->intreq
->buf
= bh
->inreq
->buf
;
2186 fsg
->intreq
->context
= bh
;
2187 start_transfer(fsg
, fsg
->intr_in
, fsg
->intreq
,
2188 &fsg
->intreq_busy
, &bh
->state
);
2191 fsg
->next_buffhd_to_fill
= bh
->next
;
2196 /*-------------------------------------------------------------------------*/
2198 /* Check whether the command is properly formed and whether its data size
2199 * and direction agree with the values we already have. */
2200 static int check_command(struct fsg_dev
*fsg
, int cmnd_size
,
2201 enum data_direction data_dir
, unsigned int mask
,
2202 int needs_medium
, const char *name
)
2205 int lun
= fsg
->cmnd
[1] >> 5;
2206 static const char dirletter
[4] = {'u', 'o', 'i', 'n'};
2208 struct fsg_lun
*curlun
;
2210 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2211 * Transparent SCSI doesn't pad. */
2212 if (protocol_is_scsi())
2215 /* There's some disagreement as to whether RBC pads commands or not.
2216 * We'll play it safe and accept either form. */
2217 else if (mod_data
.protocol_type
== USB_SC_RBC
) {
2218 if (fsg
->cmnd_size
== 12)
2221 /* All the other protocols pad to 12 bytes */
2226 if (fsg
->data_dir
!= DATA_DIR_UNKNOWN
)
2227 sprintf(hdlen
, ", H%c=%u", dirletter
[(int) fsg
->data_dir
],
2229 VDBG(fsg
, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2230 name
, cmnd_size
, dirletter
[(int) data_dir
],
2231 fsg
->data_size_from_cmnd
, fsg
->cmnd_size
, hdlen
);
2233 /* We can't reply at all until we know the correct data direction
2235 if (fsg
->data_size_from_cmnd
== 0)
2236 data_dir
= DATA_DIR_NONE
;
2237 if (fsg
->data_dir
== DATA_DIR_UNKNOWN
) { // CB or CBI
2238 fsg
->data_dir
= data_dir
;
2239 fsg
->data_size
= fsg
->data_size_from_cmnd
;
2241 } else { // Bulk-only
2242 if (fsg
->data_size
< fsg
->data_size_from_cmnd
) {
2244 /* Host data size < Device data size is a phase error.
2245 * Carry out the command, but only transfer as much
2246 * as we are allowed. */
2247 fsg
->data_size_from_cmnd
= fsg
->data_size
;
2248 fsg
->phase_error
= 1;
2251 fsg
->residue
= fsg
->usb_amount_left
= fsg
->data_size
;
2253 /* Conflicting data directions is a phase error */
2254 if (fsg
->data_dir
!= data_dir
&& fsg
->data_size_from_cmnd
> 0) {
2255 fsg
->phase_error
= 1;
2259 /* Verify the length of the command itself */
2260 if (cmnd_size
!= fsg
->cmnd_size
) {
2262 /* Special case workaround: There are plenty of buggy SCSI
2263 * implementations. Many have issues with cbw->Length
2264 * field passing a wrong command size. For those cases we
2265 * always try to work around the problem by using the length
2266 * sent by the host side provided it is at least as large
2267 * as the correct command length.
2268 * Examples of such cases would be MS-Windows, which issues
2269 * REQUEST SENSE with cbw->Length == 12 where it should
2270 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2271 * REQUEST SENSE with cbw->Length == 10 where it should
2274 if (cmnd_size
<= fsg
->cmnd_size
) {
2275 DBG(fsg
, "%s is buggy! Expected length %d "
2276 "but we got %d\n", name
,
2277 cmnd_size
, fsg
->cmnd_size
);
2278 cmnd_size
= fsg
->cmnd_size
;
2280 fsg
->phase_error
= 1;
2285 /* Check that the LUN values are consistent */
2286 if (transport_is_bbb()) {
2287 if (fsg
->lun
!= lun
)
2288 DBG(fsg
, "using LUN %d from CBW, "
2289 "not LUN %d from CDB\n",
2292 fsg
->lun
= lun
; // Use LUN from the command
2295 if (fsg
->lun
< fsg
->nluns
) {
2296 fsg
->curlun
= curlun
= &fsg
->luns
[fsg
->lun
];
2297 if (fsg
->cmnd
[0] != REQUEST_SENSE
) {
2298 curlun
->sense_data
= SS_NO_SENSE
;
2299 curlun
->sense_data_info
= 0;
2300 curlun
->info_valid
= 0;
2303 fsg
->curlun
= curlun
= NULL
;
2304 fsg
->bad_lun_okay
= 0;
2306 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2307 * to use unsupported LUNs; all others may not. */
2308 if (fsg
->cmnd
[0] != INQUIRY
&&
2309 fsg
->cmnd
[0] != REQUEST_SENSE
) {
2310 DBG(fsg
, "unsupported LUN %d\n", fsg
->lun
);
2315 /* If a unit attention condition exists, only INQUIRY and
2316 * REQUEST SENSE commands are allowed; anything else must fail. */
2317 if (curlun
&& curlun
->unit_attention_data
!= SS_NO_SENSE
&&
2318 fsg
->cmnd
[0] != INQUIRY
&&
2319 fsg
->cmnd
[0] != REQUEST_SENSE
) {
2320 curlun
->sense_data
= curlun
->unit_attention_data
;
2321 curlun
->unit_attention_data
= SS_NO_SENSE
;
2325 /* Check that only command bytes listed in the mask are non-zero */
2326 fsg
->cmnd
[1] &= 0x1f; // Mask away the LUN
2327 for (i
= 1; i
< cmnd_size
; ++i
) {
2328 if (fsg
->cmnd
[i
] && !(mask
& (1 << i
))) {
2330 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2335 /* If the medium isn't mounted and the command needs to access
2336 * it, return an error. */
2337 if (curlun
&& !fsg_lun_is_open(curlun
) && needs_medium
) {
2338 curlun
->sense_data
= SS_MEDIUM_NOT_PRESENT
;
2346 static int do_scsi_command(struct fsg_dev
*fsg
)
2348 struct fsg_buffhd
*bh
;
2350 int reply
= -EINVAL
;
2352 static char unknown
[16];
2356 /* Wait for the next buffer to become available for data or status */
2357 bh
= fsg
->next_buffhd_to_drain
= fsg
->next_buffhd_to_fill
;
2358 while (bh
->state
!= BUF_STATE_EMPTY
) {
2359 rc
= sleep_thread(fsg
);
2363 fsg
->phase_error
= 0;
2364 fsg
->short_packet_received
= 0;
2366 down_read(&fsg
->filesem
); // We're using the backing file
2367 switch (fsg
->cmnd
[0]) {
2370 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2371 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2374 reply
= do_inquiry(fsg
, bh
);
2378 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2379 if ((reply
= check_command(fsg
, 6, DATA_DIR_FROM_HOST
,
2381 "MODE SELECT(6)")) == 0)
2382 reply
= do_mode_select(fsg
, bh
);
2385 case MODE_SELECT_10
:
2386 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2387 if ((reply
= check_command(fsg
, 10, DATA_DIR_FROM_HOST
,
2389 "MODE SELECT(10)")) == 0)
2390 reply
= do_mode_select(fsg
, bh
);
2394 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2395 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2396 (1<<1) | (1<<2) | (1<<4), 0,
2397 "MODE SENSE(6)")) == 0)
2398 reply
= do_mode_sense(fsg
, bh
);
2402 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2403 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2404 (1<<1) | (1<<2) | (3<<7), 0,
2405 "MODE SENSE(10)")) == 0)
2406 reply
= do_mode_sense(fsg
, bh
);
2409 case ALLOW_MEDIUM_REMOVAL
:
2410 fsg
->data_size_from_cmnd
= 0;
2411 if ((reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2413 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2414 reply
= do_prevent_allow(fsg
);
2419 fsg
->data_size_from_cmnd
= (i
== 0 ? 256 : i
) << 9;
2420 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2423 reply
= do_read(fsg
);
2427 fsg
->data_size_from_cmnd
=
2428 get_unaligned_be16(&fsg
->cmnd
[7]) << 9;
2429 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2430 (1<<1) | (0xf<<2) | (3<<7), 1,
2432 reply
= do_read(fsg
);
2436 fsg
->data_size_from_cmnd
=
2437 get_unaligned_be32(&fsg
->cmnd
[6]) << 9;
2438 if ((reply
= check_command(fsg
, 12, DATA_DIR_TO_HOST
,
2439 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2441 reply
= do_read(fsg
);
2445 fsg
->data_size_from_cmnd
= 8;
2446 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2447 (0xf<<2) | (1<<8), 1,
2448 "READ CAPACITY")) == 0)
2449 reply
= do_read_capacity(fsg
, bh
);
2453 if (!mod_data
.cdrom
)
2455 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2456 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2457 (3<<7) | (0x1f<<1), 1,
2458 "READ HEADER")) == 0)
2459 reply
= do_read_header(fsg
, bh
);
2463 if (!mod_data
.cdrom
)
2465 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2466 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2469 reply
= do_read_toc(fsg
, bh
);
2472 case READ_FORMAT_CAPACITIES
:
2473 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2474 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2476 "READ FORMAT CAPACITIES")) == 0)
2477 reply
= do_read_format_capacities(fsg
, bh
);
2481 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2482 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2484 "REQUEST SENSE")) == 0)
2485 reply
= do_request_sense(fsg
, bh
);
2489 fsg
->data_size_from_cmnd
= 0;
2490 if ((reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2492 "START-STOP UNIT")) == 0)
2493 reply
= do_start_stop(fsg
);
2496 case SYNCHRONIZE_CACHE
:
2497 fsg
->data_size_from_cmnd
= 0;
2498 if ((reply
= check_command(fsg
, 10, DATA_DIR_NONE
,
2499 (0xf<<2) | (3<<7), 1,
2500 "SYNCHRONIZE CACHE")) == 0)
2501 reply
= do_synchronize_cache(fsg
);
2504 case TEST_UNIT_READY
:
2505 fsg
->data_size_from_cmnd
= 0;
2506 reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2511 /* Although optional, this command is used by MS-Windows. We
2512 * support a minimal version: BytChk must be 0. */
2514 fsg
->data_size_from_cmnd
= 0;
2515 if ((reply
= check_command(fsg
, 10, DATA_DIR_NONE
,
2516 (1<<1) | (0xf<<2) | (3<<7), 1,
2518 reply
= do_verify(fsg
);
2523 fsg
->data_size_from_cmnd
= (i
== 0 ? 256 : i
) << 9;
2524 if ((reply
= check_command(fsg
, 6, DATA_DIR_FROM_HOST
,
2527 reply
= do_write(fsg
);
2531 fsg
->data_size_from_cmnd
=
2532 get_unaligned_be16(&fsg
->cmnd
[7]) << 9;
2533 if ((reply
= check_command(fsg
, 10, DATA_DIR_FROM_HOST
,
2534 (1<<1) | (0xf<<2) | (3<<7), 1,
2536 reply
= do_write(fsg
);
2540 fsg
->data_size_from_cmnd
=
2541 get_unaligned_be32(&fsg
->cmnd
[6]) << 9;
2542 if ((reply
= check_command(fsg
, 12, DATA_DIR_FROM_HOST
,
2543 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2545 reply
= do_write(fsg
);
2548 /* Some mandatory commands that we recognize but don't implement.
2549 * They don't mean much in this setting. It's left as an exercise
2550 * for anyone interested to implement RESERVE and RELEASE in terms
2551 * of Posix locks. */
2555 case SEND_DIAGNOSTIC
:
2560 fsg
->data_size_from_cmnd
= 0;
2561 sprintf(unknown
, "Unknown x%02x", fsg
->cmnd
[0]);
2562 if ((reply
= check_command(fsg
, fsg
->cmnd_size
,
2563 DATA_DIR_UNKNOWN
, 0xff, 0, unknown
)) == 0) {
2564 fsg
->curlun
->sense_data
= SS_INVALID_COMMAND
;
2569 up_read(&fsg
->filesem
);
2571 if (reply
== -EINTR
|| signal_pending(current
))
2574 /* Set up the single reply buffer for finish_reply() */
2575 if (reply
== -EINVAL
)
2576 reply
= 0; // Error reply length
2577 if (reply
>= 0 && fsg
->data_dir
== DATA_DIR_TO_HOST
) {
2578 reply
= min((u32
) reply
, fsg
->data_size_from_cmnd
);
2579 bh
->inreq
->length
= reply
;
2580 bh
->state
= BUF_STATE_FULL
;
2581 fsg
->residue
-= reply
;
2582 } // Otherwise it's already set
2588 /*-------------------------------------------------------------------------*/
2590 static int received_cbw(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2592 struct usb_request
*req
= bh
->outreq
;
2593 struct fsg_bulk_cb_wrap
*cbw
= req
->buf
;
2595 /* Was this a real packet? Should it be ignored? */
2596 if (req
->status
|| test_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
))
2599 /* Is the CBW valid? */
2600 if (req
->actual
!= USB_BULK_CB_WRAP_LEN
||
2601 cbw
->Signature
!= cpu_to_le32(
2603 DBG(fsg
, "invalid CBW: len %u sig 0x%x\n",
2605 le32_to_cpu(cbw
->Signature
));
2607 /* The Bulk-only spec says we MUST stall the IN endpoint
2608 * (6.6.1), so it's unavoidable. It also says we must
2609 * retain this state until the next reset, but there's
2610 * no way to tell the controller driver it should ignore
2611 * Clear-Feature(HALT) requests.
2613 * We aren't required to halt the OUT endpoint; instead
2614 * we can simply accept and discard any data received
2615 * until the next reset. */
2616 wedge_bulk_in_endpoint(fsg
);
2617 set_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
);
2621 /* Is the CBW meaningful? */
2622 if (cbw
->Lun
>= FSG_MAX_LUNS
|| cbw
->Flags
& ~USB_BULK_IN_FLAG
||
2623 cbw
->Length
<= 0 || cbw
->Length
> MAX_COMMAND_SIZE
) {
2624 DBG(fsg
, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2626 cbw
->Lun
, cbw
->Flags
, cbw
->Length
);
2628 /* We can do anything we want here, so let's stall the
2629 * bulk pipes if we are allowed to. */
2630 if (mod_data
.can_stall
) {
2631 fsg_set_halt(fsg
, fsg
->bulk_out
);
2632 halt_bulk_in_endpoint(fsg
);
2637 /* Save the command for later */
2638 fsg
->cmnd_size
= cbw
->Length
;
2639 memcpy(fsg
->cmnd
, cbw
->CDB
, fsg
->cmnd_size
);
2640 if (cbw
->Flags
& USB_BULK_IN_FLAG
)
2641 fsg
->data_dir
= DATA_DIR_TO_HOST
;
2643 fsg
->data_dir
= DATA_DIR_FROM_HOST
;
2644 fsg
->data_size
= le32_to_cpu(cbw
->DataTransferLength
);
2645 if (fsg
->data_size
== 0)
2646 fsg
->data_dir
= DATA_DIR_NONE
;
2647 fsg
->lun
= cbw
->Lun
;
2648 fsg
->tag
= cbw
->Tag
;
2653 static int get_next_command(struct fsg_dev
*fsg
)
2655 struct fsg_buffhd
*bh
;
2658 if (transport_is_bbb()) {
2660 /* Wait for the next buffer to become available */
2661 bh
= fsg
->next_buffhd_to_fill
;
2662 while (bh
->state
!= BUF_STATE_EMPTY
) {
2663 rc
= sleep_thread(fsg
);
2668 /* Queue a request to read a Bulk-only CBW */
2669 set_bulk_out_req_length(fsg
, bh
, USB_BULK_CB_WRAP_LEN
);
2670 bh
->outreq
->short_not_ok
= 1;
2671 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
2672 &bh
->outreq_busy
, &bh
->state
);
2674 /* We will drain the buffer in software, which means we
2675 * can reuse it for the next filling. No need to advance
2676 * next_buffhd_to_fill. */
2678 /* Wait for the CBW to arrive */
2679 while (bh
->state
!= BUF_STATE_FULL
) {
2680 rc
= sleep_thread(fsg
);
2685 rc
= received_cbw(fsg
, bh
);
2686 bh
->state
= BUF_STATE_EMPTY
;
2688 } else { // USB_PR_CB or USB_PR_CBI
2690 /* Wait for the next command to arrive */
2691 while (fsg
->cbbuf_cmnd_size
== 0) {
2692 rc
= sleep_thread(fsg
);
2697 /* Is the previous status interrupt request still busy?
2698 * The host is allowed to skip reading the status,
2699 * so we must cancel it. */
2700 if (fsg
->intreq_busy
)
2701 usb_ep_dequeue(fsg
->intr_in
, fsg
->intreq
);
2703 /* Copy the command and mark the buffer empty */
2704 fsg
->data_dir
= DATA_DIR_UNKNOWN
;
2705 spin_lock_irq(&fsg
->lock
);
2706 fsg
->cmnd_size
= fsg
->cbbuf_cmnd_size
;
2707 memcpy(fsg
->cmnd
, fsg
->cbbuf_cmnd
, fsg
->cmnd_size
);
2708 fsg
->cbbuf_cmnd_size
= 0;
2709 spin_unlock_irq(&fsg
->lock
);
2715 /*-------------------------------------------------------------------------*/
2717 static int enable_endpoint(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
2718 const struct usb_endpoint_descriptor
*d
)
2722 ep
->driver_data
= fsg
;
2724 rc
= usb_ep_enable(ep
);
2726 ERROR(fsg
, "can't enable %s, result %d\n", ep
->name
, rc
);
2730 static int alloc_request(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
2731 struct usb_request
**preq
)
2733 *preq
= usb_ep_alloc_request(ep
, GFP_ATOMIC
);
2736 ERROR(fsg
, "can't allocate request for %s\n", ep
->name
);
2741 * Reset interface setting and re-init endpoint state (toggle etc).
2742 * Call with altsetting < 0 to disable the interface. The only other
2743 * available altsetting is 0, which enables the interface.
2745 static int do_set_interface(struct fsg_dev
*fsg
, int altsetting
)
2749 const struct usb_endpoint_descriptor
*d
;
2752 DBG(fsg
, "reset interface\n");
2755 /* Deallocate the requests */
2756 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2757 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
2760 usb_ep_free_request(fsg
->bulk_in
, bh
->inreq
);
2764 usb_ep_free_request(fsg
->bulk_out
, bh
->outreq
);
2769 usb_ep_free_request(fsg
->intr_in
, fsg
->intreq
);
2773 /* Disable the endpoints */
2774 if (fsg
->bulk_in_enabled
) {
2775 usb_ep_disable(fsg
->bulk_in
);
2776 fsg
->bulk_in_enabled
= 0;
2778 if (fsg
->bulk_out_enabled
) {
2779 usb_ep_disable(fsg
->bulk_out
);
2780 fsg
->bulk_out_enabled
= 0;
2782 if (fsg
->intr_in_enabled
) {
2783 usb_ep_disable(fsg
->intr_in
);
2784 fsg
->intr_in_enabled
= 0;
2788 if (altsetting
< 0 || rc
!= 0)
2791 DBG(fsg
, "set interface %d\n", altsetting
);
2793 /* Enable the endpoints */
2794 d
= fsg_ep_desc(fsg
->gadget
,
2795 &fsg_fs_bulk_in_desc
, &fsg_hs_bulk_in_desc
);
2796 if ((rc
= enable_endpoint(fsg
, fsg
->bulk_in
, d
)) != 0)
2798 fsg
->bulk_in_enabled
= 1;
2800 d
= fsg_ep_desc(fsg
->gadget
,
2801 &fsg_fs_bulk_out_desc
, &fsg_hs_bulk_out_desc
);
2802 if ((rc
= enable_endpoint(fsg
, fsg
->bulk_out
, d
)) != 0)
2804 fsg
->bulk_out_enabled
= 1;
2805 fsg
->bulk_out_maxpacket
= le16_to_cpu(d
->wMaxPacketSize
);
2806 clear_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
);
2808 if (transport_is_cbi()) {
2809 d
= fsg_ep_desc(fsg
->gadget
,
2810 &fsg_fs_intr_in_desc
, &fsg_hs_intr_in_desc
);
2811 if ((rc
= enable_endpoint(fsg
, fsg
->intr_in
, d
)) != 0)
2813 fsg
->intr_in_enabled
= 1;
2816 /* Allocate the requests */
2817 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2818 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
2820 if ((rc
= alloc_request(fsg
, fsg
->bulk_in
, &bh
->inreq
)) != 0)
2822 if ((rc
= alloc_request(fsg
, fsg
->bulk_out
, &bh
->outreq
)) != 0)
2824 bh
->inreq
->buf
= bh
->outreq
->buf
= bh
->buf
;
2825 bh
->inreq
->context
= bh
->outreq
->context
= bh
;
2826 bh
->inreq
->complete
= bulk_in_complete
;
2827 bh
->outreq
->complete
= bulk_out_complete
;
2829 if (transport_is_cbi()) {
2830 if ((rc
= alloc_request(fsg
, fsg
->intr_in
, &fsg
->intreq
)) != 0)
2832 fsg
->intreq
->complete
= intr_in_complete
;
2836 for (i
= 0; i
< fsg
->nluns
; ++i
)
2837 fsg
->luns
[i
].unit_attention_data
= SS_RESET_OCCURRED
;
2843 * Change our operational configuration. This code must agree with the code
2844 * that returns config descriptors, and with interface altsetting code.
2846 * It's also responsible for power management interactions. Some
2847 * configurations might not work with our current power sources.
2848 * For now we just assume the gadget is always self-powered.
2850 static int do_set_config(struct fsg_dev
*fsg
, u8 new_config
)
2854 /* Disable the single interface */
2855 if (fsg
->config
!= 0) {
2856 DBG(fsg
, "reset config\n");
2858 rc
= do_set_interface(fsg
, -1);
2861 /* Enable the interface */
2862 if (new_config
!= 0) {
2863 fsg
->config
= new_config
;
2864 if ((rc
= do_set_interface(fsg
, 0)) != 0)
2865 fsg
->config
= 0; // Reset on errors
2869 switch (fsg
->gadget
->speed
) {
2870 case USB_SPEED_LOW
: speed
= "low"; break;
2871 case USB_SPEED_FULL
: speed
= "full"; break;
2872 case USB_SPEED_HIGH
: speed
= "high"; break;
2873 default: speed
= "?"; break;
2875 INFO(fsg
, "%s speed config #%d\n", speed
, fsg
->config
);
2882 /*-------------------------------------------------------------------------*/
2884 static void handle_exception(struct fsg_dev
*fsg
)
2890 struct fsg_buffhd
*bh
;
2891 enum fsg_state old_state
;
2893 struct fsg_lun
*curlun
;
2894 unsigned int exception_req_tag
;
2897 /* Clear the existing signals. Anything but SIGUSR1 is converted
2898 * into a high-priority EXIT exception. */
2900 sig
= dequeue_signal_lock(current
, ¤t
->blocked
, &info
);
2903 if (sig
!= SIGUSR1
) {
2904 if (fsg
->state
< FSG_STATE_EXIT
)
2905 DBG(fsg
, "Main thread exiting on signal\n");
2906 raise_exception(fsg
, FSG_STATE_EXIT
);
2910 /* Cancel all the pending transfers */
2911 if (fsg
->intreq_busy
)
2912 usb_ep_dequeue(fsg
->intr_in
, fsg
->intreq
);
2913 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2914 bh
= &fsg
->buffhds
[i
];
2916 usb_ep_dequeue(fsg
->bulk_in
, bh
->inreq
);
2917 if (bh
->outreq_busy
)
2918 usb_ep_dequeue(fsg
->bulk_out
, bh
->outreq
);
2921 /* Wait until everything is idle */
2923 num_active
= fsg
->intreq_busy
;
2924 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2925 bh
= &fsg
->buffhds
[i
];
2926 num_active
+= bh
->inreq_busy
+ bh
->outreq_busy
;
2928 if (num_active
== 0)
2930 if (sleep_thread(fsg
))
2934 /* Clear out the controller's fifos */
2935 if (fsg
->bulk_in_enabled
)
2936 usb_ep_fifo_flush(fsg
->bulk_in
);
2937 if (fsg
->bulk_out_enabled
)
2938 usb_ep_fifo_flush(fsg
->bulk_out
);
2939 if (fsg
->intr_in_enabled
)
2940 usb_ep_fifo_flush(fsg
->intr_in
);
2942 /* Reset the I/O buffer states and pointers, the SCSI
2943 * state, and the exception. Then invoke the handler. */
2944 spin_lock_irq(&fsg
->lock
);
2946 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2947 bh
= &fsg
->buffhds
[i
];
2948 bh
->state
= BUF_STATE_EMPTY
;
2950 fsg
->next_buffhd_to_fill
= fsg
->next_buffhd_to_drain
=
2953 exception_req_tag
= fsg
->exception_req_tag
;
2954 new_config
= fsg
->new_config
;
2955 old_state
= fsg
->state
;
2957 if (old_state
== FSG_STATE_ABORT_BULK_OUT
)
2958 fsg
->state
= FSG_STATE_STATUS_PHASE
;
2960 for (i
= 0; i
< fsg
->nluns
; ++i
) {
2961 curlun
= &fsg
->luns
[i
];
2962 curlun
->prevent_medium_removal
= 0;
2963 curlun
->sense_data
= curlun
->unit_attention_data
=
2965 curlun
->sense_data_info
= 0;
2966 curlun
->info_valid
= 0;
2968 fsg
->state
= FSG_STATE_IDLE
;
2970 spin_unlock_irq(&fsg
->lock
);
2972 /* Carry out any extra actions required for the exception */
2973 switch (old_state
) {
2977 case FSG_STATE_ABORT_BULK_OUT
:
2979 spin_lock_irq(&fsg
->lock
);
2980 if (fsg
->state
== FSG_STATE_STATUS_PHASE
)
2981 fsg
->state
= FSG_STATE_IDLE
;
2982 spin_unlock_irq(&fsg
->lock
);
2985 case FSG_STATE_RESET
:
2986 /* In case we were forced against our will to halt a
2987 * bulk endpoint, clear the halt now. (The SuperH UDC
2988 * requires this.) */
2989 if (test_and_clear_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
))
2990 usb_ep_clear_halt(fsg
->bulk_in
);
2992 if (transport_is_bbb()) {
2993 if (fsg
->ep0_req_tag
== exception_req_tag
)
2994 ep0_queue(fsg
); // Complete the status stage
2996 } else if (transport_is_cbi())
2997 send_status(fsg
); // Status by interrupt pipe
2999 /* Technically this should go here, but it would only be
3000 * a waste of time. Ditto for the INTERFACE_CHANGE and
3001 * CONFIG_CHANGE cases. */
3002 // for (i = 0; i < fsg->nluns; ++i)
3003 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3006 case FSG_STATE_INTERFACE_CHANGE
:
3007 rc
= do_set_interface(fsg
, 0);
3008 if (fsg
->ep0_req_tag
!= exception_req_tag
)
3010 if (rc
!= 0) // STALL on errors
3011 fsg_set_halt(fsg
, fsg
->ep0
);
3012 else // Complete the status stage
3016 case FSG_STATE_CONFIG_CHANGE
:
3017 rc
= do_set_config(fsg
, new_config
);
3018 if (fsg
->ep0_req_tag
!= exception_req_tag
)
3020 if (rc
!= 0) // STALL on errors
3021 fsg_set_halt(fsg
, fsg
->ep0
);
3022 else // Complete the status stage
3026 case FSG_STATE_DISCONNECT
:
3027 for (i
= 0; i
< fsg
->nluns
; ++i
)
3028 fsg_lun_fsync_sub(fsg
->luns
+ i
);
3029 do_set_config(fsg
, 0); // Unconfigured state
3032 case FSG_STATE_EXIT
:
3033 case FSG_STATE_TERMINATED
:
3034 do_set_config(fsg
, 0); // Free resources
3035 spin_lock_irq(&fsg
->lock
);
3036 fsg
->state
= FSG_STATE_TERMINATED
; // Stop the thread
3037 spin_unlock_irq(&fsg
->lock
);
3043 /*-------------------------------------------------------------------------*/
3045 static int fsg_main_thread(void *fsg_
)
3047 struct fsg_dev
*fsg
= fsg_
;
3049 /* Allow the thread to be killed by a signal, but set the signal mask
3050 * to block everything but INT, TERM, KILL, and USR1. */
3051 allow_signal(SIGINT
);
3052 allow_signal(SIGTERM
);
3053 allow_signal(SIGKILL
);
3054 allow_signal(SIGUSR1
);
3056 /* Allow the thread to be frozen */
3059 /* Arrange for userspace references to be interpreted as kernel
3060 * pointers. That way we can pass a kernel pointer to a routine
3061 * that expects a __user pointer and it will work okay. */
3065 while (fsg
->state
!= FSG_STATE_TERMINATED
) {
3066 if (exception_in_progress(fsg
) || signal_pending(current
)) {
3067 handle_exception(fsg
);
3071 if (!fsg
->running
) {
3076 if (get_next_command(fsg
))
3079 spin_lock_irq(&fsg
->lock
);
3080 if (!exception_in_progress(fsg
))
3081 fsg
->state
= FSG_STATE_DATA_PHASE
;
3082 spin_unlock_irq(&fsg
->lock
);
3084 if (do_scsi_command(fsg
) || finish_reply(fsg
))
3087 spin_lock_irq(&fsg
->lock
);
3088 if (!exception_in_progress(fsg
))
3089 fsg
->state
= FSG_STATE_STATUS_PHASE
;
3090 spin_unlock_irq(&fsg
->lock
);
3092 if (send_status(fsg
))
3095 spin_lock_irq(&fsg
->lock
);
3096 if (!exception_in_progress(fsg
))
3097 fsg
->state
= FSG_STATE_IDLE
;
3098 spin_unlock_irq(&fsg
->lock
);
3101 spin_lock_irq(&fsg
->lock
);
3102 fsg
->thread_task
= NULL
;
3103 spin_unlock_irq(&fsg
->lock
);
3105 /* If we are exiting because of a signal, unregister the
3107 if (test_and_clear_bit(REGISTERED
, &fsg
->atomic_bitflags
))
3108 usb_gadget_unregister_driver(&fsg_driver
);
3110 /* Let the unbind and cleanup routines know the thread has exited */
3111 complete_and_exit(&fsg
->thread_notifier
, 0);
3115 /*-------------------------------------------------------------------------*/
3118 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3119 static DEVICE_ATTR(ro
, 0444, fsg_show_ro
, NULL
);
3120 static DEVICE_ATTR(nofua
, 0644, fsg_show_nofua
, NULL
);
3121 static DEVICE_ATTR(file
, 0444, fsg_show_file
, NULL
);
3124 /*-------------------------------------------------------------------------*/
3126 static void fsg_release(struct kref
*ref
)
3128 struct fsg_dev
*fsg
= container_of(ref
, struct fsg_dev
, ref
);
3134 static void lun_release(struct device
*dev
)
3136 struct rw_semaphore
*filesem
= dev_get_drvdata(dev
);
3137 struct fsg_dev
*fsg
=
3138 container_of(filesem
, struct fsg_dev
, filesem
);
3140 kref_put(&fsg
->ref
, fsg_release
);
3143 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget
*gadget
)
3145 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
3147 struct fsg_lun
*curlun
;
3148 struct usb_request
*req
= fsg
->ep0req
;
3150 DBG(fsg
, "unbind\n");
3151 clear_bit(REGISTERED
, &fsg
->atomic_bitflags
);
3153 /* Unregister the sysfs attribute files and the LUNs */
3154 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3155 curlun
= &fsg
->luns
[i
];
3156 if (curlun
->registered
) {
3157 device_remove_file(&curlun
->dev
, &dev_attr_nofua
);
3158 device_remove_file(&curlun
->dev
, &dev_attr_ro
);
3159 device_remove_file(&curlun
->dev
, &dev_attr_file
);
3160 fsg_lun_close(curlun
);
3161 device_unregister(&curlun
->dev
);
3162 curlun
->registered
= 0;
3166 /* If the thread isn't already dead, tell it to exit now */
3167 if (fsg
->state
!= FSG_STATE_TERMINATED
) {
3168 raise_exception(fsg
, FSG_STATE_EXIT
);
3169 wait_for_completion(&fsg
->thread_notifier
);
3171 /* The cleanup routine waits for this completion also */
3172 complete(&fsg
->thread_notifier
);
3175 /* Free the data buffers */
3176 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
)
3177 kfree(fsg
->buffhds
[i
].buf
);
3179 /* Free the request and buffer for endpoint 0 */
3182 usb_ep_free_request(fsg
->ep0
, req
);
3185 set_gadget_data(gadget
, NULL
);
3189 static int __init
check_parameters(struct fsg_dev
*fsg
)
3194 /* Store the default values */
3195 mod_data
.transport_type
= USB_PR_BULK
;
3196 mod_data
.transport_name
= "Bulk-only";
3197 mod_data
.protocol_type
= USB_SC_SCSI
;
3198 mod_data
.protocol_name
= "Transparent SCSI";
3200 /* Some peripheral controllers are known not to be able to
3201 * halt bulk endpoints correctly. If one of them is present,
3204 if (gadget_is_at91(fsg
->gadget
))
3205 mod_data
.can_stall
= 0;
3207 if (mod_data
.release
== 0xffff) { // Parameter wasn't set
3208 gcnum
= usb_gadget_controller_number(fsg
->gadget
);
3210 mod_data
.release
= 0x0300 + gcnum
;
3212 WARNING(fsg
, "controller '%s' not recognized\n",
3214 mod_data
.release
= 0x0399;
3218 prot
= simple_strtol(mod_data
.protocol_parm
, NULL
, 0);
3220 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3221 if (strnicmp(mod_data
.transport_parm
, "BBB", 10) == 0) {
3222 ; // Use default setting
3223 } else if (strnicmp(mod_data
.transport_parm
, "CB", 10) == 0) {
3224 mod_data
.transport_type
= USB_PR_CB
;
3225 mod_data
.transport_name
= "Control-Bulk";
3226 } else if (strnicmp(mod_data
.transport_parm
, "CBI", 10) == 0) {
3227 mod_data
.transport_type
= USB_PR_CBI
;
3228 mod_data
.transport_name
= "Control-Bulk-Interrupt";
3230 ERROR(fsg
, "invalid transport: %s\n", mod_data
.transport_parm
);
3234 if (strnicmp(mod_data
.protocol_parm
, "SCSI", 10) == 0 ||
3235 prot
== USB_SC_SCSI
) {
3236 ; // Use default setting
3237 } else if (strnicmp(mod_data
.protocol_parm
, "RBC", 10) == 0 ||
3238 prot
== USB_SC_RBC
) {
3239 mod_data
.protocol_type
= USB_SC_RBC
;
3240 mod_data
.protocol_name
= "RBC";
3241 } else if (strnicmp(mod_data
.protocol_parm
, "8020", 4) == 0 ||
3242 strnicmp(mod_data
.protocol_parm
, "ATAPI", 10) == 0 ||
3243 prot
== USB_SC_8020
) {
3244 mod_data
.protocol_type
= USB_SC_8020
;
3245 mod_data
.protocol_name
= "8020i (ATAPI)";
3246 } else if (strnicmp(mod_data
.protocol_parm
, "QIC", 3) == 0 ||
3247 prot
== USB_SC_QIC
) {
3248 mod_data
.protocol_type
= USB_SC_QIC
;
3249 mod_data
.protocol_name
= "QIC-157";
3250 } else if (strnicmp(mod_data
.protocol_parm
, "UFI", 10) == 0 ||
3251 prot
== USB_SC_UFI
) {
3252 mod_data
.protocol_type
= USB_SC_UFI
;
3253 mod_data
.protocol_name
= "UFI";
3254 } else if (strnicmp(mod_data
.protocol_parm
, "8070", 4) == 0 ||
3255 prot
== USB_SC_8070
) {
3256 mod_data
.protocol_type
= USB_SC_8070
;
3257 mod_data
.protocol_name
= "8070i";
3259 ERROR(fsg
, "invalid protocol: %s\n", mod_data
.protocol_parm
);
3263 mod_data
.buflen
&= PAGE_CACHE_MASK
;
3264 if (mod_data
.buflen
<= 0) {
3265 ERROR(fsg
, "invalid buflen\n");
3269 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3271 /* Serial string handling.
3272 * On a real device, the serial string would be loaded
3273 * from permanent storage. */
3274 if (mod_data
.serial
) {
3279 * The CB[I] specification limits the serial string to
3280 * 12 uppercase hexadecimal characters.
3281 * BBB need at least 12 uppercase hexadecimal characters,
3282 * with a maximum of 126. */
3283 for (ch
= mod_data
.serial
; *ch
; ++ch
) {
3285 if ((*ch
< '0' || *ch
> '9') &&
3286 (*ch
< 'A' || *ch
> 'F')) { /* not uppercase hex */
3288 "Invalid serial string character: %c\n",
3294 (mod_data
.transport_type
== USB_PR_BULK
&& len
< 12) ||
3295 (mod_data
.transport_type
!= USB_PR_BULK
&& len
> 12)) {
3296 WARNING(fsg
, "Invalid serial string length!\n");
3299 fsg_strings
[FSG_STRING_SERIAL
- 1].s
= mod_data
.serial
;
3301 WARNING(fsg
, "No serial-number string provided!\n");
3303 device_desc
.iSerialNumber
= 0;
3310 static int __init
fsg_bind(struct usb_gadget
*gadget
)
3312 struct fsg_dev
*fsg
= the_fsg
;
3315 struct fsg_lun
*curlun
;
3317 struct usb_request
*req
;
3320 fsg
->gadget
= gadget
;
3321 set_gadget_data(gadget
, fsg
);
3322 fsg
->ep0
= gadget
->ep0
;
3323 fsg
->ep0
->driver_data
= fsg
;
3325 if ((rc
= check_parameters(fsg
)) != 0)
3328 if (mod_data
.removable
) { // Enable the store_xxx attributes
3329 dev_attr_file
.attr
.mode
= 0644;
3330 dev_attr_file
.store
= fsg_store_file
;
3331 if (!mod_data
.cdrom
) {
3332 dev_attr_ro
.attr
.mode
= 0644;
3333 dev_attr_ro
.store
= fsg_store_ro
;
3337 /* Only for removable media? */
3338 dev_attr_nofua
.attr
.mode
= 0644;
3339 dev_attr_nofua
.store
= fsg_store_nofua
;
3341 /* Find out how many LUNs there should be */
3344 i
= max(mod_data
.num_filenames
, 1u);
3345 if (i
> FSG_MAX_LUNS
) {
3346 ERROR(fsg
, "invalid number of LUNs: %d\n", i
);
3351 /* Create the LUNs, open their backing files, and register the
3352 * LUN devices in sysfs. */
3353 fsg
->luns
= kzalloc(i
* sizeof(struct fsg_lun
), GFP_KERNEL
);
3360 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3361 curlun
= &fsg
->luns
[i
];
3362 curlun
->cdrom
= !!mod_data
.cdrom
;
3363 curlun
->ro
= mod_data
.cdrom
|| mod_data
.ro
[i
];
3364 curlun
->initially_ro
= curlun
->ro
;
3365 curlun
->removable
= mod_data
.removable
;
3366 curlun
->nofua
= mod_data
.nofua
[i
];
3367 curlun
->dev
.release
= lun_release
;
3368 curlun
->dev
.parent
= &gadget
->dev
;
3369 curlun
->dev
.driver
= &fsg_driver
.driver
;
3370 dev_set_drvdata(&curlun
->dev
, &fsg
->filesem
);
3371 dev_set_name(&curlun
->dev
,"%s-lun%d",
3372 dev_name(&gadget
->dev
), i
);
3374 kref_get(&fsg
->ref
);
3375 rc
= device_register(&curlun
->dev
);
3377 INFO(fsg
, "failed to register LUN%d: %d\n", i
, rc
);
3378 put_device(&curlun
->dev
);
3381 curlun
->registered
= 1;
3383 rc
= device_create_file(&curlun
->dev
, &dev_attr_ro
);
3386 rc
= device_create_file(&curlun
->dev
, &dev_attr_nofua
);
3389 rc
= device_create_file(&curlun
->dev
, &dev_attr_file
);
3393 if (mod_data
.file
[i
] && *mod_data
.file
[i
]) {
3394 rc
= fsg_lun_open(curlun
, mod_data
.file
[i
]);
3397 } else if (!mod_data
.removable
) {
3398 ERROR(fsg
, "no file given for LUN%d\n", i
);
3404 /* Find all the endpoints we will use */
3405 usb_ep_autoconfig_reset(gadget
);
3406 ep
= usb_ep_autoconfig(gadget
, &fsg_fs_bulk_in_desc
);
3409 ep
->driver_data
= fsg
; // claim the endpoint
3412 ep
= usb_ep_autoconfig(gadget
, &fsg_fs_bulk_out_desc
);
3415 ep
->driver_data
= fsg
; // claim the endpoint
3418 if (transport_is_cbi()) {
3419 ep
= usb_ep_autoconfig(gadget
, &fsg_fs_intr_in_desc
);
3422 ep
->driver_data
= fsg
; // claim the endpoint
3426 /* Fix up the descriptors */
3427 device_desc
.idVendor
= cpu_to_le16(mod_data
.vendor
);
3428 device_desc
.idProduct
= cpu_to_le16(mod_data
.product
);
3429 device_desc
.bcdDevice
= cpu_to_le16(mod_data
.release
);
3431 i
= (transport_is_cbi() ? 3 : 2); // Number of endpoints
3432 fsg_intf_desc
.bNumEndpoints
= i
;
3433 fsg_intf_desc
.bInterfaceSubClass
= mod_data
.protocol_type
;
3434 fsg_intf_desc
.bInterfaceProtocol
= mod_data
.transport_type
;
3435 fsg_fs_function
[i
+ FSG_FS_FUNCTION_PRE_EP_ENTRIES
] = NULL
;
3437 if (gadget_is_dualspeed(gadget
)) {
3438 fsg_hs_function
[i
+ FSG_HS_FUNCTION_PRE_EP_ENTRIES
] = NULL
;
3440 /* Assume endpoint addresses are the same for both speeds */
3441 fsg_hs_bulk_in_desc
.bEndpointAddress
=
3442 fsg_fs_bulk_in_desc
.bEndpointAddress
;
3443 fsg_hs_bulk_out_desc
.bEndpointAddress
=
3444 fsg_fs_bulk_out_desc
.bEndpointAddress
;
3445 fsg_hs_intr_in_desc
.bEndpointAddress
=
3446 fsg_fs_intr_in_desc
.bEndpointAddress
;
3449 if (gadget_is_otg(gadget
))
3450 fsg_otg_desc
.bmAttributes
|= USB_OTG_HNP
;
3454 /* Allocate the request and buffer for endpoint 0 */
3455 fsg
->ep0req
= req
= usb_ep_alloc_request(fsg
->ep0
, GFP_KERNEL
);
3458 req
->buf
= kmalloc(EP0_BUFSIZE
, GFP_KERNEL
);
3461 req
->complete
= ep0_complete
;
3463 /* Allocate the data buffers */
3464 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
3465 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
3467 /* Allocate for the bulk-in endpoint. We assume that
3468 * the buffer will also work with the bulk-out (and
3469 * interrupt-in) endpoint. */
3470 bh
->buf
= kmalloc(mod_data
.buflen
, GFP_KERNEL
);
3475 fsg
->buffhds
[FSG_NUM_BUFFERS
- 1].next
= &fsg
->buffhds
[0];
3477 /* This should reflect the actual gadget power source */
3478 usb_gadget_set_selfpowered(gadget
);
3480 snprintf(fsg_string_manufacturer
, sizeof fsg_string_manufacturer
,
3482 init_utsname()->sysname
, init_utsname()->release
,
3485 fsg
->thread_task
= kthread_create(fsg_main_thread
, fsg
,
3486 "file-storage-gadget");
3487 if (IS_ERR(fsg
->thread_task
)) {
3488 rc
= PTR_ERR(fsg
->thread_task
);
3492 INFO(fsg
, DRIVER_DESC
", version: " DRIVER_VERSION
"\n");
3493 INFO(fsg
, "NOTE: This driver is deprecated. "
3494 "Consider using g_mass_storage instead.\n");
3495 INFO(fsg
, "Number of LUNs=%d\n", fsg
->nluns
);
3497 pathbuf
= kmalloc(PATH_MAX
, GFP_KERNEL
);
3498 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3499 curlun
= &fsg
->luns
[i
];
3500 if (fsg_lun_is_open(curlun
)) {
3503 p
= d_path(&curlun
->filp
->f_path
,
3508 LINFO(curlun
, "ro=%d, nofua=%d, file: %s\n",
3509 curlun
->ro
, curlun
->nofua
, (p
? p
: "(error)"));
3514 DBG(fsg
, "transport=%s (x%02x)\n",
3515 mod_data
.transport_name
, mod_data
.transport_type
);
3516 DBG(fsg
, "protocol=%s (x%02x)\n",
3517 mod_data
.protocol_name
, mod_data
.protocol_type
);
3518 DBG(fsg
, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3519 mod_data
.vendor
, mod_data
.product
, mod_data
.release
);
3520 DBG(fsg
, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3521 mod_data
.removable
, mod_data
.can_stall
,
3522 mod_data
.cdrom
, mod_data
.buflen
);
3523 DBG(fsg
, "I/O thread pid: %d\n", task_pid_nr(fsg
->thread_task
));
3525 set_bit(REGISTERED
, &fsg
->atomic_bitflags
);
3527 /* Tell the thread to start working */
3528 wake_up_process(fsg
->thread_task
);
3532 ERROR(fsg
, "unable to autoconfigure all endpoints\n");
3536 fsg
->state
= FSG_STATE_TERMINATED
; // The thread is dead
3538 complete(&fsg
->thread_notifier
);
3543 /*-------------------------------------------------------------------------*/
3545 static void fsg_suspend(struct usb_gadget
*gadget
)
3547 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
3549 DBG(fsg
, "suspend\n");
3550 set_bit(SUSPENDED
, &fsg
->atomic_bitflags
);
3553 static void fsg_resume(struct usb_gadget
*gadget
)
3555 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
3557 DBG(fsg
, "resume\n");
3558 clear_bit(SUSPENDED
, &fsg
->atomic_bitflags
);
3562 /*-------------------------------------------------------------------------*/
3564 static struct usb_gadget_driver fsg_driver
= {
3565 #ifdef CONFIG_USB_GADGET_DUALSPEED
3566 .speed
= USB_SPEED_HIGH
,
3568 .speed
= USB_SPEED_FULL
,
3570 .function
= (char *) fsg_string_product
,
3571 .unbind
= fsg_unbind
,
3572 .disconnect
= fsg_disconnect
,
3574 .suspend
= fsg_suspend
,
3575 .resume
= fsg_resume
,
3578 .name
= DRIVER_NAME
,
3579 .owner
= THIS_MODULE
,
3587 static int __init
fsg_alloc(void)
3589 struct fsg_dev
*fsg
;
3591 fsg
= kzalloc(sizeof *fsg
, GFP_KERNEL
);
3594 spin_lock_init(&fsg
->lock
);
3595 init_rwsem(&fsg
->filesem
);
3596 kref_init(&fsg
->ref
);
3597 init_completion(&fsg
->thread_notifier
);
3604 static int __init
fsg_init(void)
3607 struct fsg_dev
*fsg
;
3609 if ((rc
= fsg_alloc()) != 0)
3612 if ((rc
= usb_gadget_probe_driver(&fsg_driver
, fsg_bind
)) != 0)
3613 kref_put(&fsg
->ref
, fsg_release
);
3616 module_init(fsg_init
);
3619 static void __exit
fsg_cleanup(void)
3621 struct fsg_dev
*fsg
= the_fsg
;
3623 /* Unregister the driver iff the thread hasn't already done so */
3624 if (test_and_clear_bit(REGISTERED
, &fsg
->atomic_bitflags
))
3625 usb_gadget_unregister_driver(&fsg_driver
);
3627 /* Wait for the thread to finish up */
3628 wait_for_completion(&fsg
->thread_notifier
);
3630 kref_put(&fsg
->ref
, fsg_release
);
3632 module_exit(fsg_cleanup
);