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 * ro=b[,b...] Default false, booleans for read-only access
93 * removable Default false, boolean for removable media
94 * luns=N Default N = number of filenames, number of
96 * nofua=b[,b...] Default false, booleans for ignore FUA flag
97 * in SCSI WRITE(10,12) commands
98 * stall Default determined according to the type of
99 * USB device controller (usually true),
100 * boolean to permit the driver to halt
102 * cdrom Default false, boolean for whether to emulate
104 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
105 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
106 * ATAPI, QIC, UFI, 8070, or SCSI;
108 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
109 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
110 * release=0xRRRR Override the USB release number (bcdDevice)
111 * serial=HHHH... Override serial number (string of hex chars)
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", "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/rwsem.h>
248 #include <linux/slab.h>
249 #include <linux/spinlock.h>
250 #include <linux/string.h>
251 #include <linux/freezer.h>
252 #include <linux/utsname.h>
254 #include <linux/usb/ch9.h>
255 #include <linux/usb/gadget.h>
257 #include "gadget_chips.h"
262 * Kbuild is not very cooperative with respect to linking separately
263 * compiled library objects into one module. So for now we won't use
264 * separate compilation ... ensuring init/exit sections work to shrink
265 * the runtime footprint, and giving us at least some parts of what
266 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
268 #include "usbstring.c"
270 #include "epautoconf.c"
272 /*-------------------------------------------------------------------------*/
274 #define DRIVER_DESC "File-backed Storage Gadget"
275 #define DRIVER_NAME "g_file_storage"
276 /* DRIVER_VERSION must be at least 6 characters long, as it is used
277 * to generate a fallback serial number. */
278 #define DRIVER_VERSION "20 November 2008"
280 static char fsg_string_manufacturer
[64];
281 static const char fsg_string_product
[] = DRIVER_DESC
;
282 static char fsg_string_serial
[13];
283 static const char fsg_string_config
[] = "Self-powered";
284 static const char fsg_string_interface
[] = "Mass Storage";
287 #include "storage_common.c"
290 MODULE_DESCRIPTION(DRIVER_DESC
);
291 MODULE_AUTHOR("Alan Stern");
292 MODULE_LICENSE("Dual BSD/GPL");
295 * This driver assumes self-powered hardware and has no way for users to
296 * trigger remote wakeup. It uses autoconfiguration to select endpoints
297 * and endpoint addresses.
301 /*-------------------------------------------------------------------------*/
304 /* Encapsulate the module parameter settings */
307 char *file
[FSG_MAX_LUNS
];
308 int ro
[FSG_MAX_LUNS
];
309 int nofua
[FSG_MAX_LUNS
];
310 unsigned int num_filenames
;
311 unsigned int num_ros
;
312 unsigned int num_nofuas
;
319 char *transport_parm
;
321 unsigned short vendor
;
322 unsigned short product
;
323 unsigned short release
;
328 char *transport_name
;
332 } mod_data
= { // Default values
333 .transport_parm
= "BBB",
334 .protocol_parm
= "SCSI",
338 .vendor
= FSG_VENDOR_ID
,
339 .product
= FSG_PRODUCT_ID
,
340 .release
= 0xffff, // Use controller chip type
345 module_param_array_named(file
, mod_data
.file
, charp
, &mod_data
.num_filenames
,
347 MODULE_PARM_DESC(file
, "names of backing files or devices");
349 module_param_array_named(ro
, mod_data
.ro
, bool, &mod_data
.num_ros
, S_IRUGO
);
350 MODULE_PARM_DESC(ro
, "true to force read-only");
352 module_param_array_named(nofua
, mod_data
.nofua
, bool, &mod_data
.num_nofuas
,
354 MODULE_PARM_DESC(nofua
, "true to ignore SCSI WRITE(10,12) FUA bit");
356 module_param_named(luns
, mod_data
.nluns
, uint
, S_IRUGO
);
357 MODULE_PARM_DESC(luns
, "number of LUNs");
359 module_param_named(removable
, mod_data
.removable
, bool, S_IRUGO
);
360 MODULE_PARM_DESC(removable
, "true to simulate removable media");
362 module_param_named(stall
, mod_data
.can_stall
, bool, S_IRUGO
);
363 MODULE_PARM_DESC(stall
, "false to prevent bulk stalls");
365 module_param_named(cdrom
, mod_data
.cdrom
, bool, S_IRUGO
);
366 MODULE_PARM_DESC(cdrom
, "true to emulate cdrom instead of disk");
368 module_param_named(serial
, mod_data
.serial
, charp
, S_IRUGO
);
369 MODULE_PARM_DESC(serial
, "USB serial number");
371 /* In the non-TEST version, only the module parameters listed above
373 #ifdef CONFIG_USB_FILE_STORAGE_TEST
375 module_param_named(transport
, mod_data
.transport_parm
, charp
, S_IRUGO
);
376 MODULE_PARM_DESC(transport
, "type of transport (BBB, CBI, or CB)");
378 module_param_named(protocol
, mod_data
.protocol_parm
, charp
, S_IRUGO
);
379 MODULE_PARM_DESC(protocol
, "type of protocol (RBC, 8020, QIC, UFI, "
382 module_param_named(vendor
, mod_data
.vendor
, ushort
, S_IRUGO
);
383 MODULE_PARM_DESC(vendor
, "USB Vendor ID");
385 module_param_named(product
, mod_data
.product
, ushort
, S_IRUGO
);
386 MODULE_PARM_DESC(product
, "USB Product ID");
388 module_param_named(release
, mod_data
.release
, ushort
, S_IRUGO
);
389 MODULE_PARM_DESC(release
, "USB release number");
391 module_param_named(buflen
, mod_data
.buflen
, uint
, S_IRUGO
);
392 MODULE_PARM_DESC(buflen
, "I/O buffer size");
394 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
398 * These definitions will permit the compiler to avoid generating code for
399 * parts of the driver that aren't used in the non-TEST version. Even gcc
400 * can recognize when a test of a constant expression yields a dead code
404 #ifdef CONFIG_USB_FILE_STORAGE_TEST
406 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
407 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
408 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
412 #define transport_is_bbb() 1
413 #define transport_is_cbi() 0
414 #define protocol_is_scsi() 1
416 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
419 /*-------------------------------------------------------------------------*/
423 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
425 struct usb_gadget
*gadget
;
427 /* filesem protects: backing files in use */
428 struct rw_semaphore filesem
;
430 /* reference counting: wait until all LUNs are released */
433 struct usb_ep
*ep0
; // Handy copy of gadget->ep0
434 struct usb_request
*ep0req
; // For control responses
435 unsigned int ep0_req_tag
;
436 const char *ep0req_name
;
438 struct usb_request
*intreq
; // For interrupt responses
440 struct fsg_buffhd
*intr_buffhd
;
442 unsigned int bulk_out_maxpacket
;
443 enum fsg_state state
; // For exception handling
444 unsigned int exception_req_tag
;
446 u8 config
, new_config
;
448 unsigned int running
: 1;
449 unsigned int bulk_in_enabled
: 1;
450 unsigned int bulk_out_enabled
: 1;
451 unsigned int intr_in_enabled
: 1;
452 unsigned int phase_error
: 1;
453 unsigned int short_packet_received
: 1;
454 unsigned int bad_lun_okay
: 1;
456 unsigned long atomic_bitflags
;
458 #define IGNORE_BULK_OUT 1
461 struct usb_ep
*bulk_in
;
462 struct usb_ep
*bulk_out
;
463 struct usb_ep
*intr_in
;
465 struct fsg_buffhd
*next_buffhd_to_fill
;
466 struct fsg_buffhd
*next_buffhd_to_drain
;
467 struct fsg_buffhd buffhds
[FSG_NUM_BUFFERS
];
469 int thread_wakeup_needed
;
470 struct completion thread_notifier
;
471 struct task_struct
*thread_task
;
474 u8 cmnd
[MAX_COMMAND_SIZE
];
475 enum data_direction data_dir
;
477 u32 data_size_from_cmnd
;
483 /* The CB protocol offers no way for a host to know when a command
484 * has completed. As a result the next command may arrive early,
485 * and we will still have to handle it. For that reason we need
486 * a buffer to store new commands when using CB (or CBI, which
487 * does not oblige a host to wait for command completion either). */
489 u8 cbbuf_cmnd
[MAX_COMMAND_SIZE
];
492 struct fsg_lun
*luns
;
493 struct fsg_lun
*curlun
;
496 typedef void (*fsg_routine_t
)(struct fsg_dev
*);
498 static int exception_in_progress(struct fsg_dev
*fsg
)
500 return (fsg
->state
> FSG_STATE_IDLE
);
503 /* Make bulk-out requests be divisible by the maxpacket size */
504 static void set_bulk_out_req_length(struct fsg_dev
*fsg
,
505 struct fsg_buffhd
*bh
, unsigned int length
)
509 bh
->bulk_out_intended_length
= length
;
510 rem
= length
% fsg
->bulk_out_maxpacket
;
512 length
+= fsg
->bulk_out_maxpacket
- rem
;
513 bh
->outreq
->length
= length
;
516 static struct fsg_dev
*the_fsg
;
517 static struct usb_gadget_driver fsg_driver
;
520 /*-------------------------------------------------------------------------*/
522 static int fsg_set_halt(struct fsg_dev
*fsg
, struct usb_ep
*ep
)
526 if (ep
== fsg
->bulk_in
)
528 else if (ep
== fsg
->bulk_out
)
532 DBG(fsg
, "%s set halt\n", name
);
533 return usb_ep_set_halt(ep
);
537 /*-------------------------------------------------------------------------*/
540 * DESCRIPTORS ... most are static, but strings and (full) configuration
541 * descriptors are built on demand. Also the (static) config and interface
542 * descriptors are adjusted during fsg_bind().
545 /* There is only one configuration. */
546 #define CONFIG_VALUE 1
548 static struct usb_device_descriptor
550 .bLength
= sizeof device_desc
,
551 .bDescriptorType
= USB_DT_DEVICE
,
553 .bcdUSB
= cpu_to_le16(0x0200),
554 .bDeviceClass
= USB_CLASS_PER_INTERFACE
,
556 /* The next three values can be overridden by module parameters */
557 .idVendor
= cpu_to_le16(FSG_VENDOR_ID
),
558 .idProduct
= cpu_to_le16(FSG_PRODUCT_ID
),
559 .bcdDevice
= cpu_to_le16(0xffff),
561 .iManufacturer
= FSG_STRING_MANUFACTURER
,
562 .iProduct
= FSG_STRING_PRODUCT
,
563 .iSerialNumber
= FSG_STRING_SERIAL
,
564 .bNumConfigurations
= 1,
567 static struct usb_config_descriptor
569 .bLength
= sizeof config_desc
,
570 .bDescriptorType
= USB_DT_CONFIG
,
572 /* wTotalLength computed by usb_gadget_config_buf() */
574 .bConfigurationValue
= CONFIG_VALUE
,
575 .iConfiguration
= FSG_STRING_CONFIG
,
576 .bmAttributes
= USB_CONFIG_ATT_ONE
| USB_CONFIG_ATT_SELFPOWER
,
577 .bMaxPower
= CONFIG_USB_GADGET_VBUS_DRAW
/ 2,
581 static struct usb_qualifier_descriptor
583 .bLength
= sizeof dev_qualifier
,
584 .bDescriptorType
= USB_DT_DEVICE_QUALIFIER
,
586 .bcdUSB
= cpu_to_le16(0x0200),
587 .bDeviceClass
= USB_CLASS_PER_INTERFACE
,
589 .bNumConfigurations
= 1,
595 * Config descriptors must agree with the code that sets configurations
596 * and with code managing interfaces and their altsettings. They must
597 * also handle different speeds and other-speed requests.
599 static int populate_config_buf(struct usb_gadget
*gadget
,
600 u8
*buf
, u8 type
, unsigned index
)
602 enum usb_device_speed speed
= gadget
->speed
;
604 const struct usb_descriptor_header
**function
;
609 if (gadget_is_dualspeed(gadget
) && type
== USB_DT_OTHER_SPEED_CONFIG
)
610 speed
= (USB_SPEED_FULL
+ USB_SPEED_HIGH
) - speed
;
611 function
= gadget_is_dualspeed(gadget
) && speed
== USB_SPEED_HIGH
612 ? (const struct usb_descriptor_header
**)fsg_hs_function
613 : (const struct usb_descriptor_header
**)fsg_fs_function
;
615 /* for now, don't advertise srp-only devices */
616 if (!gadget_is_otg(gadget
))
619 len
= usb_gadget_config_buf(&config_desc
, buf
, EP0_BUFSIZE
, function
);
620 ((struct usb_config_descriptor
*) buf
)->bDescriptorType
= type
;
625 /*-------------------------------------------------------------------------*/
627 /* These routines may be called in process context or in_irq */
629 /* Caller must hold fsg->lock */
630 static void wakeup_thread(struct fsg_dev
*fsg
)
632 /* Tell the main thread that something has happened */
633 fsg
->thread_wakeup_needed
= 1;
634 if (fsg
->thread_task
)
635 wake_up_process(fsg
->thread_task
);
639 static void raise_exception(struct fsg_dev
*fsg
, enum fsg_state new_state
)
643 /* Do nothing if a higher-priority exception is already in progress.
644 * If a lower-or-equal priority exception is in progress, preempt it
645 * and notify the main thread by sending it a signal. */
646 spin_lock_irqsave(&fsg
->lock
, flags
);
647 if (fsg
->state
<= new_state
) {
648 fsg
->exception_req_tag
= fsg
->ep0_req_tag
;
649 fsg
->state
= new_state
;
650 if (fsg
->thread_task
)
651 send_sig_info(SIGUSR1
, SEND_SIG_FORCED
,
654 spin_unlock_irqrestore(&fsg
->lock
, flags
);
658 /*-------------------------------------------------------------------------*/
660 /* The disconnect callback and ep0 routines. These always run in_irq,
661 * except that ep0_queue() is called in the main thread to acknowledge
662 * completion of various requests: set config, set interface, and
663 * Bulk-only device reset. */
665 static void fsg_disconnect(struct usb_gadget
*gadget
)
667 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
669 DBG(fsg
, "disconnect or port reset\n");
670 raise_exception(fsg
, FSG_STATE_DISCONNECT
);
674 static int ep0_queue(struct fsg_dev
*fsg
)
678 rc
= usb_ep_queue(fsg
->ep0
, fsg
->ep0req
, GFP_ATOMIC
);
679 if (rc
!= 0 && rc
!= -ESHUTDOWN
) {
681 /* We can't do much more than wait for a reset */
682 WARNING(fsg
, "error in submission: %s --> %d\n",
688 static void ep0_complete(struct usb_ep
*ep
, struct usb_request
*req
)
690 struct fsg_dev
*fsg
= ep
->driver_data
;
693 dump_msg(fsg
, fsg
->ep0req_name
, req
->buf
, req
->actual
);
694 if (req
->status
|| req
->actual
!= req
->length
)
695 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
696 req
->status
, req
->actual
, req
->length
);
697 if (req
->status
== -ECONNRESET
) // Request was cancelled
698 usb_ep_fifo_flush(ep
);
700 if (req
->status
== 0 && req
->context
)
701 ((fsg_routine_t
) (req
->context
))(fsg
);
705 /*-------------------------------------------------------------------------*/
707 /* Bulk and interrupt endpoint completion handlers.
708 * These always run in_irq. */
710 static void bulk_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
712 struct fsg_dev
*fsg
= ep
->driver_data
;
713 struct fsg_buffhd
*bh
= req
->context
;
715 if (req
->status
|| req
->actual
!= req
->length
)
716 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
717 req
->status
, req
->actual
, req
->length
);
718 if (req
->status
== -ECONNRESET
) // Request was cancelled
719 usb_ep_fifo_flush(ep
);
721 /* Hold the lock while we update the request and buffer states */
723 spin_lock(&fsg
->lock
);
725 bh
->state
= BUF_STATE_EMPTY
;
727 spin_unlock(&fsg
->lock
);
730 static void bulk_out_complete(struct usb_ep
*ep
, struct usb_request
*req
)
732 struct fsg_dev
*fsg
= ep
->driver_data
;
733 struct fsg_buffhd
*bh
= req
->context
;
735 dump_msg(fsg
, "bulk-out", req
->buf
, req
->actual
);
736 if (req
->status
|| req
->actual
!= bh
->bulk_out_intended_length
)
737 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
738 req
->status
, req
->actual
,
739 bh
->bulk_out_intended_length
);
740 if (req
->status
== -ECONNRESET
) // Request was cancelled
741 usb_ep_fifo_flush(ep
);
743 /* Hold the lock while we update the request and buffer states */
745 spin_lock(&fsg
->lock
);
747 bh
->state
= BUF_STATE_FULL
;
749 spin_unlock(&fsg
->lock
);
753 #ifdef CONFIG_USB_FILE_STORAGE_TEST
754 static void intr_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
756 struct fsg_dev
*fsg
= ep
->driver_data
;
757 struct fsg_buffhd
*bh
= req
->context
;
759 if (req
->status
|| req
->actual
!= req
->length
)
760 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
761 req
->status
, req
->actual
, req
->length
);
762 if (req
->status
== -ECONNRESET
) // Request was cancelled
763 usb_ep_fifo_flush(ep
);
765 /* Hold the lock while we update the request and buffer states */
767 spin_lock(&fsg
->lock
);
768 fsg
->intreq_busy
= 0;
769 bh
->state
= BUF_STATE_EMPTY
;
771 spin_unlock(&fsg
->lock
);
775 static void intr_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
777 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
780 /*-------------------------------------------------------------------------*/
782 /* Ep0 class-specific handlers. These always run in_irq. */
784 #ifdef CONFIG_USB_FILE_STORAGE_TEST
785 static void received_cbi_adsc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
787 struct usb_request
*req
= fsg
->ep0req
;
788 static u8 cbi_reset_cmnd
[6] = {
789 SC_SEND_DIAGNOSTIC
, 4, 0xff, 0xff, 0xff, 0xff};
791 /* Error in command transfer? */
792 if (req
->status
|| req
->length
!= req
->actual
||
793 req
->actual
< 6 || req
->actual
> MAX_COMMAND_SIZE
) {
795 /* Not all controllers allow a protocol stall after
796 * receiving control-out data, but we'll try anyway. */
797 fsg_set_halt(fsg
, fsg
->ep0
);
798 return; // Wait for reset
801 /* Is it the special reset command? */
802 if (req
->actual
>= sizeof cbi_reset_cmnd
&&
803 memcmp(req
->buf
, cbi_reset_cmnd
,
804 sizeof cbi_reset_cmnd
) == 0) {
806 /* Raise an exception to stop the current operation
807 * and reinitialize our state. */
808 DBG(fsg
, "cbi reset request\n");
809 raise_exception(fsg
, FSG_STATE_RESET
);
813 VDBG(fsg
, "CB[I] accept device-specific command\n");
814 spin_lock(&fsg
->lock
);
816 /* Save the command for later */
817 if (fsg
->cbbuf_cmnd_size
)
818 WARNING(fsg
, "CB[I] overwriting previous command\n");
819 fsg
->cbbuf_cmnd_size
= req
->actual
;
820 memcpy(fsg
->cbbuf_cmnd
, req
->buf
, fsg
->cbbuf_cmnd_size
);
823 spin_unlock(&fsg
->lock
);
827 static void received_cbi_adsc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
829 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
832 static int class_setup_req(struct fsg_dev
*fsg
,
833 const struct usb_ctrlrequest
*ctrl
)
835 struct usb_request
*req
= fsg
->ep0req
;
836 int value
= -EOPNOTSUPP
;
837 u16 w_index
= le16_to_cpu(ctrl
->wIndex
);
838 u16 w_value
= le16_to_cpu(ctrl
->wValue
);
839 u16 w_length
= le16_to_cpu(ctrl
->wLength
);
844 /* Handle Bulk-only class-specific requests */
845 if (transport_is_bbb()) {
846 switch (ctrl
->bRequest
) {
848 case USB_BULK_RESET_REQUEST
:
849 if (ctrl
->bRequestType
!= (USB_DIR_OUT
|
850 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
852 if (w_index
!= 0 || w_value
!= 0) {
857 /* Raise an exception to stop the current operation
858 * and reinitialize our state. */
859 DBG(fsg
, "bulk reset request\n");
860 raise_exception(fsg
, FSG_STATE_RESET
);
861 value
= DELAYED_STATUS
;
864 case USB_BULK_GET_MAX_LUN_REQUEST
:
865 if (ctrl
->bRequestType
!= (USB_DIR_IN
|
866 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
868 if (w_index
!= 0 || w_value
!= 0) {
872 VDBG(fsg
, "get max LUN\n");
873 *(u8
*) req
->buf
= fsg
->nluns
- 1;
879 /* Handle CBI class-specific requests */
881 switch (ctrl
->bRequest
) {
883 case USB_CBI_ADSC_REQUEST
:
884 if (ctrl
->bRequestType
!= (USB_DIR_OUT
|
885 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
887 if (w_index
!= 0 || w_value
!= 0) {
891 if (w_length
> MAX_COMMAND_SIZE
) {
896 fsg
->ep0req
->context
= received_cbi_adsc
;
901 if (value
== -EOPNOTSUPP
)
903 "unknown class-specific control req "
904 "%02x.%02x v%04x i%04x l%u\n",
905 ctrl
->bRequestType
, ctrl
->bRequest
,
906 le16_to_cpu(ctrl
->wValue
), w_index
, w_length
);
911 /*-------------------------------------------------------------------------*/
913 /* Ep0 standard request handlers. These always run in_irq. */
915 static int standard_setup_req(struct fsg_dev
*fsg
,
916 const struct usb_ctrlrequest
*ctrl
)
918 struct usb_request
*req
= fsg
->ep0req
;
919 int value
= -EOPNOTSUPP
;
920 u16 w_index
= le16_to_cpu(ctrl
->wIndex
);
921 u16 w_value
= le16_to_cpu(ctrl
->wValue
);
923 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
924 * but config change events will also reconfigure hardware. */
925 switch (ctrl
->bRequest
) {
927 case USB_REQ_GET_DESCRIPTOR
:
928 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
931 switch (w_value
>> 8) {
934 VDBG(fsg
, "get device descriptor\n");
935 value
= sizeof device_desc
;
936 memcpy(req
->buf
, &device_desc
, value
);
938 case USB_DT_DEVICE_QUALIFIER
:
939 VDBG(fsg
, "get device qualifier\n");
940 if (!gadget_is_dualspeed(fsg
->gadget
))
942 value
= sizeof dev_qualifier
;
943 memcpy(req
->buf
, &dev_qualifier
, value
);
946 case USB_DT_OTHER_SPEED_CONFIG
:
947 VDBG(fsg
, "get other-speed config descriptor\n");
948 if (!gadget_is_dualspeed(fsg
->gadget
))
952 VDBG(fsg
, "get configuration descriptor\n");
954 value
= populate_config_buf(fsg
->gadget
,
961 VDBG(fsg
, "get string descriptor\n");
963 /* wIndex == language code */
964 value
= usb_gadget_get_string(&fsg_stringtab
,
965 w_value
& 0xff, req
->buf
);
970 /* One config, two speeds */
971 case USB_REQ_SET_CONFIGURATION
:
972 if (ctrl
->bRequestType
!= (USB_DIR_OUT
| USB_TYPE_STANDARD
|
975 VDBG(fsg
, "set configuration\n");
976 if (w_value
== CONFIG_VALUE
|| w_value
== 0) {
977 fsg
->new_config
= w_value
;
979 /* Raise an exception to wipe out previous transaction
980 * state (queued bufs, etc) and set the new config. */
981 raise_exception(fsg
, FSG_STATE_CONFIG_CHANGE
);
982 value
= DELAYED_STATUS
;
985 case USB_REQ_GET_CONFIGURATION
:
986 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
989 VDBG(fsg
, "get configuration\n");
990 *(u8
*) req
->buf
= fsg
->config
;
994 case USB_REQ_SET_INTERFACE
:
995 if (ctrl
->bRequestType
!= (USB_DIR_OUT
| USB_TYPE_STANDARD
|
996 USB_RECIP_INTERFACE
))
998 if (fsg
->config
&& w_index
== 0) {
1000 /* Raise an exception to wipe out previous transaction
1001 * state (queued bufs, etc) and install the new
1002 * interface altsetting. */
1003 raise_exception(fsg
, FSG_STATE_INTERFACE_CHANGE
);
1004 value
= DELAYED_STATUS
;
1007 case USB_REQ_GET_INTERFACE
:
1008 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
1009 USB_RECIP_INTERFACE
))
1017 VDBG(fsg
, "get interface\n");
1018 *(u8
*) req
->buf
= 0;
1024 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1025 ctrl
->bRequestType
, ctrl
->bRequest
,
1026 w_value
, w_index
, le16_to_cpu(ctrl
->wLength
));
1033 static int fsg_setup(struct usb_gadget
*gadget
,
1034 const struct usb_ctrlrequest
*ctrl
)
1036 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
1038 int w_length
= le16_to_cpu(ctrl
->wLength
);
1040 ++fsg
->ep0_req_tag
; // Record arrival of a new request
1041 fsg
->ep0req
->context
= NULL
;
1042 fsg
->ep0req
->length
= 0;
1043 dump_msg(fsg
, "ep0-setup", (u8
*) ctrl
, sizeof(*ctrl
));
1045 if ((ctrl
->bRequestType
& USB_TYPE_MASK
) == USB_TYPE_CLASS
)
1046 rc
= class_setup_req(fsg
, ctrl
);
1048 rc
= standard_setup_req(fsg
, ctrl
);
1050 /* Respond with data/status or defer until later? */
1051 if (rc
>= 0 && rc
!= DELAYED_STATUS
) {
1052 rc
= min(rc
, w_length
);
1053 fsg
->ep0req
->length
= rc
;
1054 fsg
->ep0req
->zero
= rc
< w_length
;
1055 fsg
->ep0req_name
= (ctrl
->bRequestType
& USB_DIR_IN
?
1056 "ep0-in" : "ep0-out");
1057 rc
= ep0_queue(fsg
);
1060 /* Device either stalls (rc < 0) or reports success */
1065 /*-------------------------------------------------------------------------*/
1067 /* All the following routines run in process context */
1070 /* Use this for bulk or interrupt transfers, not ep0 */
1071 static void start_transfer(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
1072 struct usb_request
*req
, int *pbusy
,
1073 enum fsg_buffer_state
*state
)
1077 if (ep
== fsg
->bulk_in
)
1078 dump_msg(fsg
, "bulk-in", req
->buf
, req
->length
);
1079 else if (ep
== fsg
->intr_in
)
1080 dump_msg(fsg
, "intr-in", req
->buf
, req
->length
);
1082 spin_lock_irq(&fsg
->lock
);
1084 *state
= BUF_STATE_BUSY
;
1085 spin_unlock_irq(&fsg
->lock
);
1086 rc
= usb_ep_queue(ep
, req
, GFP_KERNEL
);
1089 *state
= BUF_STATE_EMPTY
;
1091 /* We can't do much more than wait for a reset */
1093 /* Note: currently the net2280 driver fails zero-length
1094 * submissions if DMA is enabled. */
1095 if (rc
!= -ESHUTDOWN
&& !(rc
== -EOPNOTSUPP
&&
1097 WARNING(fsg
, "error in submission: %s --> %d\n",
1103 static int sleep_thread(struct fsg_dev
*fsg
)
1107 /* Wait until a signal arrives or we are woken up */
1110 set_current_state(TASK_INTERRUPTIBLE
);
1111 if (signal_pending(current
)) {
1115 if (fsg
->thread_wakeup_needed
)
1119 __set_current_state(TASK_RUNNING
);
1120 fsg
->thread_wakeup_needed
= 0;
1125 /*-------------------------------------------------------------------------*/
1127 static int do_read(struct fsg_dev
*fsg
)
1129 struct fsg_lun
*curlun
= fsg
->curlun
;
1131 struct fsg_buffhd
*bh
;
1134 loff_t file_offset
, file_offset_tmp
;
1135 unsigned int amount
;
1136 unsigned int partial_page
;
1139 /* Get the starting Logical Block Address and check that it's
1141 if (fsg
->cmnd
[0] == SC_READ_6
)
1142 lba
= get_unaligned_be24(&fsg
->cmnd
[1]);
1144 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1146 /* We allow DPO (Disable Page Out = don't save data in the
1147 * cache) and FUA (Force Unit Access = don't read from the
1148 * cache), but we don't implement them. */
1149 if ((fsg
->cmnd
[1] & ~0x18) != 0) {
1150 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1154 if (lba
>= curlun
->num_sectors
) {
1155 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1158 file_offset
= ((loff_t
) lba
) << 9;
1160 /* Carry out the file reads */
1161 amount_left
= fsg
->data_size_from_cmnd
;
1162 if (unlikely(amount_left
== 0))
1163 return -EIO
; // No default reply
1167 /* Figure out how much we need to read:
1168 * Try to read the remaining amount.
1169 * But don't read more than the buffer size.
1170 * And don't try to read past the end of the file.
1171 * Finally, if we're not at a page boundary, don't read past
1173 * If this means reading 0 then we were asked to read past
1174 * the end of file. */
1175 amount
= min((unsigned int) amount_left
, mod_data
.buflen
);
1176 amount
= min((loff_t
) amount
,
1177 curlun
->file_length
- file_offset
);
1178 partial_page
= file_offset
& (PAGE_CACHE_SIZE
- 1);
1179 if (partial_page
> 0)
1180 amount
= min(amount
, (unsigned int) PAGE_CACHE_SIZE
-
1183 /* Wait for the next buffer to become available */
1184 bh
= fsg
->next_buffhd_to_fill
;
1185 while (bh
->state
!= BUF_STATE_EMPTY
) {
1186 rc
= sleep_thread(fsg
);
1191 /* If we were asked to read past the end of file,
1192 * end with an empty buffer. */
1194 curlun
->sense_data
=
1195 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1196 curlun
->sense_data_info
= file_offset
>> 9;
1197 curlun
->info_valid
= 1;
1198 bh
->inreq
->length
= 0;
1199 bh
->state
= BUF_STATE_FULL
;
1203 /* Perform the read */
1204 file_offset_tmp
= file_offset
;
1205 nread
= vfs_read(curlun
->filp
,
1206 (char __user
*) bh
->buf
,
1207 amount
, &file_offset_tmp
);
1208 VLDBG(curlun
, "file read %u @ %llu -> %d\n", amount
,
1209 (unsigned long long) file_offset
,
1211 if (signal_pending(current
))
1215 LDBG(curlun
, "error in file read: %d\n",
1218 } else if (nread
< amount
) {
1219 LDBG(curlun
, "partial file read: %d/%u\n",
1220 (int) nread
, amount
);
1221 nread
-= (nread
& 511); // Round down to a block
1223 file_offset
+= nread
;
1224 amount_left
-= nread
;
1225 fsg
->residue
-= nread
;
1226 bh
->inreq
->length
= nread
;
1227 bh
->state
= BUF_STATE_FULL
;
1229 /* If an error occurred, report it and its position */
1230 if (nread
< amount
) {
1231 curlun
->sense_data
= SS_UNRECOVERED_READ_ERROR
;
1232 curlun
->sense_data_info
= file_offset
>> 9;
1233 curlun
->info_valid
= 1;
1237 if (amount_left
== 0)
1238 break; // No more left to read
1240 /* Send this buffer and go read some more */
1241 bh
->inreq
->zero
= 0;
1242 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
1243 &bh
->inreq_busy
, &bh
->state
);
1244 fsg
->next_buffhd_to_fill
= bh
->next
;
1247 return -EIO
; // No default reply
1251 /*-------------------------------------------------------------------------*/
1253 static int do_write(struct fsg_dev
*fsg
)
1255 struct fsg_lun
*curlun
= fsg
->curlun
;
1257 struct fsg_buffhd
*bh
;
1259 u32 amount_left_to_req
, amount_left_to_write
;
1260 loff_t usb_offset
, file_offset
, file_offset_tmp
;
1261 unsigned int amount
;
1262 unsigned int partial_page
;
1267 curlun
->sense_data
= SS_WRITE_PROTECTED
;
1270 spin_lock(&curlun
->filp
->f_lock
);
1271 curlun
->filp
->f_flags
&= ~O_SYNC
; // Default is not to wait
1272 spin_unlock(&curlun
->filp
->f_lock
);
1274 /* Get the starting Logical Block Address and check that it's
1276 if (fsg
->cmnd
[0] == SC_WRITE_6
)
1277 lba
= get_unaligned_be24(&fsg
->cmnd
[1]);
1279 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1281 /* We allow DPO (Disable Page Out = don't save data in the
1282 * cache) and FUA (Force Unit Access = write directly to the
1283 * medium). We don't implement DPO; we implement FUA by
1284 * performing synchronous output. */
1285 if ((fsg
->cmnd
[1] & ~0x18) != 0) {
1286 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1290 if (!curlun
->nofua
&& (fsg
->cmnd
[1] & 0x08)) {
1291 spin_lock(&curlun
->filp
->f_lock
);
1292 curlun
->filp
->f_flags
|= O_DSYNC
;
1293 spin_unlock(&curlun
->filp
->f_lock
);
1296 if (lba
>= curlun
->num_sectors
) {
1297 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1301 /* Carry out the file writes */
1303 file_offset
= usb_offset
= ((loff_t
) lba
) << 9;
1304 amount_left_to_req
= amount_left_to_write
= fsg
->data_size_from_cmnd
;
1306 while (amount_left_to_write
> 0) {
1308 /* Queue a request for more data from the host */
1309 bh
= fsg
->next_buffhd_to_fill
;
1310 if (bh
->state
== BUF_STATE_EMPTY
&& get_some_more
) {
1312 /* Figure out how much we want to get:
1313 * Try to get the remaining amount.
1314 * But don't get more than the buffer size.
1315 * And don't try to go past the end of the file.
1316 * If we're not at a page boundary,
1317 * don't go past the next page.
1318 * If this means getting 0, then we were asked
1319 * to write past the end of file.
1320 * Finally, round down to a block boundary. */
1321 amount
= min(amount_left_to_req
, mod_data
.buflen
);
1322 amount
= min((loff_t
) amount
, curlun
->file_length
-
1324 partial_page
= usb_offset
& (PAGE_CACHE_SIZE
- 1);
1325 if (partial_page
> 0)
1326 amount
= min(amount
,
1327 (unsigned int) PAGE_CACHE_SIZE
- partial_page
);
1331 curlun
->sense_data
=
1332 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1333 curlun
->sense_data_info
= usb_offset
>> 9;
1334 curlun
->info_valid
= 1;
1337 amount
-= (amount
& 511);
1340 /* Why were we were asked to transfer a
1346 /* Get the next buffer */
1347 usb_offset
+= amount
;
1348 fsg
->usb_amount_left
-= amount
;
1349 amount_left_to_req
-= amount
;
1350 if (amount_left_to_req
== 0)
1353 /* amount is always divisible by 512, hence by
1354 * the bulk-out maxpacket size */
1355 bh
->outreq
->length
= bh
->bulk_out_intended_length
=
1357 bh
->outreq
->short_not_ok
= 1;
1358 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
1359 &bh
->outreq_busy
, &bh
->state
);
1360 fsg
->next_buffhd_to_fill
= bh
->next
;
1364 /* Write the received data to the backing file */
1365 bh
= fsg
->next_buffhd_to_drain
;
1366 if (bh
->state
== BUF_STATE_EMPTY
&& !get_some_more
)
1367 break; // We stopped early
1368 if (bh
->state
== BUF_STATE_FULL
) {
1370 fsg
->next_buffhd_to_drain
= bh
->next
;
1371 bh
->state
= BUF_STATE_EMPTY
;
1373 /* Did something go wrong with the transfer? */
1374 if (bh
->outreq
->status
!= 0) {
1375 curlun
->sense_data
= SS_COMMUNICATION_FAILURE
;
1376 curlun
->sense_data_info
= file_offset
>> 9;
1377 curlun
->info_valid
= 1;
1381 amount
= bh
->outreq
->actual
;
1382 if (curlun
->file_length
- file_offset
< amount
) {
1384 "write %u @ %llu beyond end %llu\n",
1385 amount
, (unsigned long long) file_offset
,
1386 (unsigned long long) curlun
->file_length
);
1387 amount
= curlun
->file_length
- file_offset
;
1390 /* Perform the write */
1391 file_offset_tmp
= file_offset
;
1392 nwritten
= vfs_write(curlun
->filp
,
1393 (char __user
*) bh
->buf
,
1394 amount
, &file_offset_tmp
);
1395 VLDBG(curlun
, "file write %u @ %llu -> %d\n", amount
,
1396 (unsigned long long) file_offset
,
1398 if (signal_pending(current
))
1399 return -EINTR
; // Interrupted!
1402 LDBG(curlun
, "error in file write: %d\n",
1405 } else if (nwritten
< amount
) {
1406 LDBG(curlun
, "partial file write: %d/%u\n",
1407 (int) nwritten
, amount
);
1408 nwritten
-= (nwritten
& 511);
1409 // Round down to a block
1411 file_offset
+= nwritten
;
1412 amount_left_to_write
-= nwritten
;
1413 fsg
->residue
-= nwritten
;
1415 /* If an error occurred, report it and its position */
1416 if (nwritten
< amount
) {
1417 curlun
->sense_data
= SS_WRITE_ERROR
;
1418 curlun
->sense_data_info
= file_offset
>> 9;
1419 curlun
->info_valid
= 1;
1423 /* Did the host decide to stop early? */
1424 if (bh
->outreq
->actual
!= bh
->outreq
->length
) {
1425 fsg
->short_packet_received
= 1;
1431 /* Wait for something to happen */
1432 rc
= sleep_thread(fsg
);
1437 return -EIO
; // No default reply
1441 /*-------------------------------------------------------------------------*/
1443 static int do_synchronize_cache(struct fsg_dev
*fsg
)
1445 struct fsg_lun
*curlun
= fsg
->curlun
;
1448 /* We ignore the requested LBA and write out all file's
1449 * dirty data buffers. */
1450 rc
= fsg_lun_fsync_sub(curlun
);
1452 curlun
->sense_data
= SS_WRITE_ERROR
;
1457 /*-------------------------------------------------------------------------*/
1459 static void invalidate_sub(struct fsg_lun
*curlun
)
1461 struct file
*filp
= curlun
->filp
;
1462 struct inode
*inode
= filp
->f_path
.dentry
->d_inode
;
1465 rc
= invalidate_mapping_pages(inode
->i_mapping
, 0, -1);
1466 VLDBG(curlun
, "invalidate_mapping_pages -> %ld\n", rc
);
1469 static int do_verify(struct fsg_dev
*fsg
)
1471 struct fsg_lun
*curlun
= fsg
->curlun
;
1473 u32 verification_length
;
1474 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
1475 loff_t file_offset
, file_offset_tmp
;
1477 unsigned int amount
;
1480 /* Get the starting Logical Block Address and check that it's
1482 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1483 if (lba
>= curlun
->num_sectors
) {
1484 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1488 /* We allow DPO (Disable Page Out = don't save data in the
1489 * cache) but we don't implement it. */
1490 if ((fsg
->cmnd
[1] & ~0x10) != 0) {
1491 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1495 verification_length
= get_unaligned_be16(&fsg
->cmnd
[7]);
1496 if (unlikely(verification_length
== 0))
1497 return -EIO
; // No default reply
1499 /* Prepare to carry out the file verify */
1500 amount_left
= verification_length
<< 9;
1501 file_offset
= ((loff_t
) lba
) << 9;
1503 /* Write out all the dirty buffers before invalidating them */
1504 fsg_lun_fsync_sub(curlun
);
1505 if (signal_pending(current
))
1508 invalidate_sub(curlun
);
1509 if (signal_pending(current
))
1512 /* Just try to read the requested blocks */
1513 while (amount_left
> 0) {
1515 /* Figure out how much we need to read:
1516 * Try to read the remaining amount, but not more than
1518 * And don't try to read past the end of the file.
1519 * If this means reading 0 then we were asked to read
1520 * past the end of file. */
1521 amount
= min((unsigned int) amount_left
, mod_data
.buflen
);
1522 amount
= min((loff_t
) amount
,
1523 curlun
->file_length
- file_offset
);
1525 curlun
->sense_data
=
1526 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1527 curlun
->sense_data_info
= file_offset
>> 9;
1528 curlun
->info_valid
= 1;
1532 /* Perform the read */
1533 file_offset_tmp
= file_offset
;
1534 nread
= vfs_read(curlun
->filp
,
1535 (char __user
*) bh
->buf
,
1536 amount
, &file_offset_tmp
);
1537 VLDBG(curlun
, "file read %u @ %llu -> %d\n", amount
,
1538 (unsigned long long) file_offset
,
1540 if (signal_pending(current
))
1544 LDBG(curlun
, "error in file verify: %d\n",
1547 } else if (nread
< amount
) {
1548 LDBG(curlun
, "partial file verify: %d/%u\n",
1549 (int) nread
, amount
);
1550 nread
-= (nread
& 511); // Round down to a sector
1553 curlun
->sense_data
= SS_UNRECOVERED_READ_ERROR
;
1554 curlun
->sense_data_info
= file_offset
>> 9;
1555 curlun
->info_valid
= 1;
1558 file_offset
+= nread
;
1559 amount_left
-= nread
;
1565 /*-------------------------------------------------------------------------*/
1567 static int do_inquiry(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1569 u8
*buf
= (u8
*) bh
->buf
;
1571 static char vendor_id
[] = "Linux ";
1572 static char product_disk_id
[] = "File-Stor Gadget";
1573 static char product_cdrom_id
[] = "File-CD Gadget ";
1575 if (!fsg
->curlun
) { // Unsupported LUNs are okay
1576 fsg
->bad_lun_okay
= 1;
1578 buf
[0] = 0x7f; // Unsupported, no device-type
1579 buf
[4] = 31; // Additional length
1584 buf
[0] = (mod_data
.cdrom
? TYPE_CDROM
: TYPE_DISK
);
1585 if (mod_data
.removable
)
1587 buf
[2] = 2; // ANSI SCSI level 2
1588 buf
[3] = 2; // SCSI-2 INQUIRY data format
1589 buf
[4] = 31; // Additional length
1590 // No special options
1591 sprintf(buf
+ 8, "%-8s%-16s%04x", vendor_id
,
1592 (mod_data
.cdrom
? product_cdrom_id
:
1599 static int do_request_sense(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1601 struct fsg_lun
*curlun
= fsg
->curlun
;
1602 u8
*buf
= (u8
*) bh
->buf
;
1607 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1609 * If a REQUEST SENSE command is received from an initiator
1610 * with a pending unit attention condition (before the target
1611 * generates the contingent allegiance condition), then the
1612 * target shall either:
1613 * a) report any pending sense data and preserve the unit
1614 * attention condition on the logical unit, or,
1615 * b) report the unit attention condition, may discard any
1616 * pending sense data, and clear the unit attention
1617 * condition on the logical unit for that initiator.
1619 * FSG normally uses option a); enable this code to use option b).
1622 if (curlun
&& curlun
->unit_attention_data
!= SS_NO_SENSE
) {
1623 curlun
->sense_data
= curlun
->unit_attention_data
;
1624 curlun
->unit_attention_data
= SS_NO_SENSE
;
1628 if (!curlun
) { // Unsupported LUNs are okay
1629 fsg
->bad_lun_okay
= 1;
1630 sd
= SS_LOGICAL_UNIT_NOT_SUPPORTED
;
1634 sd
= curlun
->sense_data
;
1635 sdinfo
= curlun
->sense_data_info
;
1636 valid
= curlun
->info_valid
<< 7;
1637 curlun
->sense_data
= SS_NO_SENSE
;
1638 curlun
->sense_data_info
= 0;
1639 curlun
->info_valid
= 0;
1643 buf
[0] = valid
| 0x70; // Valid, current error
1645 put_unaligned_be32(sdinfo
, &buf
[3]); /* Sense information */
1646 buf
[7] = 18 - 8; // Additional sense length
1653 static int do_read_capacity(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1655 struct fsg_lun
*curlun
= fsg
->curlun
;
1656 u32 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1657 int pmi
= fsg
->cmnd
[8];
1658 u8
*buf
= (u8
*) bh
->buf
;
1660 /* Check the PMI and LBA fields */
1661 if (pmi
> 1 || (pmi
== 0 && lba
!= 0)) {
1662 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1666 put_unaligned_be32(curlun
->num_sectors
- 1, &buf
[0]);
1667 /* Max logical block */
1668 put_unaligned_be32(512, &buf
[4]); /* Block length */
1673 static int do_read_header(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1675 struct fsg_lun
*curlun
= fsg
->curlun
;
1676 int msf
= fsg
->cmnd
[1] & 0x02;
1677 u32 lba
= get_unaligned_be32(&fsg
->cmnd
[2]);
1678 u8
*buf
= (u8
*) bh
->buf
;
1680 if ((fsg
->cmnd
[1] & ~0x02) != 0) { /* Mask away MSF */
1681 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1684 if (lba
>= curlun
->num_sectors
) {
1685 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1690 buf
[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1691 store_cdrom_address(&buf
[4], msf
, lba
);
1696 static int do_read_toc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1698 struct fsg_lun
*curlun
= fsg
->curlun
;
1699 int msf
= fsg
->cmnd
[1] & 0x02;
1700 int start_track
= fsg
->cmnd
[6];
1701 u8
*buf
= (u8
*) bh
->buf
;
1703 if ((fsg
->cmnd
[1] & ~0x02) != 0 || /* Mask away MSF */
1705 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1710 buf
[1] = (20-2); /* TOC data length */
1711 buf
[2] = 1; /* First track number */
1712 buf
[3] = 1; /* Last track number */
1713 buf
[5] = 0x16; /* Data track, copying allowed */
1714 buf
[6] = 0x01; /* Only track is number 1 */
1715 store_cdrom_address(&buf
[8], msf
, 0);
1717 buf
[13] = 0x16; /* Lead-out track is data */
1718 buf
[14] = 0xAA; /* Lead-out track number */
1719 store_cdrom_address(&buf
[16], msf
, curlun
->num_sectors
);
1724 static int do_mode_sense(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1726 struct fsg_lun
*curlun
= fsg
->curlun
;
1727 int mscmnd
= fsg
->cmnd
[0];
1728 u8
*buf
= (u8
*) bh
->buf
;
1731 int changeable_values
, all_pages
;
1735 if ((fsg
->cmnd
[1] & ~0x08) != 0) { // Mask away DBD
1736 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1739 pc
= fsg
->cmnd
[2] >> 6;
1740 page_code
= fsg
->cmnd
[2] & 0x3f;
1742 curlun
->sense_data
= SS_SAVING_PARAMETERS_NOT_SUPPORTED
;
1745 changeable_values
= (pc
== 1);
1746 all_pages
= (page_code
== 0x3f);
1748 /* Write the mode parameter header. Fixed values are: default
1749 * medium type, no cache control (DPOFUA), and no block descriptors.
1750 * The only variable value is the WriteProtect bit. We will fill in
1751 * the mode data length later. */
1753 if (mscmnd
== SC_MODE_SENSE_6
) {
1754 buf
[2] = (curlun
->ro
? 0x80 : 0x00); // WP, DPOFUA
1757 } else { // SC_MODE_SENSE_10
1758 buf
[3] = (curlun
->ro
? 0x80 : 0x00); // WP, DPOFUA
1760 limit
= 65535; // Should really be mod_data.buflen
1763 /* No block descriptors */
1765 /* The mode pages, in numerical order. The only page we support
1766 * is the Caching page. */
1767 if (page_code
== 0x08 || all_pages
) {
1769 buf
[0] = 0x08; // Page code
1770 buf
[1] = 10; // Page length
1771 memset(buf
+2, 0, 10); // None of the fields are changeable
1773 if (!changeable_values
) {
1774 buf
[2] = 0x04; // Write cache enable,
1775 // Read cache not disabled
1776 // No cache retention priorities
1777 put_unaligned_be16(0xffff, &buf
[4]);
1778 /* Don't disable prefetch */
1779 /* Minimum prefetch = 0 */
1780 put_unaligned_be16(0xffff, &buf
[8]);
1781 /* Maximum prefetch */
1782 put_unaligned_be16(0xffff, &buf
[10]);
1783 /* Maximum prefetch ceiling */
1788 /* Check that a valid page was requested and the mode data length
1789 * isn't too long. */
1791 if (!valid_page
|| len
> limit
) {
1792 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1796 /* Store the mode data length */
1797 if (mscmnd
== SC_MODE_SENSE_6
)
1800 put_unaligned_be16(len
- 2, buf0
);
1805 static int do_start_stop(struct fsg_dev
*fsg
)
1807 struct fsg_lun
*curlun
= fsg
->curlun
;
1810 if (!mod_data
.removable
) {
1811 curlun
->sense_data
= SS_INVALID_COMMAND
;
1815 // int immed = fsg->cmnd[1] & 0x01;
1816 loej
= fsg
->cmnd
[4] & 0x02;
1817 start
= fsg
->cmnd
[4] & 0x01;
1819 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1820 if ((fsg
->cmnd
[1] & ~0x01) != 0 || // Mask away Immed
1821 (fsg
->cmnd
[4] & ~0x03) != 0) { // Mask LoEj, Start
1822 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1828 /* Are we allowed to unload the media? */
1829 if (curlun
->prevent_medium_removal
) {
1830 LDBG(curlun
, "unload attempt prevented\n");
1831 curlun
->sense_data
= SS_MEDIUM_REMOVAL_PREVENTED
;
1834 if (loej
) { // Simulate an unload/eject
1835 up_read(&fsg
->filesem
);
1836 down_write(&fsg
->filesem
);
1837 fsg_lun_close(curlun
);
1838 up_write(&fsg
->filesem
);
1839 down_read(&fsg
->filesem
);
1843 /* Our emulation doesn't support mounting; the medium is
1844 * available for use as soon as it is loaded. */
1845 if (!fsg_lun_is_open(curlun
)) {
1846 curlun
->sense_data
= SS_MEDIUM_NOT_PRESENT
;
1855 static int do_prevent_allow(struct fsg_dev
*fsg
)
1857 struct fsg_lun
*curlun
= fsg
->curlun
;
1860 if (!mod_data
.removable
) {
1861 curlun
->sense_data
= SS_INVALID_COMMAND
;
1865 prevent
= fsg
->cmnd
[4] & 0x01;
1866 if ((fsg
->cmnd
[4] & ~0x01) != 0) { // Mask away Prevent
1867 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1871 if (curlun
->prevent_medium_removal
&& !prevent
)
1872 fsg_lun_fsync_sub(curlun
);
1873 curlun
->prevent_medium_removal
= prevent
;
1878 static int do_read_format_capacities(struct fsg_dev
*fsg
,
1879 struct fsg_buffhd
*bh
)
1881 struct fsg_lun
*curlun
= fsg
->curlun
;
1882 u8
*buf
= (u8
*) bh
->buf
;
1884 buf
[0] = buf
[1] = buf
[2] = 0;
1885 buf
[3] = 8; // Only the Current/Maximum Capacity Descriptor
1888 put_unaligned_be32(curlun
->num_sectors
, &buf
[0]);
1889 /* Number of blocks */
1890 put_unaligned_be32(512, &buf
[4]); /* Block length */
1891 buf
[4] = 0x02; /* Current capacity */
1896 static int do_mode_select(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1898 struct fsg_lun
*curlun
= fsg
->curlun
;
1900 /* We don't support MODE SELECT */
1901 curlun
->sense_data
= SS_INVALID_COMMAND
;
1906 /*-------------------------------------------------------------------------*/
1908 static int halt_bulk_in_endpoint(struct fsg_dev
*fsg
)
1912 rc
= fsg_set_halt(fsg
, fsg
->bulk_in
);
1914 VDBG(fsg
, "delayed bulk-in endpoint halt\n");
1916 if (rc
!= -EAGAIN
) {
1917 WARNING(fsg
, "usb_ep_set_halt -> %d\n", rc
);
1922 /* Wait for a short time and then try again */
1923 if (msleep_interruptible(100) != 0)
1925 rc
= usb_ep_set_halt(fsg
->bulk_in
);
1930 static int wedge_bulk_in_endpoint(struct fsg_dev
*fsg
)
1934 DBG(fsg
, "bulk-in set wedge\n");
1935 rc
= usb_ep_set_wedge(fsg
->bulk_in
);
1937 VDBG(fsg
, "delayed bulk-in endpoint wedge\n");
1939 if (rc
!= -EAGAIN
) {
1940 WARNING(fsg
, "usb_ep_set_wedge -> %d\n", rc
);
1945 /* Wait for a short time and then try again */
1946 if (msleep_interruptible(100) != 0)
1948 rc
= usb_ep_set_wedge(fsg
->bulk_in
);
1953 static int pad_with_zeros(struct fsg_dev
*fsg
)
1955 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
1956 u32 nkeep
= bh
->inreq
->length
;
1960 bh
->state
= BUF_STATE_EMPTY
; // For the first iteration
1961 fsg
->usb_amount_left
= nkeep
+ fsg
->residue
;
1962 while (fsg
->usb_amount_left
> 0) {
1964 /* Wait for the next buffer to be free */
1965 while (bh
->state
!= BUF_STATE_EMPTY
) {
1966 rc
= sleep_thread(fsg
);
1971 nsend
= min(fsg
->usb_amount_left
, (u32
) mod_data
.buflen
);
1972 memset(bh
->buf
+ nkeep
, 0, nsend
- nkeep
);
1973 bh
->inreq
->length
= nsend
;
1974 bh
->inreq
->zero
= 0;
1975 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
1976 &bh
->inreq_busy
, &bh
->state
);
1977 bh
= fsg
->next_buffhd_to_fill
= bh
->next
;
1978 fsg
->usb_amount_left
-= nsend
;
1984 static int throw_away_data(struct fsg_dev
*fsg
)
1986 struct fsg_buffhd
*bh
;
1990 while ((bh
= fsg
->next_buffhd_to_drain
)->state
!= BUF_STATE_EMPTY
||
1991 fsg
->usb_amount_left
> 0) {
1993 /* Throw away the data in a filled buffer */
1994 if (bh
->state
== BUF_STATE_FULL
) {
1996 bh
->state
= BUF_STATE_EMPTY
;
1997 fsg
->next_buffhd_to_drain
= bh
->next
;
1999 /* A short packet or an error ends everything */
2000 if (bh
->outreq
->actual
!= bh
->outreq
->length
||
2001 bh
->outreq
->status
!= 0) {
2002 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2008 /* Try to submit another request if we need one */
2009 bh
= fsg
->next_buffhd_to_fill
;
2010 if (bh
->state
== BUF_STATE_EMPTY
&& fsg
->usb_amount_left
> 0) {
2011 amount
= min(fsg
->usb_amount_left
,
2012 (u32
) mod_data
.buflen
);
2014 /* amount is always divisible by 512, hence by
2015 * the bulk-out maxpacket size */
2016 bh
->outreq
->length
= bh
->bulk_out_intended_length
=
2018 bh
->outreq
->short_not_ok
= 1;
2019 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
2020 &bh
->outreq_busy
, &bh
->state
);
2021 fsg
->next_buffhd_to_fill
= bh
->next
;
2022 fsg
->usb_amount_left
-= amount
;
2026 /* Otherwise wait for something to happen */
2027 rc
= sleep_thread(fsg
);
2035 static int finish_reply(struct fsg_dev
*fsg
)
2037 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
2040 switch (fsg
->data_dir
) {
2042 break; // Nothing to send
2044 /* If we don't know whether the host wants to read or write,
2045 * this must be CB or CBI with an unknown command. We mustn't
2046 * try to send or receive any data. So stall both bulk pipes
2047 * if we can and wait for a reset. */
2048 case DATA_DIR_UNKNOWN
:
2049 if (mod_data
.can_stall
) {
2050 fsg_set_halt(fsg
, fsg
->bulk_out
);
2051 rc
= halt_bulk_in_endpoint(fsg
);
2055 /* All but the last buffer of data must have already been sent */
2056 case DATA_DIR_TO_HOST
:
2057 if (fsg
->data_size
== 0)
2058 ; // Nothing to send
2060 /* If there's no residue, simply send the last buffer */
2061 else if (fsg
->residue
== 0) {
2062 bh
->inreq
->zero
= 0;
2063 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2064 &bh
->inreq_busy
, &bh
->state
);
2065 fsg
->next_buffhd_to_fill
= bh
->next
;
2068 /* There is a residue. For CB and CBI, simply mark the end
2069 * of the data with a short packet. However, if we are
2070 * allowed to stall, there was no data at all (residue ==
2071 * data_size), and the command failed (invalid LUN or
2072 * sense data is set), then halt the bulk-in endpoint
2074 else if (!transport_is_bbb()) {
2075 if (mod_data
.can_stall
&&
2076 fsg
->residue
== fsg
->data_size
&&
2077 (!fsg
->curlun
|| fsg
->curlun
->sense_data
!= SS_NO_SENSE
)) {
2078 bh
->state
= BUF_STATE_EMPTY
;
2079 rc
= halt_bulk_in_endpoint(fsg
);
2081 bh
->inreq
->zero
= 1;
2082 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2083 &bh
->inreq_busy
, &bh
->state
);
2084 fsg
->next_buffhd_to_fill
= bh
->next
;
2088 /* For Bulk-only, if we're allowed to stall then send the
2089 * short packet and halt the bulk-in endpoint. If we can't
2090 * stall, pad out the remaining data with 0's. */
2092 if (mod_data
.can_stall
) {
2093 bh
->inreq
->zero
= 1;
2094 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2095 &bh
->inreq_busy
, &bh
->state
);
2096 fsg
->next_buffhd_to_fill
= bh
->next
;
2097 rc
= halt_bulk_in_endpoint(fsg
);
2099 rc
= pad_with_zeros(fsg
);
2103 /* We have processed all we want from the data the host has sent.
2104 * There may still be outstanding bulk-out requests. */
2105 case DATA_DIR_FROM_HOST
:
2106 if (fsg
->residue
== 0)
2107 ; // Nothing to receive
2109 /* Did the host stop sending unexpectedly early? */
2110 else if (fsg
->short_packet_received
) {
2111 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2115 /* We haven't processed all the incoming data. Even though
2116 * we may be allowed to stall, doing so would cause a race.
2117 * The controller may already have ACK'ed all the remaining
2118 * bulk-out packets, in which case the host wouldn't see a
2119 * STALL. Not realizing the endpoint was halted, it wouldn't
2120 * clear the halt -- leading to problems later on. */
2122 else if (mod_data
.can_stall
) {
2123 fsg_set_halt(fsg
, fsg
->bulk_out
);
2124 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2129 /* We can't stall. Read in the excess data and throw it
2132 rc
= throw_away_data(fsg
);
2139 static int send_status(struct fsg_dev
*fsg
)
2141 struct fsg_lun
*curlun
= fsg
->curlun
;
2142 struct fsg_buffhd
*bh
;
2144 u8 status
= USB_STATUS_PASS
;
2147 /* Wait for the next buffer to become available */
2148 bh
= fsg
->next_buffhd_to_fill
;
2149 while (bh
->state
!= BUF_STATE_EMPTY
) {
2150 rc
= sleep_thread(fsg
);
2156 sd
= curlun
->sense_data
;
2157 sdinfo
= curlun
->sense_data_info
;
2158 } else if (fsg
->bad_lun_okay
)
2161 sd
= SS_LOGICAL_UNIT_NOT_SUPPORTED
;
2163 if (fsg
->phase_error
) {
2164 DBG(fsg
, "sending phase-error status\n");
2165 status
= USB_STATUS_PHASE_ERROR
;
2166 sd
= SS_INVALID_COMMAND
;
2167 } else if (sd
!= SS_NO_SENSE
) {
2168 DBG(fsg
, "sending command-failure status\n");
2169 status
= USB_STATUS_FAIL
;
2170 VDBG(fsg
, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2172 SK(sd
), ASC(sd
), ASCQ(sd
), sdinfo
);
2175 if (transport_is_bbb()) {
2176 struct bulk_cs_wrap
*csw
= bh
->buf
;
2178 /* Store and send the Bulk-only CSW */
2179 csw
->Signature
= cpu_to_le32(USB_BULK_CS_SIG
);
2180 csw
->Tag
= fsg
->tag
;
2181 csw
->Residue
= cpu_to_le32(fsg
->residue
);
2182 csw
->Status
= status
;
2184 bh
->inreq
->length
= USB_BULK_CS_WRAP_LEN
;
2185 bh
->inreq
->zero
= 0;
2186 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2187 &bh
->inreq_busy
, &bh
->state
);
2189 } else if (mod_data
.transport_type
== USB_PR_CB
) {
2191 /* Control-Bulk transport has no status phase! */
2194 } else { // USB_PR_CBI
2195 struct interrupt_data
*buf
= bh
->buf
;
2197 /* Store and send the Interrupt data. UFI sends the ASC
2198 * and ASCQ bytes. Everything else sends a Type (which
2199 * is always 0) and the status Value. */
2200 if (mod_data
.protocol_type
== USB_SC_UFI
) {
2201 buf
->bType
= ASC(sd
);
2202 buf
->bValue
= ASCQ(sd
);
2205 buf
->bValue
= status
;
2207 fsg
->intreq
->length
= CBI_INTERRUPT_DATA_LEN
;
2209 fsg
->intr_buffhd
= bh
; // Point to the right buffhd
2210 fsg
->intreq
->buf
= bh
->inreq
->buf
;
2211 fsg
->intreq
->context
= bh
;
2212 start_transfer(fsg
, fsg
->intr_in
, fsg
->intreq
,
2213 &fsg
->intreq_busy
, &bh
->state
);
2216 fsg
->next_buffhd_to_fill
= bh
->next
;
2221 /*-------------------------------------------------------------------------*/
2223 /* Check whether the command is properly formed and whether its data size
2224 * and direction agree with the values we already have. */
2225 static int check_command(struct fsg_dev
*fsg
, int cmnd_size
,
2226 enum data_direction data_dir
, unsigned int mask
,
2227 int needs_medium
, const char *name
)
2230 int lun
= fsg
->cmnd
[1] >> 5;
2231 static const char dirletter
[4] = {'u', 'o', 'i', 'n'};
2233 struct fsg_lun
*curlun
;
2235 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2236 * Transparent SCSI doesn't pad. */
2237 if (protocol_is_scsi())
2240 /* There's some disagreement as to whether RBC pads commands or not.
2241 * We'll play it safe and accept either form. */
2242 else if (mod_data
.protocol_type
== USB_SC_RBC
) {
2243 if (fsg
->cmnd_size
== 12)
2246 /* All the other protocols pad to 12 bytes */
2251 if (fsg
->data_dir
!= DATA_DIR_UNKNOWN
)
2252 sprintf(hdlen
, ", H%c=%u", dirletter
[(int) fsg
->data_dir
],
2254 VDBG(fsg
, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2255 name
, cmnd_size
, dirletter
[(int) data_dir
],
2256 fsg
->data_size_from_cmnd
, fsg
->cmnd_size
, hdlen
);
2258 /* We can't reply at all until we know the correct data direction
2260 if (fsg
->data_size_from_cmnd
== 0)
2261 data_dir
= DATA_DIR_NONE
;
2262 if (fsg
->data_dir
== DATA_DIR_UNKNOWN
) { // CB or CBI
2263 fsg
->data_dir
= data_dir
;
2264 fsg
->data_size
= fsg
->data_size_from_cmnd
;
2266 } else { // Bulk-only
2267 if (fsg
->data_size
< fsg
->data_size_from_cmnd
) {
2269 /* Host data size < Device data size is a phase error.
2270 * Carry out the command, but only transfer as much
2271 * as we are allowed. */
2272 fsg
->data_size_from_cmnd
= fsg
->data_size
;
2273 fsg
->phase_error
= 1;
2276 fsg
->residue
= fsg
->usb_amount_left
= fsg
->data_size
;
2278 /* Conflicting data directions is a phase error */
2279 if (fsg
->data_dir
!= data_dir
&& fsg
->data_size_from_cmnd
> 0) {
2280 fsg
->phase_error
= 1;
2284 /* Verify the length of the command itself */
2285 if (cmnd_size
!= fsg
->cmnd_size
) {
2287 /* Special case workaround: There are plenty of buggy SCSI
2288 * implementations. Many have issues with cbw->Length
2289 * field passing a wrong command size. For those cases we
2290 * always try to work around the problem by using the length
2291 * sent by the host side provided it is at least as large
2292 * as the correct command length.
2293 * Examples of such cases would be MS-Windows, which issues
2294 * REQUEST SENSE with cbw->Length == 12 where it should
2295 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2296 * REQUEST SENSE with cbw->Length == 10 where it should
2299 if (cmnd_size
<= fsg
->cmnd_size
) {
2300 DBG(fsg
, "%s is buggy! Expected length %d "
2301 "but we got %d\n", name
,
2302 cmnd_size
, fsg
->cmnd_size
);
2303 cmnd_size
= fsg
->cmnd_size
;
2305 fsg
->phase_error
= 1;
2310 /* Check that the LUN values are consistent */
2311 if (transport_is_bbb()) {
2312 if (fsg
->lun
!= lun
)
2313 DBG(fsg
, "using LUN %d from CBW, "
2314 "not LUN %d from CDB\n",
2317 fsg
->lun
= lun
; // Use LUN from the command
2320 if (fsg
->lun
>= 0 && fsg
->lun
< fsg
->nluns
) {
2321 fsg
->curlun
= curlun
= &fsg
->luns
[fsg
->lun
];
2322 if (fsg
->cmnd
[0] != SC_REQUEST_SENSE
) {
2323 curlun
->sense_data
= SS_NO_SENSE
;
2324 curlun
->sense_data_info
= 0;
2325 curlun
->info_valid
= 0;
2328 fsg
->curlun
= curlun
= NULL
;
2329 fsg
->bad_lun_okay
= 0;
2331 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2332 * to use unsupported LUNs; all others may not. */
2333 if (fsg
->cmnd
[0] != SC_INQUIRY
&&
2334 fsg
->cmnd
[0] != SC_REQUEST_SENSE
) {
2335 DBG(fsg
, "unsupported LUN %d\n", fsg
->lun
);
2340 /* If a unit attention condition exists, only INQUIRY and
2341 * REQUEST SENSE commands are allowed; anything else must fail. */
2342 if (curlun
&& curlun
->unit_attention_data
!= SS_NO_SENSE
&&
2343 fsg
->cmnd
[0] != SC_INQUIRY
&&
2344 fsg
->cmnd
[0] != SC_REQUEST_SENSE
) {
2345 curlun
->sense_data
= curlun
->unit_attention_data
;
2346 curlun
->unit_attention_data
= SS_NO_SENSE
;
2350 /* Check that only command bytes listed in the mask are non-zero */
2351 fsg
->cmnd
[1] &= 0x1f; // Mask away the LUN
2352 for (i
= 1; i
< cmnd_size
; ++i
) {
2353 if (fsg
->cmnd
[i
] && !(mask
& (1 << i
))) {
2355 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2360 /* If the medium isn't mounted and the command needs to access
2361 * it, return an error. */
2362 if (curlun
&& !fsg_lun_is_open(curlun
) && needs_medium
) {
2363 curlun
->sense_data
= SS_MEDIUM_NOT_PRESENT
;
2371 static int do_scsi_command(struct fsg_dev
*fsg
)
2373 struct fsg_buffhd
*bh
;
2375 int reply
= -EINVAL
;
2377 static char unknown
[16];
2381 /* Wait for the next buffer to become available for data or status */
2382 bh
= fsg
->next_buffhd_to_drain
= fsg
->next_buffhd_to_fill
;
2383 while (bh
->state
!= BUF_STATE_EMPTY
) {
2384 rc
= sleep_thread(fsg
);
2388 fsg
->phase_error
= 0;
2389 fsg
->short_packet_received
= 0;
2391 down_read(&fsg
->filesem
); // We're using the backing file
2392 switch (fsg
->cmnd
[0]) {
2395 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2396 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2399 reply
= do_inquiry(fsg
, bh
);
2402 case SC_MODE_SELECT_6
:
2403 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2404 if ((reply
= check_command(fsg
, 6, DATA_DIR_FROM_HOST
,
2406 "MODE SELECT(6)")) == 0)
2407 reply
= do_mode_select(fsg
, bh
);
2410 case SC_MODE_SELECT_10
:
2411 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2412 if ((reply
= check_command(fsg
, 10, DATA_DIR_FROM_HOST
,
2414 "MODE SELECT(10)")) == 0)
2415 reply
= do_mode_select(fsg
, bh
);
2418 case SC_MODE_SENSE_6
:
2419 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2420 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2421 (1<<1) | (1<<2) | (1<<4), 0,
2422 "MODE SENSE(6)")) == 0)
2423 reply
= do_mode_sense(fsg
, bh
);
2426 case SC_MODE_SENSE_10
:
2427 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2428 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2429 (1<<1) | (1<<2) | (3<<7), 0,
2430 "MODE SENSE(10)")) == 0)
2431 reply
= do_mode_sense(fsg
, bh
);
2434 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL
:
2435 fsg
->data_size_from_cmnd
= 0;
2436 if ((reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2438 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2439 reply
= do_prevent_allow(fsg
);
2444 fsg
->data_size_from_cmnd
= (i
== 0 ? 256 : i
) << 9;
2445 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2448 reply
= do_read(fsg
);
2452 fsg
->data_size_from_cmnd
=
2453 get_unaligned_be16(&fsg
->cmnd
[7]) << 9;
2454 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2455 (1<<1) | (0xf<<2) | (3<<7), 1,
2457 reply
= do_read(fsg
);
2461 fsg
->data_size_from_cmnd
=
2462 get_unaligned_be32(&fsg
->cmnd
[6]) << 9;
2463 if ((reply
= check_command(fsg
, 12, DATA_DIR_TO_HOST
,
2464 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2466 reply
= do_read(fsg
);
2469 case SC_READ_CAPACITY
:
2470 fsg
->data_size_from_cmnd
= 8;
2471 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2472 (0xf<<2) | (1<<8), 1,
2473 "READ CAPACITY")) == 0)
2474 reply
= do_read_capacity(fsg
, bh
);
2477 case SC_READ_HEADER
:
2478 if (!mod_data
.cdrom
)
2480 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2481 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2482 (3<<7) | (0x1f<<1), 1,
2483 "READ HEADER")) == 0)
2484 reply
= do_read_header(fsg
, bh
);
2488 if (!mod_data
.cdrom
)
2490 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2491 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2494 reply
= do_read_toc(fsg
, bh
);
2497 case SC_READ_FORMAT_CAPACITIES
:
2498 fsg
->data_size_from_cmnd
= get_unaligned_be16(&fsg
->cmnd
[7]);
2499 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2501 "READ FORMAT CAPACITIES")) == 0)
2502 reply
= do_read_format_capacities(fsg
, bh
);
2505 case SC_REQUEST_SENSE
:
2506 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2507 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2509 "REQUEST SENSE")) == 0)
2510 reply
= do_request_sense(fsg
, bh
);
2513 case SC_START_STOP_UNIT
:
2514 fsg
->data_size_from_cmnd
= 0;
2515 if ((reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2517 "START-STOP UNIT")) == 0)
2518 reply
= do_start_stop(fsg
);
2521 case SC_SYNCHRONIZE_CACHE
:
2522 fsg
->data_size_from_cmnd
= 0;
2523 if ((reply
= check_command(fsg
, 10, DATA_DIR_NONE
,
2524 (0xf<<2) | (3<<7), 1,
2525 "SYNCHRONIZE CACHE")) == 0)
2526 reply
= do_synchronize_cache(fsg
);
2529 case SC_TEST_UNIT_READY
:
2530 fsg
->data_size_from_cmnd
= 0;
2531 reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2536 /* Although optional, this command is used by MS-Windows. We
2537 * support a minimal version: BytChk must be 0. */
2539 fsg
->data_size_from_cmnd
= 0;
2540 if ((reply
= check_command(fsg
, 10, DATA_DIR_NONE
,
2541 (1<<1) | (0xf<<2) | (3<<7), 1,
2543 reply
= do_verify(fsg
);
2548 fsg
->data_size_from_cmnd
= (i
== 0 ? 256 : i
) << 9;
2549 if ((reply
= check_command(fsg
, 6, DATA_DIR_FROM_HOST
,
2552 reply
= do_write(fsg
);
2556 fsg
->data_size_from_cmnd
=
2557 get_unaligned_be16(&fsg
->cmnd
[7]) << 9;
2558 if ((reply
= check_command(fsg
, 10, DATA_DIR_FROM_HOST
,
2559 (1<<1) | (0xf<<2) | (3<<7), 1,
2561 reply
= do_write(fsg
);
2565 fsg
->data_size_from_cmnd
=
2566 get_unaligned_be32(&fsg
->cmnd
[6]) << 9;
2567 if ((reply
= check_command(fsg
, 12, DATA_DIR_FROM_HOST
,
2568 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2570 reply
= do_write(fsg
);
2573 /* Some mandatory commands that we recognize but don't implement.
2574 * They don't mean much in this setting. It's left as an exercise
2575 * for anyone interested to implement RESERVE and RELEASE in terms
2576 * of Posix locks. */
2577 case SC_FORMAT_UNIT
:
2580 case SC_SEND_DIAGNOSTIC
:
2585 fsg
->data_size_from_cmnd
= 0;
2586 sprintf(unknown
, "Unknown x%02x", fsg
->cmnd
[0]);
2587 if ((reply
= check_command(fsg
, fsg
->cmnd_size
,
2588 DATA_DIR_UNKNOWN
, 0xff, 0, unknown
)) == 0) {
2589 fsg
->curlun
->sense_data
= SS_INVALID_COMMAND
;
2594 up_read(&fsg
->filesem
);
2596 if (reply
== -EINTR
|| signal_pending(current
))
2599 /* Set up the single reply buffer for finish_reply() */
2600 if (reply
== -EINVAL
)
2601 reply
= 0; // Error reply length
2602 if (reply
>= 0 && fsg
->data_dir
== DATA_DIR_TO_HOST
) {
2603 reply
= min((u32
) reply
, fsg
->data_size_from_cmnd
);
2604 bh
->inreq
->length
= reply
;
2605 bh
->state
= BUF_STATE_FULL
;
2606 fsg
->residue
-= reply
;
2607 } // Otherwise it's already set
2613 /*-------------------------------------------------------------------------*/
2615 static int received_cbw(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2617 struct usb_request
*req
= bh
->outreq
;
2618 struct fsg_bulk_cb_wrap
*cbw
= req
->buf
;
2620 /* Was this a real packet? Should it be ignored? */
2621 if (req
->status
|| test_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
))
2624 /* Is the CBW valid? */
2625 if (req
->actual
!= USB_BULK_CB_WRAP_LEN
||
2626 cbw
->Signature
!= cpu_to_le32(
2628 DBG(fsg
, "invalid CBW: len %u sig 0x%x\n",
2630 le32_to_cpu(cbw
->Signature
));
2632 /* The Bulk-only spec says we MUST stall the IN endpoint
2633 * (6.6.1), so it's unavoidable. It also says we must
2634 * retain this state until the next reset, but there's
2635 * no way to tell the controller driver it should ignore
2636 * Clear-Feature(HALT) requests.
2638 * We aren't required to halt the OUT endpoint; instead
2639 * we can simply accept and discard any data received
2640 * until the next reset. */
2641 wedge_bulk_in_endpoint(fsg
);
2642 set_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
);
2646 /* Is the CBW meaningful? */
2647 if (cbw
->Lun
>= FSG_MAX_LUNS
|| cbw
->Flags
& ~USB_BULK_IN_FLAG
||
2648 cbw
->Length
<= 0 || cbw
->Length
> MAX_COMMAND_SIZE
) {
2649 DBG(fsg
, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2651 cbw
->Lun
, cbw
->Flags
, cbw
->Length
);
2653 /* We can do anything we want here, so let's stall the
2654 * bulk pipes if we are allowed to. */
2655 if (mod_data
.can_stall
) {
2656 fsg_set_halt(fsg
, fsg
->bulk_out
);
2657 halt_bulk_in_endpoint(fsg
);
2662 /* Save the command for later */
2663 fsg
->cmnd_size
= cbw
->Length
;
2664 memcpy(fsg
->cmnd
, cbw
->CDB
, fsg
->cmnd_size
);
2665 if (cbw
->Flags
& USB_BULK_IN_FLAG
)
2666 fsg
->data_dir
= DATA_DIR_TO_HOST
;
2668 fsg
->data_dir
= DATA_DIR_FROM_HOST
;
2669 fsg
->data_size
= le32_to_cpu(cbw
->DataTransferLength
);
2670 if (fsg
->data_size
== 0)
2671 fsg
->data_dir
= DATA_DIR_NONE
;
2672 fsg
->lun
= cbw
->Lun
;
2673 fsg
->tag
= cbw
->Tag
;
2678 static int get_next_command(struct fsg_dev
*fsg
)
2680 struct fsg_buffhd
*bh
;
2683 if (transport_is_bbb()) {
2685 /* Wait for the next buffer to become available */
2686 bh
= fsg
->next_buffhd_to_fill
;
2687 while (bh
->state
!= BUF_STATE_EMPTY
) {
2688 rc
= sleep_thread(fsg
);
2693 /* Queue a request to read a Bulk-only CBW */
2694 set_bulk_out_req_length(fsg
, bh
, USB_BULK_CB_WRAP_LEN
);
2695 bh
->outreq
->short_not_ok
= 1;
2696 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
2697 &bh
->outreq_busy
, &bh
->state
);
2699 /* We will drain the buffer in software, which means we
2700 * can reuse it for the next filling. No need to advance
2701 * next_buffhd_to_fill. */
2703 /* Wait for the CBW to arrive */
2704 while (bh
->state
!= BUF_STATE_FULL
) {
2705 rc
= sleep_thread(fsg
);
2710 rc
= received_cbw(fsg
, bh
);
2711 bh
->state
= BUF_STATE_EMPTY
;
2713 } else { // USB_PR_CB or USB_PR_CBI
2715 /* Wait for the next command to arrive */
2716 while (fsg
->cbbuf_cmnd_size
== 0) {
2717 rc
= sleep_thread(fsg
);
2722 /* Is the previous status interrupt request still busy?
2723 * The host is allowed to skip reading the status,
2724 * so we must cancel it. */
2725 if (fsg
->intreq_busy
)
2726 usb_ep_dequeue(fsg
->intr_in
, fsg
->intreq
);
2728 /* Copy the command and mark the buffer empty */
2729 fsg
->data_dir
= DATA_DIR_UNKNOWN
;
2730 spin_lock_irq(&fsg
->lock
);
2731 fsg
->cmnd_size
= fsg
->cbbuf_cmnd_size
;
2732 memcpy(fsg
->cmnd
, fsg
->cbbuf_cmnd
, fsg
->cmnd_size
);
2733 fsg
->cbbuf_cmnd_size
= 0;
2734 spin_unlock_irq(&fsg
->lock
);
2740 /*-------------------------------------------------------------------------*/
2742 static int enable_endpoint(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
2743 const struct usb_endpoint_descriptor
*d
)
2747 ep
->driver_data
= fsg
;
2748 rc
= usb_ep_enable(ep
, d
);
2750 ERROR(fsg
, "can't enable %s, result %d\n", ep
->name
, rc
);
2754 static int alloc_request(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
2755 struct usb_request
**preq
)
2757 *preq
= usb_ep_alloc_request(ep
, GFP_ATOMIC
);
2760 ERROR(fsg
, "can't allocate request for %s\n", ep
->name
);
2765 * Reset interface setting and re-init endpoint state (toggle etc).
2766 * Call with altsetting < 0 to disable the interface. The only other
2767 * available altsetting is 0, which enables the interface.
2769 static int do_set_interface(struct fsg_dev
*fsg
, int altsetting
)
2773 const struct usb_endpoint_descriptor
*d
;
2776 DBG(fsg
, "reset interface\n");
2779 /* Deallocate the requests */
2780 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2781 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
2784 usb_ep_free_request(fsg
->bulk_in
, bh
->inreq
);
2788 usb_ep_free_request(fsg
->bulk_out
, bh
->outreq
);
2793 usb_ep_free_request(fsg
->intr_in
, fsg
->intreq
);
2797 /* Disable the endpoints */
2798 if (fsg
->bulk_in_enabled
) {
2799 usb_ep_disable(fsg
->bulk_in
);
2800 fsg
->bulk_in_enabled
= 0;
2802 if (fsg
->bulk_out_enabled
) {
2803 usb_ep_disable(fsg
->bulk_out
);
2804 fsg
->bulk_out_enabled
= 0;
2806 if (fsg
->intr_in_enabled
) {
2807 usb_ep_disable(fsg
->intr_in
);
2808 fsg
->intr_in_enabled
= 0;
2812 if (altsetting
< 0 || rc
!= 0)
2815 DBG(fsg
, "set interface %d\n", altsetting
);
2817 /* Enable the endpoints */
2818 d
= fsg_ep_desc(fsg
->gadget
,
2819 &fsg_fs_bulk_in_desc
, &fsg_hs_bulk_in_desc
);
2820 if ((rc
= enable_endpoint(fsg
, fsg
->bulk_in
, d
)) != 0)
2822 fsg
->bulk_in_enabled
= 1;
2824 d
= fsg_ep_desc(fsg
->gadget
,
2825 &fsg_fs_bulk_out_desc
, &fsg_hs_bulk_out_desc
);
2826 if ((rc
= enable_endpoint(fsg
, fsg
->bulk_out
, d
)) != 0)
2828 fsg
->bulk_out_enabled
= 1;
2829 fsg
->bulk_out_maxpacket
= le16_to_cpu(d
->wMaxPacketSize
);
2830 clear_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
);
2832 if (transport_is_cbi()) {
2833 d
= fsg_ep_desc(fsg
->gadget
,
2834 &fsg_fs_intr_in_desc
, &fsg_hs_intr_in_desc
);
2835 if ((rc
= enable_endpoint(fsg
, fsg
->intr_in
, d
)) != 0)
2837 fsg
->intr_in_enabled
= 1;
2840 /* Allocate the requests */
2841 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2842 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
2844 if ((rc
= alloc_request(fsg
, fsg
->bulk_in
, &bh
->inreq
)) != 0)
2846 if ((rc
= alloc_request(fsg
, fsg
->bulk_out
, &bh
->outreq
)) != 0)
2848 bh
->inreq
->buf
= bh
->outreq
->buf
= bh
->buf
;
2849 bh
->inreq
->context
= bh
->outreq
->context
= bh
;
2850 bh
->inreq
->complete
= bulk_in_complete
;
2851 bh
->outreq
->complete
= bulk_out_complete
;
2853 if (transport_is_cbi()) {
2854 if ((rc
= alloc_request(fsg
, fsg
->intr_in
, &fsg
->intreq
)) != 0)
2856 fsg
->intreq
->complete
= intr_in_complete
;
2860 for (i
= 0; i
< fsg
->nluns
; ++i
)
2861 fsg
->luns
[i
].unit_attention_data
= SS_RESET_OCCURRED
;
2867 * Change our operational configuration. This code must agree with the code
2868 * that returns config descriptors, and with interface altsetting code.
2870 * It's also responsible for power management interactions. Some
2871 * configurations might not work with our current power sources.
2872 * For now we just assume the gadget is always self-powered.
2874 static int do_set_config(struct fsg_dev
*fsg
, u8 new_config
)
2878 /* Disable the single interface */
2879 if (fsg
->config
!= 0) {
2880 DBG(fsg
, "reset config\n");
2882 rc
= do_set_interface(fsg
, -1);
2885 /* Enable the interface */
2886 if (new_config
!= 0) {
2887 fsg
->config
= new_config
;
2888 if ((rc
= do_set_interface(fsg
, 0)) != 0)
2889 fsg
->config
= 0; // Reset on errors
2893 switch (fsg
->gadget
->speed
) {
2894 case USB_SPEED_LOW
: speed
= "low"; break;
2895 case USB_SPEED_FULL
: speed
= "full"; break;
2896 case USB_SPEED_HIGH
: speed
= "high"; break;
2897 default: speed
= "?"; break;
2899 INFO(fsg
, "%s speed config #%d\n", speed
, fsg
->config
);
2906 /*-------------------------------------------------------------------------*/
2908 static void handle_exception(struct fsg_dev
*fsg
)
2914 struct fsg_buffhd
*bh
;
2915 enum fsg_state old_state
;
2917 struct fsg_lun
*curlun
;
2918 unsigned int exception_req_tag
;
2921 /* Clear the existing signals. Anything but SIGUSR1 is converted
2922 * into a high-priority EXIT exception. */
2924 sig
= dequeue_signal_lock(current
, ¤t
->blocked
, &info
);
2927 if (sig
!= SIGUSR1
) {
2928 if (fsg
->state
< FSG_STATE_EXIT
)
2929 DBG(fsg
, "Main thread exiting on signal\n");
2930 raise_exception(fsg
, FSG_STATE_EXIT
);
2934 /* Cancel all the pending transfers */
2935 if (fsg
->intreq_busy
)
2936 usb_ep_dequeue(fsg
->intr_in
, fsg
->intreq
);
2937 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2938 bh
= &fsg
->buffhds
[i
];
2940 usb_ep_dequeue(fsg
->bulk_in
, bh
->inreq
);
2941 if (bh
->outreq_busy
)
2942 usb_ep_dequeue(fsg
->bulk_out
, bh
->outreq
);
2945 /* Wait until everything is idle */
2947 num_active
= fsg
->intreq_busy
;
2948 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2949 bh
= &fsg
->buffhds
[i
];
2950 num_active
+= bh
->inreq_busy
+ bh
->outreq_busy
;
2952 if (num_active
== 0)
2954 if (sleep_thread(fsg
))
2958 /* Clear out the controller's fifos */
2959 if (fsg
->bulk_in_enabled
)
2960 usb_ep_fifo_flush(fsg
->bulk_in
);
2961 if (fsg
->bulk_out_enabled
)
2962 usb_ep_fifo_flush(fsg
->bulk_out
);
2963 if (fsg
->intr_in_enabled
)
2964 usb_ep_fifo_flush(fsg
->intr_in
);
2966 /* Reset the I/O buffer states and pointers, the SCSI
2967 * state, and the exception. Then invoke the handler. */
2968 spin_lock_irq(&fsg
->lock
);
2970 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
2971 bh
= &fsg
->buffhds
[i
];
2972 bh
->state
= BUF_STATE_EMPTY
;
2974 fsg
->next_buffhd_to_fill
= fsg
->next_buffhd_to_drain
=
2977 exception_req_tag
= fsg
->exception_req_tag
;
2978 new_config
= fsg
->new_config
;
2979 old_state
= fsg
->state
;
2981 if (old_state
== FSG_STATE_ABORT_BULK_OUT
)
2982 fsg
->state
= FSG_STATE_STATUS_PHASE
;
2984 for (i
= 0; i
< fsg
->nluns
; ++i
) {
2985 curlun
= &fsg
->luns
[i
];
2986 curlun
->prevent_medium_removal
= 0;
2987 curlun
->sense_data
= curlun
->unit_attention_data
=
2989 curlun
->sense_data_info
= 0;
2990 curlun
->info_valid
= 0;
2992 fsg
->state
= FSG_STATE_IDLE
;
2994 spin_unlock_irq(&fsg
->lock
);
2996 /* Carry out any extra actions required for the exception */
2997 switch (old_state
) {
3001 case FSG_STATE_ABORT_BULK_OUT
:
3003 spin_lock_irq(&fsg
->lock
);
3004 if (fsg
->state
== FSG_STATE_STATUS_PHASE
)
3005 fsg
->state
= FSG_STATE_IDLE
;
3006 spin_unlock_irq(&fsg
->lock
);
3009 case FSG_STATE_RESET
:
3010 /* In case we were forced against our will to halt a
3011 * bulk endpoint, clear the halt now. (The SuperH UDC
3012 * requires this.) */
3013 if (test_and_clear_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
))
3014 usb_ep_clear_halt(fsg
->bulk_in
);
3016 if (transport_is_bbb()) {
3017 if (fsg
->ep0_req_tag
== exception_req_tag
)
3018 ep0_queue(fsg
); // Complete the status stage
3020 } else if (transport_is_cbi())
3021 send_status(fsg
); // Status by interrupt pipe
3023 /* Technically this should go here, but it would only be
3024 * a waste of time. Ditto for the INTERFACE_CHANGE and
3025 * CONFIG_CHANGE cases. */
3026 // for (i = 0; i < fsg->nluns; ++i)
3027 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3030 case FSG_STATE_INTERFACE_CHANGE
:
3031 rc
= do_set_interface(fsg
, 0);
3032 if (fsg
->ep0_req_tag
!= exception_req_tag
)
3034 if (rc
!= 0) // STALL on errors
3035 fsg_set_halt(fsg
, fsg
->ep0
);
3036 else // Complete the status stage
3040 case FSG_STATE_CONFIG_CHANGE
:
3041 rc
= do_set_config(fsg
, new_config
);
3042 if (fsg
->ep0_req_tag
!= exception_req_tag
)
3044 if (rc
!= 0) // STALL on errors
3045 fsg_set_halt(fsg
, fsg
->ep0
);
3046 else // Complete the status stage
3050 case FSG_STATE_DISCONNECT
:
3051 for (i
= 0; i
< fsg
->nluns
; ++i
)
3052 fsg_lun_fsync_sub(fsg
->luns
+ i
);
3053 do_set_config(fsg
, 0); // Unconfigured state
3056 case FSG_STATE_EXIT
:
3057 case FSG_STATE_TERMINATED
:
3058 do_set_config(fsg
, 0); // Free resources
3059 spin_lock_irq(&fsg
->lock
);
3060 fsg
->state
= FSG_STATE_TERMINATED
; // Stop the thread
3061 spin_unlock_irq(&fsg
->lock
);
3067 /*-------------------------------------------------------------------------*/
3069 static int fsg_main_thread(void *fsg_
)
3071 struct fsg_dev
*fsg
= fsg_
;
3073 /* Allow the thread to be killed by a signal, but set the signal mask
3074 * to block everything but INT, TERM, KILL, and USR1. */
3075 allow_signal(SIGINT
);
3076 allow_signal(SIGTERM
);
3077 allow_signal(SIGKILL
);
3078 allow_signal(SIGUSR1
);
3080 /* Allow the thread to be frozen */
3083 /* Arrange for userspace references to be interpreted as kernel
3084 * pointers. That way we can pass a kernel pointer to a routine
3085 * that expects a __user pointer and it will work okay. */
3089 while (fsg
->state
!= FSG_STATE_TERMINATED
) {
3090 if (exception_in_progress(fsg
) || signal_pending(current
)) {
3091 handle_exception(fsg
);
3095 if (!fsg
->running
) {
3100 if (get_next_command(fsg
))
3103 spin_lock_irq(&fsg
->lock
);
3104 if (!exception_in_progress(fsg
))
3105 fsg
->state
= FSG_STATE_DATA_PHASE
;
3106 spin_unlock_irq(&fsg
->lock
);
3108 if (do_scsi_command(fsg
) || finish_reply(fsg
))
3111 spin_lock_irq(&fsg
->lock
);
3112 if (!exception_in_progress(fsg
))
3113 fsg
->state
= FSG_STATE_STATUS_PHASE
;
3114 spin_unlock_irq(&fsg
->lock
);
3116 if (send_status(fsg
))
3119 spin_lock_irq(&fsg
->lock
);
3120 if (!exception_in_progress(fsg
))
3121 fsg
->state
= FSG_STATE_IDLE
;
3122 spin_unlock_irq(&fsg
->lock
);
3125 spin_lock_irq(&fsg
->lock
);
3126 fsg
->thread_task
= NULL
;
3127 spin_unlock_irq(&fsg
->lock
);
3129 /* If we are exiting because of a signal, unregister the
3131 if (test_and_clear_bit(REGISTERED
, &fsg
->atomic_bitflags
))
3132 usb_gadget_unregister_driver(&fsg_driver
);
3134 /* Let the unbind and cleanup routines know the thread has exited */
3135 complete_and_exit(&fsg
->thread_notifier
, 0);
3139 /*-------------------------------------------------------------------------*/
3142 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3143 static DEVICE_ATTR(ro
, 0444, fsg_show_ro
, NULL
);
3144 static DEVICE_ATTR(nofua
, 0644, fsg_show_nofua
, NULL
);
3145 static DEVICE_ATTR(file
, 0444, fsg_show_file
, NULL
);
3148 /*-------------------------------------------------------------------------*/
3150 static void fsg_release(struct kref
*ref
)
3152 struct fsg_dev
*fsg
= container_of(ref
, struct fsg_dev
, ref
);
3158 static void lun_release(struct device
*dev
)
3160 struct rw_semaphore
*filesem
= dev_get_drvdata(dev
);
3161 struct fsg_dev
*fsg
=
3162 container_of(filesem
, struct fsg_dev
, filesem
);
3164 kref_put(&fsg
->ref
, fsg_release
);
3167 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget
*gadget
)
3169 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
3171 struct fsg_lun
*curlun
;
3172 struct usb_request
*req
= fsg
->ep0req
;
3174 DBG(fsg
, "unbind\n");
3175 clear_bit(REGISTERED
, &fsg
->atomic_bitflags
);
3177 /* Unregister the sysfs attribute files and the LUNs */
3178 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3179 curlun
= &fsg
->luns
[i
];
3180 if (curlun
->registered
) {
3181 device_remove_file(&curlun
->dev
, &dev_attr_ro
);
3182 device_remove_file(&curlun
->dev
, &dev_attr_file
);
3183 fsg_lun_close(curlun
);
3184 device_unregister(&curlun
->dev
);
3185 curlun
->registered
= 0;
3189 /* If the thread isn't already dead, tell it to exit now */
3190 if (fsg
->state
!= FSG_STATE_TERMINATED
) {
3191 raise_exception(fsg
, FSG_STATE_EXIT
);
3192 wait_for_completion(&fsg
->thread_notifier
);
3194 /* The cleanup routine waits for this completion also */
3195 complete(&fsg
->thread_notifier
);
3198 /* Free the data buffers */
3199 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
)
3200 kfree(fsg
->buffhds
[i
].buf
);
3202 /* Free the request and buffer for endpoint 0 */
3205 usb_ep_free_request(fsg
->ep0
, req
);
3208 set_gadget_data(gadget
, NULL
);
3212 static int __init
check_parameters(struct fsg_dev
*fsg
)
3218 /* Store the default values */
3219 mod_data
.transport_type
= USB_PR_BULK
;
3220 mod_data
.transport_name
= "Bulk-only";
3221 mod_data
.protocol_type
= USB_SC_SCSI
;
3222 mod_data
.protocol_name
= "Transparent SCSI";
3224 /* Some peripheral controllers are known not to be able to
3225 * halt bulk endpoints correctly. If one of them is present,
3228 if (gadget_is_at91(fsg
->gadget
))
3229 mod_data
.can_stall
= 0;
3231 if (mod_data
.release
== 0xffff) { // Parameter wasn't set
3232 gcnum
= usb_gadget_controller_number(fsg
->gadget
);
3234 mod_data
.release
= 0x0300 + gcnum
;
3236 WARNING(fsg
, "controller '%s' not recognized\n",
3238 mod_data
.release
= 0x0399;
3242 prot
= simple_strtol(mod_data
.protocol_parm
, NULL
, 0);
3244 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3245 if (strnicmp(mod_data
.transport_parm
, "BBB", 10) == 0) {
3246 ; // Use default setting
3247 } else if (strnicmp(mod_data
.transport_parm
, "CB", 10) == 0) {
3248 mod_data
.transport_type
= USB_PR_CB
;
3249 mod_data
.transport_name
= "Control-Bulk";
3250 } else if (strnicmp(mod_data
.transport_parm
, "CBI", 10) == 0) {
3251 mod_data
.transport_type
= USB_PR_CBI
;
3252 mod_data
.transport_name
= "Control-Bulk-Interrupt";
3254 ERROR(fsg
, "invalid transport: %s\n", mod_data
.transport_parm
);
3258 if (strnicmp(mod_data
.protocol_parm
, "SCSI", 10) == 0 ||
3259 prot
== USB_SC_SCSI
) {
3260 ; // Use default setting
3261 } else if (strnicmp(mod_data
.protocol_parm
, "RBC", 10) == 0 ||
3262 prot
== USB_SC_RBC
) {
3263 mod_data
.protocol_type
= USB_SC_RBC
;
3264 mod_data
.protocol_name
= "RBC";
3265 } else if (strnicmp(mod_data
.protocol_parm
, "8020", 4) == 0 ||
3266 strnicmp(mod_data
.protocol_parm
, "ATAPI", 10) == 0 ||
3267 prot
== USB_SC_8020
) {
3268 mod_data
.protocol_type
= USB_SC_8020
;
3269 mod_data
.protocol_name
= "8020i (ATAPI)";
3270 } else if (strnicmp(mod_data
.protocol_parm
, "QIC", 3) == 0 ||
3271 prot
== USB_SC_QIC
) {
3272 mod_data
.protocol_type
= USB_SC_QIC
;
3273 mod_data
.protocol_name
= "QIC-157";
3274 } else if (strnicmp(mod_data
.protocol_parm
, "UFI", 10) == 0 ||
3275 prot
== USB_SC_UFI
) {
3276 mod_data
.protocol_type
= USB_SC_UFI
;
3277 mod_data
.protocol_name
= "UFI";
3278 } else if (strnicmp(mod_data
.protocol_parm
, "8070", 4) == 0 ||
3279 prot
== USB_SC_8070
) {
3280 mod_data
.protocol_type
= USB_SC_8070
;
3281 mod_data
.protocol_name
= "8070i";
3283 ERROR(fsg
, "invalid protocol: %s\n", mod_data
.protocol_parm
);
3287 mod_data
.buflen
&= PAGE_CACHE_MASK
;
3288 if (mod_data
.buflen
<= 0) {
3289 ERROR(fsg
, "invalid buflen\n");
3293 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3295 /* Serial string handling.
3296 * On a real device, the serial string would be loaded
3297 * from permanent storage. */
3298 if (mod_data
.serial
) {
3303 * The CB[I] specification limits the serial string to
3304 * 12 uppercase hexadecimal characters.
3305 * BBB need at least 12 uppercase hexadecimal characters,
3306 * with a maximum of 126. */
3307 for (ch
= mod_data
.serial
; *ch
; ++ch
) {
3309 if ((*ch
< '0' || *ch
> '9') &&
3310 (*ch
< 'A' || *ch
> 'F')) { /* not uppercase hex */
3312 "Invalid serial string character: %c; "
3313 "Failing back to default\n",
3319 (mod_data
.transport_type
== USB_PR_BULK
&& len
< 12) ||
3320 (mod_data
.transport_type
!= USB_PR_BULK
&& len
> 12)) {
3322 "Invalid serial string length; "
3323 "Failing back to default\n");
3326 fsg_strings
[FSG_STRING_SERIAL
- 1].s
= mod_data
.serial
;
3329 "Userspace failed to provide serial number; "
3330 "Failing back to default\n");
3332 /* Serial number not specified or invalid, make our own.
3333 * We just encode it from the driver version string,
3334 * 12 characters to comply with both CB[I] and BBB spec.
3335 * Warning : Two devices running the same kernel will have
3336 * the same fallback serial number. */
3337 for (i
= 0; i
< 12; i
+= 2) {
3338 unsigned char c
= DRIVER_VERSION
[i
/ 2];
3342 sprintf(&fsg_string_serial
[i
], "%02X", c
);
3350 static int __ref
fsg_bind(struct usb_gadget
*gadget
)
3352 struct fsg_dev
*fsg
= the_fsg
;
3355 struct fsg_lun
*curlun
;
3357 struct usb_request
*req
;
3360 fsg
->gadget
= gadget
;
3361 set_gadget_data(gadget
, fsg
);
3362 fsg
->ep0
= gadget
->ep0
;
3363 fsg
->ep0
->driver_data
= fsg
;
3365 if ((rc
= check_parameters(fsg
)) != 0)
3368 if (mod_data
.removable
) { // Enable the store_xxx attributes
3369 dev_attr_file
.attr
.mode
= 0644;
3370 dev_attr_file
.store
= fsg_store_file
;
3371 if (!mod_data
.cdrom
) {
3372 dev_attr_ro
.attr
.mode
= 0644;
3373 dev_attr_ro
.store
= fsg_store_ro
;
3377 /* Only for removable media? */
3378 dev_attr_nofua
.attr
.mode
= 0644;
3379 dev_attr_nofua
.store
= fsg_store_nofua
;
3381 /* Find out how many LUNs there should be */
3384 i
= max(mod_data
.num_filenames
, 1u);
3385 if (i
> FSG_MAX_LUNS
) {
3386 ERROR(fsg
, "invalid number of LUNs: %d\n", i
);
3391 /* Create the LUNs, open their backing files, and register the
3392 * LUN devices in sysfs. */
3393 fsg
->luns
= kzalloc(i
* sizeof(struct fsg_lun
), GFP_KERNEL
);
3400 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3401 curlun
= &fsg
->luns
[i
];
3402 curlun
->cdrom
= !!mod_data
.cdrom
;
3403 curlun
->ro
= mod_data
.cdrom
|| mod_data
.ro
[i
];
3404 curlun
->initially_ro
= curlun
->ro
;
3405 curlun
->removable
= mod_data
.removable
;
3406 curlun
->nofua
= mod_data
.nofua
[i
];
3407 curlun
->dev
.release
= lun_release
;
3408 curlun
->dev
.parent
= &gadget
->dev
;
3409 curlun
->dev
.driver
= &fsg_driver
.driver
;
3410 dev_set_drvdata(&curlun
->dev
, &fsg
->filesem
);
3411 dev_set_name(&curlun
->dev
,"%s-lun%d",
3412 dev_name(&gadget
->dev
), i
);
3414 if ((rc
= device_register(&curlun
->dev
)) != 0) {
3415 INFO(fsg
, "failed to register LUN%d: %d\n", i
, rc
);
3418 if ((rc
= device_create_file(&curlun
->dev
,
3419 &dev_attr_ro
)) != 0 ||
3420 (rc
= device_create_file(&curlun
->dev
,
3421 &dev_attr_nofua
)) != 0 ||
3422 (rc
= device_create_file(&curlun
->dev
,
3423 &dev_attr_file
)) != 0) {
3424 device_unregister(&curlun
->dev
);
3427 curlun
->registered
= 1;
3428 kref_get(&fsg
->ref
);
3430 if (mod_data
.file
[i
] && *mod_data
.file
[i
]) {
3431 if ((rc
= fsg_lun_open(curlun
,
3432 mod_data
.file
[i
])) != 0)
3434 } else if (!mod_data
.removable
) {
3435 ERROR(fsg
, "no file given for LUN%d\n", i
);
3441 /* Find all the endpoints we will use */
3442 usb_ep_autoconfig_reset(gadget
);
3443 ep
= usb_ep_autoconfig(gadget
, &fsg_fs_bulk_in_desc
);
3446 ep
->driver_data
= fsg
; // claim the endpoint
3449 ep
= usb_ep_autoconfig(gadget
, &fsg_fs_bulk_out_desc
);
3452 ep
->driver_data
= fsg
; // claim the endpoint
3455 if (transport_is_cbi()) {
3456 ep
= usb_ep_autoconfig(gadget
, &fsg_fs_intr_in_desc
);
3459 ep
->driver_data
= fsg
; // claim the endpoint
3463 /* Fix up the descriptors */
3464 device_desc
.bMaxPacketSize0
= fsg
->ep0
->maxpacket
;
3465 device_desc
.idVendor
= cpu_to_le16(mod_data
.vendor
);
3466 device_desc
.idProduct
= cpu_to_le16(mod_data
.product
);
3467 device_desc
.bcdDevice
= cpu_to_le16(mod_data
.release
);
3469 i
= (transport_is_cbi() ? 3 : 2); // Number of endpoints
3470 fsg_intf_desc
.bNumEndpoints
= i
;
3471 fsg_intf_desc
.bInterfaceSubClass
= mod_data
.protocol_type
;
3472 fsg_intf_desc
.bInterfaceProtocol
= mod_data
.transport_type
;
3473 fsg_fs_function
[i
+ FSG_FS_FUNCTION_PRE_EP_ENTRIES
] = NULL
;
3475 if (gadget_is_dualspeed(gadget
)) {
3476 fsg_hs_function
[i
+ FSG_HS_FUNCTION_PRE_EP_ENTRIES
] = NULL
;
3478 /* Assume ep0 uses the same maxpacket value for both speeds */
3479 dev_qualifier
.bMaxPacketSize0
= fsg
->ep0
->maxpacket
;
3481 /* Assume endpoint addresses are the same for both speeds */
3482 fsg_hs_bulk_in_desc
.bEndpointAddress
=
3483 fsg_fs_bulk_in_desc
.bEndpointAddress
;
3484 fsg_hs_bulk_out_desc
.bEndpointAddress
=
3485 fsg_fs_bulk_out_desc
.bEndpointAddress
;
3486 fsg_hs_intr_in_desc
.bEndpointAddress
=
3487 fsg_fs_intr_in_desc
.bEndpointAddress
;
3490 if (gadget_is_otg(gadget
))
3491 fsg_otg_desc
.bmAttributes
|= USB_OTG_HNP
;
3495 /* Allocate the request and buffer for endpoint 0 */
3496 fsg
->ep0req
= req
= usb_ep_alloc_request(fsg
->ep0
, GFP_KERNEL
);
3499 req
->buf
= kmalloc(EP0_BUFSIZE
, GFP_KERNEL
);
3502 req
->complete
= ep0_complete
;
3504 /* Allocate the data buffers */
3505 for (i
= 0; i
< FSG_NUM_BUFFERS
; ++i
) {
3506 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
3508 /* Allocate for the bulk-in endpoint. We assume that
3509 * the buffer will also work with the bulk-out (and
3510 * interrupt-in) endpoint. */
3511 bh
->buf
= kmalloc(mod_data
.buflen
, GFP_KERNEL
);
3516 fsg
->buffhds
[FSG_NUM_BUFFERS
- 1].next
= &fsg
->buffhds
[0];
3518 /* This should reflect the actual gadget power source */
3519 usb_gadget_set_selfpowered(gadget
);
3521 snprintf(fsg_string_manufacturer
, sizeof fsg_string_manufacturer
,
3523 init_utsname()->sysname
, init_utsname()->release
,
3526 fsg
->thread_task
= kthread_create(fsg_main_thread
, fsg
,
3527 "file-storage-gadget");
3528 if (IS_ERR(fsg
->thread_task
)) {
3529 rc
= PTR_ERR(fsg
->thread_task
);
3533 INFO(fsg
, DRIVER_DESC
", version: " DRIVER_VERSION
"\n");
3534 INFO(fsg
, "Number of LUNs=%d\n", fsg
->nluns
);
3536 pathbuf
= kmalloc(PATH_MAX
, GFP_KERNEL
);
3537 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3538 curlun
= &fsg
->luns
[i
];
3539 if (fsg_lun_is_open(curlun
)) {
3542 p
= d_path(&curlun
->filp
->f_path
,
3547 LINFO(curlun
, "ro=%d, nofua=%d, file: %s\n",
3548 curlun
->ro
, curlun
->nofua
, (p
? p
: "(error)"));
3553 DBG(fsg
, "transport=%s (x%02x)\n",
3554 mod_data
.transport_name
, mod_data
.transport_type
);
3555 DBG(fsg
, "protocol=%s (x%02x)\n",
3556 mod_data
.protocol_name
, mod_data
.protocol_type
);
3557 DBG(fsg
, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3558 mod_data
.vendor
, mod_data
.product
, mod_data
.release
);
3559 DBG(fsg
, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3560 mod_data
.removable
, mod_data
.can_stall
,
3561 mod_data
.cdrom
, mod_data
.buflen
);
3562 DBG(fsg
, "I/O thread pid: %d\n", task_pid_nr(fsg
->thread_task
));
3564 set_bit(REGISTERED
, &fsg
->atomic_bitflags
);
3566 /* Tell the thread to start working */
3567 wake_up_process(fsg
->thread_task
);
3571 ERROR(fsg
, "unable to autoconfigure all endpoints\n");
3575 fsg
->state
= FSG_STATE_TERMINATED
; // The thread is dead
3577 complete(&fsg
->thread_notifier
);
3582 /*-------------------------------------------------------------------------*/
3584 static void fsg_suspend(struct usb_gadget
*gadget
)
3586 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
3588 DBG(fsg
, "suspend\n");
3589 set_bit(SUSPENDED
, &fsg
->atomic_bitflags
);
3592 static void fsg_resume(struct usb_gadget
*gadget
)
3594 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
3596 DBG(fsg
, "resume\n");
3597 clear_bit(SUSPENDED
, &fsg
->atomic_bitflags
);
3601 /*-------------------------------------------------------------------------*/
3603 static struct usb_gadget_driver fsg_driver
= {
3604 #ifdef CONFIG_USB_GADGET_DUALSPEED
3605 .speed
= USB_SPEED_HIGH
,
3607 .speed
= USB_SPEED_FULL
,
3609 .function
= (char *) fsg_string_product
,
3611 .unbind
= fsg_unbind
,
3612 .disconnect
= fsg_disconnect
,
3614 .suspend
= fsg_suspend
,
3615 .resume
= fsg_resume
,
3618 .name
= DRIVER_NAME
,
3619 .owner
= THIS_MODULE
,
3627 static int __init
fsg_alloc(void)
3629 struct fsg_dev
*fsg
;
3631 fsg
= kzalloc(sizeof *fsg
, GFP_KERNEL
);
3634 spin_lock_init(&fsg
->lock
);
3635 init_rwsem(&fsg
->filesem
);
3636 kref_init(&fsg
->ref
);
3637 init_completion(&fsg
->thread_notifier
);
3644 static int __init
fsg_init(void)
3647 struct fsg_dev
*fsg
;
3649 if ((rc
= fsg_alloc()) != 0)
3652 if ((rc
= usb_gadget_register_driver(&fsg_driver
)) != 0)
3653 kref_put(&fsg
->ref
, fsg_release
);
3656 module_init(fsg_init
);
3659 static void __exit
fsg_cleanup(void)
3661 struct fsg_dev
*fsg
= the_fsg
;
3663 /* Unregister the driver iff the thread hasn't already done so */
3664 if (test_and_clear_bit(REGISTERED
, &fsg
->atomic_bitflags
))
3665 usb_gadget_unregister_driver(&fsg_driver
);
3667 /* Wait for the thread to finish up */
3668 wait_for_completion(&fsg
->thread_notifier
);
3670 kref_put(&fsg
->ref
, fsg_release
);
3672 module_exit(fsg_cleanup
);