bridge: Simplify interface for ATM LANE
[linux-2.6.git] / drivers / usb / gadget / file_storage.c
blob381a53b3e11c4a4e4dcd3308bdfcbfd1f2323c6d
1 /*
2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
4 * Copyright (C) 2003-2008 Alan Stern
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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
23 * later version.
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.
86 * Module options:
88 * file=filename[,filename...]
89 * Required if "removable" is not set, names of
90 * the files or block devices used for
91 * backing storage
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
95 * LUNs to support
96 * stall Default determined according to the type of
97 * USB device controller (usually true),
98 * boolean to permit the driver to halt
99 * bulk endpoints
100 * cdrom Default false, boolean for whether to emulate
101 * a CD-ROM drive
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;
105 * also 1 - 6)
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
111 * PAGE_CACHE_SIZE)
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
123 * is being used.
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>.
138 * Driver Design
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
160 * an EXIT exception.
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
183 * variables.
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"
266 #include "config.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)
304 #ifndef DEBUG
305 #undef VERBOSE_DEBUG
306 #undef DUMP_MSGS
307 #endif /* !DEBUG */
309 #ifdef VERBOSE_DEBUG
310 #define VLDBG LDBG
311 #else
312 #define VLDBG(lun,fmt,args...) \
313 do { } while (0)
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 */
342 #define MAX_LUNS 8
344 static struct {
345 char *file[MAX_LUNS];
346 int ro[MAX_LUNS];
347 unsigned int num_filenames;
348 unsigned int num_ros;
349 unsigned int nluns;
351 int removable;
352 int can_stall;
353 int cdrom;
355 char *transport_parm;
356 char *protocol_parm;
357 unsigned short vendor;
358 unsigned short product;
359 unsigned short release;
360 unsigned int buflen;
362 int transport_type;
363 char *transport_name;
364 int protocol_type;
365 char *protocol_name;
367 } mod_data = { // Default values
368 .transport_parm = "BBB",
369 .protocol_parm = "SCSI",
370 .removable = 0,
371 .can_stall = 1,
372 .cdrom = 0,
373 .vendor = DRIVER_VENDOR_ID,
374 .product = DRIVER_PRODUCT_ID,
375 .release = 0xffff, // Use controller chip type
376 .buflen = 16384,
380 module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
381 S_IRUGO);
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
401 * are available. */
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, "
409 "8070, or SCSI)");
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 {
483 u8 bType;
484 u8 bValue;
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
549 * path.
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)
558 #else
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 */
567 struct lun {
568 struct file *filp;
569 loff_t file_length;
570 loff_t num_sectors;
572 unsigned int ro : 1;
573 unsigned int prevent_medium_removal : 1;
574 unsigned int registered : 1;
575 unsigned int info_valid : 1;
577 u32 sense_data;
578 u32 sense_data_info;
579 u32 unit_attention_data;
581 struct device dev;
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 {
600 BUF_STATE_EMPTY = 0,
601 BUF_STATE_FULL,
602 BUF_STATE_BUSY
605 struct fsg_buffhd {
606 void *buf;
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;
616 int inreq_busy;
617 struct usb_request *outreq;
618 int outreq_busy;
621 enum fsg_state {
622 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
623 FSG_STATE_DATA_PHASE,
624 FSG_STATE_STATUS_PHASE,
626 FSG_STATE_IDLE = 0,
627 FSG_STATE_ABORT_BULK_OUT,
628 FSG_STATE_RESET,
629 FSG_STATE_INTERFACE_CHANGE,
630 FSG_STATE_CONFIG_CHANGE,
631 FSG_STATE_DISCONNECT,
632 FSG_STATE_EXIT,
633 FSG_STATE_TERMINATED
636 enum data_direction {
637 DATA_DIR_UNKNOWN = 0,
638 DATA_DIR_FROM_HOST,
639 DATA_DIR_TO_HOST,
640 DATA_DIR_NONE
643 struct fsg_dev {
644 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
645 spinlock_t lock;
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 */
652 struct kref ref;
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
660 int intreq_busy;
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;
678 #define REGISTERED 0
679 #define IGNORE_BULK_OUT 1
680 #define SUSPENDED 2
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;
694 int cmnd_size;
695 u8 cmnd[MAX_COMMAND_SIZE];
696 enum data_direction data_dir;
697 u32 data_size;
698 u32 data_size_from_cmnd;
699 u32 tag;
700 unsigned int lun;
701 u32 residue;
702 u32 usb_amount_left;
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). */
709 int cbbuf_cmnd_size;
710 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
712 unsigned int nluns;
713 struct lun *luns;
714 struct lun *curlun;
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)
728 unsigned int rem;
730 bh->bulk_out_intended_length = length;
731 rem = length % fsg->bulk_out_maxpacket;
732 if (rem > 0)
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);
743 /*-------------------------------------------------------------------------*/
745 #ifdef DUMP_MSGS
747 static void dump_msg(struct fsg_dev *fsg, const char *label,
748 const u8 *buf, unsigned int length)
750 if (length < 512) {
751 DBG(fsg, "%s, length %u:\n", label, length);
752 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
753 16, 1, buf, length, 0);
757 static void dump_cdb(struct fsg_dev *fsg)
760 #else
762 static void dump_msg(struct fsg_dev *fsg, const char *label,
763 const u8 *buf, unsigned int length)
766 #ifdef VERBOSE_DEBUG
768 static void dump_cdb(struct fsg_dev *fsg)
770 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,
771 16, 1, fsg->cmnd, fsg->cmnd_size, 0);
774 #else
776 static void dump_cdb(struct fsg_dev *fsg)
779 #endif /* VERBOSE_DEBUG */
780 #endif /* DUMP_MSGS */
783 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
785 const char *name;
787 if (ep == fsg->bulk_in)
788 name = "bulk-in";
789 else if (ep == fsg->bulk_out)
790 name = "bulk-out";
791 else
792 name = ep->name;
793 DBG(fsg, "%s set halt\n", name);
794 return usb_ep_set_halt(ep);
798 /*-------------------------------------------------------------------------*/
800 /* Routines for unaligned data access */
802 static u16 get_be16(u8 *buf)
804 return ((u16) buf[0] << 8) | ((u16) buf[1]);
807 static u32 get_be32(u8 *buf)
809 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
810 ((u32) buf[2] << 8) | ((u32) buf[3]);
813 static void put_be16(u8 *buf, u16 val)
815 buf[0] = val >> 8;
816 buf[1] = val;
819 static void put_be32(u8 *buf, u32 val)
821 buf[0] = val >> 24;
822 buf[1] = val >> 16;
823 buf[2] = val >> 8;
824 buf[3] = val & 0xff;
828 /*-------------------------------------------------------------------------*/
831 * DESCRIPTORS ... most are static, but strings and (full) configuration
832 * descriptors are built on demand. Also the (static) config and interface
833 * descriptors are adjusted during fsg_bind().
835 #define STRING_MANUFACTURER 1
836 #define STRING_PRODUCT 2
837 #define STRING_SERIAL 3
838 #define STRING_CONFIG 4
839 #define STRING_INTERFACE 5
841 /* There is only one configuration. */
842 #define CONFIG_VALUE 1
844 static struct usb_device_descriptor
845 device_desc = {
846 .bLength = sizeof device_desc,
847 .bDescriptorType = USB_DT_DEVICE,
849 .bcdUSB = cpu_to_le16(0x0200),
850 .bDeviceClass = USB_CLASS_PER_INTERFACE,
852 /* The next three values can be overridden by module parameters */
853 .idVendor = cpu_to_le16(DRIVER_VENDOR_ID),
854 .idProduct = cpu_to_le16(DRIVER_PRODUCT_ID),
855 .bcdDevice = cpu_to_le16(0xffff),
857 .iManufacturer = STRING_MANUFACTURER,
858 .iProduct = STRING_PRODUCT,
859 .iSerialNumber = STRING_SERIAL,
860 .bNumConfigurations = 1,
863 static struct usb_config_descriptor
864 config_desc = {
865 .bLength = sizeof config_desc,
866 .bDescriptorType = USB_DT_CONFIG,
868 /* wTotalLength computed by usb_gadget_config_buf() */
869 .bNumInterfaces = 1,
870 .bConfigurationValue = CONFIG_VALUE,
871 .iConfiguration = STRING_CONFIG,
872 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
873 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
876 static struct usb_otg_descriptor
877 otg_desc = {
878 .bLength = sizeof(otg_desc),
879 .bDescriptorType = USB_DT_OTG,
881 .bmAttributes = USB_OTG_SRP,
884 /* There is only one interface. */
886 static struct usb_interface_descriptor
887 intf_desc = {
888 .bLength = sizeof intf_desc,
889 .bDescriptorType = USB_DT_INTERFACE,
891 .bNumEndpoints = 2, // Adjusted during fsg_bind()
892 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
893 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
894 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
895 .iInterface = STRING_INTERFACE,
898 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
899 * and interrupt-in. */
901 static struct usb_endpoint_descriptor
902 fs_bulk_in_desc = {
903 .bLength = USB_DT_ENDPOINT_SIZE,
904 .bDescriptorType = USB_DT_ENDPOINT,
906 .bEndpointAddress = USB_DIR_IN,
907 .bmAttributes = USB_ENDPOINT_XFER_BULK,
908 /* wMaxPacketSize set by autoconfiguration */
911 static struct usb_endpoint_descriptor
912 fs_bulk_out_desc = {
913 .bLength = USB_DT_ENDPOINT_SIZE,
914 .bDescriptorType = USB_DT_ENDPOINT,
916 .bEndpointAddress = USB_DIR_OUT,
917 .bmAttributes = USB_ENDPOINT_XFER_BULK,
918 /* wMaxPacketSize set by autoconfiguration */
921 static struct usb_endpoint_descriptor
922 fs_intr_in_desc = {
923 .bLength = USB_DT_ENDPOINT_SIZE,
924 .bDescriptorType = USB_DT_ENDPOINT,
926 .bEndpointAddress = USB_DIR_IN,
927 .bmAttributes = USB_ENDPOINT_XFER_INT,
928 .wMaxPacketSize = cpu_to_le16(2),
929 .bInterval = 32, // frames -> 32 ms
932 static const struct usb_descriptor_header *fs_function[] = {
933 (struct usb_descriptor_header *) &otg_desc,
934 (struct usb_descriptor_header *) &intf_desc,
935 (struct usb_descriptor_header *) &fs_bulk_in_desc,
936 (struct usb_descriptor_header *) &fs_bulk_out_desc,
937 (struct usb_descriptor_header *) &fs_intr_in_desc,
938 NULL,
940 #define FS_FUNCTION_PRE_EP_ENTRIES 2
944 * USB 2.0 devices need to expose both high speed and full speed
945 * descriptors, unless they only run at full speed.
947 * That means alternate endpoint descriptors (bigger packets)
948 * and a "device qualifier" ... plus more construction options
949 * for the config descriptor.
951 static struct usb_qualifier_descriptor
952 dev_qualifier = {
953 .bLength = sizeof dev_qualifier,
954 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
956 .bcdUSB = cpu_to_le16(0x0200),
957 .bDeviceClass = USB_CLASS_PER_INTERFACE,
959 .bNumConfigurations = 1,
962 static struct usb_endpoint_descriptor
963 hs_bulk_in_desc = {
964 .bLength = USB_DT_ENDPOINT_SIZE,
965 .bDescriptorType = USB_DT_ENDPOINT,
967 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
968 .bmAttributes = USB_ENDPOINT_XFER_BULK,
969 .wMaxPacketSize = cpu_to_le16(512),
972 static struct usb_endpoint_descriptor
973 hs_bulk_out_desc = {
974 .bLength = USB_DT_ENDPOINT_SIZE,
975 .bDescriptorType = USB_DT_ENDPOINT,
977 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
978 .bmAttributes = USB_ENDPOINT_XFER_BULK,
979 .wMaxPacketSize = cpu_to_le16(512),
980 .bInterval = 1, // NAK every 1 uframe
983 static struct usb_endpoint_descriptor
984 hs_intr_in_desc = {
985 .bLength = USB_DT_ENDPOINT_SIZE,
986 .bDescriptorType = USB_DT_ENDPOINT,
988 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
989 .bmAttributes = USB_ENDPOINT_XFER_INT,
990 .wMaxPacketSize = cpu_to_le16(2),
991 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
994 static const struct usb_descriptor_header *hs_function[] = {
995 (struct usb_descriptor_header *) &otg_desc,
996 (struct usb_descriptor_header *) &intf_desc,
997 (struct usb_descriptor_header *) &hs_bulk_in_desc,
998 (struct usb_descriptor_header *) &hs_bulk_out_desc,
999 (struct usb_descriptor_header *) &hs_intr_in_desc,
1000 NULL,
1002 #define HS_FUNCTION_PRE_EP_ENTRIES 2
1004 /* Maxpacket and other transfer characteristics vary by speed. */
1005 static struct usb_endpoint_descriptor *
1006 ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
1007 struct usb_endpoint_descriptor *hs)
1009 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
1010 return hs;
1011 return fs;
1015 /* The CBI specification limits the serial string to 12 uppercase hexadecimal
1016 * characters. */
1017 static char manufacturer[64];
1018 static char serial[13];
1020 /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1021 static struct usb_string strings[] = {
1022 {STRING_MANUFACTURER, manufacturer},
1023 {STRING_PRODUCT, longname},
1024 {STRING_SERIAL, serial},
1025 {STRING_CONFIG, "Self-powered"},
1026 {STRING_INTERFACE, "Mass Storage"},
1030 static struct usb_gadget_strings stringtab = {
1031 .language = 0x0409, // en-us
1032 .strings = strings,
1037 * Config descriptors must agree with the code that sets configurations
1038 * and with code managing interfaces and their altsettings. They must
1039 * also handle different speeds and other-speed requests.
1041 static int populate_config_buf(struct usb_gadget *gadget,
1042 u8 *buf, u8 type, unsigned index)
1044 enum usb_device_speed speed = gadget->speed;
1045 int len;
1046 const struct usb_descriptor_header **function;
1048 if (index > 0)
1049 return -EINVAL;
1051 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
1052 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
1053 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
1054 function = hs_function;
1055 else
1056 function = fs_function;
1058 /* for now, don't advertise srp-only devices */
1059 if (!gadget_is_otg(gadget))
1060 function++;
1062 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
1063 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1064 return len;
1068 /*-------------------------------------------------------------------------*/
1070 /* These routines may be called in process context or in_irq */
1072 /* Caller must hold fsg->lock */
1073 static void wakeup_thread(struct fsg_dev *fsg)
1075 /* Tell the main thread that something has happened */
1076 fsg->thread_wakeup_needed = 1;
1077 if (fsg->thread_task)
1078 wake_up_process(fsg->thread_task);
1082 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
1084 unsigned long flags;
1086 /* Do nothing if a higher-priority exception is already in progress.
1087 * If a lower-or-equal priority exception is in progress, preempt it
1088 * and notify the main thread by sending it a signal. */
1089 spin_lock_irqsave(&fsg->lock, flags);
1090 if (fsg->state <= new_state) {
1091 fsg->exception_req_tag = fsg->ep0_req_tag;
1092 fsg->state = new_state;
1093 if (fsg->thread_task)
1094 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
1095 fsg->thread_task);
1097 spin_unlock_irqrestore(&fsg->lock, flags);
1101 /*-------------------------------------------------------------------------*/
1103 /* The disconnect callback and ep0 routines. These always run in_irq,
1104 * except that ep0_queue() is called in the main thread to acknowledge
1105 * completion of various requests: set config, set interface, and
1106 * Bulk-only device reset. */
1108 static void fsg_disconnect(struct usb_gadget *gadget)
1110 struct fsg_dev *fsg = get_gadget_data(gadget);
1112 DBG(fsg, "disconnect or port reset\n");
1113 raise_exception(fsg, FSG_STATE_DISCONNECT);
1117 static int ep0_queue(struct fsg_dev *fsg)
1119 int rc;
1121 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
1122 if (rc != 0 && rc != -ESHUTDOWN) {
1124 /* We can't do much more than wait for a reset */
1125 WARNING(fsg, "error in submission: %s --> %d\n",
1126 fsg->ep0->name, rc);
1128 return rc;
1131 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
1133 struct fsg_dev *fsg = ep->driver_data;
1135 if (req->actual > 0)
1136 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
1137 if (req->status || req->actual != req->length)
1138 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
1139 req->status, req->actual, req->length);
1140 if (req->status == -ECONNRESET) // Request was cancelled
1141 usb_ep_fifo_flush(ep);
1143 if (req->status == 0 && req->context)
1144 ((fsg_routine_t) (req->context))(fsg);
1148 /*-------------------------------------------------------------------------*/
1150 /* Bulk and interrupt endpoint completion handlers.
1151 * These always run in_irq. */
1153 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
1155 struct fsg_dev *fsg = ep->driver_data;
1156 struct fsg_buffhd *bh = req->context;
1158 if (req->status || req->actual != req->length)
1159 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
1160 req->status, req->actual, req->length);
1161 if (req->status == -ECONNRESET) // Request was cancelled
1162 usb_ep_fifo_flush(ep);
1164 /* Hold the lock while we update the request and buffer states */
1165 smp_wmb();
1166 spin_lock(&fsg->lock);
1167 bh->inreq_busy = 0;
1168 bh->state = BUF_STATE_EMPTY;
1169 wakeup_thread(fsg);
1170 spin_unlock(&fsg->lock);
1173 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
1175 struct fsg_dev *fsg = ep->driver_data;
1176 struct fsg_buffhd *bh = req->context;
1178 dump_msg(fsg, "bulk-out", req->buf, req->actual);
1179 if (req->status || req->actual != bh->bulk_out_intended_length)
1180 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
1181 req->status, req->actual,
1182 bh->bulk_out_intended_length);
1183 if (req->status == -ECONNRESET) // Request was cancelled
1184 usb_ep_fifo_flush(ep);
1186 /* Hold the lock while we update the request and buffer states */
1187 smp_wmb();
1188 spin_lock(&fsg->lock);
1189 bh->outreq_busy = 0;
1190 bh->state = BUF_STATE_FULL;
1191 wakeup_thread(fsg);
1192 spin_unlock(&fsg->lock);
1196 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1197 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1199 struct fsg_dev *fsg = ep->driver_data;
1200 struct fsg_buffhd *bh = req->context;
1202 if (req->status || req->actual != req->length)
1203 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
1204 req->status, req->actual, req->length);
1205 if (req->status == -ECONNRESET) // Request was cancelled
1206 usb_ep_fifo_flush(ep);
1208 /* Hold the lock while we update the request and buffer states */
1209 smp_wmb();
1210 spin_lock(&fsg->lock);
1211 fsg->intreq_busy = 0;
1212 bh->state = BUF_STATE_EMPTY;
1213 wakeup_thread(fsg);
1214 spin_unlock(&fsg->lock);
1217 #else
1218 static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1220 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1223 /*-------------------------------------------------------------------------*/
1225 /* Ep0 class-specific handlers. These always run in_irq. */
1227 #ifdef CONFIG_USB_FILE_STORAGE_TEST
1228 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1230 struct usb_request *req = fsg->ep0req;
1231 static u8 cbi_reset_cmnd[6] = {
1232 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
1234 /* Error in command transfer? */
1235 if (req->status || req->length != req->actual ||
1236 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
1238 /* Not all controllers allow a protocol stall after
1239 * receiving control-out data, but we'll try anyway. */
1240 fsg_set_halt(fsg, fsg->ep0);
1241 return; // Wait for reset
1244 /* Is it the special reset command? */
1245 if (req->actual >= sizeof cbi_reset_cmnd &&
1246 memcmp(req->buf, cbi_reset_cmnd,
1247 sizeof cbi_reset_cmnd) == 0) {
1249 /* Raise an exception to stop the current operation
1250 * and reinitialize our state. */
1251 DBG(fsg, "cbi reset request\n");
1252 raise_exception(fsg, FSG_STATE_RESET);
1253 return;
1256 VDBG(fsg, "CB[I] accept device-specific command\n");
1257 spin_lock(&fsg->lock);
1259 /* Save the command for later */
1260 if (fsg->cbbuf_cmnd_size)
1261 WARNING(fsg, "CB[I] overwriting previous command\n");
1262 fsg->cbbuf_cmnd_size = req->actual;
1263 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
1265 wakeup_thread(fsg);
1266 spin_unlock(&fsg->lock);
1269 #else
1270 static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1272 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
1275 static int class_setup_req(struct fsg_dev *fsg,
1276 const struct usb_ctrlrequest *ctrl)
1278 struct usb_request *req = fsg->ep0req;
1279 int value = -EOPNOTSUPP;
1280 u16 w_index = le16_to_cpu(ctrl->wIndex);
1281 u16 w_value = le16_to_cpu(ctrl->wValue);
1282 u16 w_length = le16_to_cpu(ctrl->wLength);
1284 if (!fsg->config)
1285 return value;
1287 /* Handle Bulk-only class-specific requests */
1288 if (transport_is_bbb()) {
1289 switch (ctrl->bRequest) {
1291 case USB_BULK_RESET_REQUEST:
1292 if (ctrl->bRequestType != (USB_DIR_OUT |
1293 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1294 break;
1295 if (w_index != 0 || w_value != 0) {
1296 value = -EDOM;
1297 break;
1300 /* Raise an exception to stop the current operation
1301 * and reinitialize our state. */
1302 DBG(fsg, "bulk reset request\n");
1303 raise_exception(fsg, FSG_STATE_RESET);
1304 value = DELAYED_STATUS;
1305 break;
1307 case USB_BULK_GET_MAX_LUN_REQUEST:
1308 if (ctrl->bRequestType != (USB_DIR_IN |
1309 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1310 break;
1311 if (w_index != 0 || w_value != 0) {
1312 value = -EDOM;
1313 break;
1315 VDBG(fsg, "get max LUN\n");
1316 *(u8 *) req->buf = fsg->nluns - 1;
1317 value = 1;
1318 break;
1322 /* Handle CBI class-specific requests */
1323 else {
1324 switch (ctrl->bRequest) {
1326 case USB_CBI_ADSC_REQUEST:
1327 if (ctrl->bRequestType != (USB_DIR_OUT |
1328 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1329 break;
1330 if (w_index != 0 || w_value != 0) {
1331 value = -EDOM;
1332 break;
1334 if (w_length > MAX_COMMAND_SIZE) {
1335 value = -EOVERFLOW;
1336 break;
1338 value = w_length;
1339 fsg->ep0req->context = received_cbi_adsc;
1340 break;
1344 if (value == -EOPNOTSUPP)
1345 VDBG(fsg,
1346 "unknown class-specific control req "
1347 "%02x.%02x v%04x i%04x l%u\n",
1348 ctrl->bRequestType, ctrl->bRequest,
1349 le16_to_cpu(ctrl->wValue), w_index, w_length);
1350 return value;
1354 /*-------------------------------------------------------------------------*/
1356 /* Ep0 standard request handlers. These always run in_irq. */
1358 static int standard_setup_req(struct fsg_dev *fsg,
1359 const struct usb_ctrlrequest *ctrl)
1361 struct usb_request *req = fsg->ep0req;
1362 int value = -EOPNOTSUPP;
1363 u16 w_index = le16_to_cpu(ctrl->wIndex);
1364 u16 w_value = le16_to_cpu(ctrl->wValue);
1366 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1367 * but config change events will also reconfigure hardware. */
1368 switch (ctrl->bRequest) {
1370 case USB_REQ_GET_DESCRIPTOR:
1371 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1372 USB_RECIP_DEVICE))
1373 break;
1374 switch (w_value >> 8) {
1376 case USB_DT_DEVICE:
1377 VDBG(fsg, "get device descriptor\n");
1378 value = sizeof device_desc;
1379 memcpy(req->buf, &device_desc, value);
1380 break;
1381 case USB_DT_DEVICE_QUALIFIER:
1382 VDBG(fsg, "get device qualifier\n");
1383 if (!gadget_is_dualspeed(fsg->gadget))
1384 break;
1385 value = sizeof dev_qualifier;
1386 memcpy(req->buf, &dev_qualifier, value);
1387 break;
1389 case USB_DT_OTHER_SPEED_CONFIG:
1390 VDBG(fsg, "get other-speed config descriptor\n");
1391 if (!gadget_is_dualspeed(fsg->gadget))
1392 break;
1393 goto get_config;
1394 case USB_DT_CONFIG:
1395 VDBG(fsg, "get configuration descriptor\n");
1396 get_config:
1397 value = populate_config_buf(fsg->gadget,
1398 req->buf,
1399 w_value >> 8,
1400 w_value & 0xff);
1401 break;
1403 case USB_DT_STRING:
1404 VDBG(fsg, "get string descriptor\n");
1406 /* wIndex == language code */
1407 value = usb_gadget_get_string(&stringtab,
1408 w_value & 0xff, req->buf);
1409 break;
1411 break;
1413 /* One config, two speeds */
1414 case USB_REQ_SET_CONFIGURATION:
1415 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
1416 USB_RECIP_DEVICE))
1417 break;
1418 VDBG(fsg, "set configuration\n");
1419 if (w_value == CONFIG_VALUE || w_value == 0) {
1420 fsg->new_config = w_value;
1422 /* Raise an exception to wipe out previous transaction
1423 * state (queued bufs, etc) and set the new config. */
1424 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1425 value = DELAYED_STATUS;
1427 break;
1428 case USB_REQ_GET_CONFIGURATION:
1429 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1430 USB_RECIP_DEVICE))
1431 break;
1432 VDBG(fsg, "get configuration\n");
1433 *(u8 *) req->buf = fsg->config;
1434 value = 1;
1435 break;
1437 case USB_REQ_SET_INTERFACE:
1438 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1439 USB_RECIP_INTERFACE))
1440 break;
1441 if (fsg->config && w_index == 0) {
1443 /* Raise an exception to wipe out previous transaction
1444 * state (queued bufs, etc) and install the new
1445 * interface altsetting. */
1446 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1447 value = DELAYED_STATUS;
1449 break;
1450 case USB_REQ_GET_INTERFACE:
1451 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1452 USB_RECIP_INTERFACE))
1453 break;
1454 if (!fsg->config)
1455 break;
1456 if (w_index != 0) {
1457 value = -EDOM;
1458 break;
1460 VDBG(fsg, "get interface\n");
1461 *(u8 *) req->buf = 0;
1462 value = 1;
1463 break;
1465 default:
1466 VDBG(fsg,
1467 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1468 ctrl->bRequestType, ctrl->bRequest,
1469 w_value, w_index, le16_to_cpu(ctrl->wLength));
1472 return value;
1476 static int fsg_setup(struct usb_gadget *gadget,
1477 const struct usb_ctrlrequest *ctrl)
1479 struct fsg_dev *fsg = get_gadget_data(gadget);
1480 int rc;
1481 int w_length = le16_to_cpu(ctrl->wLength);
1483 ++fsg->ep0_req_tag; // Record arrival of a new request
1484 fsg->ep0req->context = NULL;
1485 fsg->ep0req->length = 0;
1486 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1488 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1489 rc = class_setup_req(fsg, ctrl);
1490 else
1491 rc = standard_setup_req(fsg, ctrl);
1493 /* Respond with data/status or defer until later? */
1494 if (rc >= 0 && rc != DELAYED_STATUS) {
1495 rc = min(rc, w_length);
1496 fsg->ep0req->length = rc;
1497 fsg->ep0req->zero = rc < w_length;
1498 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1499 "ep0-in" : "ep0-out");
1500 rc = ep0_queue(fsg);
1503 /* Device either stalls (rc < 0) or reports success */
1504 return rc;
1508 /*-------------------------------------------------------------------------*/
1510 /* All the following routines run in process context */
1513 /* Use this for bulk or interrupt transfers, not ep0 */
1514 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
1515 struct usb_request *req, int *pbusy,
1516 enum fsg_buffer_state *state)
1518 int rc;
1520 if (ep == fsg->bulk_in)
1521 dump_msg(fsg, "bulk-in", req->buf, req->length);
1522 else if (ep == fsg->intr_in)
1523 dump_msg(fsg, "intr-in", req->buf, req->length);
1525 spin_lock_irq(&fsg->lock);
1526 *pbusy = 1;
1527 *state = BUF_STATE_BUSY;
1528 spin_unlock_irq(&fsg->lock);
1529 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1530 if (rc != 0) {
1531 *pbusy = 0;
1532 *state = BUF_STATE_EMPTY;
1534 /* We can't do much more than wait for a reset */
1536 /* Note: currently the net2280 driver fails zero-length
1537 * submissions if DMA is enabled. */
1538 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1539 req->length == 0))
1540 WARNING(fsg, "error in submission: %s --> %d\n",
1541 ep->name, rc);
1546 static int sleep_thread(struct fsg_dev *fsg)
1548 int rc = 0;
1550 /* Wait until a signal arrives or we are woken up */
1551 for (;;) {
1552 try_to_freeze();
1553 set_current_state(TASK_INTERRUPTIBLE);
1554 if (signal_pending(current)) {
1555 rc = -EINTR;
1556 break;
1558 if (fsg->thread_wakeup_needed)
1559 break;
1560 schedule();
1562 __set_current_state(TASK_RUNNING);
1563 fsg->thread_wakeup_needed = 0;
1564 return rc;
1568 /*-------------------------------------------------------------------------*/
1570 static int do_read(struct fsg_dev *fsg)
1572 struct lun *curlun = fsg->curlun;
1573 u32 lba;
1574 struct fsg_buffhd *bh;
1575 int rc;
1576 u32 amount_left;
1577 loff_t file_offset, file_offset_tmp;
1578 unsigned int amount;
1579 unsigned int partial_page;
1580 ssize_t nread;
1582 /* Get the starting Logical Block Address and check that it's
1583 * not too big */
1584 if (fsg->cmnd[0] == SC_READ_6)
1585 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1586 else {
1587 lba = get_be32(&fsg->cmnd[2]);
1589 /* We allow DPO (Disable Page Out = don't save data in the
1590 * cache) and FUA (Force Unit Access = don't read from the
1591 * cache), but we don't implement them. */
1592 if ((fsg->cmnd[1] & ~0x18) != 0) {
1593 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1594 return -EINVAL;
1597 if (lba >= curlun->num_sectors) {
1598 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1599 return -EINVAL;
1601 file_offset = ((loff_t) lba) << 9;
1603 /* Carry out the file reads */
1604 amount_left = fsg->data_size_from_cmnd;
1605 if (unlikely(amount_left == 0))
1606 return -EIO; // No default reply
1608 for (;;) {
1610 /* Figure out how much we need to read:
1611 * Try to read the remaining amount.
1612 * But don't read more than the buffer size.
1613 * And don't try to read past the end of the file.
1614 * Finally, if we're not at a page boundary, don't read past
1615 * the next page.
1616 * If this means reading 0 then we were asked to read past
1617 * the end of file. */
1618 amount = min((unsigned int) amount_left, mod_data.buflen);
1619 amount = min((loff_t) amount,
1620 curlun->file_length - file_offset);
1621 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1622 if (partial_page > 0)
1623 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1624 partial_page);
1626 /* Wait for the next buffer to become available */
1627 bh = fsg->next_buffhd_to_fill;
1628 while (bh->state != BUF_STATE_EMPTY) {
1629 rc = sleep_thread(fsg);
1630 if (rc)
1631 return rc;
1634 /* If we were asked to read past the end of file,
1635 * end with an empty buffer. */
1636 if (amount == 0) {
1637 curlun->sense_data =
1638 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1639 curlun->sense_data_info = file_offset >> 9;
1640 curlun->info_valid = 1;
1641 bh->inreq->length = 0;
1642 bh->state = BUF_STATE_FULL;
1643 break;
1646 /* Perform the read */
1647 file_offset_tmp = file_offset;
1648 nread = vfs_read(curlun->filp,
1649 (char __user *) bh->buf,
1650 amount, &file_offset_tmp);
1651 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1652 (unsigned long long) file_offset,
1653 (int) nread);
1654 if (signal_pending(current))
1655 return -EINTR;
1657 if (nread < 0) {
1658 LDBG(curlun, "error in file read: %d\n",
1659 (int) nread);
1660 nread = 0;
1661 } else if (nread < amount) {
1662 LDBG(curlun, "partial file read: %d/%u\n",
1663 (int) nread, amount);
1664 nread -= (nread & 511); // Round down to a block
1666 file_offset += nread;
1667 amount_left -= nread;
1668 fsg->residue -= nread;
1669 bh->inreq->length = nread;
1670 bh->state = BUF_STATE_FULL;
1672 /* If an error occurred, report it and its position */
1673 if (nread < amount) {
1674 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1675 curlun->sense_data_info = file_offset >> 9;
1676 curlun->info_valid = 1;
1677 break;
1680 if (amount_left == 0)
1681 break; // No more left to read
1683 /* Send this buffer and go read some more */
1684 bh->inreq->zero = 0;
1685 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1686 &bh->inreq_busy, &bh->state);
1687 fsg->next_buffhd_to_fill = bh->next;
1690 return -EIO; // No default reply
1694 /*-------------------------------------------------------------------------*/
1696 static int do_write(struct fsg_dev *fsg)
1698 struct lun *curlun = fsg->curlun;
1699 u32 lba;
1700 struct fsg_buffhd *bh;
1701 int get_some_more;
1702 u32 amount_left_to_req, amount_left_to_write;
1703 loff_t usb_offset, file_offset, file_offset_tmp;
1704 unsigned int amount;
1705 unsigned int partial_page;
1706 ssize_t nwritten;
1707 int rc;
1709 if (curlun->ro) {
1710 curlun->sense_data = SS_WRITE_PROTECTED;
1711 return -EINVAL;
1713 spin_lock(&curlun->filp->f_lock);
1714 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1715 spin_unlock(&curlun->filp->f_lock);
1717 /* Get the starting Logical Block Address and check that it's
1718 * not too big */
1719 if (fsg->cmnd[0] == SC_WRITE_6)
1720 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1721 else {
1722 lba = get_be32(&fsg->cmnd[2]);
1724 /* We allow DPO (Disable Page Out = don't save data in the
1725 * cache) and FUA (Force Unit Access = write directly to the
1726 * medium). We don't implement DPO; we implement FUA by
1727 * performing synchronous output. */
1728 if ((fsg->cmnd[1] & ~0x18) != 0) {
1729 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1730 return -EINVAL;
1732 if (fsg->cmnd[1] & 0x08) { // FUA
1733 spin_lock(&curlun->filp->f_lock);
1734 curlun->filp->f_flags |= O_SYNC;
1735 spin_unlock(&curlun->filp->f_lock);
1738 if (lba >= curlun->num_sectors) {
1739 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1740 return -EINVAL;
1743 /* Carry out the file writes */
1744 get_some_more = 1;
1745 file_offset = usb_offset = ((loff_t) lba) << 9;
1746 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1748 while (amount_left_to_write > 0) {
1750 /* Queue a request for more data from the host */
1751 bh = fsg->next_buffhd_to_fill;
1752 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1754 /* Figure out how much we want to get:
1755 * Try to get the remaining amount.
1756 * But don't get more than the buffer size.
1757 * And don't try to go past the end of the file.
1758 * If we're not at a page boundary,
1759 * don't go past the next page.
1760 * If this means getting 0, then we were asked
1761 * to write past the end of file.
1762 * Finally, round down to a block boundary. */
1763 amount = min(amount_left_to_req, mod_data.buflen);
1764 amount = min((loff_t) amount, curlun->file_length -
1765 usb_offset);
1766 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1767 if (partial_page > 0)
1768 amount = min(amount,
1769 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1771 if (amount == 0) {
1772 get_some_more = 0;
1773 curlun->sense_data =
1774 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1775 curlun->sense_data_info = usb_offset >> 9;
1776 curlun->info_valid = 1;
1777 continue;
1779 amount -= (amount & 511);
1780 if (amount == 0) {
1782 /* Why were we were asked to transfer a
1783 * partial block? */
1784 get_some_more = 0;
1785 continue;
1788 /* Get the next buffer */
1789 usb_offset += amount;
1790 fsg->usb_amount_left -= amount;
1791 amount_left_to_req -= amount;
1792 if (amount_left_to_req == 0)
1793 get_some_more = 0;
1795 /* amount is always divisible by 512, hence by
1796 * the bulk-out maxpacket size */
1797 bh->outreq->length = bh->bulk_out_intended_length =
1798 amount;
1799 bh->outreq->short_not_ok = 1;
1800 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1801 &bh->outreq_busy, &bh->state);
1802 fsg->next_buffhd_to_fill = bh->next;
1803 continue;
1806 /* Write the received data to the backing file */
1807 bh = fsg->next_buffhd_to_drain;
1808 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1809 break; // We stopped early
1810 if (bh->state == BUF_STATE_FULL) {
1811 smp_rmb();
1812 fsg->next_buffhd_to_drain = bh->next;
1813 bh->state = BUF_STATE_EMPTY;
1815 /* Did something go wrong with the transfer? */
1816 if (bh->outreq->status != 0) {
1817 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1818 curlun->sense_data_info = file_offset >> 9;
1819 curlun->info_valid = 1;
1820 break;
1823 amount = bh->outreq->actual;
1824 if (curlun->file_length - file_offset < amount) {
1825 LERROR(curlun,
1826 "write %u @ %llu beyond end %llu\n",
1827 amount, (unsigned long long) file_offset,
1828 (unsigned long long) curlun->file_length);
1829 amount = curlun->file_length - file_offset;
1832 /* Perform the write */
1833 file_offset_tmp = file_offset;
1834 nwritten = vfs_write(curlun->filp,
1835 (char __user *) bh->buf,
1836 amount, &file_offset_tmp);
1837 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1838 (unsigned long long) file_offset,
1839 (int) nwritten);
1840 if (signal_pending(current))
1841 return -EINTR; // Interrupted!
1843 if (nwritten < 0) {
1844 LDBG(curlun, "error in file write: %d\n",
1845 (int) nwritten);
1846 nwritten = 0;
1847 } else if (nwritten < amount) {
1848 LDBG(curlun, "partial file write: %d/%u\n",
1849 (int) nwritten, amount);
1850 nwritten -= (nwritten & 511);
1851 // Round down to a block
1853 file_offset += nwritten;
1854 amount_left_to_write -= nwritten;
1855 fsg->residue -= nwritten;
1857 /* If an error occurred, report it and its position */
1858 if (nwritten < amount) {
1859 curlun->sense_data = SS_WRITE_ERROR;
1860 curlun->sense_data_info = file_offset >> 9;
1861 curlun->info_valid = 1;
1862 break;
1865 /* Did the host decide to stop early? */
1866 if (bh->outreq->actual != bh->outreq->length) {
1867 fsg->short_packet_received = 1;
1868 break;
1870 continue;
1873 /* Wait for something to happen */
1874 rc = sleep_thread(fsg);
1875 if (rc)
1876 return rc;
1879 return -EIO; // No default reply
1883 /*-------------------------------------------------------------------------*/
1885 /* Sync the file data, don't bother with the metadata.
1886 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1887 static int fsync_sub(struct lun *curlun)
1889 struct file *filp = curlun->filp;
1891 if (curlun->ro || !filp)
1892 return 0;
1893 return vfs_fsync(filp, filp->f_path.dentry, 1);
1896 static void fsync_all(struct fsg_dev *fsg)
1898 int i;
1900 for (i = 0; i < fsg->nluns; ++i)
1901 fsync_sub(&fsg->luns[i]);
1904 static int do_synchronize_cache(struct fsg_dev *fsg)
1906 struct lun *curlun = fsg->curlun;
1907 int rc;
1909 /* We ignore the requested LBA and write out all file's
1910 * dirty data buffers. */
1911 rc = fsync_sub(curlun);
1912 if (rc)
1913 curlun->sense_data = SS_WRITE_ERROR;
1914 return 0;
1918 /*-------------------------------------------------------------------------*/
1920 static void invalidate_sub(struct lun *curlun)
1922 struct file *filp = curlun->filp;
1923 struct inode *inode = filp->f_path.dentry->d_inode;
1924 unsigned long rc;
1926 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1927 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1930 static int do_verify(struct fsg_dev *fsg)
1932 struct lun *curlun = fsg->curlun;
1933 u32 lba;
1934 u32 verification_length;
1935 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1936 loff_t file_offset, file_offset_tmp;
1937 u32 amount_left;
1938 unsigned int amount;
1939 ssize_t nread;
1941 /* Get the starting Logical Block Address and check that it's
1942 * not too big */
1943 lba = get_be32(&fsg->cmnd[2]);
1944 if (lba >= curlun->num_sectors) {
1945 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1946 return -EINVAL;
1949 /* We allow DPO (Disable Page Out = don't save data in the
1950 * cache) but we don't implement it. */
1951 if ((fsg->cmnd[1] & ~0x10) != 0) {
1952 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1953 return -EINVAL;
1956 verification_length = get_be16(&fsg->cmnd[7]);
1957 if (unlikely(verification_length == 0))
1958 return -EIO; // No default reply
1960 /* Prepare to carry out the file verify */
1961 amount_left = verification_length << 9;
1962 file_offset = ((loff_t) lba) << 9;
1964 /* Write out all the dirty buffers before invalidating them */
1965 fsync_sub(curlun);
1966 if (signal_pending(current))
1967 return -EINTR;
1969 invalidate_sub(curlun);
1970 if (signal_pending(current))
1971 return -EINTR;
1973 /* Just try to read the requested blocks */
1974 while (amount_left > 0) {
1976 /* Figure out how much we need to read:
1977 * Try to read the remaining amount, but not more than
1978 * the buffer size.
1979 * And don't try to read past the end of the file.
1980 * If this means reading 0 then we were asked to read
1981 * past the end of file. */
1982 amount = min((unsigned int) amount_left, mod_data.buflen);
1983 amount = min((loff_t) amount,
1984 curlun->file_length - file_offset);
1985 if (amount == 0) {
1986 curlun->sense_data =
1987 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1988 curlun->sense_data_info = file_offset >> 9;
1989 curlun->info_valid = 1;
1990 break;
1993 /* Perform the read */
1994 file_offset_tmp = file_offset;
1995 nread = vfs_read(curlun->filp,
1996 (char __user *) bh->buf,
1997 amount, &file_offset_tmp);
1998 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1999 (unsigned long long) file_offset,
2000 (int) nread);
2001 if (signal_pending(current))
2002 return -EINTR;
2004 if (nread < 0) {
2005 LDBG(curlun, "error in file verify: %d\n",
2006 (int) nread);
2007 nread = 0;
2008 } else if (nread < amount) {
2009 LDBG(curlun, "partial file verify: %d/%u\n",
2010 (int) nread, amount);
2011 nread -= (nread & 511); // Round down to a sector
2013 if (nread == 0) {
2014 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
2015 curlun->sense_data_info = file_offset >> 9;
2016 curlun->info_valid = 1;
2017 break;
2019 file_offset += nread;
2020 amount_left -= nread;
2022 return 0;
2026 /*-------------------------------------------------------------------------*/
2028 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2030 u8 *buf = (u8 *) bh->buf;
2032 static char vendor_id[] = "Linux ";
2033 static char product_disk_id[] = "File-Stor Gadget";
2034 static char product_cdrom_id[] = "File-CD Gadget ";
2036 if (!fsg->curlun) { // Unsupported LUNs are okay
2037 fsg->bad_lun_okay = 1;
2038 memset(buf, 0, 36);
2039 buf[0] = 0x7f; // Unsupported, no device-type
2040 buf[4] = 31; // Additional length
2041 return 36;
2044 memset(buf, 0, 8);
2045 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
2046 if (mod_data.removable)
2047 buf[1] = 0x80;
2048 buf[2] = 2; // ANSI SCSI level 2
2049 buf[3] = 2; // SCSI-2 INQUIRY data format
2050 buf[4] = 31; // Additional length
2051 // No special options
2052 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
2053 (mod_data.cdrom ? product_cdrom_id :
2054 product_disk_id),
2055 mod_data.release);
2056 return 36;
2060 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2062 struct lun *curlun = fsg->curlun;
2063 u8 *buf = (u8 *) bh->buf;
2064 u32 sd, sdinfo;
2065 int valid;
2068 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2070 * If a REQUEST SENSE command is received from an initiator
2071 * with a pending unit attention condition (before the target
2072 * generates the contingent allegiance condition), then the
2073 * target shall either:
2074 * a) report any pending sense data and preserve the unit
2075 * attention condition on the logical unit, or,
2076 * b) report the unit attention condition, may discard any
2077 * pending sense data, and clear the unit attention
2078 * condition on the logical unit for that initiator.
2080 * FSG normally uses option a); enable this code to use option b).
2082 #if 0
2083 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2084 curlun->sense_data = curlun->unit_attention_data;
2085 curlun->unit_attention_data = SS_NO_SENSE;
2087 #endif
2089 if (!curlun) { // Unsupported LUNs are okay
2090 fsg->bad_lun_okay = 1;
2091 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2092 sdinfo = 0;
2093 valid = 0;
2094 } else {
2095 sd = curlun->sense_data;
2096 sdinfo = curlun->sense_data_info;
2097 valid = curlun->info_valid << 7;
2098 curlun->sense_data = SS_NO_SENSE;
2099 curlun->sense_data_info = 0;
2100 curlun->info_valid = 0;
2103 memset(buf, 0, 18);
2104 buf[0] = valid | 0x70; // Valid, current error
2105 buf[2] = SK(sd);
2106 put_be32(&buf[3], sdinfo); // Sense information
2107 buf[7] = 18 - 8; // Additional sense length
2108 buf[12] = ASC(sd);
2109 buf[13] = ASCQ(sd);
2110 return 18;
2114 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2116 struct lun *curlun = fsg->curlun;
2117 u32 lba = get_be32(&fsg->cmnd[2]);
2118 int pmi = fsg->cmnd[8];
2119 u8 *buf = (u8 *) bh->buf;
2121 /* Check the PMI and LBA fields */
2122 if (pmi > 1 || (pmi == 0 && lba != 0)) {
2123 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2124 return -EINVAL;
2127 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block
2128 put_be32(&buf[4], 512); // Block length
2129 return 8;
2133 static void store_cdrom_address(u8 *dest, int msf, u32 addr)
2135 if (msf) {
2136 /* Convert to Minutes-Seconds-Frames */
2137 addr >>= 2; /* Convert to 2048-byte frames */
2138 addr += 2*75; /* Lead-in occupies 2 seconds */
2139 dest[3] = addr % 75; /* Frames */
2140 addr /= 75;
2141 dest[2] = addr % 60; /* Seconds */
2142 addr /= 60;
2143 dest[1] = addr; /* Minutes */
2144 dest[0] = 0; /* Reserved */
2145 } else {
2146 /* Absolute sector */
2147 put_be32(dest, addr);
2151 static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2153 struct lun *curlun = fsg->curlun;
2154 int msf = fsg->cmnd[1] & 0x02;
2155 u32 lba = get_be32(&fsg->cmnd[2]);
2156 u8 *buf = (u8 *) bh->buf;
2158 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
2159 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2160 return -EINVAL;
2162 if (lba >= curlun->num_sectors) {
2163 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
2164 return -EINVAL;
2167 memset(buf, 0, 8);
2168 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
2169 store_cdrom_address(&buf[4], msf, lba);
2170 return 8;
2174 static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2176 struct lun *curlun = fsg->curlun;
2177 int msf = fsg->cmnd[1] & 0x02;
2178 int start_track = fsg->cmnd[6];
2179 u8 *buf = (u8 *) bh->buf;
2181 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
2182 start_track > 1) {
2183 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2184 return -EINVAL;
2187 memset(buf, 0, 20);
2188 buf[1] = (20-2); /* TOC data length */
2189 buf[2] = 1; /* First track number */
2190 buf[3] = 1; /* Last track number */
2191 buf[5] = 0x16; /* Data track, copying allowed */
2192 buf[6] = 0x01; /* Only track is number 1 */
2193 store_cdrom_address(&buf[8], msf, 0);
2195 buf[13] = 0x16; /* Lead-out track is data */
2196 buf[14] = 0xAA; /* Lead-out track number */
2197 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
2198 return 20;
2202 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2204 struct lun *curlun = fsg->curlun;
2205 int mscmnd = fsg->cmnd[0];
2206 u8 *buf = (u8 *) bh->buf;
2207 u8 *buf0 = buf;
2208 int pc, page_code;
2209 int changeable_values, all_pages;
2210 int valid_page = 0;
2211 int len, limit;
2213 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
2214 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2215 return -EINVAL;
2217 pc = fsg->cmnd[2] >> 6;
2218 page_code = fsg->cmnd[2] & 0x3f;
2219 if (pc == 3) {
2220 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2221 return -EINVAL;
2223 changeable_values = (pc == 1);
2224 all_pages = (page_code == 0x3f);
2226 /* Write the mode parameter header. Fixed values are: default
2227 * medium type, no cache control (DPOFUA), and no block descriptors.
2228 * The only variable value is the WriteProtect bit. We will fill in
2229 * the mode data length later. */
2230 memset(buf, 0, 8);
2231 if (mscmnd == SC_MODE_SENSE_6) {
2232 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2233 buf += 4;
2234 limit = 255;
2235 } else { // SC_MODE_SENSE_10
2236 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2237 buf += 8;
2238 limit = 65535; // Should really be mod_data.buflen
2241 /* No block descriptors */
2243 /* The mode pages, in numerical order. The only page we support
2244 * is the Caching page. */
2245 if (page_code == 0x08 || all_pages) {
2246 valid_page = 1;
2247 buf[0] = 0x08; // Page code
2248 buf[1] = 10; // Page length
2249 memset(buf+2, 0, 10); // None of the fields are changeable
2251 if (!changeable_values) {
2252 buf[2] = 0x04; // Write cache enable,
2253 // Read cache not disabled
2254 // No cache retention priorities
2255 put_be16(&buf[4], 0xffff); // Don't disable prefetch
2256 // Minimum prefetch = 0
2257 put_be16(&buf[8], 0xffff); // Maximum prefetch
2258 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2260 buf += 12;
2263 /* Check that a valid page was requested and the mode data length
2264 * isn't too long. */
2265 len = buf - buf0;
2266 if (!valid_page || len > limit) {
2267 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2268 return -EINVAL;
2271 /* Store the mode data length */
2272 if (mscmnd == SC_MODE_SENSE_6)
2273 buf0[0] = len - 1;
2274 else
2275 put_be16(buf0, len - 2);
2276 return len;
2280 static int do_start_stop(struct fsg_dev *fsg)
2282 struct lun *curlun = fsg->curlun;
2283 int loej, start;
2285 if (!mod_data.removable) {
2286 curlun->sense_data = SS_INVALID_COMMAND;
2287 return -EINVAL;
2290 // int immed = fsg->cmnd[1] & 0x01;
2291 loej = fsg->cmnd[4] & 0x02;
2292 start = fsg->cmnd[4] & 0x01;
2294 #ifdef CONFIG_USB_FILE_STORAGE_TEST
2295 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
2296 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
2297 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2298 return -EINVAL;
2301 if (!start) {
2303 /* Are we allowed to unload the media? */
2304 if (curlun->prevent_medium_removal) {
2305 LDBG(curlun, "unload attempt prevented\n");
2306 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2307 return -EINVAL;
2309 if (loej) { // Simulate an unload/eject
2310 up_read(&fsg->filesem);
2311 down_write(&fsg->filesem);
2312 close_backing_file(curlun);
2313 up_write(&fsg->filesem);
2314 down_read(&fsg->filesem);
2316 } else {
2318 /* Our emulation doesn't support mounting; the medium is
2319 * available for use as soon as it is loaded. */
2320 if (!backing_file_is_open(curlun)) {
2321 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2322 return -EINVAL;
2325 #endif
2326 return 0;
2330 static int do_prevent_allow(struct fsg_dev *fsg)
2332 struct lun *curlun = fsg->curlun;
2333 int prevent;
2335 if (!mod_data.removable) {
2336 curlun->sense_data = SS_INVALID_COMMAND;
2337 return -EINVAL;
2340 prevent = fsg->cmnd[4] & 0x01;
2341 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
2342 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2343 return -EINVAL;
2346 if (curlun->prevent_medium_removal && !prevent)
2347 fsync_sub(curlun);
2348 curlun->prevent_medium_removal = prevent;
2349 return 0;
2353 static int do_read_format_capacities(struct fsg_dev *fsg,
2354 struct fsg_buffhd *bh)
2356 struct lun *curlun = fsg->curlun;
2357 u8 *buf = (u8 *) bh->buf;
2359 buf[0] = buf[1] = buf[2] = 0;
2360 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
2361 buf += 4;
2363 put_be32(&buf[0], curlun->num_sectors); // Number of blocks
2364 put_be32(&buf[4], 512); // Block length
2365 buf[4] = 0x02; // Current capacity
2366 return 12;
2370 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2372 struct lun *curlun = fsg->curlun;
2374 /* We don't support MODE SELECT */
2375 curlun->sense_data = SS_INVALID_COMMAND;
2376 return -EINVAL;
2380 /*-------------------------------------------------------------------------*/
2382 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2384 int rc;
2386 rc = fsg_set_halt(fsg, fsg->bulk_in);
2387 if (rc == -EAGAIN)
2388 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2389 while (rc != 0) {
2390 if (rc != -EAGAIN) {
2391 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
2392 rc = 0;
2393 break;
2396 /* Wait for a short time and then try again */
2397 if (msleep_interruptible(100) != 0)
2398 return -EINTR;
2399 rc = usb_ep_set_halt(fsg->bulk_in);
2401 return rc;
2404 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
2406 int rc;
2408 DBG(fsg, "bulk-in set wedge\n");
2409 rc = usb_ep_set_wedge(fsg->bulk_in);
2410 if (rc == -EAGAIN)
2411 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
2412 while (rc != 0) {
2413 if (rc != -EAGAIN) {
2414 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
2415 rc = 0;
2416 break;
2419 /* Wait for a short time and then try again */
2420 if (msleep_interruptible(100) != 0)
2421 return -EINTR;
2422 rc = usb_ep_set_wedge(fsg->bulk_in);
2424 return rc;
2427 static int pad_with_zeros(struct fsg_dev *fsg)
2429 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2430 u32 nkeep = bh->inreq->length;
2431 u32 nsend;
2432 int rc;
2434 bh->state = BUF_STATE_EMPTY; // For the first iteration
2435 fsg->usb_amount_left = nkeep + fsg->residue;
2436 while (fsg->usb_amount_left > 0) {
2438 /* Wait for the next buffer to be free */
2439 while (bh->state != BUF_STATE_EMPTY) {
2440 rc = sleep_thread(fsg);
2441 if (rc)
2442 return rc;
2445 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2446 memset(bh->buf + nkeep, 0, nsend - nkeep);
2447 bh->inreq->length = nsend;
2448 bh->inreq->zero = 0;
2449 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2450 &bh->inreq_busy, &bh->state);
2451 bh = fsg->next_buffhd_to_fill = bh->next;
2452 fsg->usb_amount_left -= nsend;
2453 nkeep = 0;
2455 return 0;
2458 static int throw_away_data(struct fsg_dev *fsg)
2460 struct fsg_buffhd *bh;
2461 u32 amount;
2462 int rc;
2464 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2465 fsg->usb_amount_left > 0) {
2467 /* Throw away the data in a filled buffer */
2468 if (bh->state == BUF_STATE_FULL) {
2469 smp_rmb();
2470 bh->state = BUF_STATE_EMPTY;
2471 fsg->next_buffhd_to_drain = bh->next;
2473 /* A short packet or an error ends everything */
2474 if (bh->outreq->actual != bh->outreq->length ||
2475 bh->outreq->status != 0) {
2476 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2477 return -EINTR;
2479 continue;
2482 /* Try to submit another request if we need one */
2483 bh = fsg->next_buffhd_to_fill;
2484 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2485 amount = min(fsg->usb_amount_left,
2486 (u32) mod_data.buflen);
2488 /* amount is always divisible by 512, hence by
2489 * the bulk-out maxpacket size */
2490 bh->outreq->length = bh->bulk_out_intended_length =
2491 amount;
2492 bh->outreq->short_not_ok = 1;
2493 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2494 &bh->outreq_busy, &bh->state);
2495 fsg->next_buffhd_to_fill = bh->next;
2496 fsg->usb_amount_left -= amount;
2497 continue;
2500 /* Otherwise wait for something to happen */
2501 rc = sleep_thread(fsg);
2502 if (rc)
2503 return rc;
2505 return 0;
2509 static int finish_reply(struct fsg_dev *fsg)
2511 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2512 int rc = 0;
2514 switch (fsg->data_dir) {
2515 case DATA_DIR_NONE:
2516 break; // Nothing to send
2518 /* If we don't know whether the host wants to read or write,
2519 * this must be CB or CBI with an unknown command. We mustn't
2520 * try to send or receive any data. So stall both bulk pipes
2521 * if we can and wait for a reset. */
2522 case DATA_DIR_UNKNOWN:
2523 if (mod_data.can_stall) {
2524 fsg_set_halt(fsg, fsg->bulk_out);
2525 rc = halt_bulk_in_endpoint(fsg);
2527 break;
2529 /* All but the last buffer of data must have already been sent */
2530 case DATA_DIR_TO_HOST:
2531 if (fsg->data_size == 0)
2532 ; // Nothing to send
2534 /* If there's no residue, simply send the last buffer */
2535 else if (fsg->residue == 0) {
2536 bh->inreq->zero = 0;
2537 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2538 &bh->inreq_busy, &bh->state);
2539 fsg->next_buffhd_to_fill = bh->next;
2542 /* There is a residue. For CB and CBI, simply mark the end
2543 * of the data with a short packet. However, if we are
2544 * allowed to stall, there was no data at all (residue ==
2545 * data_size), and the command failed (invalid LUN or
2546 * sense data is set), then halt the bulk-in endpoint
2547 * instead. */
2548 else if (!transport_is_bbb()) {
2549 if (mod_data.can_stall &&
2550 fsg->residue == fsg->data_size &&
2551 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2552 bh->state = BUF_STATE_EMPTY;
2553 rc = halt_bulk_in_endpoint(fsg);
2554 } else {
2555 bh->inreq->zero = 1;
2556 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2557 &bh->inreq_busy, &bh->state);
2558 fsg->next_buffhd_to_fill = bh->next;
2562 /* For Bulk-only, if we're allowed to stall then send the
2563 * short packet and halt the bulk-in endpoint. If we can't
2564 * stall, pad out the remaining data with 0's. */
2565 else {
2566 if (mod_data.can_stall) {
2567 bh->inreq->zero = 1;
2568 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2569 &bh->inreq_busy, &bh->state);
2570 fsg->next_buffhd_to_fill = bh->next;
2571 rc = halt_bulk_in_endpoint(fsg);
2572 } else
2573 rc = pad_with_zeros(fsg);
2575 break;
2577 /* We have processed all we want from the data the host has sent.
2578 * There may still be outstanding bulk-out requests. */
2579 case DATA_DIR_FROM_HOST:
2580 if (fsg->residue == 0)
2581 ; // Nothing to receive
2583 /* Did the host stop sending unexpectedly early? */
2584 else if (fsg->short_packet_received) {
2585 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2586 rc = -EINTR;
2589 /* We haven't processed all the incoming data. Even though
2590 * we may be allowed to stall, doing so would cause a race.
2591 * The controller may already have ACK'ed all the remaining
2592 * bulk-out packets, in which case the host wouldn't see a
2593 * STALL. Not realizing the endpoint was halted, it wouldn't
2594 * clear the halt -- leading to problems later on. */
2595 #if 0
2596 else if (mod_data.can_stall) {
2597 fsg_set_halt(fsg, fsg->bulk_out);
2598 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2599 rc = -EINTR;
2601 #endif
2603 /* We can't stall. Read in the excess data and throw it
2604 * all away. */
2605 else
2606 rc = throw_away_data(fsg);
2607 break;
2609 return rc;
2613 static int send_status(struct fsg_dev *fsg)
2615 struct lun *curlun = fsg->curlun;
2616 struct fsg_buffhd *bh;
2617 int rc;
2618 u8 status = USB_STATUS_PASS;
2619 u32 sd, sdinfo = 0;
2621 /* Wait for the next buffer to become available */
2622 bh = fsg->next_buffhd_to_fill;
2623 while (bh->state != BUF_STATE_EMPTY) {
2624 rc = sleep_thread(fsg);
2625 if (rc)
2626 return rc;
2629 if (curlun) {
2630 sd = curlun->sense_data;
2631 sdinfo = curlun->sense_data_info;
2632 } else if (fsg->bad_lun_okay)
2633 sd = SS_NO_SENSE;
2634 else
2635 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2637 if (fsg->phase_error) {
2638 DBG(fsg, "sending phase-error status\n");
2639 status = USB_STATUS_PHASE_ERROR;
2640 sd = SS_INVALID_COMMAND;
2641 } else if (sd != SS_NO_SENSE) {
2642 DBG(fsg, "sending command-failure status\n");
2643 status = USB_STATUS_FAIL;
2644 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2645 " info x%x\n",
2646 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2649 if (transport_is_bbb()) {
2650 struct bulk_cs_wrap *csw = bh->buf;
2652 /* Store and send the Bulk-only CSW */
2653 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
2654 csw->Tag = fsg->tag;
2655 csw->Residue = cpu_to_le32(fsg->residue);
2656 csw->Status = status;
2658 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2659 bh->inreq->zero = 0;
2660 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2661 &bh->inreq_busy, &bh->state);
2663 } else if (mod_data.transport_type == USB_PR_CB) {
2665 /* Control-Bulk transport has no status phase! */
2666 return 0;
2668 } else { // USB_PR_CBI
2669 struct interrupt_data *buf = bh->buf;
2671 /* Store and send the Interrupt data. UFI sends the ASC
2672 * and ASCQ bytes. Everything else sends a Type (which
2673 * is always 0) and the status Value. */
2674 if (mod_data.protocol_type == USB_SC_UFI) {
2675 buf->bType = ASC(sd);
2676 buf->bValue = ASCQ(sd);
2677 } else {
2678 buf->bType = 0;
2679 buf->bValue = status;
2681 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2683 fsg->intr_buffhd = bh; // Point to the right buffhd
2684 fsg->intreq->buf = bh->inreq->buf;
2685 fsg->intreq->context = bh;
2686 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2687 &fsg->intreq_busy, &bh->state);
2690 fsg->next_buffhd_to_fill = bh->next;
2691 return 0;
2695 /*-------------------------------------------------------------------------*/
2697 /* Check whether the command is properly formed and whether its data size
2698 * and direction agree with the values we already have. */
2699 static int check_command(struct fsg_dev *fsg, int cmnd_size,
2700 enum data_direction data_dir, unsigned int mask,
2701 int needs_medium, const char *name)
2703 int i;
2704 int lun = fsg->cmnd[1] >> 5;
2705 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2706 char hdlen[20];
2707 struct lun *curlun;
2709 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2710 * Transparent SCSI doesn't pad. */
2711 if (protocol_is_scsi())
2714 /* There's some disagreement as to whether RBC pads commands or not.
2715 * We'll play it safe and accept either form. */
2716 else if (mod_data.protocol_type == USB_SC_RBC) {
2717 if (fsg->cmnd_size == 12)
2718 cmnd_size = 12;
2720 /* All the other protocols pad to 12 bytes */
2721 } else
2722 cmnd_size = 12;
2724 hdlen[0] = 0;
2725 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2726 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2727 fsg->data_size);
2728 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2729 name, cmnd_size, dirletter[(int) data_dir],
2730 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2732 /* We can't reply at all until we know the correct data direction
2733 * and size. */
2734 if (fsg->data_size_from_cmnd == 0)
2735 data_dir = DATA_DIR_NONE;
2736 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2737 fsg->data_dir = data_dir;
2738 fsg->data_size = fsg->data_size_from_cmnd;
2740 } else { // Bulk-only
2741 if (fsg->data_size < fsg->data_size_from_cmnd) {
2743 /* Host data size < Device data size is a phase error.
2744 * Carry out the command, but only transfer as much
2745 * as we are allowed. */
2746 fsg->data_size_from_cmnd = fsg->data_size;
2747 fsg->phase_error = 1;
2750 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2752 /* Conflicting data directions is a phase error */
2753 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2754 fsg->phase_error = 1;
2755 return -EINVAL;
2758 /* Verify the length of the command itself */
2759 if (cmnd_size != fsg->cmnd_size) {
2761 /* Special case workaround: There are plenty of buggy SCSI
2762 * implementations. Many have issues with cbw->Length
2763 * field passing a wrong command size. For those cases we
2764 * always try to work around the problem by using the length
2765 * sent by the host side provided it is at least as large
2766 * as the correct command length.
2767 * Examples of such cases would be MS-Windows, which issues
2768 * REQUEST SENSE with cbw->Length == 12 where it should
2769 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2770 * REQUEST SENSE with cbw->Length == 10 where it should
2771 * be 6 as well.
2773 if (cmnd_size <= fsg->cmnd_size) {
2774 DBG(fsg, "%s is buggy! Expected length %d "
2775 "but we got %d\n", name,
2776 cmnd_size, fsg->cmnd_size);
2777 cmnd_size = fsg->cmnd_size;
2778 } else {
2779 fsg->phase_error = 1;
2780 return -EINVAL;
2784 /* Check that the LUN values are consistent */
2785 if (transport_is_bbb()) {
2786 if (fsg->lun != lun)
2787 DBG(fsg, "using LUN %d from CBW, "
2788 "not LUN %d from CDB\n",
2789 fsg->lun, lun);
2790 } else
2791 fsg->lun = lun; // Use LUN from the command
2793 /* Check the LUN */
2794 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2795 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2796 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2797 curlun->sense_data = SS_NO_SENSE;
2798 curlun->sense_data_info = 0;
2799 curlun->info_valid = 0;
2801 } else {
2802 fsg->curlun = curlun = NULL;
2803 fsg->bad_lun_okay = 0;
2805 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2806 * to use unsupported LUNs; all others may not. */
2807 if (fsg->cmnd[0] != SC_INQUIRY &&
2808 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2809 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2810 return -EINVAL;
2814 /* If a unit attention condition exists, only INQUIRY and
2815 * REQUEST SENSE commands are allowed; anything else must fail. */
2816 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2817 fsg->cmnd[0] != SC_INQUIRY &&
2818 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2819 curlun->sense_data = curlun->unit_attention_data;
2820 curlun->unit_attention_data = SS_NO_SENSE;
2821 return -EINVAL;
2824 /* Check that only command bytes listed in the mask are non-zero */
2825 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2826 for (i = 1; i < cmnd_size; ++i) {
2827 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2828 if (curlun)
2829 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2830 return -EINVAL;
2834 /* If the medium isn't mounted and the command needs to access
2835 * it, return an error. */
2836 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2837 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2838 return -EINVAL;
2841 return 0;
2845 static int do_scsi_command(struct fsg_dev *fsg)
2847 struct fsg_buffhd *bh;
2848 int rc;
2849 int reply = -EINVAL;
2850 int i;
2851 static char unknown[16];
2853 dump_cdb(fsg);
2855 /* Wait for the next buffer to become available for data or status */
2856 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2857 while (bh->state != BUF_STATE_EMPTY) {
2858 rc = sleep_thread(fsg);
2859 if (rc)
2860 return rc;
2862 fsg->phase_error = 0;
2863 fsg->short_packet_received = 0;
2865 down_read(&fsg->filesem); // We're using the backing file
2866 switch (fsg->cmnd[0]) {
2868 case SC_INQUIRY:
2869 fsg->data_size_from_cmnd = fsg->cmnd[4];
2870 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2871 (1<<4), 0,
2872 "INQUIRY")) == 0)
2873 reply = do_inquiry(fsg, bh);
2874 break;
2876 case SC_MODE_SELECT_6:
2877 fsg->data_size_from_cmnd = fsg->cmnd[4];
2878 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2879 (1<<1) | (1<<4), 0,
2880 "MODE SELECT(6)")) == 0)
2881 reply = do_mode_select(fsg, bh);
2882 break;
2884 case SC_MODE_SELECT_10:
2885 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2886 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2887 (1<<1) | (3<<7), 0,
2888 "MODE SELECT(10)")) == 0)
2889 reply = do_mode_select(fsg, bh);
2890 break;
2892 case SC_MODE_SENSE_6:
2893 fsg->data_size_from_cmnd = fsg->cmnd[4];
2894 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2895 (1<<1) | (1<<2) | (1<<4), 0,
2896 "MODE SENSE(6)")) == 0)
2897 reply = do_mode_sense(fsg, bh);
2898 break;
2900 case SC_MODE_SENSE_10:
2901 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2902 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2903 (1<<1) | (1<<2) | (3<<7), 0,
2904 "MODE SENSE(10)")) == 0)
2905 reply = do_mode_sense(fsg, bh);
2906 break;
2908 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2909 fsg->data_size_from_cmnd = 0;
2910 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2911 (1<<4), 0,
2912 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2913 reply = do_prevent_allow(fsg);
2914 break;
2916 case SC_READ_6:
2917 i = fsg->cmnd[4];
2918 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2919 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2920 (7<<1) | (1<<4), 1,
2921 "READ(6)")) == 0)
2922 reply = do_read(fsg);
2923 break;
2925 case SC_READ_10:
2926 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2927 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2928 (1<<1) | (0xf<<2) | (3<<7), 1,
2929 "READ(10)")) == 0)
2930 reply = do_read(fsg);
2931 break;
2933 case SC_READ_12:
2934 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2935 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2936 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2937 "READ(12)")) == 0)
2938 reply = do_read(fsg);
2939 break;
2941 case SC_READ_CAPACITY:
2942 fsg->data_size_from_cmnd = 8;
2943 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2944 (0xf<<2) | (1<<8), 1,
2945 "READ CAPACITY")) == 0)
2946 reply = do_read_capacity(fsg, bh);
2947 break;
2949 case SC_READ_HEADER:
2950 if (!mod_data.cdrom)
2951 goto unknown_cmnd;
2952 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2953 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2954 (3<<7) | (0x1f<<1), 1,
2955 "READ HEADER")) == 0)
2956 reply = do_read_header(fsg, bh);
2957 break;
2959 case SC_READ_TOC:
2960 if (!mod_data.cdrom)
2961 goto unknown_cmnd;
2962 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2963 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2964 (7<<6) | (1<<1), 1,
2965 "READ TOC")) == 0)
2966 reply = do_read_toc(fsg, bh);
2967 break;
2969 case SC_READ_FORMAT_CAPACITIES:
2970 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2971 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2972 (3<<7), 1,
2973 "READ FORMAT CAPACITIES")) == 0)
2974 reply = do_read_format_capacities(fsg, bh);
2975 break;
2977 case SC_REQUEST_SENSE:
2978 fsg->data_size_from_cmnd = fsg->cmnd[4];
2979 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2980 (1<<4), 0,
2981 "REQUEST SENSE")) == 0)
2982 reply = do_request_sense(fsg, bh);
2983 break;
2985 case SC_START_STOP_UNIT:
2986 fsg->data_size_from_cmnd = 0;
2987 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2988 (1<<1) | (1<<4), 0,
2989 "START-STOP UNIT")) == 0)
2990 reply = do_start_stop(fsg);
2991 break;
2993 case SC_SYNCHRONIZE_CACHE:
2994 fsg->data_size_from_cmnd = 0;
2995 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2996 (0xf<<2) | (3<<7), 1,
2997 "SYNCHRONIZE CACHE")) == 0)
2998 reply = do_synchronize_cache(fsg);
2999 break;
3001 case SC_TEST_UNIT_READY:
3002 fsg->data_size_from_cmnd = 0;
3003 reply = check_command(fsg, 6, DATA_DIR_NONE,
3004 0, 1,
3005 "TEST UNIT READY");
3006 break;
3008 /* Although optional, this command is used by MS-Windows. We
3009 * support a minimal version: BytChk must be 0. */
3010 case SC_VERIFY:
3011 fsg->data_size_from_cmnd = 0;
3012 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
3013 (1<<1) | (0xf<<2) | (3<<7), 1,
3014 "VERIFY")) == 0)
3015 reply = do_verify(fsg);
3016 break;
3018 case SC_WRITE_6:
3019 i = fsg->cmnd[4];
3020 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
3021 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
3022 (7<<1) | (1<<4), 1,
3023 "WRITE(6)")) == 0)
3024 reply = do_write(fsg);
3025 break;
3027 case SC_WRITE_10:
3028 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
3029 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
3030 (1<<1) | (0xf<<2) | (3<<7), 1,
3031 "WRITE(10)")) == 0)
3032 reply = do_write(fsg);
3033 break;
3035 case SC_WRITE_12:
3036 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
3037 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
3038 (1<<1) | (0xf<<2) | (0xf<<6), 1,
3039 "WRITE(12)")) == 0)
3040 reply = do_write(fsg);
3041 break;
3043 /* Some mandatory commands that we recognize but don't implement.
3044 * They don't mean much in this setting. It's left as an exercise
3045 * for anyone interested to implement RESERVE and RELEASE in terms
3046 * of Posix locks. */
3047 case SC_FORMAT_UNIT:
3048 case SC_RELEASE:
3049 case SC_RESERVE:
3050 case SC_SEND_DIAGNOSTIC:
3051 // Fall through
3053 default:
3054 unknown_cmnd:
3055 fsg->data_size_from_cmnd = 0;
3056 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
3057 if ((reply = check_command(fsg, fsg->cmnd_size,
3058 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
3059 fsg->curlun->sense_data = SS_INVALID_COMMAND;
3060 reply = -EINVAL;
3062 break;
3064 up_read(&fsg->filesem);
3066 if (reply == -EINTR || signal_pending(current))
3067 return -EINTR;
3069 /* Set up the single reply buffer for finish_reply() */
3070 if (reply == -EINVAL)
3071 reply = 0; // Error reply length
3072 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
3073 reply = min((u32) reply, fsg->data_size_from_cmnd);
3074 bh->inreq->length = reply;
3075 bh->state = BUF_STATE_FULL;
3076 fsg->residue -= reply;
3077 } // Otherwise it's already set
3079 return 0;
3083 /*-------------------------------------------------------------------------*/
3085 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
3087 struct usb_request *req = bh->outreq;
3088 struct bulk_cb_wrap *cbw = req->buf;
3090 /* Was this a real packet? Should it be ignored? */
3091 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
3092 return -EINVAL;
3094 /* Is the CBW valid? */
3095 if (req->actual != USB_BULK_CB_WRAP_LEN ||
3096 cbw->Signature != cpu_to_le32(
3097 USB_BULK_CB_SIG)) {
3098 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
3099 req->actual,
3100 le32_to_cpu(cbw->Signature));
3102 /* The Bulk-only spec says we MUST stall the IN endpoint
3103 * (6.6.1), so it's unavoidable. It also says we must
3104 * retain this state until the next reset, but there's
3105 * no way to tell the controller driver it should ignore
3106 * Clear-Feature(HALT) requests.
3108 * We aren't required to halt the OUT endpoint; instead
3109 * we can simply accept and discard any data received
3110 * until the next reset. */
3111 wedge_bulk_in_endpoint(fsg);
3112 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
3113 return -EINVAL;
3116 /* Is the CBW meaningful? */
3117 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
3118 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
3119 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
3120 "cmdlen %u\n",
3121 cbw->Lun, cbw->Flags, cbw->Length);
3123 /* We can do anything we want here, so let's stall the
3124 * bulk pipes if we are allowed to. */
3125 if (mod_data.can_stall) {
3126 fsg_set_halt(fsg, fsg->bulk_out);
3127 halt_bulk_in_endpoint(fsg);
3129 return -EINVAL;
3132 /* Save the command for later */
3133 fsg->cmnd_size = cbw->Length;
3134 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
3135 if (cbw->Flags & USB_BULK_IN_FLAG)
3136 fsg->data_dir = DATA_DIR_TO_HOST;
3137 else
3138 fsg->data_dir = DATA_DIR_FROM_HOST;
3139 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
3140 if (fsg->data_size == 0)
3141 fsg->data_dir = DATA_DIR_NONE;
3142 fsg->lun = cbw->Lun;
3143 fsg->tag = cbw->Tag;
3144 return 0;
3148 static int get_next_command(struct fsg_dev *fsg)
3150 struct fsg_buffhd *bh;
3151 int rc = 0;
3153 if (transport_is_bbb()) {
3155 /* Wait for the next buffer to become available */
3156 bh = fsg->next_buffhd_to_fill;
3157 while (bh->state != BUF_STATE_EMPTY) {
3158 rc = sleep_thread(fsg);
3159 if (rc)
3160 return rc;
3163 /* Queue a request to read a Bulk-only CBW */
3164 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
3165 bh->outreq->short_not_ok = 1;
3166 start_transfer(fsg, fsg->bulk_out, bh->outreq,
3167 &bh->outreq_busy, &bh->state);
3169 /* We will drain the buffer in software, which means we
3170 * can reuse it for the next filling. No need to advance
3171 * next_buffhd_to_fill. */
3173 /* Wait for the CBW to arrive */
3174 while (bh->state != BUF_STATE_FULL) {
3175 rc = sleep_thread(fsg);
3176 if (rc)
3177 return rc;
3179 smp_rmb();
3180 rc = received_cbw(fsg, bh);
3181 bh->state = BUF_STATE_EMPTY;
3183 } else { // USB_PR_CB or USB_PR_CBI
3185 /* Wait for the next command to arrive */
3186 while (fsg->cbbuf_cmnd_size == 0) {
3187 rc = sleep_thread(fsg);
3188 if (rc)
3189 return rc;
3192 /* Is the previous status interrupt request still busy?
3193 * The host is allowed to skip reading the status,
3194 * so we must cancel it. */
3195 if (fsg->intreq_busy)
3196 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3198 /* Copy the command and mark the buffer empty */
3199 fsg->data_dir = DATA_DIR_UNKNOWN;
3200 spin_lock_irq(&fsg->lock);
3201 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3202 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3203 fsg->cbbuf_cmnd_size = 0;
3204 spin_unlock_irq(&fsg->lock);
3206 return rc;
3210 /*-------------------------------------------------------------------------*/
3212 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3213 const struct usb_endpoint_descriptor *d)
3215 int rc;
3217 ep->driver_data = fsg;
3218 rc = usb_ep_enable(ep, d);
3219 if (rc)
3220 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3221 return rc;
3224 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3225 struct usb_request **preq)
3227 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3228 if (*preq)
3229 return 0;
3230 ERROR(fsg, "can't allocate request for %s\n", ep->name);
3231 return -ENOMEM;
3235 * Reset interface setting and re-init endpoint state (toggle etc).
3236 * Call with altsetting < 0 to disable the interface. The only other
3237 * available altsetting is 0, which enables the interface.
3239 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3241 int rc = 0;
3242 int i;
3243 const struct usb_endpoint_descriptor *d;
3245 if (fsg->running)
3246 DBG(fsg, "reset interface\n");
3248 reset:
3249 /* Deallocate the requests */
3250 for (i = 0; i < NUM_BUFFERS; ++i) {
3251 struct fsg_buffhd *bh = &fsg->buffhds[i];
3253 if (bh->inreq) {
3254 usb_ep_free_request(fsg->bulk_in, bh->inreq);
3255 bh->inreq = NULL;
3257 if (bh->outreq) {
3258 usb_ep_free_request(fsg->bulk_out, bh->outreq);
3259 bh->outreq = NULL;
3262 if (fsg->intreq) {
3263 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3264 fsg->intreq = NULL;
3267 /* Disable the endpoints */
3268 if (fsg->bulk_in_enabled) {
3269 usb_ep_disable(fsg->bulk_in);
3270 fsg->bulk_in_enabled = 0;
3272 if (fsg->bulk_out_enabled) {
3273 usb_ep_disable(fsg->bulk_out);
3274 fsg->bulk_out_enabled = 0;
3276 if (fsg->intr_in_enabled) {
3277 usb_ep_disable(fsg->intr_in);
3278 fsg->intr_in_enabled = 0;
3281 fsg->running = 0;
3282 if (altsetting < 0 || rc != 0)
3283 return rc;
3285 DBG(fsg, "set interface %d\n", altsetting);
3287 /* Enable the endpoints */
3288 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3289 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3290 goto reset;
3291 fsg->bulk_in_enabled = 1;
3293 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3294 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3295 goto reset;
3296 fsg->bulk_out_enabled = 1;
3297 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
3298 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
3300 if (transport_is_cbi()) {
3301 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3302 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3303 goto reset;
3304 fsg->intr_in_enabled = 1;
3307 /* Allocate the requests */
3308 for (i = 0; i < NUM_BUFFERS; ++i) {
3309 struct fsg_buffhd *bh = &fsg->buffhds[i];
3311 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3312 goto reset;
3313 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3314 goto reset;
3315 bh->inreq->buf = bh->outreq->buf = bh->buf;
3316 bh->inreq->context = bh->outreq->context = bh;
3317 bh->inreq->complete = bulk_in_complete;
3318 bh->outreq->complete = bulk_out_complete;
3320 if (transport_is_cbi()) {
3321 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3322 goto reset;
3323 fsg->intreq->complete = intr_in_complete;
3326 fsg->running = 1;
3327 for (i = 0; i < fsg->nluns; ++i)
3328 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3329 return rc;
3334 * Change our operational configuration. This code must agree with the code
3335 * that returns config descriptors, and with interface altsetting code.
3337 * It's also responsible for power management interactions. Some
3338 * configurations might not work with our current power sources.
3339 * For now we just assume the gadget is always self-powered.
3341 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3343 int rc = 0;
3345 /* Disable the single interface */
3346 if (fsg->config != 0) {
3347 DBG(fsg, "reset config\n");
3348 fsg->config = 0;
3349 rc = do_set_interface(fsg, -1);
3352 /* Enable the interface */
3353 if (new_config != 0) {
3354 fsg->config = new_config;
3355 if ((rc = do_set_interface(fsg, 0)) != 0)
3356 fsg->config = 0; // Reset on errors
3357 else {
3358 char *speed;
3360 switch (fsg->gadget->speed) {
3361 case USB_SPEED_LOW: speed = "low"; break;
3362 case USB_SPEED_FULL: speed = "full"; break;
3363 case USB_SPEED_HIGH: speed = "high"; break;
3364 default: speed = "?"; break;
3366 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3369 return rc;
3373 /*-------------------------------------------------------------------------*/
3375 static void handle_exception(struct fsg_dev *fsg)
3377 siginfo_t info;
3378 int sig;
3379 int i;
3380 int num_active;
3381 struct fsg_buffhd *bh;
3382 enum fsg_state old_state;
3383 u8 new_config;
3384 struct lun *curlun;
3385 unsigned int exception_req_tag;
3386 int rc;
3388 /* Clear the existing signals. Anything but SIGUSR1 is converted
3389 * into a high-priority EXIT exception. */
3390 for (;;) {
3391 sig = dequeue_signal_lock(current, &current->blocked, &info);
3392 if (!sig)
3393 break;
3394 if (sig != SIGUSR1) {
3395 if (fsg->state < FSG_STATE_EXIT)
3396 DBG(fsg, "Main thread exiting on signal\n");
3397 raise_exception(fsg, FSG_STATE_EXIT);
3401 /* Cancel all the pending transfers */
3402 if (fsg->intreq_busy)
3403 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3404 for (i = 0; i < NUM_BUFFERS; ++i) {
3405 bh = &fsg->buffhds[i];
3406 if (bh->inreq_busy)
3407 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3408 if (bh->outreq_busy)
3409 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3412 /* Wait until everything is idle */
3413 for (;;) {
3414 num_active = fsg->intreq_busy;
3415 for (i = 0; i < NUM_BUFFERS; ++i) {
3416 bh = &fsg->buffhds[i];
3417 num_active += bh->inreq_busy + bh->outreq_busy;
3419 if (num_active == 0)
3420 break;
3421 if (sleep_thread(fsg))
3422 return;
3425 /* Clear out the controller's fifos */
3426 if (fsg->bulk_in_enabled)
3427 usb_ep_fifo_flush(fsg->bulk_in);
3428 if (fsg->bulk_out_enabled)
3429 usb_ep_fifo_flush(fsg->bulk_out);
3430 if (fsg->intr_in_enabled)
3431 usb_ep_fifo_flush(fsg->intr_in);
3433 /* Reset the I/O buffer states and pointers, the SCSI
3434 * state, and the exception. Then invoke the handler. */
3435 spin_lock_irq(&fsg->lock);
3437 for (i = 0; i < NUM_BUFFERS; ++i) {
3438 bh = &fsg->buffhds[i];
3439 bh->state = BUF_STATE_EMPTY;
3441 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3442 &fsg->buffhds[0];
3444 exception_req_tag = fsg->exception_req_tag;
3445 new_config = fsg->new_config;
3446 old_state = fsg->state;
3448 if (old_state == FSG_STATE_ABORT_BULK_OUT)
3449 fsg->state = FSG_STATE_STATUS_PHASE;
3450 else {
3451 for (i = 0; i < fsg->nluns; ++i) {
3452 curlun = &fsg->luns[i];
3453 curlun->prevent_medium_removal = 0;
3454 curlun->sense_data = curlun->unit_attention_data =
3455 SS_NO_SENSE;
3456 curlun->sense_data_info = 0;
3457 curlun->info_valid = 0;
3459 fsg->state = FSG_STATE_IDLE;
3461 spin_unlock_irq(&fsg->lock);
3463 /* Carry out any extra actions required for the exception */
3464 switch (old_state) {
3465 default:
3466 break;
3468 case FSG_STATE_ABORT_BULK_OUT:
3469 send_status(fsg);
3470 spin_lock_irq(&fsg->lock);
3471 if (fsg->state == FSG_STATE_STATUS_PHASE)
3472 fsg->state = FSG_STATE_IDLE;
3473 spin_unlock_irq(&fsg->lock);
3474 break;
3476 case FSG_STATE_RESET:
3477 /* In case we were forced against our will to halt a
3478 * bulk endpoint, clear the halt now. (The SuperH UDC
3479 * requires this.) */
3480 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
3481 usb_ep_clear_halt(fsg->bulk_in);
3483 if (transport_is_bbb()) {
3484 if (fsg->ep0_req_tag == exception_req_tag)
3485 ep0_queue(fsg); // Complete the status stage
3487 } else if (transport_is_cbi())
3488 send_status(fsg); // Status by interrupt pipe
3490 /* Technically this should go here, but it would only be
3491 * a waste of time. Ditto for the INTERFACE_CHANGE and
3492 * CONFIG_CHANGE cases. */
3493 // for (i = 0; i < fsg->nluns; ++i)
3494 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3495 break;
3497 case FSG_STATE_INTERFACE_CHANGE:
3498 rc = do_set_interface(fsg, 0);
3499 if (fsg->ep0_req_tag != exception_req_tag)
3500 break;
3501 if (rc != 0) // STALL on errors
3502 fsg_set_halt(fsg, fsg->ep0);
3503 else // Complete the status stage
3504 ep0_queue(fsg);
3505 break;
3507 case FSG_STATE_CONFIG_CHANGE:
3508 rc = do_set_config(fsg, new_config);
3509 if (fsg->ep0_req_tag != exception_req_tag)
3510 break;
3511 if (rc != 0) // STALL on errors
3512 fsg_set_halt(fsg, fsg->ep0);
3513 else // Complete the status stage
3514 ep0_queue(fsg);
3515 break;
3517 case FSG_STATE_DISCONNECT:
3518 fsync_all(fsg);
3519 do_set_config(fsg, 0); // Unconfigured state
3520 break;
3522 case FSG_STATE_EXIT:
3523 case FSG_STATE_TERMINATED:
3524 do_set_config(fsg, 0); // Free resources
3525 spin_lock_irq(&fsg->lock);
3526 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3527 spin_unlock_irq(&fsg->lock);
3528 break;
3533 /*-------------------------------------------------------------------------*/
3535 static int fsg_main_thread(void *fsg_)
3537 struct fsg_dev *fsg = fsg_;
3539 /* Allow the thread to be killed by a signal, but set the signal mask
3540 * to block everything but INT, TERM, KILL, and USR1. */
3541 allow_signal(SIGINT);
3542 allow_signal(SIGTERM);
3543 allow_signal(SIGKILL);
3544 allow_signal(SIGUSR1);
3546 /* Allow the thread to be frozen */
3547 set_freezable();
3549 /* Arrange for userspace references to be interpreted as kernel
3550 * pointers. That way we can pass a kernel pointer to a routine
3551 * that expects a __user pointer and it will work okay. */
3552 set_fs(get_ds());
3554 /* The main loop */
3555 while (fsg->state != FSG_STATE_TERMINATED) {
3556 if (exception_in_progress(fsg) || signal_pending(current)) {
3557 handle_exception(fsg);
3558 continue;
3561 if (!fsg->running) {
3562 sleep_thread(fsg);
3563 continue;
3566 if (get_next_command(fsg))
3567 continue;
3569 spin_lock_irq(&fsg->lock);
3570 if (!exception_in_progress(fsg))
3571 fsg->state = FSG_STATE_DATA_PHASE;
3572 spin_unlock_irq(&fsg->lock);
3574 if (do_scsi_command(fsg) || finish_reply(fsg))
3575 continue;
3577 spin_lock_irq(&fsg->lock);
3578 if (!exception_in_progress(fsg))
3579 fsg->state = FSG_STATE_STATUS_PHASE;
3580 spin_unlock_irq(&fsg->lock);
3582 if (send_status(fsg))
3583 continue;
3585 spin_lock_irq(&fsg->lock);
3586 if (!exception_in_progress(fsg))
3587 fsg->state = FSG_STATE_IDLE;
3588 spin_unlock_irq(&fsg->lock);
3591 spin_lock_irq(&fsg->lock);
3592 fsg->thread_task = NULL;
3593 spin_unlock_irq(&fsg->lock);
3595 /* If we are exiting because of a signal, unregister the
3596 * gadget driver. */
3597 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3598 usb_gadget_unregister_driver(&fsg_driver);
3600 /* Let the unbind and cleanup routines know the thread has exited */
3601 complete_and_exit(&fsg->thread_notifier, 0);
3605 /*-------------------------------------------------------------------------*/
3607 /* If the next two routines are called while the gadget is registered,
3608 * the caller must own fsg->filesem for writing. */
3610 static int open_backing_file(struct lun *curlun, const char *filename)
3612 int ro;
3613 struct file *filp = NULL;
3614 int rc = -EINVAL;
3615 struct inode *inode = NULL;
3616 loff_t size;
3617 loff_t num_sectors;
3618 loff_t min_sectors;
3620 /* R/W if we can, R/O if we must */
3621 ro = curlun->ro;
3622 if (!ro) {
3623 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3624 if (-EROFS == PTR_ERR(filp))
3625 ro = 1;
3627 if (ro)
3628 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3629 if (IS_ERR(filp)) {
3630 LINFO(curlun, "unable to open backing file: %s\n", filename);
3631 return PTR_ERR(filp);
3634 if (!(filp->f_mode & FMODE_WRITE))
3635 ro = 1;
3637 if (filp->f_path.dentry)
3638 inode = filp->f_path.dentry->d_inode;
3639 if (inode && S_ISBLK(inode->i_mode)) {
3640 if (bdev_read_only(inode->i_bdev))
3641 ro = 1;
3642 } else if (!inode || !S_ISREG(inode->i_mode)) {
3643 LINFO(curlun, "invalid file type: %s\n", filename);
3644 goto out;
3647 /* If we can't read the file, it's no good.
3648 * If we can't write the file, use it read-only. */
3649 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3650 LINFO(curlun, "file not readable: %s\n", filename);
3651 goto out;
3653 if (!(filp->f_op->write || filp->f_op->aio_write))
3654 ro = 1;
3656 size = i_size_read(inode->i_mapping->host);
3657 if (size < 0) {
3658 LINFO(curlun, "unable to find file size: %s\n", filename);
3659 rc = (int) size;
3660 goto out;
3662 num_sectors = size >> 9; // File size in 512-byte blocks
3663 min_sectors = 1;
3664 if (mod_data.cdrom) {
3665 num_sectors &= ~3; // Reduce to a multiple of 2048
3666 min_sectors = 300*4; // Smallest track is 300 frames
3667 if (num_sectors >= 256*60*75*4) {
3668 num_sectors = (256*60*75 - 1) * 4;
3669 LINFO(curlun, "file too big: %s\n", filename);
3670 LINFO(curlun, "using only first %d blocks\n",
3671 (int) num_sectors);
3674 if (num_sectors < min_sectors) {
3675 LINFO(curlun, "file too small: %s\n", filename);
3676 rc = -ETOOSMALL;
3677 goto out;
3680 get_file(filp);
3681 curlun->ro = ro;
3682 curlun->filp = filp;
3683 curlun->file_length = size;
3684 curlun->num_sectors = num_sectors;
3685 LDBG(curlun, "open backing file: %s\n", filename);
3686 rc = 0;
3688 out:
3689 filp_close(filp, current->files);
3690 return rc;
3694 static void close_backing_file(struct lun *curlun)
3696 if (curlun->filp) {
3697 LDBG(curlun, "close backing file\n");
3698 fput(curlun->filp);
3699 curlun->filp = NULL;
3704 static ssize_t show_ro(struct device *dev, struct device_attribute *attr, char *buf)
3706 struct lun *curlun = dev_to_lun(dev);
3708 return sprintf(buf, "%d\n", curlun->ro);
3711 static ssize_t show_file(struct device *dev, struct device_attribute *attr,
3712 char *buf)
3714 struct lun *curlun = dev_to_lun(dev);
3715 struct fsg_dev *fsg = dev_get_drvdata(dev);
3716 char *p;
3717 ssize_t rc;
3719 down_read(&fsg->filesem);
3720 if (backing_file_is_open(curlun)) { // Get the complete pathname
3721 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
3722 if (IS_ERR(p))
3723 rc = PTR_ERR(p);
3724 else {
3725 rc = strlen(p);
3726 memmove(buf, p, rc);
3727 buf[rc] = '\n'; // Add a newline
3728 buf[++rc] = 0;
3730 } else { // No file, return 0 bytes
3731 *buf = 0;
3732 rc = 0;
3734 up_read(&fsg->filesem);
3735 return rc;
3739 static ssize_t store_ro(struct device *dev, struct device_attribute *attr,
3740 const char *buf, size_t count)
3742 ssize_t rc = count;
3743 struct lun *curlun = dev_to_lun(dev);
3744 struct fsg_dev *fsg = dev_get_drvdata(dev);
3745 int i;
3747 if (sscanf(buf, "%d", &i) != 1)
3748 return -EINVAL;
3750 /* Allow the write-enable status to change only while the backing file
3751 * is closed. */
3752 down_read(&fsg->filesem);
3753 if (backing_file_is_open(curlun)) {
3754 LDBG(curlun, "read-only status change prevented\n");
3755 rc = -EBUSY;
3756 } else {
3757 curlun->ro = !!i;
3758 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3760 up_read(&fsg->filesem);
3761 return rc;
3764 static ssize_t store_file(struct device *dev, struct device_attribute *attr,
3765 const char *buf, size_t count)
3767 struct lun *curlun = dev_to_lun(dev);
3768 struct fsg_dev *fsg = dev_get_drvdata(dev);
3769 int rc = 0;
3771 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3772 LDBG(curlun, "eject attempt prevented\n");
3773 return -EBUSY; // "Door is locked"
3776 /* Remove a trailing newline */
3777 if (count > 0 && buf[count-1] == '\n')
3778 ((char *) buf)[count-1] = 0; // Ugh!
3780 /* Eject current medium */
3781 down_write(&fsg->filesem);
3782 if (backing_file_is_open(curlun)) {
3783 close_backing_file(curlun);
3784 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3787 /* Load new medium */
3788 if (count > 0 && buf[0]) {
3789 rc = open_backing_file(curlun, buf);
3790 if (rc == 0)
3791 curlun->unit_attention_data =
3792 SS_NOT_READY_TO_READY_TRANSITION;
3794 up_write(&fsg->filesem);
3795 return (rc < 0 ? rc : count);
3799 /* The write permissions and store_xxx pointers are set in fsg_bind() */
3800 static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3801 static DEVICE_ATTR(file, 0444, show_file, NULL);
3804 /*-------------------------------------------------------------------------*/
3806 static void fsg_release(struct kref *ref)
3808 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3810 kfree(fsg->luns);
3811 kfree(fsg);
3814 static void lun_release(struct device *dev)
3816 struct fsg_dev *fsg = dev_get_drvdata(dev);
3818 kref_put(&fsg->ref, fsg_release);
3821 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
3823 struct fsg_dev *fsg = get_gadget_data(gadget);
3824 int i;
3825 struct lun *curlun;
3826 struct usb_request *req = fsg->ep0req;
3828 DBG(fsg, "unbind\n");
3829 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3831 /* Unregister the sysfs attribute files and the LUNs */
3832 for (i = 0; i < fsg->nluns; ++i) {
3833 curlun = &fsg->luns[i];
3834 if (curlun->registered) {
3835 device_remove_file(&curlun->dev, &dev_attr_ro);
3836 device_remove_file(&curlun->dev, &dev_attr_file);
3837 close_backing_file(curlun);
3838 device_unregister(&curlun->dev);
3839 curlun->registered = 0;
3843 /* If the thread isn't already dead, tell it to exit now */
3844 if (fsg->state != FSG_STATE_TERMINATED) {
3845 raise_exception(fsg, FSG_STATE_EXIT);
3846 wait_for_completion(&fsg->thread_notifier);
3848 /* The cleanup routine waits for this completion also */
3849 complete(&fsg->thread_notifier);
3852 /* Free the data buffers */
3853 for (i = 0; i < NUM_BUFFERS; ++i)
3854 kfree(fsg->buffhds[i].buf);
3856 /* Free the request and buffer for endpoint 0 */
3857 if (req) {
3858 kfree(req->buf);
3859 usb_ep_free_request(fsg->ep0, req);
3862 set_gadget_data(gadget, NULL);
3866 static int __init check_parameters(struct fsg_dev *fsg)
3868 int prot;
3869 int gcnum;
3871 /* Store the default values */
3872 mod_data.transport_type = USB_PR_BULK;
3873 mod_data.transport_name = "Bulk-only";
3874 mod_data.protocol_type = USB_SC_SCSI;
3875 mod_data.protocol_name = "Transparent SCSI";
3877 /* Some peripheral controllers are known not to be able to
3878 * halt bulk endpoints correctly. If one of them is present,
3879 * disable stalls.
3881 if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
3882 mod_data.can_stall = 0;
3884 if (mod_data.release == 0xffff) { // Parameter wasn't set
3885 /* The sa1100 controller is not supported */
3886 if (gadget_is_sa1100(fsg->gadget))
3887 gcnum = -1;
3888 else
3889 gcnum = usb_gadget_controller_number(fsg->gadget);
3890 if (gcnum >= 0)
3891 mod_data.release = 0x0300 + gcnum;
3892 else {
3893 WARNING(fsg, "controller '%s' not recognized\n",
3894 fsg->gadget->name);
3895 mod_data.release = 0x0399;
3899 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3901 #ifdef CONFIG_USB_FILE_STORAGE_TEST
3902 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3903 ; // Use default setting
3904 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3905 mod_data.transport_type = USB_PR_CB;
3906 mod_data.transport_name = "Control-Bulk";
3907 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3908 mod_data.transport_type = USB_PR_CBI;
3909 mod_data.transport_name = "Control-Bulk-Interrupt";
3910 } else {
3911 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3912 return -EINVAL;
3915 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3916 prot == USB_SC_SCSI) {
3917 ; // Use default setting
3918 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3919 prot == USB_SC_RBC) {
3920 mod_data.protocol_type = USB_SC_RBC;
3921 mod_data.protocol_name = "RBC";
3922 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3923 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3924 prot == USB_SC_8020) {
3925 mod_data.protocol_type = USB_SC_8020;
3926 mod_data.protocol_name = "8020i (ATAPI)";
3927 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3928 prot == USB_SC_QIC) {
3929 mod_data.protocol_type = USB_SC_QIC;
3930 mod_data.protocol_name = "QIC-157";
3931 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3932 prot == USB_SC_UFI) {
3933 mod_data.protocol_type = USB_SC_UFI;
3934 mod_data.protocol_name = "UFI";
3935 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3936 prot == USB_SC_8070) {
3937 mod_data.protocol_type = USB_SC_8070;
3938 mod_data.protocol_name = "8070i";
3939 } else {
3940 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3941 return -EINVAL;
3944 mod_data.buflen &= PAGE_CACHE_MASK;
3945 if (mod_data.buflen <= 0) {
3946 ERROR(fsg, "invalid buflen\n");
3947 return -ETOOSMALL;
3949 #endif /* CONFIG_USB_FILE_STORAGE_TEST */
3951 return 0;
3955 static int __init fsg_bind(struct usb_gadget *gadget)
3957 struct fsg_dev *fsg = the_fsg;
3958 int rc;
3959 int i;
3960 struct lun *curlun;
3961 struct usb_ep *ep;
3962 struct usb_request *req;
3963 char *pathbuf, *p;
3965 fsg->gadget = gadget;
3966 set_gadget_data(gadget, fsg);
3967 fsg->ep0 = gadget->ep0;
3968 fsg->ep0->driver_data = fsg;
3970 if ((rc = check_parameters(fsg)) != 0)
3971 goto out;
3973 if (mod_data.removable) { // Enable the store_xxx attributes
3974 dev_attr_file.attr.mode = 0644;
3975 dev_attr_file.store = store_file;
3976 if (!mod_data.cdrom) {
3977 dev_attr_ro.attr.mode = 0644;
3978 dev_attr_ro.store = store_ro;
3982 /* Find out how many LUNs there should be */
3983 i = mod_data.nluns;
3984 if (i == 0)
3985 i = max(mod_data.num_filenames, 1u);
3986 if (i > MAX_LUNS) {
3987 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3988 rc = -EINVAL;
3989 goto out;
3992 /* Create the LUNs, open their backing files, and register the
3993 * LUN devices in sysfs. */
3994 fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL);
3995 if (!fsg->luns) {
3996 rc = -ENOMEM;
3997 goto out;
3999 fsg->nluns = i;
4001 for (i = 0; i < fsg->nluns; ++i) {
4002 curlun = &fsg->luns[i];
4003 curlun->ro = mod_data.ro[i];
4004 if (mod_data.cdrom)
4005 curlun->ro = 1;
4006 curlun->dev.release = lun_release;
4007 curlun->dev.parent = &gadget->dev;
4008 curlun->dev.driver = &fsg_driver.driver;
4009 dev_set_drvdata(&curlun->dev, fsg);
4010 dev_set_name(&curlun->dev,"%s-lun%d",
4011 dev_name(&gadget->dev), i);
4013 if ((rc = device_register(&curlun->dev)) != 0) {
4014 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
4015 goto out;
4017 if ((rc = device_create_file(&curlun->dev,
4018 &dev_attr_ro)) != 0 ||
4019 (rc = device_create_file(&curlun->dev,
4020 &dev_attr_file)) != 0) {
4021 device_unregister(&curlun->dev);
4022 goto out;
4024 curlun->registered = 1;
4025 kref_get(&fsg->ref);
4027 if (mod_data.file[i] && *mod_data.file[i]) {
4028 if ((rc = open_backing_file(curlun,
4029 mod_data.file[i])) != 0)
4030 goto out;
4031 } else if (!mod_data.removable) {
4032 ERROR(fsg, "no file given for LUN%d\n", i);
4033 rc = -EINVAL;
4034 goto out;
4038 /* Find all the endpoints we will use */
4039 usb_ep_autoconfig_reset(gadget);
4040 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
4041 if (!ep)
4042 goto autoconf_fail;
4043 ep->driver_data = fsg; // claim the endpoint
4044 fsg->bulk_in = ep;
4046 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
4047 if (!ep)
4048 goto autoconf_fail;
4049 ep->driver_data = fsg; // claim the endpoint
4050 fsg->bulk_out = ep;
4052 if (transport_is_cbi()) {
4053 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
4054 if (!ep)
4055 goto autoconf_fail;
4056 ep->driver_data = fsg; // claim the endpoint
4057 fsg->intr_in = ep;
4060 /* Fix up the descriptors */
4061 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
4062 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
4063 device_desc.idProduct = cpu_to_le16(mod_data.product);
4064 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
4066 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
4067 intf_desc.bNumEndpoints = i;
4068 intf_desc.bInterfaceSubClass = mod_data.protocol_type;
4069 intf_desc.bInterfaceProtocol = mod_data.transport_type;
4070 fs_function[i + FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
4072 if (gadget_is_dualspeed(gadget)) {
4073 hs_function[i + HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
4075 /* Assume ep0 uses the same maxpacket value for both speeds */
4076 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
4078 /* Assume endpoint addresses are the same for both speeds */
4079 hs_bulk_in_desc.bEndpointAddress =
4080 fs_bulk_in_desc.bEndpointAddress;
4081 hs_bulk_out_desc.bEndpointAddress =
4082 fs_bulk_out_desc.bEndpointAddress;
4083 hs_intr_in_desc.bEndpointAddress =
4084 fs_intr_in_desc.bEndpointAddress;
4087 if (gadget_is_otg(gadget))
4088 otg_desc.bmAttributes |= USB_OTG_HNP;
4090 rc = -ENOMEM;
4092 /* Allocate the request and buffer for endpoint 0 */
4093 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
4094 if (!req)
4095 goto out;
4096 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
4097 if (!req->buf)
4098 goto out;
4099 req->complete = ep0_complete;
4101 /* Allocate the data buffers */
4102 for (i = 0; i < NUM_BUFFERS; ++i) {
4103 struct fsg_buffhd *bh = &fsg->buffhds[i];
4105 /* Allocate for the bulk-in endpoint. We assume that
4106 * the buffer will also work with the bulk-out (and
4107 * interrupt-in) endpoint. */
4108 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
4109 if (!bh->buf)
4110 goto out;
4111 bh->next = bh + 1;
4113 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
4115 /* This should reflect the actual gadget power source */
4116 usb_gadget_set_selfpowered(gadget);
4118 snprintf(manufacturer, sizeof manufacturer, "%s %s with %s",
4119 init_utsname()->sysname, init_utsname()->release,
4120 gadget->name);
4122 /* On a real device, serial[] would be loaded from permanent
4123 * storage. We just encode it from the driver version string. */
4124 for (i = 0; i < sizeof(serial) - 2; i += 2) {
4125 unsigned char c = DRIVER_VERSION[i / 2];
4127 if (!c)
4128 break;
4129 sprintf(&serial[i], "%02X", c);
4132 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
4133 "file-storage-gadget");
4134 if (IS_ERR(fsg->thread_task)) {
4135 rc = PTR_ERR(fsg->thread_task);
4136 goto out;
4139 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
4140 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
4142 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4143 for (i = 0; i < fsg->nluns; ++i) {
4144 curlun = &fsg->luns[i];
4145 if (backing_file_is_open(curlun)) {
4146 p = NULL;
4147 if (pathbuf) {
4148 p = d_path(&curlun->filp->f_path,
4149 pathbuf, PATH_MAX);
4150 if (IS_ERR(p))
4151 p = NULL;
4153 LINFO(curlun, "ro=%d, file: %s\n",
4154 curlun->ro, (p ? p : "(error)"));
4157 kfree(pathbuf);
4159 DBG(fsg, "transport=%s (x%02x)\n",
4160 mod_data.transport_name, mod_data.transport_type);
4161 DBG(fsg, "protocol=%s (x%02x)\n",
4162 mod_data.protocol_name, mod_data.protocol_type);
4163 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
4164 mod_data.vendor, mod_data.product, mod_data.release);
4165 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
4166 mod_data.removable, mod_data.can_stall,
4167 mod_data.cdrom, mod_data.buflen);
4168 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
4170 set_bit(REGISTERED, &fsg->atomic_bitflags);
4172 /* Tell the thread to start working */
4173 wake_up_process(fsg->thread_task);
4174 return 0;
4176 autoconf_fail:
4177 ERROR(fsg, "unable to autoconfigure all endpoints\n");
4178 rc = -ENOTSUPP;
4180 out:
4181 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
4182 fsg_unbind(gadget);
4183 complete(&fsg->thread_notifier);
4184 return rc;
4188 /*-------------------------------------------------------------------------*/
4190 static void fsg_suspend(struct usb_gadget *gadget)
4192 struct fsg_dev *fsg = get_gadget_data(gadget);
4194 DBG(fsg, "suspend\n");
4195 set_bit(SUSPENDED, &fsg->atomic_bitflags);
4198 static void fsg_resume(struct usb_gadget *gadget)
4200 struct fsg_dev *fsg = get_gadget_data(gadget);
4202 DBG(fsg, "resume\n");
4203 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
4207 /*-------------------------------------------------------------------------*/
4209 static struct usb_gadget_driver fsg_driver = {
4210 #ifdef CONFIG_USB_GADGET_DUALSPEED
4211 .speed = USB_SPEED_HIGH,
4212 #else
4213 .speed = USB_SPEED_FULL,
4214 #endif
4215 .function = (char *) longname,
4216 .bind = fsg_bind,
4217 .unbind = fsg_unbind,
4218 .disconnect = fsg_disconnect,
4219 .setup = fsg_setup,
4220 .suspend = fsg_suspend,
4221 .resume = fsg_resume,
4223 .driver = {
4224 .name = (char *) shortname,
4225 .owner = THIS_MODULE,
4226 // .release = ...
4227 // .suspend = ...
4228 // .resume = ...
4233 static int __init fsg_alloc(void)
4235 struct fsg_dev *fsg;
4237 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
4238 if (!fsg)
4239 return -ENOMEM;
4240 spin_lock_init(&fsg->lock);
4241 init_rwsem(&fsg->filesem);
4242 kref_init(&fsg->ref);
4243 init_completion(&fsg->thread_notifier);
4245 the_fsg = fsg;
4246 return 0;
4250 static int __init fsg_init(void)
4252 int rc;
4253 struct fsg_dev *fsg;
4255 if ((rc = fsg_alloc()) != 0)
4256 return rc;
4257 fsg = the_fsg;
4258 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
4259 kref_put(&fsg->ref, fsg_release);
4260 return rc;
4262 module_init(fsg_init);
4265 static void __exit fsg_cleanup(void)
4267 struct fsg_dev *fsg = the_fsg;
4269 /* Unregister the driver iff the thread hasn't already done so */
4270 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4271 usb_gadget_unregister_driver(&fsg_driver);
4273 /* Wait for the thread to finish up */
4274 wait_for_completion(&fsg->thread_notifier);
4276 kref_put(&fsg->ref, fsg_release);
4278 module_exit(fsg_cleanup);