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, and release 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 * stall Default determined according to the type of
97 * USB device controller (usually true),
98 * boolean to permit the driver to halt
100 * cdrom Default false, boolean for whether to emulate
102 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
103 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
104 * ATAPI, QIC, UFI, 8070, or SCSI;
106 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
107 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
108 * release=0xRRRR Override the USB release number (bcdDevice)
109 * buflen=N Default N=16384, buffer size used (will be
110 * rounded down to a multiple of
113 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
114 * "removable", "luns", "stall", and "cdrom" options are available; default
115 * values are used for everything else.
117 * The pathnames of the backing files and the ro settings are available in
118 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
119 * gadget's sysfs directory. If the "removable" option is set, writing to
120 * these files will simulate ejecting/loading the medium (writing an empty
121 * line means eject) and adjusting a write-enable tab. Changes to the ro
122 * setting are not allowed when the medium is loaded or if CD-ROM emulation
125 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
126 * The driver's SCSI command interface was based on the "Information
127 * technology - Small Computer System Interface - 2" document from
128 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
129 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
130 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
131 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
132 * document, Revision 1.0, December 14, 1998, available at
133 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
140 * The FSG driver is fairly straightforward. There is a main kernel
141 * thread that handles most of the work. Interrupt routines field
142 * callbacks from the controller driver: bulk- and interrupt-request
143 * completion notifications, endpoint-0 events, and disconnect events.
144 * Completion events are passed to the main thread by wakeup calls. Many
145 * ep0 requests are handled at interrupt time, but SetInterface,
146 * SetConfiguration, and device reset requests are forwarded to the
147 * thread in the form of "exceptions" using SIGUSR1 signals (since they
148 * should interrupt any ongoing file I/O operations).
150 * The thread's main routine implements the standard command/data/status
151 * parts of a SCSI interaction. It and its subroutines are full of tests
152 * for pending signals/exceptions -- all this polling is necessary since
153 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
154 * indication that the driver really wants to be running in userspace.)
155 * An important point is that so long as the thread is alive it keeps an
156 * open reference to the backing file. This will prevent unmounting
157 * the backing file's underlying filesystem and could cause problems
158 * during system shutdown, for example. To prevent such problems, the
159 * thread catches INT, TERM, and KILL signals and converts them into
162 * In normal operation the main thread is started during the gadget's
163 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
164 * exit when it receives a signal, and there's no point leaving the
165 * gadget running when the thread is dead. So just before the thread
166 * exits, it deregisters the gadget driver. This makes things a little
167 * tricky: The driver is deregistered at two places, and the exiting
168 * thread can indirectly call fsg_unbind() which in turn can tell the
169 * thread to exit. The first problem is resolved through the use of the
170 * REGISTERED atomic bitflag; the driver will only be deregistered once.
171 * The second problem is resolved by having fsg_unbind() check
172 * fsg->state; it won't try to stop the thread if the state is already
173 * FSG_STATE_TERMINATED.
175 * To provide maximum throughput, the driver uses a circular pipeline of
176 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
177 * arbitrarily long; in practice the benefits don't justify having more
178 * than 2 stages (i.e., double buffering). But it helps to think of the
179 * pipeline as being a long one. Each buffer head contains a bulk-in and
180 * a bulk-out request pointer (since the buffer can be used for both
181 * output and input -- directions always are given from the host's
182 * point of view) as well as a pointer to the buffer and various state
185 * Use of the pipeline follows a simple protocol. There is a variable
186 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
187 * At any time that buffer head may still be in use from an earlier
188 * request, so each buffer head has a state variable indicating whether
189 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
190 * buffer head to be EMPTY, filling the buffer either by file I/O or by
191 * USB I/O (during which the buffer head is BUSY), and marking the buffer
192 * head FULL when the I/O is complete. Then the buffer will be emptied
193 * (again possibly by USB I/O, during which it is marked BUSY) and
194 * finally marked EMPTY again (possibly by a completion routine).
196 * A module parameter tells the driver to avoid stalling the bulk
197 * endpoints wherever the transport specification allows. This is
198 * necessary for some UDCs like the SuperH, which cannot reliably clear a
199 * halt on a bulk endpoint. However, under certain circumstances the
200 * Bulk-only specification requires a stall. In such cases the driver
201 * will halt the endpoint and set a flag indicating that it should clear
202 * the halt in software during the next device reset. Hopefully this
203 * will permit everything to work correctly. Furthermore, although the
204 * specification allows the bulk-out endpoint to halt when the host sends
205 * too much data, implementing this would cause an unavoidable race.
206 * The driver will always use the "no-stall" approach for OUT transfers.
208 * One subtle point concerns sending status-stage responses for ep0
209 * requests. Some of these requests, such as device reset, can involve
210 * interrupting an ongoing file I/O operation, which might take an
211 * arbitrarily long time. During that delay the host might give up on
212 * the original ep0 request and issue a new one. When that happens the
213 * driver should not notify the host about completion of the original
214 * request, as the host will no longer be waiting for it. So the driver
215 * assigns to each ep0 request a unique tag, and it keeps track of the
216 * tag value of the request associated with a long-running exception
217 * (device-reset, interface-change, or configuration-change). When the
218 * exception handler is finished, the status-stage response is submitted
219 * only if the current ep0 request tag is equal to the exception request
220 * tag. Thus only the most recently received ep0 request will get a
221 * status-stage response.
223 * Warning: This driver source file is too long. It ought to be split up
224 * into a header file plus about 3 separate .c files, to handle the details
225 * of the Gadget, USB Mass Storage, and SCSI protocols.
229 /* #define VERBOSE_DEBUG */
230 /* #define DUMP_MSGS */
233 #include <linux/blkdev.h>
234 #include <linux/completion.h>
235 #include <linux/dcache.h>
236 #include <linux/delay.h>
237 #include <linux/device.h>
238 #include <linux/fcntl.h>
239 #include <linux/file.h>
240 #include <linux/fs.h>
241 #include <linux/kref.h>
242 #include <linux/kthread.h>
243 #include <linux/limits.h>
244 #include <linux/rwsem.h>
245 #include <linux/slab.h>
246 #include <linux/spinlock.h>
247 #include <linux/string.h>
248 #include <linux/freezer.h>
249 #include <linux/utsname.h>
251 #include <linux/usb/ch9.h>
252 #include <linux/usb/gadget.h>
254 #include "gadget_chips.h"
259 * Kbuild is not very cooperative with respect to linking separately
260 * compiled library objects into one module. So for now we won't use
261 * separate compilation ... ensuring init/exit sections work to shrink
262 * the runtime footprint, and giving us at least some parts of what
263 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
265 #include "usbstring.c"
267 #include "epautoconf.c"
269 /*-------------------------------------------------------------------------*/
271 #define DRIVER_DESC "File-backed Storage Gadget"
272 #define DRIVER_NAME "g_file_storage"
273 #define DRIVER_VERSION "20 November 2008"
275 static const char longname
[] = DRIVER_DESC
;
276 static const char shortname
[] = DRIVER_NAME
;
278 MODULE_DESCRIPTION(DRIVER_DESC
);
279 MODULE_AUTHOR("Alan Stern");
280 MODULE_LICENSE("Dual BSD/GPL");
282 /* Thanks to NetChip Technologies for donating this product ID.
284 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
285 * Instead: allocate your own, using normal USB-IF procedures. */
286 #define DRIVER_VENDOR_ID 0x0525 // NetChip
287 #define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
291 * This driver assumes self-powered hardware and has no way for users to
292 * trigger remote wakeup. It uses autoconfiguration to select endpoints
293 * and endpoint addresses.
297 /*-------------------------------------------------------------------------*/
299 #define LDBG(lun,fmt,args...) \
300 dev_dbg(&(lun)->dev , fmt , ## args)
301 #define MDBG(fmt,args...) \
302 pr_debug(DRIVER_NAME ": " fmt , ## args)
312 #define VLDBG(lun,fmt,args...) \
314 #endif /* VERBOSE_DEBUG */
316 #define LERROR(lun,fmt,args...) \
317 dev_err(&(lun)->dev , fmt , ## args)
318 #define LWARN(lun,fmt,args...) \
319 dev_warn(&(lun)->dev , fmt , ## args)
320 #define LINFO(lun,fmt,args...) \
321 dev_info(&(lun)->dev , fmt , ## args)
323 #define MINFO(fmt,args...) \
324 pr_info(DRIVER_NAME ": " fmt , ## args)
326 #define DBG(d, fmt, args...) \
327 dev_dbg(&(d)->gadget->dev , fmt , ## args)
328 #define VDBG(d, fmt, args...) \
329 dev_vdbg(&(d)->gadget->dev , fmt , ## args)
330 #define ERROR(d, fmt, args...) \
331 dev_err(&(d)->gadget->dev , fmt , ## args)
332 #define WARNING(d, fmt, args...) \
333 dev_warn(&(d)->gadget->dev , fmt , ## args)
334 #define INFO(d, fmt, args...) \
335 dev_info(&(d)->gadget->dev , fmt , ## args)
338 /*-------------------------------------------------------------------------*/
340 /* Encapsulate the module parameter settings */
345 char *file
[MAX_LUNS
];
347 unsigned int num_filenames
;
348 unsigned int num_ros
;
355 char *transport_parm
;
357 unsigned short vendor
;
358 unsigned short product
;
359 unsigned short release
;
363 char *transport_name
;
367 } mod_data
= { // Default values
368 .transport_parm
= "BBB",
369 .protocol_parm
= "SCSI",
373 .vendor
= DRIVER_VENDOR_ID
,
374 .product
= DRIVER_PRODUCT_ID
,
375 .release
= 0xffff, // Use controller chip type
380 module_param_array_named(file
, mod_data
.file
, charp
, &mod_data
.num_filenames
,
382 MODULE_PARM_DESC(file
, "names of backing files or devices");
384 module_param_array_named(ro
, mod_data
.ro
, bool, &mod_data
.num_ros
, S_IRUGO
);
385 MODULE_PARM_DESC(ro
, "true to force read-only");
387 module_param_named(luns
, mod_data
.nluns
, uint
, S_IRUGO
);
388 MODULE_PARM_DESC(luns
, "number of LUNs");
390 module_param_named(removable
, mod_data
.removable
, bool, S_IRUGO
);
391 MODULE_PARM_DESC(removable
, "true to simulate removable media");
393 module_param_named(stall
, mod_data
.can_stall
, bool, S_IRUGO
);
394 MODULE_PARM_DESC(stall
, "false to prevent bulk stalls");
396 module_param_named(cdrom
, mod_data
.cdrom
, bool, S_IRUGO
);
397 MODULE_PARM_DESC(cdrom
, "true to emulate cdrom instead of disk");
400 /* In the non-TEST version, only the module parameters listed above
402 #ifdef CONFIG_USB_FILE_STORAGE_TEST
404 module_param_named(transport
, mod_data
.transport_parm
, charp
, S_IRUGO
);
405 MODULE_PARM_DESC(transport
, "type of transport (BBB, CBI, or CB)");
407 module_param_named(protocol
, mod_data
.protocol_parm
, charp
, S_IRUGO
);
408 MODULE_PARM_DESC(protocol
, "type of protocol (RBC, 8020, QIC, UFI, "
411 module_param_named(vendor
, mod_data
.vendor
, ushort
, S_IRUGO
);
412 MODULE_PARM_DESC(vendor
, "USB Vendor ID");
414 module_param_named(product
, mod_data
.product
, ushort
, S_IRUGO
);
415 MODULE_PARM_DESC(product
, "USB Product ID");
417 module_param_named(release
, mod_data
.release
, ushort
, S_IRUGO
);
418 MODULE_PARM_DESC(release
, "USB release number");
420 module_param_named(buflen
, mod_data
.buflen
, uint
, S_IRUGO
);
421 MODULE_PARM_DESC(buflen
, "I/O buffer size");
423 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
426 /*-------------------------------------------------------------------------*/
428 /* SCSI device types */
429 #define TYPE_DISK 0x00
430 #define TYPE_CDROM 0x05
432 /* USB protocol value = the transport method */
433 #define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
434 #define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
435 #define USB_PR_BULK 0x50 // Bulk-only
437 /* USB subclass value = the protocol encapsulation */
438 #define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
439 #define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
440 #define USB_SC_QIC 0x03 // QIC-157 (tape)
441 #define USB_SC_UFI 0x04 // UFI (floppy)
442 #define USB_SC_8070 0x05 // SFF-8070i (removable)
443 #define USB_SC_SCSI 0x06 // Transparent SCSI
445 /* Bulk-only data structures */
447 /* Command Block Wrapper */
448 struct bulk_cb_wrap
{
449 __le32 Signature
; // Contains 'USBC'
450 u32 Tag
; // Unique per command id
451 __le32 DataTransferLength
; // Size of the data
452 u8 Flags
; // Direction in bit 7
453 u8 Lun
; // LUN (normally 0)
454 u8 Length
; // Of the CDB, <= MAX_COMMAND_SIZE
455 u8 CDB
[16]; // Command Data Block
458 #define USB_BULK_CB_WRAP_LEN 31
459 #define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
460 #define USB_BULK_IN_FLAG 0x80
462 /* Command Status Wrapper */
463 struct bulk_cs_wrap
{
464 __le32 Signature
; // Should = 'USBS'
465 u32 Tag
; // Same as original command
466 __le32 Residue
; // Amount not transferred
467 u8 Status
; // See below
470 #define USB_BULK_CS_WRAP_LEN 13
471 #define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
472 #define USB_STATUS_PASS 0
473 #define USB_STATUS_FAIL 1
474 #define USB_STATUS_PHASE_ERROR 2
476 /* Bulk-only class specific requests */
477 #define USB_BULK_RESET_REQUEST 0xff
478 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
481 /* CBI Interrupt data structure */
482 struct interrupt_data
{
487 #define CBI_INTERRUPT_DATA_LEN 2
489 /* CBI Accept Device-Specific Command request */
490 #define USB_CBI_ADSC_REQUEST 0x00
493 #define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
495 /* SCSI commands that we recognize */
496 #define SC_FORMAT_UNIT 0x04
497 #define SC_INQUIRY 0x12
498 #define SC_MODE_SELECT_6 0x15
499 #define SC_MODE_SELECT_10 0x55
500 #define SC_MODE_SENSE_6 0x1a
501 #define SC_MODE_SENSE_10 0x5a
502 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
503 #define SC_READ_6 0x08
504 #define SC_READ_10 0x28
505 #define SC_READ_12 0xa8
506 #define SC_READ_CAPACITY 0x25
507 #define SC_READ_FORMAT_CAPACITIES 0x23
508 #define SC_READ_HEADER 0x44
509 #define SC_READ_TOC 0x43
510 #define SC_RELEASE 0x17
511 #define SC_REQUEST_SENSE 0x03
512 #define SC_RESERVE 0x16
513 #define SC_SEND_DIAGNOSTIC 0x1d
514 #define SC_START_STOP_UNIT 0x1b
515 #define SC_SYNCHRONIZE_CACHE 0x35
516 #define SC_TEST_UNIT_READY 0x00
517 #define SC_VERIFY 0x2f
518 #define SC_WRITE_6 0x0a
519 #define SC_WRITE_10 0x2a
520 #define SC_WRITE_12 0xaa
522 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
523 #define SS_NO_SENSE 0
524 #define SS_COMMUNICATION_FAILURE 0x040800
525 #define SS_INVALID_COMMAND 0x052000
526 #define SS_INVALID_FIELD_IN_CDB 0x052400
527 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
528 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
529 #define SS_MEDIUM_NOT_PRESENT 0x023a00
530 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
531 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
532 #define SS_RESET_OCCURRED 0x062900
533 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
534 #define SS_UNRECOVERED_READ_ERROR 0x031100
535 #define SS_WRITE_ERROR 0x030c02
536 #define SS_WRITE_PROTECTED 0x072700
538 #define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
539 #define ASC(x) ((u8) ((x) >> 8))
540 #define ASCQ(x) ((u8) (x))
543 /*-------------------------------------------------------------------------*/
546 * These definitions will permit the compiler to avoid generating code for
547 * parts of the driver that aren't used in the non-TEST version. Even gcc
548 * can recognize when a test of a constant expression yields a dead code
552 #ifdef CONFIG_USB_FILE_STORAGE_TEST
554 #define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
555 #define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
556 #define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
560 #define transport_is_bbb() 1
561 #define transport_is_cbi() 0
562 #define protocol_is_scsi() 1
564 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
573 unsigned int prevent_medium_removal
: 1;
574 unsigned int registered
: 1;
575 unsigned int info_valid
: 1;
579 u32 unit_attention_data
;
584 #define backing_file_is_open(curlun) ((curlun)->filp != NULL)
586 static struct lun
*dev_to_lun(struct device
*dev
)
588 return container_of(dev
, struct lun
, dev
);
592 /* Big enough to hold our biggest descriptor */
593 #define EP0_BUFSIZE 256
594 #define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
596 /* Number of buffers we will use. 2 is enough for double-buffering */
597 #define NUM_BUFFERS 2
599 enum fsg_buffer_state
{
607 enum fsg_buffer_state state
;
608 struct fsg_buffhd
*next
;
610 /* The NetChip 2280 is faster, and handles some protocol faults
611 * better, if we don't submit any short bulk-out read requests.
612 * So we will record the intended request length here. */
613 unsigned int bulk_out_intended_length
;
615 struct usb_request
*inreq
;
617 struct usb_request
*outreq
;
622 FSG_STATE_COMMAND_PHASE
= -10, // This one isn't used anywhere
623 FSG_STATE_DATA_PHASE
,
624 FSG_STATE_STATUS_PHASE
,
627 FSG_STATE_ABORT_BULK_OUT
,
629 FSG_STATE_INTERFACE_CHANGE
,
630 FSG_STATE_CONFIG_CHANGE
,
631 FSG_STATE_DISCONNECT
,
636 enum data_direction
{
637 DATA_DIR_UNKNOWN
= 0,
644 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
646 struct usb_gadget
*gadget
;
648 /* filesem protects: backing files in use */
649 struct rw_semaphore filesem
;
651 /* reference counting: wait until all LUNs are released */
654 struct usb_ep
*ep0
; // Handy copy of gadget->ep0
655 struct usb_request
*ep0req
; // For control responses
656 unsigned int ep0_req_tag
;
657 const char *ep0req_name
;
659 struct usb_request
*intreq
; // For interrupt responses
661 struct fsg_buffhd
*intr_buffhd
;
663 unsigned int bulk_out_maxpacket
;
664 enum fsg_state state
; // For exception handling
665 unsigned int exception_req_tag
;
667 u8 config
, new_config
;
669 unsigned int running
: 1;
670 unsigned int bulk_in_enabled
: 1;
671 unsigned int bulk_out_enabled
: 1;
672 unsigned int intr_in_enabled
: 1;
673 unsigned int phase_error
: 1;
674 unsigned int short_packet_received
: 1;
675 unsigned int bad_lun_okay
: 1;
677 unsigned long atomic_bitflags
;
679 #define IGNORE_BULK_OUT 1
682 struct usb_ep
*bulk_in
;
683 struct usb_ep
*bulk_out
;
684 struct usb_ep
*intr_in
;
686 struct fsg_buffhd
*next_buffhd_to_fill
;
687 struct fsg_buffhd
*next_buffhd_to_drain
;
688 struct fsg_buffhd buffhds
[NUM_BUFFERS
];
690 int thread_wakeup_needed
;
691 struct completion thread_notifier
;
692 struct task_struct
*thread_task
;
695 u8 cmnd
[MAX_COMMAND_SIZE
];
696 enum data_direction data_dir
;
698 u32 data_size_from_cmnd
;
704 /* The CB protocol offers no way for a host to know when a command
705 * has completed. As a result the next command may arrive early,
706 * and we will still have to handle it. For that reason we need
707 * a buffer to store new commands when using CB (or CBI, which
708 * does not oblige a host to wait for command completion either). */
710 u8 cbbuf_cmnd
[MAX_COMMAND_SIZE
];
717 typedef void (*fsg_routine_t
)(struct fsg_dev
*);
719 static int exception_in_progress(struct fsg_dev
*fsg
)
721 return (fsg
->state
> FSG_STATE_IDLE
);
724 /* Make bulk-out requests be divisible by the maxpacket size */
725 static void set_bulk_out_req_length(struct fsg_dev
*fsg
,
726 struct fsg_buffhd
*bh
, unsigned int length
)
730 bh
->bulk_out_intended_length
= length
;
731 rem
= length
% fsg
->bulk_out_maxpacket
;
733 length
+= fsg
->bulk_out_maxpacket
- rem
;
734 bh
->outreq
->length
= length
;
737 static struct fsg_dev
*the_fsg
;
738 static struct usb_gadget_driver fsg_driver
;
740 static void close_backing_file(struct lun
*curlun
);
741 static void close_all_backing_files(struct fsg_dev
*fsg
);
744 /*-------------------------------------------------------------------------*/
748 static void dump_msg(struct fsg_dev
*fsg
, const char *label
,
749 const u8
*buf
, unsigned int length
)
752 DBG(fsg
, "%s, length %u:\n", label
, length
);
753 print_hex_dump(KERN_DEBUG
, "", DUMP_PREFIX_OFFSET
,
754 16, 1, buf
, length
, 0);
758 static void dump_cdb(struct fsg_dev
*fsg
)
763 static void dump_msg(struct fsg_dev
*fsg
, const char *label
,
764 const u8
*buf
, unsigned int length
)
769 static void dump_cdb(struct fsg_dev
*fsg
)
771 print_hex_dump(KERN_DEBUG
, "SCSI CDB: ", DUMP_PREFIX_NONE
,
772 16, 1, fsg
->cmnd
, fsg
->cmnd_size
, 0);
777 static void dump_cdb(struct fsg_dev
*fsg
)
780 #endif /* VERBOSE_DEBUG */
781 #endif /* DUMP_MSGS */
784 static int fsg_set_halt(struct fsg_dev
*fsg
, struct usb_ep
*ep
)
788 if (ep
== fsg
->bulk_in
)
790 else if (ep
== fsg
->bulk_out
)
794 DBG(fsg
, "%s set halt\n", name
);
795 return usb_ep_set_halt(ep
);
799 /*-------------------------------------------------------------------------*/
801 /* Routines for unaligned data access */
803 static u16
get_be16(u8
*buf
)
805 return ((u16
) buf
[0] << 8) | ((u16
) buf
[1]);
808 static u32
get_be32(u8
*buf
)
810 return ((u32
) buf
[0] << 24) | ((u32
) buf
[1] << 16) |
811 ((u32
) buf
[2] << 8) | ((u32
) buf
[3]);
814 static void put_be16(u8
*buf
, u16 val
)
820 static void put_be32(u8
*buf
, u32 val
)
829 /*-------------------------------------------------------------------------*/
832 * DESCRIPTORS ... most are static, but strings and (full) configuration
833 * descriptors are built on demand. Also the (static) config and interface
834 * descriptors are adjusted during fsg_bind().
836 #define STRING_MANUFACTURER 1
837 #define STRING_PRODUCT 2
838 #define STRING_SERIAL 3
839 #define STRING_CONFIG 4
840 #define STRING_INTERFACE 5
842 /* There is only one configuration. */
843 #define CONFIG_VALUE 1
845 static struct usb_device_descriptor
847 .bLength
= sizeof device_desc
,
848 .bDescriptorType
= USB_DT_DEVICE
,
850 .bcdUSB
= __constant_cpu_to_le16(0x0200),
851 .bDeviceClass
= USB_CLASS_PER_INTERFACE
,
853 /* The next three values can be overridden by module parameters */
854 .idVendor
= __constant_cpu_to_le16(DRIVER_VENDOR_ID
),
855 .idProduct
= __constant_cpu_to_le16(DRIVER_PRODUCT_ID
),
856 .bcdDevice
= __constant_cpu_to_le16(0xffff),
858 .iManufacturer
= STRING_MANUFACTURER
,
859 .iProduct
= STRING_PRODUCT
,
860 .iSerialNumber
= STRING_SERIAL
,
861 .bNumConfigurations
= 1,
864 static struct usb_config_descriptor
866 .bLength
= sizeof config_desc
,
867 .bDescriptorType
= USB_DT_CONFIG
,
869 /* wTotalLength computed by usb_gadget_config_buf() */
871 .bConfigurationValue
= CONFIG_VALUE
,
872 .iConfiguration
= STRING_CONFIG
,
873 .bmAttributes
= USB_CONFIG_ATT_ONE
| USB_CONFIG_ATT_SELFPOWER
,
874 .bMaxPower
= CONFIG_USB_GADGET_VBUS_DRAW
/ 2,
877 static struct usb_otg_descriptor
879 .bLength
= sizeof(otg_desc
),
880 .bDescriptorType
= USB_DT_OTG
,
882 .bmAttributes
= USB_OTG_SRP
,
885 /* There is only one interface. */
887 static struct usb_interface_descriptor
889 .bLength
= sizeof intf_desc
,
890 .bDescriptorType
= USB_DT_INTERFACE
,
892 .bNumEndpoints
= 2, // Adjusted during fsg_bind()
893 .bInterfaceClass
= USB_CLASS_MASS_STORAGE
,
894 .bInterfaceSubClass
= USB_SC_SCSI
, // Adjusted during fsg_bind()
895 .bInterfaceProtocol
= USB_PR_BULK
, // Adjusted during fsg_bind()
896 .iInterface
= STRING_INTERFACE
,
899 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
900 * and interrupt-in. */
902 static struct usb_endpoint_descriptor
904 .bLength
= USB_DT_ENDPOINT_SIZE
,
905 .bDescriptorType
= USB_DT_ENDPOINT
,
907 .bEndpointAddress
= USB_DIR_IN
,
908 .bmAttributes
= USB_ENDPOINT_XFER_BULK
,
909 /* wMaxPacketSize set by autoconfiguration */
912 static struct usb_endpoint_descriptor
914 .bLength
= USB_DT_ENDPOINT_SIZE
,
915 .bDescriptorType
= USB_DT_ENDPOINT
,
917 .bEndpointAddress
= USB_DIR_OUT
,
918 .bmAttributes
= USB_ENDPOINT_XFER_BULK
,
919 /* wMaxPacketSize set by autoconfiguration */
922 static struct usb_endpoint_descriptor
924 .bLength
= USB_DT_ENDPOINT_SIZE
,
925 .bDescriptorType
= USB_DT_ENDPOINT
,
927 .bEndpointAddress
= USB_DIR_IN
,
928 .bmAttributes
= USB_ENDPOINT_XFER_INT
,
929 .wMaxPacketSize
= __constant_cpu_to_le16(2),
930 .bInterval
= 32, // frames -> 32 ms
933 static const struct usb_descriptor_header
*fs_function
[] = {
934 (struct usb_descriptor_header
*) &otg_desc
,
935 (struct usb_descriptor_header
*) &intf_desc
,
936 (struct usb_descriptor_header
*) &fs_bulk_in_desc
,
937 (struct usb_descriptor_header
*) &fs_bulk_out_desc
,
938 (struct usb_descriptor_header
*) &fs_intr_in_desc
,
941 #define FS_FUNCTION_PRE_EP_ENTRIES 2
945 * USB 2.0 devices need to expose both high speed and full speed
946 * descriptors, unless they only run at full speed.
948 * That means alternate endpoint descriptors (bigger packets)
949 * and a "device qualifier" ... plus more construction options
950 * for the config descriptor.
952 static struct usb_qualifier_descriptor
954 .bLength
= sizeof dev_qualifier
,
955 .bDescriptorType
= USB_DT_DEVICE_QUALIFIER
,
957 .bcdUSB
= __constant_cpu_to_le16(0x0200),
958 .bDeviceClass
= USB_CLASS_PER_INTERFACE
,
960 .bNumConfigurations
= 1,
963 static struct usb_endpoint_descriptor
965 .bLength
= USB_DT_ENDPOINT_SIZE
,
966 .bDescriptorType
= USB_DT_ENDPOINT
,
968 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
969 .bmAttributes
= USB_ENDPOINT_XFER_BULK
,
970 .wMaxPacketSize
= __constant_cpu_to_le16(512),
973 static struct usb_endpoint_descriptor
975 .bLength
= USB_DT_ENDPOINT_SIZE
,
976 .bDescriptorType
= USB_DT_ENDPOINT
,
978 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
979 .bmAttributes
= USB_ENDPOINT_XFER_BULK
,
980 .wMaxPacketSize
= __constant_cpu_to_le16(512),
981 .bInterval
= 1, // NAK every 1 uframe
984 static struct usb_endpoint_descriptor
986 .bLength
= USB_DT_ENDPOINT_SIZE
,
987 .bDescriptorType
= USB_DT_ENDPOINT
,
989 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
990 .bmAttributes
= USB_ENDPOINT_XFER_INT
,
991 .wMaxPacketSize
= __constant_cpu_to_le16(2),
992 .bInterval
= 9, // 2**(9-1) = 256 uframes -> 32 ms
995 static const struct usb_descriptor_header
*hs_function
[] = {
996 (struct usb_descriptor_header
*) &otg_desc
,
997 (struct usb_descriptor_header
*) &intf_desc
,
998 (struct usb_descriptor_header
*) &hs_bulk_in_desc
,
999 (struct usb_descriptor_header
*) &hs_bulk_out_desc
,
1000 (struct usb_descriptor_header
*) &hs_intr_in_desc
,
1003 #define HS_FUNCTION_PRE_EP_ENTRIES 2
1005 /* Maxpacket and other transfer characteristics vary by speed. */
1006 static struct usb_endpoint_descriptor
*
1007 ep_desc(struct usb_gadget
*g
, struct usb_endpoint_descriptor
*fs
,
1008 struct usb_endpoint_descriptor
*hs
)
1010 if (gadget_is_dualspeed(g
) && g
->speed
== USB_SPEED_HIGH
)
1016 /* The CBI specification limits the serial string to 12 uppercase hexadecimal
1018 static char manufacturer
[64];
1019 static char serial
[13];
1021 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1022 static struct usb_string strings
[] = {
1023 {STRING_MANUFACTURER
, manufacturer
},
1024 {STRING_PRODUCT
, longname
},
1025 {STRING_SERIAL
, serial
},
1026 {STRING_CONFIG
, "Self-powered"},
1027 {STRING_INTERFACE
, "Mass Storage"},
1031 static struct usb_gadget_strings stringtab
= {
1032 .language
= 0x0409, // en-us
1038 * Config descriptors must agree with the code that sets configurations
1039 * and with code managing interfaces and their altsettings. They must
1040 * also handle different speeds and other-speed requests.
1042 static int populate_config_buf(struct usb_gadget
*gadget
,
1043 u8
*buf
, u8 type
, unsigned index
)
1045 enum usb_device_speed speed
= gadget
->speed
;
1047 const struct usb_descriptor_header
**function
;
1052 if (gadget_is_dualspeed(gadget
) && type
== USB_DT_OTHER_SPEED_CONFIG
)
1053 speed
= (USB_SPEED_FULL
+ USB_SPEED_HIGH
) - speed
;
1054 if (gadget_is_dualspeed(gadget
) && speed
== USB_SPEED_HIGH
)
1055 function
= hs_function
;
1057 function
= fs_function
;
1059 /* for now, don't advertise srp-only devices */
1060 if (!gadget_is_otg(gadget
))
1063 len
= usb_gadget_config_buf(&config_desc
, buf
, EP0_BUFSIZE
, function
);
1064 ((struct usb_config_descriptor
*) buf
)->bDescriptorType
= type
;
1069 /*-------------------------------------------------------------------------*/
1071 /* These routines may be called in process context or in_irq */
1073 /* Caller must hold fsg->lock */
1074 static void wakeup_thread(struct fsg_dev
*fsg
)
1076 /* Tell the main thread that something has happened */
1077 fsg
->thread_wakeup_needed
= 1;
1078 if (fsg
->thread_task
)
1079 wake_up_process(fsg
->thread_task
);
1083 static void raise_exception(struct fsg_dev
*fsg
, enum fsg_state new_state
)
1085 unsigned long flags
;
1087 /* Do nothing if a higher-priority exception is already in progress.
1088 * If a lower-or-equal priority exception is in progress, preempt it
1089 * and notify the main thread by sending it a signal. */
1090 spin_lock_irqsave(&fsg
->lock
, flags
);
1091 if (fsg
->state
<= new_state
) {
1092 fsg
->exception_req_tag
= fsg
->ep0_req_tag
;
1093 fsg
->state
= new_state
;
1094 if (fsg
->thread_task
)
1095 send_sig_info(SIGUSR1
, SEND_SIG_FORCED
,
1098 spin_unlock_irqrestore(&fsg
->lock
, flags
);
1102 /*-------------------------------------------------------------------------*/
1104 /* The disconnect callback and ep0 routines. These always run in_irq,
1105 * except that ep0_queue() is called in the main thread to acknowledge
1106 * completion of various requests: set config, set interface, and
1107 * Bulk-only device reset. */
1109 static void fsg_disconnect(struct usb_gadget
*gadget
)
1111 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
1113 DBG(fsg
, "disconnect or port reset\n");
1114 raise_exception(fsg
, FSG_STATE_DISCONNECT
);
1118 static int ep0_queue(struct fsg_dev
*fsg
)
1122 rc
= usb_ep_queue(fsg
->ep0
, fsg
->ep0req
, GFP_ATOMIC
);
1123 if (rc
!= 0 && rc
!= -ESHUTDOWN
) {
1125 /* We can't do much more than wait for a reset */
1126 WARNING(fsg
, "error in submission: %s --> %d\n",
1127 fsg
->ep0
->name
, rc
);
1132 static void ep0_complete(struct usb_ep
*ep
, struct usb_request
*req
)
1134 struct fsg_dev
*fsg
= ep
->driver_data
;
1136 if (req
->actual
> 0)
1137 dump_msg(fsg
, fsg
->ep0req_name
, req
->buf
, req
->actual
);
1138 if (req
->status
|| req
->actual
!= req
->length
)
1139 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
1140 req
->status
, req
->actual
, req
->length
);
1141 if (req
->status
== -ECONNRESET
) // Request was cancelled
1142 usb_ep_fifo_flush(ep
);
1144 if (req
->status
== 0 && req
->context
)
1145 ((fsg_routine_t
) (req
->context
))(fsg
);
1149 /*-------------------------------------------------------------------------*/
1151 /* Bulk and interrupt endpoint completion handlers.
1152 * These always run in_irq. */
1154 static void bulk_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
1156 struct fsg_dev
*fsg
= ep
->driver_data
;
1157 struct fsg_buffhd
*bh
= req
->context
;
1159 if (req
->status
|| req
->actual
!= req
->length
)
1160 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
1161 req
->status
, req
->actual
, req
->length
);
1162 if (req
->status
== -ECONNRESET
) // Request was cancelled
1163 usb_ep_fifo_flush(ep
);
1165 /* Hold the lock while we update the request and buffer states */
1167 spin_lock(&fsg
->lock
);
1169 bh
->state
= BUF_STATE_EMPTY
;
1171 spin_unlock(&fsg
->lock
);
1174 static void bulk_out_complete(struct usb_ep
*ep
, struct usb_request
*req
)
1176 struct fsg_dev
*fsg
= ep
->driver_data
;
1177 struct fsg_buffhd
*bh
= req
->context
;
1179 dump_msg(fsg
, "bulk-out", req
->buf
, req
->actual
);
1180 if (req
->status
|| req
->actual
!= bh
->bulk_out_intended_length
)
1181 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
1182 req
->status
, req
->actual
,
1183 bh
->bulk_out_intended_length
);
1184 if (req
->status
== -ECONNRESET
) // Request was cancelled
1185 usb_ep_fifo_flush(ep
);
1187 /* Hold the lock while we update the request and buffer states */
1189 spin_lock(&fsg
->lock
);
1190 bh
->outreq_busy
= 0;
1191 bh
->state
= BUF_STATE_FULL
;
1193 spin_unlock(&fsg
->lock
);
1197 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1198 static void intr_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
1200 struct fsg_dev
*fsg
= ep
->driver_data
;
1201 struct fsg_buffhd
*bh
= req
->context
;
1203 if (req
->status
|| req
->actual
!= req
->length
)
1204 DBG(fsg
, "%s --> %d, %u/%u\n", __func__
,
1205 req
->status
, req
->actual
, req
->length
);
1206 if (req
->status
== -ECONNRESET
) // Request was cancelled
1207 usb_ep_fifo_flush(ep
);
1209 /* Hold the lock while we update the request and buffer states */
1211 spin_lock(&fsg
->lock
);
1212 fsg
->intreq_busy
= 0;
1213 bh
->state
= BUF_STATE_EMPTY
;
1215 spin_unlock(&fsg
->lock
);
1219 static void intr_in_complete(struct usb_ep
*ep
, struct usb_request
*req
)
1221 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1224 /*-------------------------------------------------------------------------*/
1226 /* Ep0 class-specific handlers. These always run in_irq. */
1228 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1229 static void received_cbi_adsc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1231 struct usb_request
*req
= fsg
->ep0req
;
1232 static u8 cbi_reset_cmnd
[6] = {
1233 SC_SEND_DIAGNOSTIC
, 4, 0xff, 0xff, 0xff, 0xff};
1235 /* Error in command transfer? */
1236 if (req
->status
|| req
->length
!= req
->actual
||
1237 req
->actual
< 6 || req
->actual
> MAX_COMMAND_SIZE
) {
1239 /* Not all controllers allow a protocol stall after
1240 * receiving control-out data, but we'll try anyway. */
1241 fsg_set_halt(fsg
, fsg
->ep0
);
1242 return; // Wait for reset
1245 /* Is it the special reset command? */
1246 if (req
->actual
>= sizeof cbi_reset_cmnd
&&
1247 memcmp(req
->buf
, cbi_reset_cmnd
,
1248 sizeof cbi_reset_cmnd
) == 0) {
1250 /* Raise an exception to stop the current operation
1251 * and reinitialize our state. */
1252 DBG(fsg
, "cbi reset request\n");
1253 raise_exception(fsg
, FSG_STATE_RESET
);
1257 VDBG(fsg
, "CB[I] accept device-specific command\n");
1258 spin_lock(&fsg
->lock
);
1260 /* Save the command for later */
1261 if (fsg
->cbbuf_cmnd_size
)
1262 WARNING(fsg
, "CB[I] overwriting previous command\n");
1263 fsg
->cbbuf_cmnd_size
= req
->actual
;
1264 memcpy(fsg
->cbbuf_cmnd
, req
->buf
, fsg
->cbbuf_cmnd_size
);
1267 spin_unlock(&fsg
->lock
);
1271 static void received_cbi_adsc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
1273 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1276 static int class_setup_req(struct fsg_dev
*fsg
,
1277 const struct usb_ctrlrequest
*ctrl
)
1279 struct usb_request
*req
= fsg
->ep0req
;
1280 int value
= -EOPNOTSUPP
;
1281 u16 w_index
= le16_to_cpu(ctrl
->wIndex
);
1282 u16 w_value
= le16_to_cpu(ctrl
->wValue
);
1283 u16 w_length
= le16_to_cpu(ctrl
->wLength
);
1288 /* Handle Bulk-only class-specific requests */
1289 if (transport_is_bbb()) {
1290 switch (ctrl
->bRequest
) {
1292 case USB_BULK_RESET_REQUEST
:
1293 if (ctrl
->bRequestType
!= (USB_DIR_OUT
|
1294 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
1296 if (w_index
!= 0 || w_value
!= 0) {
1301 /* Raise an exception to stop the current operation
1302 * and reinitialize our state. */
1303 DBG(fsg
, "bulk reset request\n");
1304 raise_exception(fsg
, FSG_STATE_RESET
);
1305 value
= DELAYED_STATUS
;
1308 case USB_BULK_GET_MAX_LUN_REQUEST
:
1309 if (ctrl
->bRequestType
!= (USB_DIR_IN
|
1310 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
1312 if (w_index
!= 0 || w_value
!= 0) {
1316 VDBG(fsg
, "get max LUN\n");
1317 *(u8
*) req
->buf
= fsg
->nluns
- 1;
1323 /* Handle CBI class-specific requests */
1325 switch (ctrl
->bRequest
) {
1327 case USB_CBI_ADSC_REQUEST
:
1328 if (ctrl
->bRequestType
!= (USB_DIR_OUT
|
1329 USB_TYPE_CLASS
| USB_RECIP_INTERFACE
))
1331 if (w_index
!= 0 || w_value
!= 0) {
1335 if (w_length
> MAX_COMMAND_SIZE
) {
1340 fsg
->ep0req
->context
= received_cbi_adsc
;
1345 if (value
== -EOPNOTSUPP
)
1347 "unknown class-specific control req "
1348 "%02x.%02x v%04x i%04x l%u\n",
1349 ctrl
->bRequestType
, ctrl
->bRequest
,
1350 le16_to_cpu(ctrl
->wValue
), w_index
, w_length
);
1355 /*-------------------------------------------------------------------------*/
1357 /* Ep0 standard request handlers. These always run in_irq. */
1359 static int standard_setup_req(struct fsg_dev
*fsg
,
1360 const struct usb_ctrlrequest
*ctrl
)
1362 struct usb_request
*req
= fsg
->ep0req
;
1363 int value
= -EOPNOTSUPP
;
1364 u16 w_index
= le16_to_cpu(ctrl
->wIndex
);
1365 u16 w_value
= le16_to_cpu(ctrl
->wValue
);
1367 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1368 * but config change events will also reconfigure hardware. */
1369 switch (ctrl
->bRequest
) {
1371 case USB_REQ_GET_DESCRIPTOR
:
1372 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
1375 switch (w_value
>> 8) {
1378 VDBG(fsg
, "get device descriptor\n");
1379 value
= sizeof device_desc
;
1380 memcpy(req
->buf
, &device_desc
, value
);
1382 case USB_DT_DEVICE_QUALIFIER
:
1383 VDBG(fsg
, "get device qualifier\n");
1384 if (!gadget_is_dualspeed(fsg
->gadget
))
1386 value
= sizeof dev_qualifier
;
1387 memcpy(req
->buf
, &dev_qualifier
, value
);
1390 case USB_DT_OTHER_SPEED_CONFIG
:
1391 VDBG(fsg
, "get other-speed config descriptor\n");
1392 if (!gadget_is_dualspeed(fsg
->gadget
))
1396 VDBG(fsg
, "get configuration descriptor\n");
1398 value
= populate_config_buf(fsg
->gadget
,
1405 VDBG(fsg
, "get string descriptor\n");
1407 /* wIndex == language code */
1408 value
= usb_gadget_get_string(&stringtab
,
1409 w_value
& 0xff, req
->buf
);
1414 /* One config, two speeds */
1415 case USB_REQ_SET_CONFIGURATION
:
1416 if (ctrl
->bRequestType
!= (USB_DIR_OUT
| USB_TYPE_STANDARD
|
1419 VDBG(fsg
, "set configuration\n");
1420 if (w_value
== CONFIG_VALUE
|| w_value
== 0) {
1421 fsg
->new_config
= w_value
;
1423 /* Raise an exception to wipe out previous transaction
1424 * state (queued bufs, etc) and set the new config. */
1425 raise_exception(fsg
, FSG_STATE_CONFIG_CHANGE
);
1426 value
= DELAYED_STATUS
;
1429 case USB_REQ_GET_CONFIGURATION
:
1430 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
1433 VDBG(fsg
, "get configuration\n");
1434 *(u8
*) req
->buf
= fsg
->config
;
1438 case USB_REQ_SET_INTERFACE
:
1439 if (ctrl
->bRequestType
!= (USB_DIR_OUT
| USB_TYPE_STANDARD
|
1440 USB_RECIP_INTERFACE
))
1442 if (fsg
->config
&& w_index
== 0) {
1444 /* Raise an exception to wipe out previous transaction
1445 * state (queued bufs, etc) and install the new
1446 * interface altsetting. */
1447 raise_exception(fsg
, FSG_STATE_INTERFACE_CHANGE
);
1448 value
= DELAYED_STATUS
;
1451 case USB_REQ_GET_INTERFACE
:
1452 if (ctrl
->bRequestType
!= (USB_DIR_IN
| USB_TYPE_STANDARD
|
1453 USB_RECIP_INTERFACE
))
1461 VDBG(fsg
, "get interface\n");
1462 *(u8
*) req
->buf
= 0;
1468 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1469 ctrl
->bRequestType
, ctrl
->bRequest
,
1470 w_value
, w_index
, le16_to_cpu(ctrl
->wLength
));
1477 static int fsg_setup(struct usb_gadget
*gadget
,
1478 const struct usb_ctrlrequest
*ctrl
)
1480 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
1482 int w_length
= le16_to_cpu(ctrl
->wLength
);
1484 ++fsg
->ep0_req_tag
; // Record arrival of a new request
1485 fsg
->ep0req
->context
= NULL
;
1486 fsg
->ep0req
->length
= 0;
1487 dump_msg(fsg
, "ep0-setup", (u8
*) ctrl
, sizeof(*ctrl
));
1489 if ((ctrl
->bRequestType
& USB_TYPE_MASK
) == USB_TYPE_CLASS
)
1490 rc
= class_setup_req(fsg
, ctrl
);
1492 rc
= standard_setup_req(fsg
, ctrl
);
1494 /* Respond with data/status or defer until later? */
1495 if (rc
>= 0 && rc
!= DELAYED_STATUS
) {
1496 rc
= min(rc
, w_length
);
1497 fsg
->ep0req
->length
= rc
;
1498 fsg
->ep0req
->zero
= rc
< w_length
;
1499 fsg
->ep0req_name
= (ctrl
->bRequestType
& USB_DIR_IN
?
1500 "ep0-in" : "ep0-out");
1501 rc
= ep0_queue(fsg
);
1504 /* Device either stalls (rc < 0) or reports success */
1509 /*-------------------------------------------------------------------------*/
1511 /* All the following routines run in process context */
1514 /* Use this for bulk or interrupt transfers, not ep0 */
1515 static void start_transfer(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
1516 struct usb_request
*req
, int *pbusy
,
1517 enum fsg_buffer_state
*state
)
1521 if (ep
== fsg
->bulk_in
)
1522 dump_msg(fsg
, "bulk-in", req
->buf
, req
->length
);
1523 else if (ep
== fsg
->intr_in
)
1524 dump_msg(fsg
, "intr-in", req
->buf
, req
->length
);
1526 spin_lock_irq(&fsg
->lock
);
1528 *state
= BUF_STATE_BUSY
;
1529 spin_unlock_irq(&fsg
->lock
);
1530 rc
= usb_ep_queue(ep
, req
, GFP_KERNEL
);
1533 *state
= BUF_STATE_EMPTY
;
1535 /* We can't do much more than wait for a reset */
1537 /* Note: currently the net2280 driver fails zero-length
1538 * submissions if DMA is enabled. */
1539 if (rc
!= -ESHUTDOWN
&& !(rc
== -EOPNOTSUPP
&&
1541 WARNING(fsg
, "error in submission: %s --> %d\n",
1547 static int sleep_thread(struct fsg_dev
*fsg
)
1551 /* Wait until a signal arrives or we are woken up */
1554 set_current_state(TASK_INTERRUPTIBLE
);
1555 if (signal_pending(current
)) {
1559 if (fsg
->thread_wakeup_needed
)
1563 __set_current_state(TASK_RUNNING
);
1564 fsg
->thread_wakeup_needed
= 0;
1569 /*-------------------------------------------------------------------------*/
1571 static int do_read(struct fsg_dev
*fsg
)
1573 struct lun
*curlun
= fsg
->curlun
;
1575 struct fsg_buffhd
*bh
;
1578 loff_t file_offset
, file_offset_tmp
;
1579 unsigned int amount
;
1580 unsigned int partial_page
;
1583 /* Get the starting Logical Block Address and check that it's
1585 if (fsg
->cmnd
[0] == SC_READ_6
)
1586 lba
= (fsg
->cmnd
[1] << 16) | get_be16(&fsg
->cmnd
[2]);
1588 lba
= get_be32(&fsg
->cmnd
[2]);
1590 /* We allow DPO (Disable Page Out = don't save data in the
1591 * cache) and FUA (Force Unit Access = don't read from the
1592 * cache), but we don't implement them. */
1593 if ((fsg
->cmnd
[1] & ~0x18) != 0) {
1594 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1598 if (lba
>= curlun
->num_sectors
) {
1599 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1602 file_offset
= ((loff_t
) lba
) << 9;
1604 /* Carry out the file reads */
1605 amount_left
= fsg
->data_size_from_cmnd
;
1606 if (unlikely(amount_left
== 0))
1607 return -EIO
; // No default reply
1611 /* Figure out how much we need to read:
1612 * Try to read the remaining amount.
1613 * But don't read more than the buffer size.
1614 * And don't try to read past the end of the file.
1615 * Finally, if we're not at a page boundary, don't read past
1617 * If this means reading 0 then we were asked to read past
1618 * the end of file. */
1619 amount
= min((unsigned int) amount_left
, mod_data
.buflen
);
1620 amount
= min((loff_t
) amount
,
1621 curlun
->file_length
- file_offset
);
1622 partial_page
= file_offset
& (PAGE_CACHE_SIZE
- 1);
1623 if (partial_page
> 0)
1624 amount
= min(amount
, (unsigned int) PAGE_CACHE_SIZE
-
1627 /* Wait for the next buffer to become available */
1628 bh
= fsg
->next_buffhd_to_fill
;
1629 while (bh
->state
!= BUF_STATE_EMPTY
) {
1630 rc
= sleep_thread(fsg
);
1635 /* If we were asked to read past the end of file,
1636 * end with an empty buffer. */
1638 curlun
->sense_data
=
1639 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1640 curlun
->sense_data_info
= file_offset
>> 9;
1641 curlun
->info_valid
= 1;
1642 bh
->inreq
->length
= 0;
1643 bh
->state
= BUF_STATE_FULL
;
1647 /* Perform the read */
1648 file_offset_tmp
= file_offset
;
1649 nread
= vfs_read(curlun
->filp
,
1650 (char __user
*) bh
->buf
,
1651 amount
, &file_offset_tmp
);
1652 VLDBG(curlun
, "file read %u @ %llu -> %d\n", amount
,
1653 (unsigned long long) file_offset
,
1655 if (signal_pending(current
))
1659 LDBG(curlun
, "error in file read: %d\n",
1662 } else if (nread
< amount
) {
1663 LDBG(curlun
, "partial file read: %d/%u\n",
1664 (int) nread
, amount
);
1665 nread
-= (nread
& 511); // Round down to a block
1667 file_offset
+= nread
;
1668 amount_left
-= nread
;
1669 fsg
->residue
-= nread
;
1670 bh
->inreq
->length
= nread
;
1671 bh
->state
= BUF_STATE_FULL
;
1673 /* If an error occurred, report it and its position */
1674 if (nread
< amount
) {
1675 curlun
->sense_data
= SS_UNRECOVERED_READ_ERROR
;
1676 curlun
->sense_data_info
= file_offset
>> 9;
1677 curlun
->info_valid
= 1;
1681 if (amount_left
== 0)
1682 break; // No more left to read
1684 /* Send this buffer and go read some more */
1685 bh
->inreq
->zero
= 0;
1686 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
1687 &bh
->inreq_busy
, &bh
->state
);
1688 fsg
->next_buffhd_to_fill
= bh
->next
;
1691 return -EIO
; // No default reply
1695 /*-------------------------------------------------------------------------*/
1697 static int do_write(struct fsg_dev
*fsg
)
1699 struct lun
*curlun
= fsg
->curlun
;
1701 struct fsg_buffhd
*bh
;
1703 u32 amount_left_to_req
, amount_left_to_write
;
1704 loff_t usb_offset
, file_offset
, file_offset_tmp
;
1705 unsigned int amount
;
1706 unsigned int partial_page
;
1711 curlun
->sense_data
= SS_WRITE_PROTECTED
;
1714 curlun
->filp
->f_flags
&= ~O_SYNC
; // Default is not to wait
1716 /* Get the starting Logical Block Address and check that it's
1718 if (fsg
->cmnd
[0] == SC_WRITE_6
)
1719 lba
= (fsg
->cmnd
[1] << 16) | get_be16(&fsg
->cmnd
[2]);
1721 lba
= get_be32(&fsg
->cmnd
[2]);
1723 /* We allow DPO (Disable Page Out = don't save data in the
1724 * cache) and FUA (Force Unit Access = write directly to the
1725 * medium). We don't implement DPO; we implement FUA by
1726 * performing synchronous output. */
1727 if ((fsg
->cmnd
[1] & ~0x18) != 0) {
1728 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1731 if (fsg
->cmnd
[1] & 0x08) // FUA
1732 curlun
->filp
->f_flags
|= O_SYNC
;
1734 if (lba
>= curlun
->num_sectors
) {
1735 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1739 /* Carry out the file writes */
1741 file_offset
= usb_offset
= ((loff_t
) lba
) << 9;
1742 amount_left_to_req
= amount_left_to_write
= fsg
->data_size_from_cmnd
;
1744 while (amount_left_to_write
> 0) {
1746 /* Queue a request for more data from the host */
1747 bh
= fsg
->next_buffhd_to_fill
;
1748 if (bh
->state
== BUF_STATE_EMPTY
&& get_some_more
) {
1750 /* Figure out how much we want to get:
1751 * Try to get the remaining amount.
1752 * But don't get more than the buffer size.
1753 * And don't try to go past the end of the file.
1754 * If we're not at a page boundary,
1755 * don't go past the next page.
1756 * If this means getting 0, then we were asked
1757 * to write past the end of file.
1758 * Finally, round down to a block boundary. */
1759 amount
= min(amount_left_to_req
, mod_data
.buflen
);
1760 amount
= min((loff_t
) amount
, curlun
->file_length
-
1762 partial_page
= usb_offset
& (PAGE_CACHE_SIZE
- 1);
1763 if (partial_page
> 0)
1764 amount
= min(amount
,
1765 (unsigned int) PAGE_CACHE_SIZE
- partial_page
);
1769 curlun
->sense_data
=
1770 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1771 curlun
->sense_data_info
= usb_offset
>> 9;
1772 curlun
->info_valid
= 1;
1775 amount
-= (amount
& 511);
1778 /* Why were we were asked to transfer a
1784 /* Get the next buffer */
1785 usb_offset
+= amount
;
1786 fsg
->usb_amount_left
-= amount
;
1787 amount_left_to_req
-= amount
;
1788 if (amount_left_to_req
== 0)
1791 /* amount is always divisible by 512, hence by
1792 * the bulk-out maxpacket size */
1793 bh
->outreq
->length
= bh
->bulk_out_intended_length
=
1795 bh
->outreq
->short_not_ok
= 1;
1796 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
1797 &bh
->outreq_busy
, &bh
->state
);
1798 fsg
->next_buffhd_to_fill
= bh
->next
;
1802 /* Write the received data to the backing file */
1803 bh
= fsg
->next_buffhd_to_drain
;
1804 if (bh
->state
== BUF_STATE_EMPTY
&& !get_some_more
)
1805 break; // We stopped early
1806 if (bh
->state
== BUF_STATE_FULL
) {
1808 fsg
->next_buffhd_to_drain
= bh
->next
;
1809 bh
->state
= BUF_STATE_EMPTY
;
1811 /* Did something go wrong with the transfer? */
1812 if (bh
->outreq
->status
!= 0) {
1813 curlun
->sense_data
= SS_COMMUNICATION_FAILURE
;
1814 curlun
->sense_data_info
= file_offset
>> 9;
1815 curlun
->info_valid
= 1;
1819 amount
= bh
->outreq
->actual
;
1820 if (curlun
->file_length
- file_offset
< amount
) {
1822 "write %u @ %llu beyond end %llu\n",
1823 amount
, (unsigned long long) file_offset
,
1824 (unsigned long long) curlun
->file_length
);
1825 amount
= curlun
->file_length
- file_offset
;
1828 /* Perform the write */
1829 file_offset_tmp
= file_offset
;
1830 nwritten
= vfs_write(curlun
->filp
,
1831 (char __user
*) bh
->buf
,
1832 amount
, &file_offset_tmp
);
1833 VLDBG(curlun
, "file write %u @ %llu -> %d\n", amount
,
1834 (unsigned long long) file_offset
,
1836 if (signal_pending(current
))
1837 return -EINTR
; // Interrupted!
1840 LDBG(curlun
, "error in file write: %d\n",
1843 } else if (nwritten
< amount
) {
1844 LDBG(curlun
, "partial file write: %d/%u\n",
1845 (int) nwritten
, amount
);
1846 nwritten
-= (nwritten
& 511);
1847 // Round down to a block
1849 file_offset
+= nwritten
;
1850 amount_left_to_write
-= nwritten
;
1851 fsg
->residue
-= nwritten
;
1853 /* If an error occurred, report it and its position */
1854 if (nwritten
< amount
) {
1855 curlun
->sense_data
= SS_WRITE_ERROR
;
1856 curlun
->sense_data_info
= file_offset
>> 9;
1857 curlun
->info_valid
= 1;
1861 /* Did the host decide to stop early? */
1862 if (bh
->outreq
->actual
!= bh
->outreq
->length
) {
1863 fsg
->short_packet_received
= 1;
1869 /* Wait for something to happen */
1870 rc
= sleep_thread(fsg
);
1875 return -EIO
; // No default reply
1879 /*-------------------------------------------------------------------------*/
1881 /* Sync the file data, don't bother with the metadata.
1882 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1883 static int fsync_sub(struct lun
*curlun
)
1885 struct file
*filp
= curlun
->filp
;
1887 if (curlun
->ro
|| !filp
)
1889 return vfs_fsync(filp
, filp
->f_path
.dentry
, 1);
1892 static void fsync_all(struct fsg_dev
*fsg
)
1896 for (i
= 0; i
< fsg
->nluns
; ++i
)
1897 fsync_sub(&fsg
->luns
[i
]);
1900 static int do_synchronize_cache(struct fsg_dev
*fsg
)
1902 struct lun
*curlun
= fsg
->curlun
;
1905 /* We ignore the requested LBA and write out all file's
1906 * dirty data buffers. */
1907 rc
= fsync_sub(curlun
);
1909 curlun
->sense_data
= SS_WRITE_ERROR
;
1914 /*-------------------------------------------------------------------------*/
1916 static void invalidate_sub(struct lun
*curlun
)
1918 struct file
*filp
= curlun
->filp
;
1919 struct inode
*inode
= filp
->f_path
.dentry
->d_inode
;
1922 rc
= invalidate_mapping_pages(inode
->i_mapping
, 0, -1);
1923 VLDBG(curlun
, "invalidate_inode_pages -> %ld\n", rc
);
1926 static int do_verify(struct fsg_dev
*fsg
)
1928 struct lun
*curlun
= fsg
->curlun
;
1930 u32 verification_length
;
1931 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
1932 loff_t file_offset
, file_offset_tmp
;
1934 unsigned int amount
;
1937 /* Get the starting Logical Block Address and check that it's
1939 lba
= get_be32(&fsg
->cmnd
[2]);
1940 if (lba
>= curlun
->num_sectors
) {
1941 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1945 /* We allow DPO (Disable Page Out = don't save data in the
1946 * cache) but we don't implement it. */
1947 if ((fsg
->cmnd
[1] & ~0x10) != 0) {
1948 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
1952 verification_length
= get_be16(&fsg
->cmnd
[7]);
1953 if (unlikely(verification_length
== 0))
1954 return -EIO
; // No default reply
1956 /* Prepare to carry out the file verify */
1957 amount_left
= verification_length
<< 9;
1958 file_offset
= ((loff_t
) lba
) << 9;
1960 /* Write out all the dirty buffers before invalidating them */
1962 if (signal_pending(current
))
1965 invalidate_sub(curlun
);
1966 if (signal_pending(current
))
1969 /* Just try to read the requested blocks */
1970 while (amount_left
> 0) {
1972 /* Figure out how much we need to read:
1973 * Try to read the remaining amount, but not more than
1975 * And don't try to read past the end of the file.
1976 * If this means reading 0 then we were asked to read
1977 * past the end of file. */
1978 amount
= min((unsigned int) amount_left
, mod_data
.buflen
);
1979 amount
= min((loff_t
) amount
,
1980 curlun
->file_length
- file_offset
);
1982 curlun
->sense_data
=
1983 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
1984 curlun
->sense_data_info
= file_offset
>> 9;
1985 curlun
->info_valid
= 1;
1989 /* Perform the read */
1990 file_offset_tmp
= file_offset
;
1991 nread
= vfs_read(curlun
->filp
,
1992 (char __user
*) bh
->buf
,
1993 amount
, &file_offset_tmp
);
1994 VLDBG(curlun
, "file read %u @ %llu -> %d\n", amount
,
1995 (unsigned long long) file_offset
,
1997 if (signal_pending(current
))
2001 LDBG(curlun
, "error in file verify: %d\n",
2004 } else if (nread
< amount
) {
2005 LDBG(curlun
, "partial file verify: %d/%u\n",
2006 (int) nread
, amount
);
2007 nread
-= (nread
& 511); // Round down to a sector
2010 curlun
->sense_data
= SS_UNRECOVERED_READ_ERROR
;
2011 curlun
->sense_data_info
= file_offset
>> 9;
2012 curlun
->info_valid
= 1;
2015 file_offset
+= nread
;
2016 amount_left
-= nread
;
2022 /*-------------------------------------------------------------------------*/
2024 static int do_inquiry(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2026 u8
*buf
= (u8
*) bh
->buf
;
2028 static char vendor_id
[] = "Linux ";
2029 static char product_disk_id
[] = "File-Stor Gadget";
2030 static char product_cdrom_id
[] = "File-CD Gadget ";
2032 if (!fsg
->curlun
) { // Unsupported LUNs are okay
2033 fsg
->bad_lun_okay
= 1;
2035 buf
[0] = 0x7f; // Unsupported, no device-type
2036 buf
[4] = 31; // Additional length
2041 buf
[0] = (mod_data
.cdrom
? TYPE_CDROM
: TYPE_DISK
);
2042 if (mod_data
.removable
)
2044 buf
[2] = 2; // ANSI SCSI level 2
2045 buf
[3] = 2; // SCSI-2 INQUIRY data format
2046 buf
[4] = 31; // Additional length
2047 // No special options
2048 sprintf(buf
+ 8, "%-8s%-16s%04x", vendor_id
,
2049 (mod_data
.cdrom
? product_cdrom_id
:
2056 static int do_request_sense(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2058 struct lun
*curlun
= fsg
->curlun
;
2059 u8
*buf
= (u8
*) bh
->buf
;
2064 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2066 * If a REQUEST SENSE command is received from an initiator
2067 * with a pending unit attention condition (before the target
2068 * generates the contingent allegiance condition), then the
2069 * target shall either:
2070 * a) report any pending sense data and preserve the unit
2071 * attention condition on the logical unit, or,
2072 * b) report the unit attention condition, may discard any
2073 * pending sense data, and clear the unit attention
2074 * condition on the logical unit for that initiator.
2076 * FSG normally uses option a); enable this code to use option b).
2079 if (curlun
&& curlun
->unit_attention_data
!= SS_NO_SENSE
) {
2080 curlun
->sense_data
= curlun
->unit_attention_data
;
2081 curlun
->unit_attention_data
= SS_NO_SENSE
;
2085 if (!curlun
) { // Unsupported LUNs are okay
2086 fsg
->bad_lun_okay
= 1;
2087 sd
= SS_LOGICAL_UNIT_NOT_SUPPORTED
;
2091 sd
= curlun
->sense_data
;
2092 sdinfo
= curlun
->sense_data_info
;
2093 valid
= curlun
->info_valid
<< 7;
2094 curlun
->sense_data
= SS_NO_SENSE
;
2095 curlun
->sense_data_info
= 0;
2096 curlun
->info_valid
= 0;
2100 buf
[0] = valid
| 0x70; // Valid, current error
2102 put_be32(&buf
[3], sdinfo
); // Sense information
2103 buf
[7] = 18 - 8; // Additional sense length
2110 static int do_read_capacity(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2112 struct lun
*curlun
= fsg
->curlun
;
2113 u32 lba
= get_be32(&fsg
->cmnd
[2]);
2114 int pmi
= fsg
->cmnd
[8];
2115 u8
*buf
= (u8
*) bh
->buf
;
2117 /* Check the PMI and LBA fields */
2118 if (pmi
> 1 || (pmi
== 0 && lba
!= 0)) {
2119 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2123 put_be32(&buf
[0], curlun
->num_sectors
- 1); // Max logical block
2124 put_be32(&buf
[4], 512); // Block length
2129 static void store_cdrom_address(u8
*dest
, int msf
, u32 addr
)
2132 /* Convert to Minutes-Seconds-Frames */
2133 addr
>>= 2; /* Convert to 2048-byte frames */
2134 addr
+= 2*75; /* Lead-in occupies 2 seconds */
2135 dest
[3] = addr
% 75; /* Frames */
2137 dest
[2] = addr
% 60; /* Seconds */
2139 dest
[1] = addr
; /* Minutes */
2140 dest
[0] = 0; /* Reserved */
2142 /* Absolute sector */
2143 put_be32(dest
, addr
);
2147 static int do_read_header(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2149 struct lun
*curlun
= fsg
->curlun
;
2150 int msf
= fsg
->cmnd
[1] & 0x02;
2151 u32 lba
= get_be32(&fsg
->cmnd
[2]);
2152 u8
*buf
= (u8
*) bh
->buf
;
2154 if ((fsg
->cmnd
[1] & ~0x02) != 0) { /* Mask away MSF */
2155 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2158 if (lba
>= curlun
->num_sectors
) {
2159 curlun
->sense_data
= SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
;
2164 buf
[0] = 0x01; /* 2048 bytes of user data, rest is EC */
2165 store_cdrom_address(&buf
[4], msf
, lba
);
2170 static int do_read_toc(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2172 struct lun
*curlun
= fsg
->curlun
;
2173 int msf
= fsg
->cmnd
[1] & 0x02;
2174 int start_track
= fsg
->cmnd
[6];
2175 u8
*buf
= (u8
*) bh
->buf
;
2177 if ((fsg
->cmnd
[1] & ~0x02) != 0 || /* Mask away MSF */
2179 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2184 buf
[1] = (20-2); /* TOC data length */
2185 buf
[2] = 1; /* First track number */
2186 buf
[3] = 1; /* Last track number */
2187 buf
[5] = 0x16; /* Data track, copying allowed */
2188 buf
[6] = 0x01; /* Only track is number 1 */
2189 store_cdrom_address(&buf
[8], msf
, 0);
2191 buf
[13] = 0x16; /* Lead-out track is data */
2192 buf
[14] = 0xAA; /* Lead-out track number */
2193 store_cdrom_address(&buf
[16], msf
, curlun
->num_sectors
);
2198 static int do_mode_sense(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2200 struct lun
*curlun
= fsg
->curlun
;
2201 int mscmnd
= fsg
->cmnd
[0];
2202 u8
*buf
= (u8
*) bh
->buf
;
2205 int changeable_values
, all_pages
;
2209 if ((fsg
->cmnd
[1] & ~0x08) != 0) { // Mask away DBD
2210 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2213 pc
= fsg
->cmnd
[2] >> 6;
2214 page_code
= fsg
->cmnd
[2] & 0x3f;
2216 curlun
->sense_data
= SS_SAVING_PARAMETERS_NOT_SUPPORTED
;
2219 changeable_values
= (pc
== 1);
2220 all_pages
= (page_code
== 0x3f);
2222 /* Write the mode parameter header. Fixed values are: default
2223 * medium type, no cache control (DPOFUA), and no block descriptors.
2224 * The only variable value is the WriteProtect bit. We will fill in
2225 * the mode data length later. */
2227 if (mscmnd
== SC_MODE_SENSE_6
) {
2228 buf
[2] = (curlun
->ro
? 0x80 : 0x00); // WP, DPOFUA
2231 } else { // SC_MODE_SENSE_10
2232 buf
[3] = (curlun
->ro
? 0x80 : 0x00); // WP, DPOFUA
2234 limit
= 65535; // Should really be mod_data.buflen
2237 /* No block descriptors */
2239 /* The mode pages, in numerical order. The only page we support
2240 * is the Caching page. */
2241 if (page_code
== 0x08 || all_pages
) {
2243 buf
[0] = 0x08; // Page code
2244 buf
[1] = 10; // Page length
2245 memset(buf
+2, 0, 10); // None of the fields are changeable
2247 if (!changeable_values
) {
2248 buf
[2] = 0x04; // Write cache enable,
2249 // Read cache not disabled
2250 // No cache retention priorities
2251 put_be16(&buf
[4], 0xffff); // Don't disable prefetch
2252 // Minimum prefetch = 0
2253 put_be16(&buf
[8], 0xffff); // Maximum prefetch
2254 put_be16(&buf
[10], 0xffff); // Maximum prefetch ceiling
2259 /* Check that a valid page was requested and the mode data length
2260 * isn't too long. */
2262 if (!valid_page
|| len
> limit
) {
2263 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2267 /* Store the mode data length */
2268 if (mscmnd
== SC_MODE_SENSE_6
)
2271 put_be16(buf0
, len
- 2);
2276 static int do_start_stop(struct fsg_dev
*fsg
)
2278 struct lun
*curlun
= fsg
->curlun
;
2281 if (!mod_data
.removable
) {
2282 curlun
->sense_data
= SS_INVALID_COMMAND
;
2286 // int immed = fsg->cmnd[1] & 0x01;
2287 loej
= fsg
->cmnd
[4] & 0x02;
2288 start
= fsg
->cmnd
[4] & 0x01;
2290 #ifdef CONFIG_USB_FILE_STORAGE_TEST
2291 if ((fsg
->cmnd
[1] & ~0x01) != 0 || // Mask away Immed
2292 (fsg
->cmnd
[4] & ~0x03) != 0) { // Mask LoEj, Start
2293 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2299 /* Are we allowed to unload the media? */
2300 if (curlun
->prevent_medium_removal
) {
2301 LDBG(curlun
, "unload attempt prevented\n");
2302 curlun
->sense_data
= SS_MEDIUM_REMOVAL_PREVENTED
;
2305 if (loej
) { // Simulate an unload/eject
2306 up_read(&fsg
->filesem
);
2307 down_write(&fsg
->filesem
);
2308 close_backing_file(curlun
);
2309 up_write(&fsg
->filesem
);
2310 down_read(&fsg
->filesem
);
2314 /* Our emulation doesn't support mounting; the medium is
2315 * available for use as soon as it is loaded. */
2316 if (!backing_file_is_open(curlun
)) {
2317 curlun
->sense_data
= SS_MEDIUM_NOT_PRESENT
;
2326 static int do_prevent_allow(struct fsg_dev
*fsg
)
2328 struct lun
*curlun
= fsg
->curlun
;
2331 if (!mod_data
.removable
) {
2332 curlun
->sense_data
= SS_INVALID_COMMAND
;
2336 prevent
= fsg
->cmnd
[4] & 0x01;
2337 if ((fsg
->cmnd
[4] & ~0x01) != 0) { // Mask away Prevent
2338 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2342 if (curlun
->prevent_medium_removal
&& !prevent
)
2344 curlun
->prevent_medium_removal
= prevent
;
2349 static int do_read_format_capacities(struct fsg_dev
*fsg
,
2350 struct fsg_buffhd
*bh
)
2352 struct lun
*curlun
= fsg
->curlun
;
2353 u8
*buf
= (u8
*) bh
->buf
;
2355 buf
[0] = buf
[1] = buf
[2] = 0;
2356 buf
[3] = 8; // Only the Current/Maximum Capacity Descriptor
2359 put_be32(&buf
[0], curlun
->num_sectors
); // Number of blocks
2360 put_be32(&buf
[4], 512); // Block length
2361 buf
[4] = 0x02; // Current capacity
2366 static int do_mode_select(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
2368 struct lun
*curlun
= fsg
->curlun
;
2370 /* We don't support MODE SELECT */
2371 curlun
->sense_data
= SS_INVALID_COMMAND
;
2376 /*-------------------------------------------------------------------------*/
2378 static int halt_bulk_in_endpoint(struct fsg_dev
*fsg
)
2382 rc
= fsg_set_halt(fsg
, fsg
->bulk_in
);
2384 VDBG(fsg
, "delayed bulk-in endpoint halt\n");
2386 if (rc
!= -EAGAIN
) {
2387 WARNING(fsg
, "usb_ep_set_halt -> %d\n", rc
);
2392 /* Wait for a short time and then try again */
2393 if (msleep_interruptible(100) != 0)
2395 rc
= usb_ep_set_halt(fsg
->bulk_in
);
2400 static int wedge_bulk_in_endpoint(struct fsg_dev
*fsg
)
2404 DBG(fsg
, "bulk-in set wedge\n");
2405 rc
= usb_ep_set_wedge(fsg
->bulk_in
);
2407 VDBG(fsg
, "delayed bulk-in endpoint wedge\n");
2409 if (rc
!= -EAGAIN
) {
2410 WARNING(fsg
, "usb_ep_set_wedge -> %d\n", rc
);
2415 /* Wait for a short time and then try again */
2416 if (msleep_interruptible(100) != 0)
2418 rc
= usb_ep_set_wedge(fsg
->bulk_in
);
2423 static int pad_with_zeros(struct fsg_dev
*fsg
)
2425 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
2426 u32 nkeep
= bh
->inreq
->length
;
2430 bh
->state
= BUF_STATE_EMPTY
; // For the first iteration
2431 fsg
->usb_amount_left
= nkeep
+ fsg
->residue
;
2432 while (fsg
->usb_amount_left
> 0) {
2434 /* Wait for the next buffer to be free */
2435 while (bh
->state
!= BUF_STATE_EMPTY
) {
2436 rc
= sleep_thread(fsg
);
2441 nsend
= min(fsg
->usb_amount_left
, (u32
) mod_data
.buflen
);
2442 memset(bh
->buf
+ nkeep
, 0, nsend
- nkeep
);
2443 bh
->inreq
->length
= nsend
;
2444 bh
->inreq
->zero
= 0;
2445 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2446 &bh
->inreq_busy
, &bh
->state
);
2447 bh
= fsg
->next_buffhd_to_fill
= bh
->next
;
2448 fsg
->usb_amount_left
-= nsend
;
2454 static int throw_away_data(struct fsg_dev
*fsg
)
2456 struct fsg_buffhd
*bh
;
2460 while ((bh
= fsg
->next_buffhd_to_drain
)->state
!= BUF_STATE_EMPTY
||
2461 fsg
->usb_amount_left
> 0) {
2463 /* Throw away the data in a filled buffer */
2464 if (bh
->state
== BUF_STATE_FULL
) {
2466 bh
->state
= BUF_STATE_EMPTY
;
2467 fsg
->next_buffhd_to_drain
= bh
->next
;
2469 /* A short packet or an error ends everything */
2470 if (bh
->outreq
->actual
!= bh
->outreq
->length
||
2471 bh
->outreq
->status
!= 0) {
2472 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2478 /* Try to submit another request if we need one */
2479 bh
= fsg
->next_buffhd_to_fill
;
2480 if (bh
->state
== BUF_STATE_EMPTY
&& fsg
->usb_amount_left
> 0) {
2481 amount
= min(fsg
->usb_amount_left
,
2482 (u32
) mod_data
.buflen
);
2484 /* amount is always divisible by 512, hence by
2485 * the bulk-out maxpacket size */
2486 bh
->outreq
->length
= bh
->bulk_out_intended_length
=
2488 bh
->outreq
->short_not_ok
= 1;
2489 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
2490 &bh
->outreq_busy
, &bh
->state
);
2491 fsg
->next_buffhd_to_fill
= bh
->next
;
2492 fsg
->usb_amount_left
-= amount
;
2496 /* Otherwise wait for something to happen */
2497 rc
= sleep_thread(fsg
);
2505 static int finish_reply(struct fsg_dev
*fsg
)
2507 struct fsg_buffhd
*bh
= fsg
->next_buffhd_to_fill
;
2510 switch (fsg
->data_dir
) {
2512 break; // Nothing to send
2514 /* If we don't know whether the host wants to read or write,
2515 * this must be CB or CBI with an unknown command. We mustn't
2516 * try to send or receive any data. So stall both bulk pipes
2517 * if we can and wait for a reset. */
2518 case DATA_DIR_UNKNOWN
:
2519 if (mod_data
.can_stall
) {
2520 fsg_set_halt(fsg
, fsg
->bulk_out
);
2521 rc
= halt_bulk_in_endpoint(fsg
);
2525 /* All but the last buffer of data must have already been sent */
2526 case DATA_DIR_TO_HOST
:
2527 if (fsg
->data_size
== 0)
2528 ; // Nothing to send
2530 /* If there's no residue, simply send the last buffer */
2531 else if (fsg
->residue
== 0) {
2532 bh
->inreq
->zero
= 0;
2533 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2534 &bh
->inreq_busy
, &bh
->state
);
2535 fsg
->next_buffhd_to_fill
= bh
->next
;
2538 /* There is a residue. For CB and CBI, simply mark the end
2539 * of the data with a short packet. However, if we are
2540 * allowed to stall, there was no data at all (residue ==
2541 * data_size), and the command failed (invalid LUN or
2542 * sense data is set), then halt the bulk-in endpoint
2544 else if (!transport_is_bbb()) {
2545 if (mod_data
.can_stall
&&
2546 fsg
->residue
== fsg
->data_size
&&
2547 (!fsg
->curlun
|| fsg
->curlun
->sense_data
!= SS_NO_SENSE
)) {
2548 bh
->state
= BUF_STATE_EMPTY
;
2549 rc
= halt_bulk_in_endpoint(fsg
);
2551 bh
->inreq
->zero
= 1;
2552 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2553 &bh
->inreq_busy
, &bh
->state
);
2554 fsg
->next_buffhd_to_fill
= bh
->next
;
2558 /* For Bulk-only, if we're allowed to stall then send the
2559 * short packet and halt the bulk-in endpoint. If we can't
2560 * stall, pad out the remaining data with 0's. */
2562 if (mod_data
.can_stall
) {
2563 bh
->inreq
->zero
= 1;
2564 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2565 &bh
->inreq_busy
, &bh
->state
);
2566 fsg
->next_buffhd_to_fill
= bh
->next
;
2567 rc
= halt_bulk_in_endpoint(fsg
);
2569 rc
= pad_with_zeros(fsg
);
2573 /* We have processed all we want from the data the host has sent.
2574 * There may still be outstanding bulk-out requests. */
2575 case DATA_DIR_FROM_HOST
:
2576 if (fsg
->residue
== 0)
2577 ; // Nothing to receive
2579 /* Did the host stop sending unexpectedly early? */
2580 else if (fsg
->short_packet_received
) {
2581 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2585 /* We haven't processed all the incoming data. Even though
2586 * we may be allowed to stall, doing so would cause a race.
2587 * The controller may already have ACK'ed all the remaining
2588 * bulk-out packets, in which case the host wouldn't see a
2589 * STALL. Not realizing the endpoint was halted, it wouldn't
2590 * clear the halt -- leading to problems later on. */
2592 else if (mod_data
.can_stall
) {
2593 fsg_set_halt(fsg
, fsg
->bulk_out
);
2594 raise_exception(fsg
, FSG_STATE_ABORT_BULK_OUT
);
2599 /* We can't stall. Read in the excess data and throw it
2602 rc
= throw_away_data(fsg
);
2609 static int send_status(struct fsg_dev
*fsg
)
2611 struct lun
*curlun
= fsg
->curlun
;
2612 struct fsg_buffhd
*bh
;
2614 u8 status
= USB_STATUS_PASS
;
2617 /* Wait for the next buffer to become available */
2618 bh
= fsg
->next_buffhd_to_fill
;
2619 while (bh
->state
!= BUF_STATE_EMPTY
) {
2620 rc
= sleep_thread(fsg
);
2626 sd
= curlun
->sense_data
;
2627 sdinfo
= curlun
->sense_data_info
;
2628 } else if (fsg
->bad_lun_okay
)
2631 sd
= SS_LOGICAL_UNIT_NOT_SUPPORTED
;
2633 if (fsg
->phase_error
) {
2634 DBG(fsg
, "sending phase-error status\n");
2635 status
= USB_STATUS_PHASE_ERROR
;
2636 sd
= SS_INVALID_COMMAND
;
2637 } else if (sd
!= SS_NO_SENSE
) {
2638 DBG(fsg
, "sending command-failure status\n");
2639 status
= USB_STATUS_FAIL
;
2640 VDBG(fsg
, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2642 SK(sd
), ASC(sd
), ASCQ(sd
), sdinfo
);
2645 if (transport_is_bbb()) {
2646 struct bulk_cs_wrap
*csw
= bh
->buf
;
2648 /* Store and send the Bulk-only CSW */
2649 csw
->Signature
= __constant_cpu_to_le32(USB_BULK_CS_SIG
);
2650 csw
->Tag
= fsg
->tag
;
2651 csw
->Residue
= cpu_to_le32(fsg
->residue
);
2652 csw
->Status
= status
;
2654 bh
->inreq
->length
= USB_BULK_CS_WRAP_LEN
;
2655 bh
->inreq
->zero
= 0;
2656 start_transfer(fsg
, fsg
->bulk_in
, bh
->inreq
,
2657 &bh
->inreq_busy
, &bh
->state
);
2659 } else if (mod_data
.transport_type
== USB_PR_CB
) {
2661 /* Control-Bulk transport has no status phase! */
2664 } else { // USB_PR_CBI
2665 struct interrupt_data
*buf
= bh
->buf
;
2667 /* Store and send the Interrupt data. UFI sends the ASC
2668 * and ASCQ bytes. Everything else sends a Type (which
2669 * is always 0) and the status Value. */
2670 if (mod_data
.protocol_type
== USB_SC_UFI
) {
2671 buf
->bType
= ASC(sd
);
2672 buf
->bValue
= ASCQ(sd
);
2675 buf
->bValue
= status
;
2677 fsg
->intreq
->length
= CBI_INTERRUPT_DATA_LEN
;
2679 fsg
->intr_buffhd
= bh
; // Point to the right buffhd
2680 fsg
->intreq
->buf
= bh
->inreq
->buf
;
2681 fsg
->intreq
->context
= bh
;
2682 start_transfer(fsg
, fsg
->intr_in
, fsg
->intreq
,
2683 &fsg
->intreq_busy
, &bh
->state
);
2686 fsg
->next_buffhd_to_fill
= bh
->next
;
2691 /*-------------------------------------------------------------------------*/
2693 /* Check whether the command is properly formed and whether its data size
2694 * and direction agree with the values we already have. */
2695 static int check_command(struct fsg_dev
*fsg
, int cmnd_size
,
2696 enum data_direction data_dir
, unsigned int mask
,
2697 int needs_medium
, const char *name
)
2700 int lun
= fsg
->cmnd
[1] >> 5;
2701 static const char dirletter
[4] = {'u', 'o', 'i', 'n'};
2705 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2706 * Transparent SCSI doesn't pad. */
2707 if (protocol_is_scsi())
2710 /* There's some disagreement as to whether RBC pads commands or not.
2711 * We'll play it safe and accept either form. */
2712 else if (mod_data
.protocol_type
== USB_SC_RBC
) {
2713 if (fsg
->cmnd_size
== 12)
2716 /* All the other protocols pad to 12 bytes */
2721 if (fsg
->data_dir
!= DATA_DIR_UNKNOWN
)
2722 sprintf(hdlen
, ", H%c=%u", dirletter
[(int) fsg
->data_dir
],
2724 VDBG(fsg
, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2725 name
, cmnd_size
, dirletter
[(int) data_dir
],
2726 fsg
->data_size_from_cmnd
, fsg
->cmnd_size
, hdlen
);
2728 /* We can't reply at all until we know the correct data direction
2730 if (fsg
->data_size_from_cmnd
== 0)
2731 data_dir
= DATA_DIR_NONE
;
2732 if (fsg
->data_dir
== DATA_DIR_UNKNOWN
) { // CB or CBI
2733 fsg
->data_dir
= data_dir
;
2734 fsg
->data_size
= fsg
->data_size_from_cmnd
;
2736 } else { // Bulk-only
2737 if (fsg
->data_size
< fsg
->data_size_from_cmnd
) {
2739 /* Host data size < Device data size is a phase error.
2740 * Carry out the command, but only transfer as much
2741 * as we are allowed. */
2742 fsg
->data_size_from_cmnd
= fsg
->data_size
;
2743 fsg
->phase_error
= 1;
2746 fsg
->residue
= fsg
->usb_amount_left
= fsg
->data_size
;
2748 /* Conflicting data directions is a phase error */
2749 if (fsg
->data_dir
!= data_dir
&& fsg
->data_size_from_cmnd
> 0) {
2750 fsg
->phase_error
= 1;
2754 /* Verify the length of the command itself */
2755 if (cmnd_size
!= fsg
->cmnd_size
) {
2757 /* Special case workaround: There are plenty of buggy SCSI
2758 * implementations. Many have issues with cbw->Length
2759 * field passing a wrong command size. For those cases we
2760 * always try to work around the problem by using the length
2761 * sent by the host side provided it is at least as large
2762 * as the correct command length.
2763 * Examples of such cases would be MS-Windows, which issues
2764 * REQUEST SENSE with cbw->Length == 12 where it should
2765 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2766 * REQUEST SENSE with cbw->Length == 10 where it should
2769 if (cmnd_size
<= fsg
->cmnd_size
) {
2770 DBG(fsg
, "%s is buggy! Expected length %d "
2771 "but we got %d\n", name
,
2772 cmnd_size
, fsg
->cmnd_size
);
2773 cmnd_size
= fsg
->cmnd_size
;
2775 fsg
->phase_error
= 1;
2780 /* Check that the LUN values are consistent */
2781 if (transport_is_bbb()) {
2782 if (fsg
->lun
!= lun
)
2783 DBG(fsg
, "using LUN %d from CBW, "
2784 "not LUN %d from CDB\n",
2787 fsg
->lun
= lun
; // Use LUN from the command
2790 if (fsg
->lun
>= 0 && fsg
->lun
< fsg
->nluns
) {
2791 fsg
->curlun
= curlun
= &fsg
->luns
[fsg
->lun
];
2792 if (fsg
->cmnd
[0] != SC_REQUEST_SENSE
) {
2793 curlun
->sense_data
= SS_NO_SENSE
;
2794 curlun
->sense_data_info
= 0;
2795 curlun
->info_valid
= 0;
2798 fsg
->curlun
= curlun
= NULL
;
2799 fsg
->bad_lun_okay
= 0;
2801 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2802 * to use unsupported LUNs; all others may not. */
2803 if (fsg
->cmnd
[0] != SC_INQUIRY
&&
2804 fsg
->cmnd
[0] != SC_REQUEST_SENSE
) {
2805 DBG(fsg
, "unsupported LUN %d\n", fsg
->lun
);
2810 /* If a unit attention condition exists, only INQUIRY and
2811 * REQUEST SENSE commands are allowed; anything else must fail. */
2812 if (curlun
&& curlun
->unit_attention_data
!= SS_NO_SENSE
&&
2813 fsg
->cmnd
[0] != SC_INQUIRY
&&
2814 fsg
->cmnd
[0] != SC_REQUEST_SENSE
) {
2815 curlun
->sense_data
= curlun
->unit_attention_data
;
2816 curlun
->unit_attention_data
= SS_NO_SENSE
;
2820 /* Check that only command bytes listed in the mask are non-zero */
2821 fsg
->cmnd
[1] &= 0x1f; // Mask away the LUN
2822 for (i
= 1; i
< cmnd_size
; ++i
) {
2823 if (fsg
->cmnd
[i
] && !(mask
& (1 << i
))) {
2825 curlun
->sense_data
= SS_INVALID_FIELD_IN_CDB
;
2830 /* If the medium isn't mounted and the command needs to access
2831 * it, return an error. */
2832 if (curlun
&& !backing_file_is_open(curlun
) && needs_medium
) {
2833 curlun
->sense_data
= SS_MEDIUM_NOT_PRESENT
;
2841 static int do_scsi_command(struct fsg_dev
*fsg
)
2843 struct fsg_buffhd
*bh
;
2845 int reply
= -EINVAL
;
2847 static char unknown
[16];
2851 /* Wait for the next buffer to become available for data or status */
2852 bh
= fsg
->next_buffhd_to_drain
= fsg
->next_buffhd_to_fill
;
2853 while (bh
->state
!= BUF_STATE_EMPTY
) {
2854 rc
= sleep_thread(fsg
);
2858 fsg
->phase_error
= 0;
2859 fsg
->short_packet_received
= 0;
2861 down_read(&fsg
->filesem
); // We're using the backing file
2862 switch (fsg
->cmnd
[0]) {
2865 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2866 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2869 reply
= do_inquiry(fsg
, bh
);
2872 case SC_MODE_SELECT_6
:
2873 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2874 if ((reply
= check_command(fsg
, 6, DATA_DIR_FROM_HOST
,
2876 "MODE SELECT(6)")) == 0)
2877 reply
= do_mode_select(fsg
, bh
);
2880 case SC_MODE_SELECT_10
:
2881 fsg
->data_size_from_cmnd
= get_be16(&fsg
->cmnd
[7]);
2882 if ((reply
= check_command(fsg
, 10, DATA_DIR_FROM_HOST
,
2884 "MODE SELECT(10)")) == 0)
2885 reply
= do_mode_select(fsg
, bh
);
2888 case SC_MODE_SENSE_6
:
2889 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2890 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2891 (1<<1) | (1<<2) | (1<<4), 0,
2892 "MODE SENSE(6)")) == 0)
2893 reply
= do_mode_sense(fsg
, bh
);
2896 case SC_MODE_SENSE_10
:
2897 fsg
->data_size_from_cmnd
= get_be16(&fsg
->cmnd
[7]);
2898 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2899 (1<<1) | (1<<2) | (3<<7), 0,
2900 "MODE SENSE(10)")) == 0)
2901 reply
= do_mode_sense(fsg
, bh
);
2904 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL
:
2905 fsg
->data_size_from_cmnd
= 0;
2906 if ((reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2908 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2909 reply
= do_prevent_allow(fsg
);
2914 fsg
->data_size_from_cmnd
= (i
== 0 ? 256 : i
) << 9;
2915 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2918 reply
= do_read(fsg
);
2922 fsg
->data_size_from_cmnd
= get_be16(&fsg
->cmnd
[7]) << 9;
2923 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2924 (1<<1) | (0xf<<2) | (3<<7), 1,
2926 reply
= do_read(fsg
);
2930 fsg
->data_size_from_cmnd
= get_be32(&fsg
->cmnd
[6]) << 9;
2931 if ((reply
= check_command(fsg
, 12, DATA_DIR_TO_HOST
,
2932 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2934 reply
= do_read(fsg
);
2937 case SC_READ_CAPACITY
:
2938 fsg
->data_size_from_cmnd
= 8;
2939 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2940 (0xf<<2) | (1<<8), 1,
2941 "READ CAPACITY")) == 0)
2942 reply
= do_read_capacity(fsg
, bh
);
2945 case SC_READ_HEADER
:
2946 if (!mod_data
.cdrom
)
2948 fsg
->data_size_from_cmnd
= get_be16(&fsg
->cmnd
[7]);
2949 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2950 (3<<7) | (0x1f<<1), 1,
2951 "READ HEADER")) == 0)
2952 reply
= do_read_header(fsg
, bh
);
2956 if (!mod_data
.cdrom
)
2958 fsg
->data_size_from_cmnd
= get_be16(&fsg
->cmnd
[7]);
2959 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2962 reply
= do_read_toc(fsg
, bh
);
2965 case SC_READ_FORMAT_CAPACITIES
:
2966 fsg
->data_size_from_cmnd
= get_be16(&fsg
->cmnd
[7]);
2967 if ((reply
= check_command(fsg
, 10, DATA_DIR_TO_HOST
,
2969 "READ FORMAT CAPACITIES")) == 0)
2970 reply
= do_read_format_capacities(fsg
, bh
);
2973 case SC_REQUEST_SENSE
:
2974 fsg
->data_size_from_cmnd
= fsg
->cmnd
[4];
2975 if ((reply
= check_command(fsg
, 6, DATA_DIR_TO_HOST
,
2977 "REQUEST SENSE")) == 0)
2978 reply
= do_request_sense(fsg
, bh
);
2981 case SC_START_STOP_UNIT
:
2982 fsg
->data_size_from_cmnd
= 0;
2983 if ((reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
2985 "START-STOP UNIT")) == 0)
2986 reply
= do_start_stop(fsg
);
2989 case SC_SYNCHRONIZE_CACHE
:
2990 fsg
->data_size_from_cmnd
= 0;
2991 if ((reply
= check_command(fsg
, 10, DATA_DIR_NONE
,
2992 (0xf<<2) | (3<<7), 1,
2993 "SYNCHRONIZE CACHE")) == 0)
2994 reply
= do_synchronize_cache(fsg
);
2997 case SC_TEST_UNIT_READY
:
2998 fsg
->data_size_from_cmnd
= 0;
2999 reply
= check_command(fsg
, 6, DATA_DIR_NONE
,
3004 /* Although optional, this command is used by MS-Windows. We
3005 * support a minimal version: BytChk must be 0. */
3007 fsg
->data_size_from_cmnd
= 0;
3008 if ((reply
= check_command(fsg
, 10, DATA_DIR_NONE
,
3009 (1<<1) | (0xf<<2) | (3<<7), 1,
3011 reply
= do_verify(fsg
);
3016 fsg
->data_size_from_cmnd
= (i
== 0 ? 256 : i
) << 9;
3017 if ((reply
= check_command(fsg
, 6, DATA_DIR_FROM_HOST
,
3020 reply
= do_write(fsg
);
3024 fsg
->data_size_from_cmnd
= get_be16(&fsg
->cmnd
[7]) << 9;
3025 if ((reply
= check_command(fsg
, 10, DATA_DIR_FROM_HOST
,
3026 (1<<1) | (0xf<<2) | (3<<7), 1,
3028 reply
= do_write(fsg
);
3032 fsg
->data_size_from_cmnd
= get_be32(&fsg
->cmnd
[6]) << 9;
3033 if ((reply
= check_command(fsg
, 12, DATA_DIR_FROM_HOST
,
3034 (1<<1) | (0xf<<2) | (0xf<<6), 1,
3036 reply
= do_write(fsg
);
3039 /* Some mandatory commands that we recognize but don't implement.
3040 * They don't mean much in this setting. It's left as an exercise
3041 * for anyone interested to implement RESERVE and RELEASE in terms
3042 * of Posix locks. */
3043 case SC_FORMAT_UNIT
:
3046 case SC_SEND_DIAGNOSTIC
:
3051 fsg
->data_size_from_cmnd
= 0;
3052 sprintf(unknown
, "Unknown x%02x", fsg
->cmnd
[0]);
3053 if ((reply
= check_command(fsg
, fsg
->cmnd_size
,
3054 DATA_DIR_UNKNOWN
, 0xff, 0, unknown
)) == 0) {
3055 fsg
->curlun
->sense_data
= SS_INVALID_COMMAND
;
3060 up_read(&fsg
->filesem
);
3062 if (reply
== -EINTR
|| signal_pending(current
))
3065 /* Set up the single reply buffer for finish_reply() */
3066 if (reply
== -EINVAL
)
3067 reply
= 0; // Error reply length
3068 if (reply
>= 0 && fsg
->data_dir
== DATA_DIR_TO_HOST
) {
3069 reply
= min((u32
) reply
, fsg
->data_size_from_cmnd
);
3070 bh
->inreq
->length
= reply
;
3071 bh
->state
= BUF_STATE_FULL
;
3072 fsg
->residue
-= reply
;
3073 } // Otherwise it's already set
3079 /*-------------------------------------------------------------------------*/
3081 static int received_cbw(struct fsg_dev
*fsg
, struct fsg_buffhd
*bh
)
3083 struct usb_request
*req
= bh
->outreq
;
3084 struct bulk_cb_wrap
*cbw
= req
->buf
;
3086 /* Was this a real packet? Should it be ignored? */
3087 if (req
->status
|| test_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
))
3090 /* Is the CBW valid? */
3091 if (req
->actual
!= USB_BULK_CB_WRAP_LEN
||
3092 cbw
->Signature
!= __constant_cpu_to_le32(
3094 DBG(fsg
, "invalid CBW: len %u sig 0x%x\n",
3096 le32_to_cpu(cbw
->Signature
));
3098 /* The Bulk-only spec says we MUST stall the IN endpoint
3099 * (6.6.1), so it's unavoidable. It also says we must
3100 * retain this state until the next reset, but there's
3101 * no way to tell the controller driver it should ignore
3102 * Clear-Feature(HALT) requests.
3104 * We aren't required to halt the OUT endpoint; instead
3105 * we can simply accept and discard any data received
3106 * until the next reset. */
3107 wedge_bulk_in_endpoint(fsg
);
3108 set_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
);
3112 /* Is the CBW meaningful? */
3113 if (cbw
->Lun
>= MAX_LUNS
|| cbw
->Flags
& ~USB_BULK_IN_FLAG
||
3114 cbw
->Length
<= 0 || cbw
->Length
> MAX_COMMAND_SIZE
) {
3115 DBG(fsg
, "non-meaningful CBW: lun = %u, flags = 0x%x, "
3117 cbw
->Lun
, cbw
->Flags
, cbw
->Length
);
3119 /* We can do anything we want here, so let's stall the
3120 * bulk pipes if we are allowed to. */
3121 if (mod_data
.can_stall
) {
3122 fsg_set_halt(fsg
, fsg
->bulk_out
);
3123 halt_bulk_in_endpoint(fsg
);
3128 /* Save the command for later */
3129 fsg
->cmnd_size
= cbw
->Length
;
3130 memcpy(fsg
->cmnd
, cbw
->CDB
, fsg
->cmnd_size
);
3131 if (cbw
->Flags
& USB_BULK_IN_FLAG
)
3132 fsg
->data_dir
= DATA_DIR_TO_HOST
;
3134 fsg
->data_dir
= DATA_DIR_FROM_HOST
;
3135 fsg
->data_size
= le32_to_cpu(cbw
->DataTransferLength
);
3136 if (fsg
->data_size
== 0)
3137 fsg
->data_dir
= DATA_DIR_NONE
;
3138 fsg
->lun
= cbw
->Lun
;
3139 fsg
->tag
= cbw
->Tag
;
3144 static int get_next_command(struct fsg_dev
*fsg
)
3146 struct fsg_buffhd
*bh
;
3149 if (transport_is_bbb()) {
3151 /* Wait for the next buffer to become available */
3152 bh
= fsg
->next_buffhd_to_fill
;
3153 while (bh
->state
!= BUF_STATE_EMPTY
) {
3154 rc
= sleep_thread(fsg
);
3159 /* Queue a request to read a Bulk-only CBW */
3160 set_bulk_out_req_length(fsg
, bh
, USB_BULK_CB_WRAP_LEN
);
3161 bh
->outreq
->short_not_ok
= 1;
3162 start_transfer(fsg
, fsg
->bulk_out
, bh
->outreq
,
3163 &bh
->outreq_busy
, &bh
->state
);
3165 /* We will drain the buffer in software, which means we
3166 * can reuse it for the next filling. No need to advance
3167 * next_buffhd_to_fill. */
3169 /* Wait for the CBW to arrive */
3170 while (bh
->state
!= BUF_STATE_FULL
) {
3171 rc
= sleep_thread(fsg
);
3176 rc
= received_cbw(fsg
, bh
);
3177 bh
->state
= BUF_STATE_EMPTY
;
3179 } else { // USB_PR_CB or USB_PR_CBI
3181 /* Wait for the next command to arrive */
3182 while (fsg
->cbbuf_cmnd_size
== 0) {
3183 rc
= sleep_thread(fsg
);
3188 /* Is the previous status interrupt request still busy?
3189 * The host is allowed to skip reading the status,
3190 * so we must cancel it. */
3191 if (fsg
->intreq_busy
)
3192 usb_ep_dequeue(fsg
->intr_in
, fsg
->intreq
);
3194 /* Copy the command and mark the buffer empty */
3195 fsg
->data_dir
= DATA_DIR_UNKNOWN
;
3196 spin_lock_irq(&fsg
->lock
);
3197 fsg
->cmnd_size
= fsg
->cbbuf_cmnd_size
;
3198 memcpy(fsg
->cmnd
, fsg
->cbbuf_cmnd
, fsg
->cmnd_size
);
3199 fsg
->cbbuf_cmnd_size
= 0;
3200 spin_unlock_irq(&fsg
->lock
);
3206 /*-------------------------------------------------------------------------*/
3208 static int enable_endpoint(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
3209 const struct usb_endpoint_descriptor
*d
)
3213 ep
->driver_data
= fsg
;
3214 rc
= usb_ep_enable(ep
, d
);
3216 ERROR(fsg
, "can't enable %s, result %d\n", ep
->name
, rc
);
3220 static int alloc_request(struct fsg_dev
*fsg
, struct usb_ep
*ep
,
3221 struct usb_request
**preq
)
3223 *preq
= usb_ep_alloc_request(ep
, GFP_ATOMIC
);
3226 ERROR(fsg
, "can't allocate request for %s\n", ep
->name
);
3231 * Reset interface setting and re-init endpoint state (toggle etc).
3232 * Call with altsetting < 0 to disable the interface. The only other
3233 * available altsetting is 0, which enables the interface.
3235 static int do_set_interface(struct fsg_dev
*fsg
, int altsetting
)
3239 const struct usb_endpoint_descriptor
*d
;
3242 DBG(fsg
, "reset interface\n");
3245 /* Deallocate the requests */
3246 for (i
= 0; i
< NUM_BUFFERS
; ++i
) {
3247 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
3250 usb_ep_free_request(fsg
->bulk_in
, bh
->inreq
);
3254 usb_ep_free_request(fsg
->bulk_out
, bh
->outreq
);
3259 usb_ep_free_request(fsg
->intr_in
, fsg
->intreq
);
3263 /* Disable the endpoints */
3264 if (fsg
->bulk_in_enabled
) {
3265 usb_ep_disable(fsg
->bulk_in
);
3266 fsg
->bulk_in_enabled
= 0;
3268 if (fsg
->bulk_out_enabled
) {
3269 usb_ep_disable(fsg
->bulk_out
);
3270 fsg
->bulk_out_enabled
= 0;
3272 if (fsg
->intr_in_enabled
) {
3273 usb_ep_disable(fsg
->intr_in
);
3274 fsg
->intr_in_enabled
= 0;
3278 if (altsetting
< 0 || rc
!= 0)
3281 DBG(fsg
, "set interface %d\n", altsetting
);
3283 /* Enable the endpoints */
3284 d
= ep_desc(fsg
->gadget
, &fs_bulk_in_desc
, &hs_bulk_in_desc
);
3285 if ((rc
= enable_endpoint(fsg
, fsg
->bulk_in
, d
)) != 0)
3287 fsg
->bulk_in_enabled
= 1;
3289 d
= ep_desc(fsg
->gadget
, &fs_bulk_out_desc
, &hs_bulk_out_desc
);
3290 if ((rc
= enable_endpoint(fsg
, fsg
->bulk_out
, d
)) != 0)
3292 fsg
->bulk_out_enabled
= 1;
3293 fsg
->bulk_out_maxpacket
= le16_to_cpu(d
->wMaxPacketSize
);
3294 clear_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
);
3296 if (transport_is_cbi()) {
3297 d
= ep_desc(fsg
->gadget
, &fs_intr_in_desc
, &hs_intr_in_desc
);
3298 if ((rc
= enable_endpoint(fsg
, fsg
->intr_in
, d
)) != 0)
3300 fsg
->intr_in_enabled
= 1;
3303 /* Allocate the requests */
3304 for (i
= 0; i
< NUM_BUFFERS
; ++i
) {
3305 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
3307 if ((rc
= alloc_request(fsg
, fsg
->bulk_in
, &bh
->inreq
)) != 0)
3309 if ((rc
= alloc_request(fsg
, fsg
->bulk_out
, &bh
->outreq
)) != 0)
3311 bh
->inreq
->buf
= bh
->outreq
->buf
= bh
->buf
;
3312 bh
->inreq
->context
= bh
->outreq
->context
= bh
;
3313 bh
->inreq
->complete
= bulk_in_complete
;
3314 bh
->outreq
->complete
= bulk_out_complete
;
3316 if (transport_is_cbi()) {
3317 if ((rc
= alloc_request(fsg
, fsg
->intr_in
, &fsg
->intreq
)) != 0)
3319 fsg
->intreq
->complete
= intr_in_complete
;
3323 for (i
= 0; i
< fsg
->nluns
; ++i
)
3324 fsg
->luns
[i
].unit_attention_data
= SS_RESET_OCCURRED
;
3330 * Change our operational configuration. This code must agree with the code
3331 * that returns config descriptors, and with interface altsetting code.
3333 * It's also responsible for power management interactions. Some
3334 * configurations might not work with our current power sources.
3335 * For now we just assume the gadget is always self-powered.
3337 static int do_set_config(struct fsg_dev
*fsg
, u8 new_config
)
3341 /* Disable the single interface */
3342 if (fsg
->config
!= 0) {
3343 DBG(fsg
, "reset config\n");
3345 rc
= do_set_interface(fsg
, -1);
3348 /* Enable the interface */
3349 if (new_config
!= 0) {
3350 fsg
->config
= new_config
;
3351 if ((rc
= do_set_interface(fsg
, 0)) != 0)
3352 fsg
->config
= 0; // Reset on errors
3356 switch (fsg
->gadget
->speed
) {
3357 case USB_SPEED_LOW
: speed
= "low"; break;
3358 case USB_SPEED_FULL
: speed
= "full"; break;
3359 case USB_SPEED_HIGH
: speed
= "high"; break;
3360 default: speed
= "?"; break;
3362 INFO(fsg
, "%s speed config #%d\n", speed
, fsg
->config
);
3369 /*-------------------------------------------------------------------------*/
3371 static void handle_exception(struct fsg_dev
*fsg
)
3377 struct fsg_buffhd
*bh
;
3378 enum fsg_state old_state
;
3381 unsigned int exception_req_tag
;
3384 /* Clear the existing signals. Anything but SIGUSR1 is converted
3385 * into a high-priority EXIT exception. */
3387 sig
= dequeue_signal_lock(current
, ¤t
->blocked
, &info
);
3390 if (sig
!= SIGUSR1
) {
3391 if (fsg
->state
< FSG_STATE_EXIT
)
3392 DBG(fsg
, "Main thread exiting on signal\n");
3393 raise_exception(fsg
, FSG_STATE_EXIT
);
3397 /* Cancel all the pending transfers */
3398 if (fsg
->intreq_busy
)
3399 usb_ep_dequeue(fsg
->intr_in
, fsg
->intreq
);
3400 for (i
= 0; i
< NUM_BUFFERS
; ++i
) {
3401 bh
= &fsg
->buffhds
[i
];
3403 usb_ep_dequeue(fsg
->bulk_in
, bh
->inreq
);
3404 if (bh
->outreq_busy
)
3405 usb_ep_dequeue(fsg
->bulk_out
, bh
->outreq
);
3408 /* Wait until everything is idle */
3410 num_active
= fsg
->intreq_busy
;
3411 for (i
= 0; i
< NUM_BUFFERS
; ++i
) {
3412 bh
= &fsg
->buffhds
[i
];
3413 num_active
+= bh
->inreq_busy
+ bh
->outreq_busy
;
3415 if (num_active
== 0)
3417 if (sleep_thread(fsg
))
3421 /* Clear out the controller's fifos */
3422 if (fsg
->bulk_in_enabled
)
3423 usb_ep_fifo_flush(fsg
->bulk_in
);
3424 if (fsg
->bulk_out_enabled
)
3425 usb_ep_fifo_flush(fsg
->bulk_out
);
3426 if (fsg
->intr_in_enabled
)
3427 usb_ep_fifo_flush(fsg
->intr_in
);
3429 /* Reset the I/O buffer states and pointers, the SCSI
3430 * state, and the exception. Then invoke the handler. */
3431 spin_lock_irq(&fsg
->lock
);
3433 for (i
= 0; i
< NUM_BUFFERS
; ++i
) {
3434 bh
= &fsg
->buffhds
[i
];
3435 bh
->state
= BUF_STATE_EMPTY
;
3437 fsg
->next_buffhd_to_fill
= fsg
->next_buffhd_to_drain
=
3440 exception_req_tag
= fsg
->exception_req_tag
;
3441 new_config
= fsg
->new_config
;
3442 old_state
= fsg
->state
;
3444 if (old_state
== FSG_STATE_ABORT_BULK_OUT
)
3445 fsg
->state
= FSG_STATE_STATUS_PHASE
;
3447 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3448 curlun
= &fsg
->luns
[i
];
3449 curlun
->prevent_medium_removal
= 0;
3450 curlun
->sense_data
= curlun
->unit_attention_data
=
3452 curlun
->sense_data_info
= 0;
3453 curlun
->info_valid
= 0;
3455 fsg
->state
= FSG_STATE_IDLE
;
3457 spin_unlock_irq(&fsg
->lock
);
3459 /* Carry out any extra actions required for the exception */
3460 switch (old_state
) {
3464 case FSG_STATE_ABORT_BULK_OUT
:
3466 spin_lock_irq(&fsg
->lock
);
3467 if (fsg
->state
== FSG_STATE_STATUS_PHASE
)
3468 fsg
->state
= FSG_STATE_IDLE
;
3469 spin_unlock_irq(&fsg
->lock
);
3472 case FSG_STATE_RESET
:
3473 /* In case we were forced against our will to halt a
3474 * bulk endpoint, clear the halt now. (The SuperH UDC
3475 * requires this.) */
3476 if (test_and_clear_bit(IGNORE_BULK_OUT
, &fsg
->atomic_bitflags
))
3477 usb_ep_clear_halt(fsg
->bulk_in
);
3479 if (transport_is_bbb()) {
3480 if (fsg
->ep0_req_tag
== exception_req_tag
)
3481 ep0_queue(fsg
); // Complete the status stage
3483 } else if (transport_is_cbi())
3484 send_status(fsg
); // Status by interrupt pipe
3486 /* Technically this should go here, but it would only be
3487 * a waste of time. Ditto for the INTERFACE_CHANGE and
3488 * CONFIG_CHANGE cases. */
3489 // for (i = 0; i < fsg->nluns; ++i)
3490 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3493 case FSG_STATE_INTERFACE_CHANGE
:
3494 rc
= do_set_interface(fsg
, 0);
3495 if (fsg
->ep0_req_tag
!= exception_req_tag
)
3497 if (rc
!= 0) // STALL on errors
3498 fsg_set_halt(fsg
, fsg
->ep0
);
3499 else // Complete the status stage
3503 case FSG_STATE_CONFIG_CHANGE
:
3504 rc
= do_set_config(fsg
, new_config
);
3505 if (fsg
->ep0_req_tag
!= exception_req_tag
)
3507 if (rc
!= 0) // STALL on errors
3508 fsg_set_halt(fsg
, fsg
->ep0
);
3509 else // Complete the status stage
3513 case FSG_STATE_DISCONNECT
:
3515 do_set_config(fsg
, 0); // Unconfigured state
3518 case FSG_STATE_EXIT
:
3519 case FSG_STATE_TERMINATED
:
3520 do_set_config(fsg
, 0); // Free resources
3521 spin_lock_irq(&fsg
->lock
);
3522 fsg
->state
= FSG_STATE_TERMINATED
; // Stop the thread
3523 spin_unlock_irq(&fsg
->lock
);
3529 /*-------------------------------------------------------------------------*/
3531 static int fsg_main_thread(void *fsg_
)
3533 struct fsg_dev
*fsg
= fsg_
;
3535 /* Allow the thread to be killed by a signal, but set the signal mask
3536 * to block everything but INT, TERM, KILL, and USR1. */
3537 allow_signal(SIGINT
);
3538 allow_signal(SIGTERM
);
3539 allow_signal(SIGKILL
);
3540 allow_signal(SIGUSR1
);
3542 /* Allow the thread to be frozen */
3545 /* Arrange for userspace references to be interpreted as kernel
3546 * pointers. That way we can pass a kernel pointer to a routine
3547 * that expects a __user pointer and it will work okay. */
3551 while (fsg
->state
!= FSG_STATE_TERMINATED
) {
3552 if (exception_in_progress(fsg
) || signal_pending(current
)) {
3553 handle_exception(fsg
);
3557 if (!fsg
->running
) {
3562 if (get_next_command(fsg
))
3565 spin_lock_irq(&fsg
->lock
);
3566 if (!exception_in_progress(fsg
))
3567 fsg
->state
= FSG_STATE_DATA_PHASE
;
3568 spin_unlock_irq(&fsg
->lock
);
3570 if (do_scsi_command(fsg
) || finish_reply(fsg
))
3573 spin_lock_irq(&fsg
->lock
);
3574 if (!exception_in_progress(fsg
))
3575 fsg
->state
= FSG_STATE_STATUS_PHASE
;
3576 spin_unlock_irq(&fsg
->lock
);
3578 if (send_status(fsg
))
3581 spin_lock_irq(&fsg
->lock
);
3582 if (!exception_in_progress(fsg
))
3583 fsg
->state
= FSG_STATE_IDLE
;
3584 spin_unlock_irq(&fsg
->lock
);
3587 spin_lock_irq(&fsg
->lock
);
3588 fsg
->thread_task
= NULL
;
3589 spin_unlock_irq(&fsg
->lock
);
3591 /* In case we are exiting because of a signal, unregister the
3592 * gadget driver and close the backing file. */
3593 if (test_and_clear_bit(REGISTERED
, &fsg
->atomic_bitflags
)) {
3594 usb_gadget_unregister_driver(&fsg_driver
);
3595 close_all_backing_files(fsg
);
3598 /* Let the unbind and cleanup routines know the thread has exited */
3599 complete_and_exit(&fsg
->thread_notifier
, 0);
3603 /*-------------------------------------------------------------------------*/
3605 /* If the next two routines are called while the gadget is registered,
3606 * the caller must own fsg->filesem for writing. */
3608 static int open_backing_file(struct lun
*curlun
, const char *filename
)
3611 struct file
*filp
= NULL
;
3613 struct inode
*inode
= NULL
;
3618 /* R/W if we can, R/O if we must */
3621 filp
= filp_open(filename
, O_RDWR
| O_LARGEFILE
, 0);
3622 if (-EROFS
== PTR_ERR(filp
))
3626 filp
= filp_open(filename
, O_RDONLY
| O_LARGEFILE
, 0);
3628 LINFO(curlun
, "unable to open backing file: %s\n", filename
);
3629 return PTR_ERR(filp
);
3632 if (!(filp
->f_mode
& FMODE_WRITE
))
3635 if (filp
->f_path
.dentry
)
3636 inode
= filp
->f_path
.dentry
->d_inode
;
3637 if (inode
&& S_ISBLK(inode
->i_mode
)) {
3638 if (bdev_read_only(inode
->i_bdev
))
3640 } else if (!inode
|| !S_ISREG(inode
->i_mode
)) {
3641 LINFO(curlun
, "invalid file type: %s\n", filename
);
3645 /* If we can't read the file, it's no good.
3646 * If we can't write the file, use it read-only. */
3647 if (!filp
->f_op
|| !(filp
->f_op
->read
|| filp
->f_op
->aio_read
)) {
3648 LINFO(curlun
, "file not readable: %s\n", filename
);
3651 if (!(filp
->f_op
->write
|| filp
->f_op
->aio_write
))
3654 size
= i_size_read(inode
->i_mapping
->host
);
3656 LINFO(curlun
, "unable to find file size: %s\n", filename
);
3660 num_sectors
= size
>> 9; // File size in 512-byte blocks
3662 if (mod_data
.cdrom
) {
3663 num_sectors
&= ~3; // Reduce to a multiple of 2048
3664 min_sectors
= 300*4; // Smallest track is 300 frames
3665 if (num_sectors
>= 256*60*75*4) {
3666 num_sectors
= (256*60*75 - 1) * 4;
3667 LINFO(curlun
, "file too big: %s\n", filename
);
3668 LINFO(curlun
, "using only first %d blocks\n",
3672 if (num_sectors
< min_sectors
) {
3673 LINFO(curlun
, "file too small: %s\n", filename
);
3680 curlun
->filp
= filp
;
3681 curlun
->file_length
= size
;
3682 curlun
->num_sectors
= num_sectors
;
3683 LDBG(curlun
, "open backing file: %s\n", filename
);
3687 filp_close(filp
, current
->files
);
3692 static void close_backing_file(struct lun
*curlun
)
3695 LDBG(curlun
, "close backing file\n");
3697 curlun
->filp
= NULL
;
3701 static void close_all_backing_files(struct fsg_dev
*fsg
)
3705 for (i
= 0; i
< fsg
->nluns
; ++i
)
3706 close_backing_file(&fsg
->luns
[i
]);
3710 static ssize_t
show_ro(struct device
*dev
, struct device_attribute
*attr
, char *buf
)
3712 struct lun
*curlun
= dev_to_lun(dev
);
3714 return sprintf(buf
, "%d\n", curlun
->ro
);
3717 static ssize_t
show_file(struct device
*dev
, struct device_attribute
*attr
,
3720 struct lun
*curlun
= dev_to_lun(dev
);
3721 struct fsg_dev
*fsg
= dev_get_drvdata(dev
);
3725 down_read(&fsg
->filesem
);
3726 if (backing_file_is_open(curlun
)) { // Get the complete pathname
3727 p
= d_path(&curlun
->filp
->f_path
, buf
, PAGE_SIZE
- 1);
3732 memmove(buf
, p
, rc
);
3733 buf
[rc
] = '\n'; // Add a newline
3736 } else { // No file, return 0 bytes
3740 up_read(&fsg
->filesem
);
3745 static ssize_t
store_ro(struct device
*dev
, struct device_attribute
*attr
,
3746 const char *buf
, size_t count
)
3749 struct lun
*curlun
= dev_to_lun(dev
);
3750 struct fsg_dev
*fsg
= dev_get_drvdata(dev
);
3753 if (sscanf(buf
, "%d", &i
) != 1)
3756 /* Allow the write-enable status to change only while the backing file
3758 down_read(&fsg
->filesem
);
3759 if (backing_file_is_open(curlun
)) {
3760 LDBG(curlun
, "read-only status change prevented\n");
3764 LDBG(curlun
, "read-only status set to %d\n", curlun
->ro
);
3766 up_read(&fsg
->filesem
);
3770 static ssize_t
store_file(struct device
*dev
, struct device_attribute
*attr
,
3771 const char *buf
, size_t count
)
3773 struct lun
*curlun
= dev_to_lun(dev
);
3774 struct fsg_dev
*fsg
= dev_get_drvdata(dev
);
3777 if (curlun
->prevent_medium_removal
&& backing_file_is_open(curlun
)) {
3778 LDBG(curlun
, "eject attempt prevented\n");
3779 return -EBUSY
; // "Door is locked"
3782 /* Remove a trailing newline */
3783 if (count
> 0 && buf
[count
-1] == '\n')
3784 ((char *) buf
)[count
-1] = 0; // Ugh!
3786 /* Eject current medium */
3787 down_write(&fsg
->filesem
);
3788 if (backing_file_is_open(curlun
)) {
3789 close_backing_file(curlun
);
3790 curlun
->unit_attention_data
= SS_MEDIUM_NOT_PRESENT
;
3793 /* Load new medium */
3794 if (count
> 0 && buf
[0]) {
3795 rc
= open_backing_file(curlun
, buf
);
3797 curlun
->unit_attention_data
=
3798 SS_NOT_READY_TO_READY_TRANSITION
;
3800 up_write(&fsg
->filesem
);
3801 return (rc
< 0 ? rc
: count
);
3805 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3806 static DEVICE_ATTR(ro
, 0444, show_ro
, NULL
);
3807 static DEVICE_ATTR(file
, 0444, show_file
, NULL
);
3810 /*-------------------------------------------------------------------------*/
3812 static void fsg_release(struct kref
*ref
)
3814 struct fsg_dev
*fsg
= container_of(ref
, struct fsg_dev
, ref
);
3820 static void lun_release(struct device
*dev
)
3822 struct fsg_dev
*fsg
= dev_get_drvdata(dev
);
3824 kref_put(&fsg
->ref
, fsg_release
);
3827 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget
*gadget
)
3829 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
3832 struct usb_request
*req
= fsg
->ep0req
;
3834 DBG(fsg
, "unbind\n");
3835 clear_bit(REGISTERED
, &fsg
->atomic_bitflags
);
3837 /* Unregister the sysfs attribute files and the LUNs */
3838 for (i
= 0; i
< fsg
->nluns
; ++i
) {
3839 curlun
= &fsg
->luns
[i
];
3840 if (curlun
->registered
) {
3841 device_remove_file(&curlun
->dev
, &dev_attr_ro
);
3842 device_remove_file(&curlun
->dev
, &dev_attr_file
);
3843 device_unregister(&curlun
->dev
);
3844 curlun
->registered
= 0;
3848 /* If the thread isn't already dead, tell it to exit now */
3849 if (fsg
->state
!= FSG_STATE_TERMINATED
) {
3850 raise_exception(fsg
, FSG_STATE_EXIT
);
3851 wait_for_completion(&fsg
->thread_notifier
);
3853 /* The cleanup routine waits for this completion also */
3854 complete(&fsg
->thread_notifier
);
3857 /* Free the data buffers */
3858 for (i
= 0; i
< NUM_BUFFERS
; ++i
)
3859 kfree(fsg
->buffhds
[i
].buf
);
3861 /* Free the request and buffer for endpoint 0 */
3864 usb_ep_free_request(fsg
->ep0
, req
);
3867 set_gadget_data(gadget
, NULL
);
3871 static int __init
check_parameters(struct fsg_dev
*fsg
)
3876 /* Store the default values */
3877 mod_data
.transport_type
= USB_PR_BULK
;
3878 mod_data
.transport_name
= "Bulk-only";
3879 mod_data
.protocol_type
= USB_SC_SCSI
;
3880 mod_data
.protocol_name
= "Transparent SCSI";
3882 /* Some peripheral controllers are known not to be able to
3883 * halt bulk endpoints correctly. If one of them is present,
3886 if (gadget_is_sh(fsg
->gadget
) || gadget_is_at91(fsg
->gadget
))
3887 mod_data
.can_stall
= 0;
3889 if (mod_data
.release
== 0xffff) { // Parameter wasn't set
3890 /* The sa1100 controller is not supported */
3891 if (gadget_is_sa1100(fsg
->gadget
))
3894 gcnum
= usb_gadget_controller_number(fsg
->gadget
);
3896 mod_data
.release
= 0x0300 + gcnum
;
3898 WARNING(fsg
, "controller '%s' not recognized\n",
3900 mod_data
.release
= 0x0399;
3904 prot
= simple_strtol(mod_data
.protocol_parm
, NULL
, 0);
3906 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3907 if (strnicmp(mod_data
.transport_parm
, "BBB", 10) == 0) {
3908 ; // Use default setting
3909 } else if (strnicmp(mod_data
.transport_parm
, "CB", 10) == 0) {
3910 mod_data
.transport_type
= USB_PR_CB
;
3911 mod_data
.transport_name
= "Control-Bulk";
3912 } else if (strnicmp(mod_data
.transport_parm
, "CBI", 10) == 0) {
3913 mod_data
.transport_type
= USB_PR_CBI
;
3914 mod_data
.transport_name
= "Control-Bulk-Interrupt";
3916 ERROR(fsg
, "invalid transport: %s\n", mod_data
.transport_parm
);
3920 if (strnicmp(mod_data
.protocol_parm
, "SCSI", 10) == 0 ||
3921 prot
== USB_SC_SCSI
) {
3922 ; // Use default setting
3923 } else if (strnicmp(mod_data
.protocol_parm
, "RBC", 10) == 0 ||
3924 prot
== USB_SC_RBC
) {
3925 mod_data
.protocol_type
= USB_SC_RBC
;
3926 mod_data
.protocol_name
= "RBC";
3927 } else if (strnicmp(mod_data
.protocol_parm
, "8020", 4) == 0 ||
3928 strnicmp(mod_data
.protocol_parm
, "ATAPI", 10) == 0 ||
3929 prot
== USB_SC_8020
) {
3930 mod_data
.protocol_type
= USB_SC_8020
;
3931 mod_data
.protocol_name
= "8020i (ATAPI)";
3932 } else if (strnicmp(mod_data
.protocol_parm
, "QIC", 3) == 0 ||
3933 prot
== USB_SC_QIC
) {
3934 mod_data
.protocol_type
= USB_SC_QIC
;
3935 mod_data
.protocol_name
= "QIC-157";
3936 } else if (strnicmp(mod_data
.protocol_parm
, "UFI", 10) == 0 ||
3937 prot
== USB_SC_UFI
) {
3938 mod_data
.protocol_type
= USB_SC_UFI
;
3939 mod_data
.protocol_name
= "UFI";
3940 } else if (strnicmp(mod_data
.protocol_parm
, "8070", 4) == 0 ||
3941 prot
== USB_SC_8070
) {
3942 mod_data
.protocol_type
= USB_SC_8070
;
3943 mod_data
.protocol_name
= "8070i";
3945 ERROR(fsg
, "invalid protocol: %s\n", mod_data
.protocol_parm
);
3949 mod_data
.buflen
&= PAGE_CACHE_MASK
;
3950 if (mod_data
.buflen
<= 0) {
3951 ERROR(fsg
, "invalid buflen\n");
3954 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3960 static int __init
fsg_bind(struct usb_gadget
*gadget
)
3962 struct fsg_dev
*fsg
= the_fsg
;
3967 struct usb_request
*req
;
3970 fsg
->gadget
= gadget
;
3971 set_gadget_data(gadget
, fsg
);
3972 fsg
->ep0
= gadget
->ep0
;
3973 fsg
->ep0
->driver_data
= fsg
;
3975 if ((rc
= check_parameters(fsg
)) != 0)
3978 if (mod_data
.removable
) { // Enable the store_xxx attributes
3979 dev_attr_file
.attr
.mode
= 0644;
3980 dev_attr_file
.store
= store_file
;
3981 if (!mod_data
.cdrom
) {
3982 dev_attr_ro
.attr
.mode
= 0644;
3983 dev_attr_ro
.store
= store_ro
;
3987 /* Find out how many LUNs there should be */
3990 i
= max(mod_data
.num_filenames
, 1u);
3992 ERROR(fsg
, "invalid number of LUNs: %d\n", i
);
3997 /* Create the LUNs, open their backing files, and register the
3998 * LUN devices in sysfs. */
3999 fsg
->luns
= kzalloc(i
* sizeof(struct lun
), GFP_KERNEL
);
4006 for (i
= 0; i
< fsg
->nluns
; ++i
) {
4007 curlun
= &fsg
->luns
[i
];
4008 curlun
->ro
= mod_data
.ro
[i
];
4011 curlun
->dev
.release
= lun_release
;
4012 curlun
->dev
.parent
= &gadget
->dev
;
4013 curlun
->dev
.driver
= &fsg_driver
.driver
;
4014 dev_set_drvdata(&curlun
->dev
, fsg
);
4015 dev_set_name(&curlun
->dev
,"%s-lun%d",
4016 dev_name(&gadget
->dev
), i
);
4018 if ((rc
= device_register(&curlun
->dev
)) != 0) {
4019 INFO(fsg
, "failed to register LUN%d: %d\n", i
, rc
);
4022 if ((rc
= device_create_file(&curlun
->dev
,
4023 &dev_attr_ro
)) != 0 ||
4024 (rc
= device_create_file(&curlun
->dev
,
4025 &dev_attr_file
)) != 0) {
4026 device_unregister(&curlun
->dev
);
4029 curlun
->registered
= 1;
4030 kref_get(&fsg
->ref
);
4032 if (mod_data
.file
[i
] && *mod_data
.file
[i
]) {
4033 if ((rc
= open_backing_file(curlun
,
4034 mod_data
.file
[i
])) != 0)
4036 } else if (!mod_data
.removable
) {
4037 ERROR(fsg
, "no file given for LUN%d\n", i
);
4043 /* Find all the endpoints we will use */
4044 usb_ep_autoconfig_reset(gadget
);
4045 ep
= usb_ep_autoconfig(gadget
, &fs_bulk_in_desc
);
4048 ep
->driver_data
= fsg
; // claim the endpoint
4051 ep
= usb_ep_autoconfig(gadget
, &fs_bulk_out_desc
);
4054 ep
->driver_data
= fsg
; // claim the endpoint
4057 if (transport_is_cbi()) {
4058 ep
= usb_ep_autoconfig(gadget
, &fs_intr_in_desc
);
4061 ep
->driver_data
= fsg
; // claim the endpoint
4065 /* Fix up the descriptors */
4066 device_desc
.bMaxPacketSize0
= fsg
->ep0
->maxpacket
;
4067 device_desc
.idVendor
= cpu_to_le16(mod_data
.vendor
);
4068 device_desc
.idProduct
= cpu_to_le16(mod_data
.product
);
4069 device_desc
.bcdDevice
= cpu_to_le16(mod_data
.release
);
4071 i
= (transport_is_cbi() ? 3 : 2); // Number of endpoints
4072 intf_desc
.bNumEndpoints
= i
;
4073 intf_desc
.bInterfaceSubClass
= mod_data
.protocol_type
;
4074 intf_desc
.bInterfaceProtocol
= mod_data
.transport_type
;
4075 fs_function
[i
+ FS_FUNCTION_PRE_EP_ENTRIES
] = NULL
;
4077 if (gadget_is_dualspeed(gadget
)) {
4078 hs_function
[i
+ HS_FUNCTION_PRE_EP_ENTRIES
] = NULL
;
4080 /* Assume ep0 uses the same maxpacket value for both speeds */
4081 dev_qualifier
.bMaxPacketSize0
= fsg
->ep0
->maxpacket
;
4083 /* Assume endpoint addresses are the same for both speeds */
4084 hs_bulk_in_desc
.bEndpointAddress
=
4085 fs_bulk_in_desc
.bEndpointAddress
;
4086 hs_bulk_out_desc
.bEndpointAddress
=
4087 fs_bulk_out_desc
.bEndpointAddress
;
4088 hs_intr_in_desc
.bEndpointAddress
=
4089 fs_intr_in_desc
.bEndpointAddress
;
4092 if (gadget_is_otg(gadget
))
4093 otg_desc
.bmAttributes
|= USB_OTG_HNP
;
4097 /* Allocate the request and buffer for endpoint 0 */
4098 fsg
->ep0req
= req
= usb_ep_alloc_request(fsg
->ep0
, GFP_KERNEL
);
4101 req
->buf
= kmalloc(EP0_BUFSIZE
, GFP_KERNEL
);
4104 req
->complete
= ep0_complete
;
4106 /* Allocate the data buffers */
4107 for (i
= 0; i
< NUM_BUFFERS
; ++i
) {
4108 struct fsg_buffhd
*bh
= &fsg
->buffhds
[i
];
4110 /* Allocate for the bulk-in endpoint. We assume that
4111 * the buffer will also work with the bulk-out (and
4112 * interrupt-in) endpoint. */
4113 bh
->buf
= kmalloc(mod_data
.buflen
, GFP_KERNEL
);
4118 fsg
->buffhds
[NUM_BUFFERS
- 1].next
= &fsg
->buffhds
[0];
4120 /* This should reflect the actual gadget power source */
4121 usb_gadget_set_selfpowered(gadget
);
4123 snprintf(manufacturer
, sizeof manufacturer
, "%s %s with %s",
4124 init_utsname()->sysname
, init_utsname()->release
,
4127 /* On a real device, serial[] would be loaded from permanent
4128 * storage. We just encode it from the driver version string. */
4129 for (i
= 0; i
< sizeof(serial
) - 2; i
+= 2) {
4130 unsigned char c
= DRIVER_VERSION
[i
/ 2];
4134 sprintf(&serial
[i
], "%02X", c
);
4137 fsg
->thread_task
= kthread_create(fsg_main_thread
, fsg
,
4138 "file-storage-gadget");
4139 if (IS_ERR(fsg
->thread_task
)) {
4140 rc
= PTR_ERR(fsg
->thread_task
);
4144 INFO(fsg
, DRIVER_DESC
", version: " DRIVER_VERSION
"\n");
4145 INFO(fsg
, "Number of LUNs=%d\n", fsg
->nluns
);
4147 pathbuf
= kmalloc(PATH_MAX
, GFP_KERNEL
);
4148 for (i
= 0; i
< fsg
->nluns
; ++i
) {
4149 curlun
= &fsg
->luns
[i
];
4150 if (backing_file_is_open(curlun
)) {
4153 p
= d_path(&curlun
->filp
->f_path
,
4158 LINFO(curlun
, "ro=%d, file: %s\n",
4159 curlun
->ro
, (p
? p
: "(error)"));
4164 DBG(fsg
, "transport=%s (x%02x)\n",
4165 mod_data
.transport_name
, mod_data
.transport_type
);
4166 DBG(fsg
, "protocol=%s (x%02x)\n",
4167 mod_data
.protocol_name
, mod_data
.protocol_type
);
4168 DBG(fsg
, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
4169 mod_data
.vendor
, mod_data
.product
, mod_data
.release
);
4170 DBG(fsg
, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
4171 mod_data
.removable
, mod_data
.can_stall
,
4172 mod_data
.cdrom
, mod_data
.buflen
);
4173 DBG(fsg
, "I/O thread pid: %d\n", task_pid_nr(fsg
->thread_task
));
4175 set_bit(REGISTERED
, &fsg
->atomic_bitflags
);
4177 /* Tell the thread to start working */
4178 wake_up_process(fsg
->thread_task
);
4182 ERROR(fsg
, "unable to autoconfigure all endpoints\n");
4186 fsg
->state
= FSG_STATE_TERMINATED
; // The thread is dead
4188 close_all_backing_files(fsg
);
4189 complete(&fsg
->thread_notifier
);
4194 /*-------------------------------------------------------------------------*/
4196 static void fsg_suspend(struct usb_gadget
*gadget
)
4198 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
4200 DBG(fsg
, "suspend\n");
4201 set_bit(SUSPENDED
, &fsg
->atomic_bitflags
);
4204 static void fsg_resume(struct usb_gadget
*gadget
)
4206 struct fsg_dev
*fsg
= get_gadget_data(gadget
);
4208 DBG(fsg
, "resume\n");
4209 clear_bit(SUSPENDED
, &fsg
->atomic_bitflags
);
4213 /*-------------------------------------------------------------------------*/
4215 static struct usb_gadget_driver fsg_driver
= {
4216 #ifdef CONFIG_USB_GADGET_DUALSPEED
4217 .speed
= USB_SPEED_HIGH
,
4219 .speed
= USB_SPEED_FULL
,
4221 .function
= (char *) longname
,
4223 .unbind
= fsg_unbind
,
4224 .disconnect
= fsg_disconnect
,
4226 .suspend
= fsg_suspend
,
4227 .resume
= fsg_resume
,
4230 .name
= (char *) shortname
,
4231 .owner
= THIS_MODULE
,
4239 static int __init
fsg_alloc(void)
4241 struct fsg_dev
*fsg
;
4243 fsg
= kzalloc(sizeof *fsg
, GFP_KERNEL
);
4246 spin_lock_init(&fsg
->lock
);
4247 init_rwsem(&fsg
->filesem
);
4248 kref_init(&fsg
->ref
);
4249 init_completion(&fsg
->thread_notifier
);
4256 static int __init
fsg_init(void)
4259 struct fsg_dev
*fsg
;
4261 if ((rc
= fsg_alloc()) != 0)
4264 if ((rc
= usb_gadget_register_driver(&fsg_driver
)) != 0)
4265 kref_put(&fsg
->ref
, fsg_release
);
4268 module_init(fsg_init
);
4271 static void __exit
fsg_cleanup(void)
4273 struct fsg_dev
*fsg
= the_fsg
;
4275 /* Unregister the driver iff the thread hasn't already done so */
4276 if (test_and_clear_bit(REGISTERED
, &fsg
->atomic_bitflags
))
4277 usb_gadget_unregister_driver(&fsg_driver
);
4279 /* Wait for the thread to finish up */
4280 wait_for_completion(&fsg
->thread_notifier
);
4282 close_all_backing_files(fsg
);
4283 kref_put(&fsg
->ref
, fsg_release
);
4285 module_exit(fsg_cleanup
);