blob: aae04c20b0eade080fb0ee279ed49922b5c44acd [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
3 *
Alan Stern12aae682008-11-20 14:13:12 -05004 * Copyright (C) 2003-2008 Alan Stern
Linus Torvalds1da177e2005-04-16 15:20:36 -07005 * All rights reserved.
6 *
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.
19 *
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.
24 *
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.
36 */
37
38
39/*
40 * The File-backed Storage Gadget acts as a USB Mass Storage device,
Alan Stern12aae682008-11-20 14:13:12 -050041 * 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.
Linus Torvalds1da177e2005-04-16 15:20:36 -070046 *
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
Alan Stern12aae682008-11-20 14:13:12 -050049 * 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.
Linus Torvalds1da177e2005-04-16 15:20:36 -070052 *
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
Yann Cantin87eb1be2010-06-05 23:06:31 +020059 * Vendor ID, Product ID, release number and serial number can be overridden.
Linus Torvalds1da177e2005-04-16 15:20:36 -070060 *
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
Alan Stern12aae682008-11-20 14:13:12 -050068 * 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.
Linus Torvalds1da177e2005-04-16 15:20:36 -070074 *
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.
79 *
Alan Stern14cd5f82006-03-23 15:07:25 -050080 * 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.
85 *
Linus Torvalds1da177e2005-04-16 15:20:36 -070086 * Module options:
87 *
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
Andy Shevchenkoa93917d2010-07-22 17:53:56 +030096 * nofua=b[,b...] Default false, booleans for ignore FUA flag
97 * in SCSI WRITE(10,12) commands
Alan Sternd794ac72005-04-18 12:43:25 -040098 * stall Default determined according to the type of
99 * USB device controller (usually true),
100 * boolean to permit the driver to halt
101 * bulk endpoints
Alan Stern12aae682008-11-20 14:13:12 -0500102 * cdrom Default false, boolean for whether to emulate
103 * a CD-ROM drive
Linus Torvalds1da177e2005-04-16 15:20:36 -0700104 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
105 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
106 * ATAPI, QIC, UFI, 8070, or SCSI;
107 * also 1 - 6)
108 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
109 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
110 * release=0xRRRR Override the USB release number (bcdDevice)
Yann Cantin87eb1be2010-06-05 23:06:31 +0200111 * serial=HHHH... Override serial number (string of hex chars)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700112 * buflen=N Default N=16384, buffer size used (will be
113 * rounded down to a multiple of
114 * PAGE_CACHE_SIZE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700115 *
116 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300117 * "removable", "luns", "nofua", "stall", and "cdrom" options are available;
118 * default values are used for everything else.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700119 *
120 * The pathnames of the backing files and the ro settings are available in
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300121 * the attribute files "file", "nofua", and "ro" in the lun<n> subdirectory of
122 * the gadget's sysfs directory. If the "removable" option is set, writing to
Linus Torvalds1da177e2005-04-16 15:20:36 -0700123 * these files will simulate ejecting/loading the medium (writing an empty
124 * line means eject) and adjusting a write-enable tab. Changes to the ro
Alan Stern12aae682008-11-20 14:13:12 -0500125 * setting are not allowed when the medium is loaded or if CD-ROM emulation
126 * is being used.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700127 *
128 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
Alan Sternaafe5bd2006-03-31 11:46:43 -0500129 * The driver's SCSI command interface was based on the "Information
130 * technology - Small Computer System Interface - 2" document from
131 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
132 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
133 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
134 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
135 * document, Revision 1.0, December 14, 1998, available at
136 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700137 */
138
139
140/*
141 * Driver Design
142 *
143 * The FSG driver is fairly straightforward. There is a main kernel
144 * thread that handles most of the work. Interrupt routines field
145 * callbacks from the controller driver: bulk- and interrupt-request
146 * completion notifications, endpoint-0 events, and disconnect events.
147 * Completion events are passed to the main thread by wakeup calls. Many
148 * ep0 requests are handled at interrupt time, but SetInterface,
149 * SetConfiguration, and device reset requests are forwarded to the
150 * thread in the form of "exceptions" using SIGUSR1 signals (since they
151 * should interrupt any ongoing file I/O operations).
152 *
153 * The thread's main routine implements the standard command/data/status
154 * parts of a SCSI interaction. It and its subroutines are full of tests
155 * for pending signals/exceptions -- all this polling is necessary since
156 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
157 * indication that the driver really wants to be running in userspace.)
158 * An important point is that so long as the thread is alive it keeps an
159 * open reference to the backing file. This will prevent unmounting
160 * the backing file's underlying filesystem and could cause problems
161 * during system shutdown, for example. To prevent such problems, the
162 * thread catches INT, TERM, and KILL signals and converts them into
163 * an EXIT exception.
164 *
165 * In normal operation the main thread is started during the gadget's
166 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
167 * exit when it receives a signal, and there's no point leaving the
168 * gadget running when the thread is dead. So just before the thread
169 * exits, it deregisters the gadget driver. This makes things a little
170 * tricky: The driver is deregistered at two places, and the exiting
171 * thread can indirectly call fsg_unbind() which in turn can tell the
172 * thread to exit. The first problem is resolved through the use of the
173 * REGISTERED atomic bitflag; the driver will only be deregistered once.
174 * The second problem is resolved by having fsg_unbind() check
175 * fsg->state; it won't try to stop the thread if the state is already
176 * FSG_STATE_TERMINATED.
177 *
178 * To provide maximum throughput, the driver uses a circular pipeline of
179 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
180 * arbitrarily long; in practice the benefits don't justify having more
181 * than 2 stages (i.e., double buffering). But it helps to think of the
182 * pipeline as being a long one. Each buffer head contains a bulk-in and
183 * a bulk-out request pointer (since the buffer can be used for both
184 * output and input -- directions always are given from the host's
185 * point of view) as well as a pointer to the buffer and various state
186 * variables.
187 *
188 * Use of the pipeline follows a simple protocol. There is a variable
189 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
190 * At any time that buffer head may still be in use from an earlier
191 * request, so each buffer head has a state variable indicating whether
192 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
193 * buffer head to be EMPTY, filling the buffer either by file I/O or by
194 * USB I/O (during which the buffer head is BUSY), and marking the buffer
195 * head FULL when the I/O is complete. Then the buffer will be emptied
196 * (again possibly by USB I/O, during which it is marked BUSY) and
197 * finally marked EMPTY again (possibly by a completion routine).
198 *
199 * A module parameter tells the driver to avoid stalling the bulk
200 * endpoints wherever the transport specification allows. This is
201 * necessary for some UDCs like the SuperH, which cannot reliably clear a
202 * halt on a bulk endpoint. However, under certain circumstances the
203 * Bulk-only specification requires a stall. In such cases the driver
204 * will halt the endpoint and set a flag indicating that it should clear
205 * the halt in software during the next device reset. Hopefully this
206 * will permit everything to work correctly. Furthermore, although the
207 * specification allows the bulk-out endpoint to halt when the host sends
208 * too much data, implementing this would cause an unavoidable race.
209 * The driver will always use the "no-stall" approach for OUT transfers.
210 *
211 * One subtle point concerns sending status-stage responses for ep0
212 * requests. Some of these requests, such as device reset, can involve
213 * interrupting an ongoing file I/O operation, which might take an
214 * arbitrarily long time. During that delay the host might give up on
215 * the original ep0 request and issue a new one. When that happens the
216 * driver should not notify the host about completion of the original
217 * request, as the host will no longer be waiting for it. So the driver
218 * assigns to each ep0 request a unique tag, and it keeps track of the
219 * tag value of the request associated with a long-running exception
220 * (device-reset, interface-change, or configuration-change). When the
221 * exception handler is finished, the status-stage response is submitted
222 * only if the current ep0 request tag is equal to the exception request
223 * tag. Thus only the most recently received ep0 request will get a
224 * status-stage response.
225 *
226 * Warning: This driver source file is too long. It ought to be split up
227 * into a header file plus about 3 separate .c files, to handle the details
228 * of the Gadget, USB Mass Storage, and SCSI protocols.
229 */
230
231
David Brownell2e806f62007-08-02 00:03:39 -0700232/* #define VERBOSE_DEBUG */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400233/* #define DUMP_MSGS */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700234
Linus Torvalds1da177e2005-04-16 15:20:36 -0700235
Linus Torvalds1da177e2005-04-16 15:20:36 -0700236#include <linux/blkdev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700237#include <linux/completion.h>
238#include <linux/dcache.h>
239#include <linux/delay.h>
240#include <linux/device.h>
241#include <linux/fcntl.h>
242#include <linux/file.h>
243#include <linux/fs.h>
Alan Stern87c42522005-11-09 16:59:56 -0500244#include <linux/kref.h>
Alan Stern22efcf42005-09-26 16:12:02 -0400245#include <linux/kthread.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700246#include <linux/limits.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700247#include <linux/rwsem.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700248#include <linux/slab.h>
249#include <linux/spinlock.h>
250#include <linux/string.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -0800251#include <linux/freezer.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700252#include <linux/utsname.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700253
David Brownell5f848132006-12-16 15:34:53 -0800254#include <linux/usb/ch9.h>
David Brownell9454a572007-10-04 18:05:17 -0700255#include <linux/usb/gadget.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700256
257#include "gadget_chips.h"
258
259
David Brownell352e2b92008-08-18 17:43:25 -0700260
261/*
262 * Kbuild is not very cooperative with respect to linking separately
263 * compiled library objects into one module. So for now we won't use
264 * separate compilation ... ensuring init/exit sections work to shrink
265 * the runtime footprint, and giving us at least some parts of what
266 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
267 */
268#include "usbstring.c"
269#include "config.c"
270#include "epautoconf.c"
271
Linus Torvalds1da177e2005-04-16 15:20:36 -0700272/*-------------------------------------------------------------------------*/
273
274#define DRIVER_DESC "File-backed Storage Gadget"
275#define DRIVER_NAME "g_file_storage"
Yann Cantin87eb1be2010-06-05 23:06:31 +0200276/* DRIVER_VERSION must be at least 6 characters long, as it is used
277 * to generate a fallback serial number. */
Alan Stern12aae682008-11-20 14:13:12 -0500278#define DRIVER_VERSION "20 November 2008"
Linus Torvalds1da177e2005-04-16 15:20:36 -0700279
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100280static char fsg_string_manufacturer[64];
281static const char fsg_string_product[] = DRIVER_DESC;
282static char fsg_string_serial[13];
283static const char fsg_string_config[] = "Self-powered";
284static const char fsg_string_interface[] = "Mass Storage";
Linus Torvalds1da177e2005-04-16 15:20:36 -0700285
Michal Nazarewicz93f93742009-10-28 16:57:17 +0100286
287#include "storage_common.c"
288
289
Linus Torvalds1da177e2005-04-16 15:20:36 -0700290MODULE_DESCRIPTION(DRIVER_DESC);
291MODULE_AUTHOR("Alan Stern");
292MODULE_LICENSE("Dual BSD/GPL");
293
Linus Torvalds1da177e2005-04-16 15:20:36 -0700294/*
295 * This driver assumes self-powered hardware and has no way for users to
296 * trigger remote wakeup. It uses autoconfiguration to select endpoints
297 * and endpoint addresses.
298 */
299
300
301/*-------------------------------------------------------------------------*/
302
Linus Torvalds1da177e2005-04-16 15:20:36 -0700303
304/* Encapsulate the module parameter settings */
305
Linus Torvalds1da177e2005-04-16 15:20:36 -0700306static struct {
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100307 char *file[FSG_MAX_LUNS];
308 int ro[FSG_MAX_LUNS];
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300309 int nofua[FSG_MAX_LUNS];
David Brownell2e806f62007-08-02 00:03:39 -0700310 unsigned int num_filenames;
311 unsigned int num_ros;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300312 unsigned int num_nofuas;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700313 unsigned int nluns;
314
Alan Sternd794ac72005-04-18 12:43:25 -0400315 int removable;
316 int can_stall;
Alan Stern12aae682008-11-20 14:13:12 -0500317 int cdrom;
Alan Sternd794ac72005-04-18 12:43:25 -0400318
Linus Torvalds1da177e2005-04-16 15:20:36 -0700319 char *transport_parm;
320 char *protocol_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700321 unsigned short vendor;
322 unsigned short product;
323 unsigned short release;
Michal Nazarewicz56706492010-07-22 14:16:37 +0200324 char *serial;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700325 unsigned int buflen;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700326
327 int transport_type;
328 char *transport_name;
329 int protocol_type;
330 char *protocol_name;
331
332} mod_data = { // Default values
333 .transport_parm = "BBB",
334 .protocol_parm = "SCSI",
335 .removable = 0,
Alan Sternd794ac72005-04-18 12:43:25 -0400336 .can_stall = 1,
Alan Stern12aae682008-11-20 14:13:12 -0500337 .cdrom = 0,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100338 .vendor = FSG_VENDOR_ID,
339 .product = FSG_PRODUCT_ID,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700340 .release = 0xffff, // Use controller chip type
341 .buflen = 16384,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700342 };
343
344
Alan Sternaafe5bd2006-03-31 11:46:43 -0500345module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
346 S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700347MODULE_PARM_DESC(file, "names of backing files or devices");
348
Alan Sternaafe5bd2006-03-31 11:46:43 -0500349module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700350MODULE_PARM_DESC(ro, "true to force read-only");
351
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300352module_param_array_named(nofua, mod_data.nofua, bool, &mod_data.num_nofuas,
353 S_IRUGO);
354MODULE_PARM_DESC(nofua, "true to ignore SCSI WRITE(10,12) FUA bit");
355
Linus Torvalds1da177e2005-04-16 15:20:36 -0700356module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
357MODULE_PARM_DESC(luns, "number of LUNs");
358
359module_param_named(removable, mod_data.removable, bool, S_IRUGO);
360MODULE_PARM_DESC(removable, "true to simulate removable media");
361
Alan Sternd794ac72005-04-18 12:43:25 -0400362module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
363MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
364
Alan Stern12aae682008-11-20 14:13:12 -0500365module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
366MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
367
Michal Nazarewicz56706492010-07-22 14:16:37 +0200368module_param_named(serial, mod_data.serial, charp, S_IRUGO);
369MODULE_PARM_DESC(serial, "USB serial number");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700370
371/* In the non-TEST version, only the module parameters listed above
372 * are available. */
373#ifdef CONFIG_USB_FILE_STORAGE_TEST
374
375module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
376MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
377
378module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
379MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
380 "8070, or SCSI)");
381
382module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
383MODULE_PARM_DESC(vendor, "USB Vendor ID");
384
385module_param_named(product, mod_data.product, ushort, S_IRUGO);
386MODULE_PARM_DESC(product, "USB Product ID");
387
388module_param_named(release, mod_data.release, ushort, S_IRUGO);
389MODULE_PARM_DESC(release, "USB release number");
390
391module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
392MODULE_PARM_DESC(buflen, "I/O buffer size");
393
Linus Torvalds1da177e2005-04-16 15:20:36 -0700394#endif /* CONFIG_USB_FILE_STORAGE_TEST */
395
396
Linus Torvalds1da177e2005-04-16 15:20:36 -0700397/*
398 * These definitions will permit the compiler to avoid generating code for
399 * parts of the driver that aren't used in the non-TEST version. Even gcc
400 * can recognize when a test of a constant expression yields a dead code
401 * path.
402 */
403
404#ifdef CONFIG_USB_FILE_STORAGE_TEST
405
406#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
407#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
408#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
409
410#else
411
412#define transport_is_bbb() 1
413#define transport_is_cbi() 0
414#define protocol_is_scsi() 1
415
416#endif /* CONFIG_USB_FILE_STORAGE_TEST */
417
418
Michal Nazarewiczb6058d02009-10-28 16:57:14 +0100419/*-------------------------------------------------------------------------*/
Linus Torvalds1da177e2005-04-16 15:20:36 -0700420
Linus Torvalds1da177e2005-04-16 15:20:36 -0700421
422struct fsg_dev {
423 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
424 spinlock_t lock;
425 struct usb_gadget *gadget;
426
427 /* filesem protects: backing files in use */
428 struct rw_semaphore filesem;
429
Alan Stern87c42522005-11-09 16:59:56 -0500430 /* reference counting: wait until all LUNs are released */
431 struct kref ref;
432
Linus Torvalds1da177e2005-04-16 15:20:36 -0700433 struct usb_ep *ep0; // Handy copy of gadget->ep0
434 struct usb_request *ep0req; // For control responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500435 unsigned int ep0_req_tag;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700436 const char *ep0req_name;
437
438 struct usb_request *intreq; // For interrupt responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500439 int intreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700440 struct fsg_buffhd *intr_buffhd;
441
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100442 unsigned int bulk_out_maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700443 enum fsg_state state; // For exception handling
444 unsigned int exception_req_tag;
445
446 u8 config, new_config;
447
448 unsigned int running : 1;
449 unsigned int bulk_in_enabled : 1;
450 unsigned int bulk_out_enabled : 1;
451 unsigned int intr_in_enabled : 1;
452 unsigned int phase_error : 1;
453 unsigned int short_packet_received : 1;
454 unsigned int bad_lun_okay : 1;
455
456 unsigned long atomic_bitflags;
457#define REGISTERED 0
Alan Sternb950bdb2008-04-14 11:45:29 -0400458#define IGNORE_BULK_OUT 1
Linus Torvalds1da177e2005-04-16 15:20:36 -0700459#define SUSPENDED 2
460
461 struct usb_ep *bulk_in;
462 struct usb_ep *bulk_out;
463 struct usb_ep *intr_in;
464
465 struct fsg_buffhd *next_buffhd_to_fill;
466 struct fsg_buffhd *next_buffhd_to_drain;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100467 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700468
Linus Torvalds1da177e2005-04-16 15:20:36 -0700469 int thread_wakeup_needed;
470 struct completion thread_notifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700471 struct task_struct *thread_task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700472
473 int cmnd_size;
474 u8 cmnd[MAX_COMMAND_SIZE];
475 enum data_direction data_dir;
476 u32 data_size;
477 u32 data_size_from_cmnd;
478 u32 tag;
479 unsigned int lun;
480 u32 residue;
481 u32 usb_amount_left;
482
483 /* The CB protocol offers no way for a host to know when a command
484 * has completed. As a result the next command may arrive early,
485 * and we will still have to handle it. For that reason we need
486 * a buffer to store new commands when using CB (or CBI, which
487 * does not oblige a host to wait for command completion either). */
488 int cbbuf_cmnd_size;
489 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
490
491 unsigned int nluns;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100492 struct fsg_lun *luns;
493 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700494};
495
496typedef void (*fsg_routine_t)(struct fsg_dev *);
497
Alan Stern79a7d9e2007-08-08 17:10:11 -0400498static int exception_in_progress(struct fsg_dev *fsg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700499{
500 return (fsg->state > FSG_STATE_IDLE);
501}
502
503/* Make bulk-out requests be divisible by the maxpacket size */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400504static void set_bulk_out_req_length(struct fsg_dev *fsg,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700505 struct fsg_buffhd *bh, unsigned int length)
506{
507 unsigned int rem;
508
509 bh->bulk_out_intended_length = length;
510 rem = length % fsg->bulk_out_maxpacket;
511 if (rem > 0)
512 length += fsg->bulk_out_maxpacket - rem;
513 bh->outreq->length = length;
514}
515
516static struct fsg_dev *the_fsg;
517static struct usb_gadget_driver fsg_driver;
518
Linus Torvalds1da177e2005-04-16 15:20:36 -0700519
520/*-------------------------------------------------------------------------*/
521
Linus Torvalds1da177e2005-04-16 15:20:36 -0700522static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
523{
524 const char *name;
525
526 if (ep == fsg->bulk_in)
527 name = "bulk-in";
528 else if (ep == fsg->bulk_out)
529 name = "bulk-out";
530 else
531 name = ep->name;
532 DBG(fsg, "%s set halt\n", name);
533 return usb_ep_set_halt(ep);
534}
535
536
537/*-------------------------------------------------------------------------*/
538
Linus Torvalds1da177e2005-04-16 15:20:36 -0700539/*
540 * DESCRIPTORS ... most are static, but strings and (full) configuration
541 * descriptors are built on demand. Also the (static) config and interface
542 * descriptors are adjusted during fsg_bind().
543 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700544
545/* There is only one configuration. */
546#define CONFIG_VALUE 1
547
548static struct usb_device_descriptor
549device_desc = {
550 .bLength = sizeof device_desc,
551 .bDescriptorType = USB_DT_DEVICE,
552
Harvey Harrison551509d2009-02-11 14:11:36 -0800553 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700554 .bDeviceClass = USB_CLASS_PER_INTERFACE,
555
556 /* The next three values can be overridden by module parameters */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100557 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
558 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
Harvey Harrison551509d2009-02-11 14:11:36 -0800559 .bcdDevice = cpu_to_le16(0xffff),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700560
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100561 .iManufacturer = FSG_STRING_MANUFACTURER,
562 .iProduct = FSG_STRING_PRODUCT,
563 .iSerialNumber = FSG_STRING_SERIAL,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700564 .bNumConfigurations = 1,
565};
566
567static struct usb_config_descriptor
568config_desc = {
569 .bLength = sizeof config_desc,
570 .bDescriptorType = USB_DT_CONFIG,
571
572 /* wTotalLength computed by usb_gadget_config_buf() */
573 .bNumInterfaces = 1,
574 .bConfigurationValue = CONFIG_VALUE,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100575 .iConfiguration = FSG_STRING_CONFIG,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700576 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
David Brownell36e893d2008-09-12 09:39:06 -0700577 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700578};
579
Linus Torvalds1da177e2005-04-16 15:20:36 -0700580
Linus Torvalds1da177e2005-04-16 15:20:36 -0700581static struct usb_qualifier_descriptor
582dev_qualifier = {
583 .bLength = sizeof dev_qualifier,
584 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
585
Harvey Harrison551509d2009-02-11 14:11:36 -0800586 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700587 .bDeviceClass = USB_CLASS_PER_INTERFACE,
588
589 .bNumConfigurations = 1,
590};
591
Linus Torvalds1da177e2005-04-16 15:20:36 -0700592
593
594/*
595 * Config descriptors must agree with the code that sets configurations
596 * and with code managing interfaces and their altsettings. They must
597 * also handle different speeds and other-speed requests.
598 */
599static int populate_config_buf(struct usb_gadget *gadget,
600 u8 *buf, u8 type, unsigned index)
601{
Linus Torvalds1da177e2005-04-16 15:20:36 -0700602 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700603 int len;
604 const struct usb_descriptor_header **function;
605
606 if (index > 0)
607 return -EINVAL;
608
David Brownell2e806f62007-08-02 00:03:39 -0700609 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700610 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
Michal Nazarewiczd23b0f02009-11-09 14:15:20 +0100611 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
612 ? (const struct usb_descriptor_header **)fsg_hs_function
613 : (const struct usb_descriptor_header **)fsg_fs_function;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700614
615 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -0700616 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700617 function++;
618
619 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
620 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
621 return len;
622}
623
624
625/*-------------------------------------------------------------------------*/
626
627/* These routines may be called in process context or in_irq */
628
Alan Sterna21d4fe2005-11-29 12:04:24 -0500629/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700630static void wakeup_thread(struct fsg_dev *fsg)
631{
632 /* Tell the main thread that something has happened */
633 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500634 if (fsg->thread_task)
635 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700636}
637
638
639static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
640{
641 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700642
643 /* Do nothing if a higher-priority exception is already in progress.
644 * If a lower-or-equal priority exception is in progress, preempt it
645 * and notify the main thread by sending it a signal. */
646 spin_lock_irqsave(&fsg->lock, flags);
647 if (fsg->state <= new_state) {
648 fsg->exception_req_tag = fsg->ep0_req_tag;
649 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -0400650 if (fsg->thread_task)
651 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
652 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700653 }
654 spin_unlock_irqrestore(&fsg->lock, flags);
655}
656
657
658/*-------------------------------------------------------------------------*/
659
660/* The disconnect callback and ep0 routines. These always run in_irq,
661 * except that ep0_queue() is called in the main thread to acknowledge
662 * completion of various requests: set config, set interface, and
663 * Bulk-only device reset. */
664
665static void fsg_disconnect(struct usb_gadget *gadget)
666{
667 struct fsg_dev *fsg = get_gadget_data(gadget);
668
669 DBG(fsg, "disconnect or port reset\n");
670 raise_exception(fsg, FSG_STATE_DISCONNECT);
671}
672
673
674static int ep0_queue(struct fsg_dev *fsg)
675{
676 int rc;
677
678 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
679 if (rc != 0 && rc != -ESHUTDOWN) {
680
681 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -0700682 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -0700683 fsg->ep0->name, rc);
684 }
685 return rc;
686}
687
688static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
689{
John Daiker7ca46b82006-12-29 19:02:06 -0800690 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700691
692 if (req->actual > 0)
693 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
694 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800695 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700696 req->status, req->actual, req->length);
697 if (req->status == -ECONNRESET) // Request was cancelled
698 usb_ep_fifo_flush(ep);
699
700 if (req->status == 0 && req->context)
701 ((fsg_routine_t) (req->context))(fsg);
702}
703
704
705/*-------------------------------------------------------------------------*/
706
707/* Bulk and interrupt endpoint completion handlers.
708 * These always run in_irq. */
709
710static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
711{
John Daiker7ca46b82006-12-29 19:02:06 -0800712 struct fsg_dev *fsg = ep->driver_data;
713 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700714
715 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800716 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700717 req->status, req->actual, req->length);
718 if (req->status == -ECONNRESET) // Request was cancelled
719 usb_ep_fifo_flush(ep);
720
721 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500722 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700723 spin_lock(&fsg->lock);
724 bh->inreq_busy = 0;
725 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700726 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500727 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700728}
729
730static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
731{
John Daiker7ca46b82006-12-29 19:02:06 -0800732 struct fsg_dev *fsg = ep->driver_data;
733 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700734
735 dump_msg(fsg, "bulk-out", req->buf, req->actual);
736 if (req->status || req->actual != bh->bulk_out_intended_length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800737 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700738 req->status, req->actual,
739 bh->bulk_out_intended_length);
740 if (req->status == -ECONNRESET) // Request was cancelled
741 usb_ep_fifo_flush(ep);
742
743 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500744 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700745 spin_lock(&fsg->lock);
746 bh->outreq_busy = 0;
747 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700748 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500749 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700750}
751
752
753#ifdef CONFIG_USB_FILE_STORAGE_TEST
754static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
755{
John Daiker7ca46b82006-12-29 19:02:06 -0800756 struct fsg_dev *fsg = ep->driver_data;
757 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700758
759 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800760 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700761 req->status, req->actual, req->length);
762 if (req->status == -ECONNRESET) // Request was cancelled
763 usb_ep_fifo_flush(ep);
764
765 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500766 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700767 spin_lock(&fsg->lock);
768 fsg->intreq_busy = 0;
769 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700770 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500771 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700772}
773
774#else
775static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
776{}
777#endif /* CONFIG_USB_FILE_STORAGE_TEST */
778
779
780/*-------------------------------------------------------------------------*/
781
782/* Ep0 class-specific handlers. These always run in_irq. */
783
784#ifdef CONFIG_USB_FILE_STORAGE_TEST
785static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
786{
787 struct usb_request *req = fsg->ep0req;
788 static u8 cbi_reset_cmnd[6] = {
789 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
790
791 /* Error in command transfer? */
792 if (req->status || req->length != req->actual ||
793 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
794
795 /* Not all controllers allow a protocol stall after
796 * receiving control-out data, but we'll try anyway. */
797 fsg_set_halt(fsg, fsg->ep0);
798 return; // Wait for reset
799 }
800
801 /* Is it the special reset command? */
802 if (req->actual >= sizeof cbi_reset_cmnd &&
803 memcmp(req->buf, cbi_reset_cmnd,
804 sizeof cbi_reset_cmnd) == 0) {
805
806 /* Raise an exception to stop the current operation
807 * and reinitialize our state. */
808 DBG(fsg, "cbi reset request\n");
809 raise_exception(fsg, FSG_STATE_RESET);
810 return;
811 }
812
813 VDBG(fsg, "CB[I] accept device-specific command\n");
814 spin_lock(&fsg->lock);
815
816 /* Save the command for later */
817 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700818 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700819 fsg->cbbuf_cmnd_size = req->actual;
820 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
821
Linus Torvalds1da177e2005-04-16 15:20:36 -0700822 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500823 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700824}
825
826#else
827static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
828{}
829#endif /* CONFIG_USB_FILE_STORAGE_TEST */
830
831
832static int class_setup_req(struct fsg_dev *fsg,
833 const struct usb_ctrlrequest *ctrl)
834{
835 struct usb_request *req = fsg->ep0req;
836 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700837 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -0400838 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -0700839 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700840
841 if (!fsg->config)
842 return value;
843
844 /* Handle Bulk-only class-specific requests */
845 if (transport_is_bbb()) {
846 switch (ctrl->bRequest) {
847
848 case USB_BULK_RESET_REQUEST:
849 if (ctrl->bRequestType != (USB_DIR_OUT |
850 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
851 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400852 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700853 value = -EDOM;
854 break;
855 }
856
857 /* Raise an exception to stop the current operation
858 * and reinitialize our state. */
859 DBG(fsg, "bulk reset request\n");
860 raise_exception(fsg, FSG_STATE_RESET);
861 value = DELAYED_STATUS;
862 break;
863
864 case USB_BULK_GET_MAX_LUN_REQUEST:
865 if (ctrl->bRequestType != (USB_DIR_IN |
866 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
867 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400868 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700869 value = -EDOM;
870 break;
871 }
872 VDBG(fsg, "get max LUN\n");
873 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -0400874 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700875 break;
876 }
877 }
878
879 /* Handle CBI class-specific requests */
880 else {
881 switch (ctrl->bRequest) {
882
883 case USB_CBI_ADSC_REQUEST:
884 if (ctrl->bRequestType != (USB_DIR_OUT |
885 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
886 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400887 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700888 value = -EDOM;
889 break;
890 }
891 if (w_length > MAX_COMMAND_SIZE) {
892 value = -EOVERFLOW;
893 break;
894 }
895 value = w_length;
896 fsg->ep0req->context = received_cbi_adsc;
897 break;
898 }
899 }
900
901 if (value == -EOPNOTSUPP)
902 VDBG(fsg,
903 "unknown class-specific control req "
904 "%02x.%02x v%04x i%04x l%u\n",
905 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -0700906 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700907 return value;
908}
909
910
911/*-------------------------------------------------------------------------*/
912
913/* Ep0 standard request handlers. These always run in_irq. */
914
915static int standard_setup_req(struct fsg_dev *fsg,
916 const struct usb_ctrlrequest *ctrl)
917{
918 struct usb_request *req = fsg->ep0req;
919 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700920 u16 w_index = le16_to_cpu(ctrl->wIndex);
921 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700922
923 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
924 * but config change events will also reconfigure hardware. */
925 switch (ctrl->bRequest) {
926
927 case USB_REQ_GET_DESCRIPTOR:
928 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
929 USB_RECIP_DEVICE))
930 break;
931 switch (w_value >> 8) {
932
933 case USB_DT_DEVICE:
934 VDBG(fsg, "get device descriptor\n");
Alan Stern76f4af82005-04-05 11:56:54 -0400935 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936 memcpy(req->buf, &device_desc, value);
937 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700938 case USB_DT_DEVICE_QUALIFIER:
939 VDBG(fsg, "get device qualifier\n");
David Brownell2e806f62007-08-02 00:03:39 -0700940 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700941 break;
Alan Stern76f4af82005-04-05 11:56:54 -0400942 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700943 memcpy(req->buf, &dev_qualifier, value);
944 break;
945
946 case USB_DT_OTHER_SPEED_CONFIG:
947 VDBG(fsg, "get other-speed config descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700948 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700949 break;
950 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951 case USB_DT_CONFIG:
952 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700953get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700954 value = populate_config_buf(fsg->gadget,
955 req->buf,
956 w_value >> 8,
957 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700958 break;
959
960 case USB_DT_STRING:
961 VDBG(fsg, "get string descriptor\n");
962
963 /* wIndex == language code */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100964 value = usb_gadget_get_string(&fsg_stringtab,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700965 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700966 break;
967 }
968 break;
969
970 /* One config, two speeds */
971 case USB_REQ_SET_CONFIGURATION:
972 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
973 USB_RECIP_DEVICE))
974 break;
975 VDBG(fsg, "set configuration\n");
976 if (w_value == CONFIG_VALUE || w_value == 0) {
977 fsg->new_config = w_value;
978
979 /* Raise an exception to wipe out previous transaction
980 * state (queued bufs, etc) and set the new config. */
981 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
982 value = DELAYED_STATUS;
983 }
984 break;
985 case USB_REQ_GET_CONFIGURATION:
986 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
987 USB_RECIP_DEVICE))
988 break;
989 VDBG(fsg, "get configuration\n");
990 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -0400991 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700992 break;
993
994 case USB_REQ_SET_INTERFACE:
995 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
996 USB_RECIP_INTERFACE))
997 break;
998 if (fsg->config && w_index == 0) {
999
1000 /* Raise an exception to wipe out previous transaction
1001 * state (queued bufs, etc) and install the new
1002 * interface altsetting. */
1003 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1004 value = DELAYED_STATUS;
1005 }
1006 break;
1007 case USB_REQ_GET_INTERFACE:
1008 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1009 USB_RECIP_INTERFACE))
1010 break;
1011 if (!fsg->config)
1012 break;
1013 if (w_index != 0) {
1014 value = -EDOM;
1015 break;
1016 }
1017 VDBG(fsg, "get interface\n");
1018 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001019 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001020 break;
1021
1022 default:
1023 VDBG(fsg,
1024 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1025 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001026 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001027 }
1028
1029 return value;
1030}
1031
1032
1033static int fsg_setup(struct usb_gadget *gadget,
1034 const struct usb_ctrlrequest *ctrl)
1035{
1036 struct fsg_dev *fsg = get_gadget_data(gadget);
1037 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001038 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001039
1040 ++fsg->ep0_req_tag; // Record arrival of a new request
1041 fsg->ep0req->context = NULL;
1042 fsg->ep0req->length = 0;
1043 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1044
1045 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1046 rc = class_setup_req(fsg, ctrl);
1047 else
1048 rc = standard_setup_req(fsg, ctrl);
1049
1050 /* Respond with data/status or defer until later? */
1051 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001052 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001053 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001054 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001055 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1056 "ep0-in" : "ep0-out");
1057 rc = ep0_queue(fsg);
1058 }
1059
1060 /* Device either stalls (rc < 0) or reports success */
1061 return rc;
1062}
1063
1064
1065/*-------------------------------------------------------------------------*/
1066
1067/* All the following routines run in process context */
1068
1069
1070/* Use this for bulk or interrupt transfers, not ep0 */
1071static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001072 struct usb_request *req, int *pbusy,
1073 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001074{
1075 int rc;
1076
1077 if (ep == fsg->bulk_in)
1078 dump_msg(fsg, "bulk-in", req->buf, req->length);
1079 else if (ep == fsg->intr_in)
1080 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001081
1082 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001083 *pbusy = 1;
1084 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001085 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001086 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1087 if (rc != 0) {
1088 *pbusy = 0;
1089 *state = BUF_STATE_EMPTY;
1090
1091 /* We can't do much more than wait for a reset */
1092
1093 /* Note: currently the net2280 driver fails zero-length
1094 * submissions if DMA is enabled. */
1095 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1096 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001097 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001098 ep->name, rc);
1099 }
1100}
1101
1102
1103static int sleep_thread(struct fsg_dev *fsg)
1104{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001105 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001106
1107 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001108 for (;;) {
1109 try_to_freeze();
1110 set_current_state(TASK_INTERRUPTIBLE);
1111 if (signal_pending(current)) {
1112 rc = -EINTR;
1113 break;
1114 }
1115 if (fsg->thread_wakeup_needed)
1116 break;
1117 schedule();
1118 }
1119 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001120 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001121 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001122}
1123
1124
1125/*-------------------------------------------------------------------------*/
1126
1127static int do_read(struct fsg_dev *fsg)
1128{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001129 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001130 u32 lba;
1131 struct fsg_buffhd *bh;
1132 int rc;
1133 u32 amount_left;
1134 loff_t file_offset, file_offset_tmp;
1135 unsigned int amount;
1136 unsigned int partial_page;
1137 ssize_t nread;
1138
1139 /* Get the starting Logical Block Address and check that it's
1140 * not too big */
1141 if (fsg->cmnd[0] == SC_READ_6)
Alan Stern604eb892009-04-27 13:19:41 -04001142 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001143 else {
Alan Stern604eb892009-04-27 13:19:41 -04001144 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001145
1146 /* We allow DPO (Disable Page Out = don't save data in the
1147 * cache) and FUA (Force Unit Access = don't read from the
1148 * cache), but we don't implement them. */
1149 if ((fsg->cmnd[1] & ~0x18) != 0) {
1150 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1151 return -EINVAL;
1152 }
1153 }
1154 if (lba >= curlun->num_sectors) {
1155 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1156 return -EINVAL;
1157 }
1158 file_offset = ((loff_t) lba) << 9;
1159
1160 /* Carry out the file reads */
1161 amount_left = fsg->data_size_from_cmnd;
1162 if (unlikely(amount_left == 0))
1163 return -EIO; // No default reply
1164
1165 for (;;) {
1166
1167 /* Figure out how much we need to read:
1168 * Try to read the remaining amount.
1169 * But don't read more than the buffer size.
1170 * And don't try to read past the end of the file.
1171 * Finally, if we're not at a page boundary, don't read past
1172 * the next page.
1173 * If this means reading 0 then we were asked to read past
1174 * the end of file. */
1175 amount = min((unsigned int) amount_left, mod_data.buflen);
1176 amount = min((loff_t) amount,
1177 curlun->file_length - file_offset);
1178 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1179 if (partial_page > 0)
1180 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1181 partial_page);
1182
1183 /* Wait for the next buffer to become available */
1184 bh = fsg->next_buffhd_to_fill;
1185 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001186 rc = sleep_thread(fsg);
1187 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001188 return rc;
1189 }
1190
1191 /* If we were asked to read past the end of file,
1192 * end with an empty buffer. */
1193 if (amount == 0) {
1194 curlun->sense_data =
1195 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1196 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001197 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001198 bh->inreq->length = 0;
1199 bh->state = BUF_STATE_FULL;
1200 break;
1201 }
1202
1203 /* Perform the read */
1204 file_offset_tmp = file_offset;
1205 nread = vfs_read(curlun->filp,
1206 (char __user *) bh->buf,
1207 amount, &file_offset_tmp);
1208 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1209 (unsigned long long) file_offset,
1210 (int) nread);
1211 if (signal_pending(current))
1212 return -EINTR;
1213
1214 if (nread < 0) {
1215 LDBG(curlun, "error in file read: %d\n",
1216 (int) nread);
1217 nread = 0;
1218 } else if (nread < amount) {
1219 LDBG(curlun, "partial file read: %d/%u\n",
1220 (int) nread, amount);
1221 nread -= (nread & 511); // Round down to a block
1222 }
1223 file_offset += nread;
1224 amount_left -= nread;
1225 fsg->residue -= nread;
1226 bh->inreq->length = nread;
1227 bh->state = BUF_STATE_FULL;
1228
1229 /* If an error occurred, report it and its position */
1230 if (nread < amount) {
1231 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1232 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001233 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001234 break;
1235 }
1236
1237 if (amount_left == 0)
1238 break; // No more left to read
1239
1240 /* Send this buffer and go read some more */
1241 bh->inreq->zero = 0;
1242 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1243 &bh->inreq_busy, &bh->state);
1244 fsg->next_buffhd_to_fill = bh->next;
1245 }
1246
1247 return -EIO; // No default reply
1248}
1249
1250
1251/*-------------------------------------------------------------------------*/
1252
1253static int do_write(struct fsg_dev *fsg)
1254{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001255 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001256 u32 lba;
1257 struct fsg_buffhd *bh;
1258 int get_some_more;
1259 u32 amount_left_to_req, amount_left_to_write;
1260 loff_t usb_offset, file_offset, file_offset_tmp;
1261 unsigned int amount;
1262 unsigned int partial_page;
1263 ssize_t nwritten;
1264 int rc;
1265
1266 if (curlun->ro) {
1267 curlun->sense_data = SS_WRITE_PROTECTED;
1268 return -EINVAL;
1269 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001270 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001271 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001272 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001273
1274 /* Get the starting Logical Block Address and check that it's
1275 * not too big */
1276 if (fsg->cmnd[0] == SC_WRITE_6)
Alan Stern604eb892009-04-27 13:19:41 -04001277 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001278 else {
Alan Stern604eb892009-04-27 13:19:41 -04001279 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001280
1281 /* We allow DPO (Disable Page Out = don't save data in the
1282 * cache) and FUA (Force Unit Access = write directly to the
1283 * medium). We don't implement DPO; we implement FUA by
1284 * performing synchronous output. */
1285 if ((fsg->cmnd[1] & ~0x18) != 0) {
1286 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1287 return -EINVAL;
1288 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03001289 /* FUA */
1290 if (!curlun->nofua && (fsg->cmnd[1] & 0x08)) {
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001291 spin_lock(&curlun->filp->f_lock);
Christoph Hellwig6b2f3d12009-10-27 11:05:28 +01001292 curlun->filp->f_flags |= O_DSYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001293 spin_unlock(&curlun->filp->f_lock);
1294 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001295 }
1296 if (lba >= curlun->num_sectors) {
1297 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1298 return -EINVAL;
1299 }
1300
1301 /* Carry out the file writes */
1302 get_some_more = 1;
1303 file_offset = usb_offset = ((loff_t) lba) << 9;
1304 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1305
1306 while (amount_left_to_write > 0) {
1307
1308 /* Queue a request for more data from the host */
1309 bh = fsg->next_buffhd_to_fill;
1310 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1311
1312 /* Figure out how much we want to get:
1313 * Try to get the remaining amount.
1314 * But don't get more than the buffer size.
1315 * And don't try to go past the end of the file.
1316 * If we're not at a page boundary,
1317 * don't go past the next page.
1318 * If this means getting 0, then we were asked
1319 * to write past the end of file.
1320 * Finally, round down to a block boundary. */
1321 amount = min(amount_left_to_req, mod_data.buflen);
1322 amount = min((loff_t) amount, curlun->file_length -
1323 usb_offset);
1324 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1325 if (partial_page > 0)
1326 amount = min(amount,
1327 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1328
1329 if (amount == 0) {
1330 get_some_more = 0;
1331 curlun->sense_data =
1332 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1333 curlun->sense_data_info = usb_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001334 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001335 continue;
1336 }
1337 amount -= (amount & 511);
1338 if (amount == 0) {
1339
1340 /* Why were we were asked to transfer a
1341 * partial block? */
1342 get_some_more = 0;
1343 continue;
1344 }
1345
1346 /* Get the next buffer */
1347 usb_offset += amount;
1348 fsg->usb_amount_left -= amount;
1349 amount_left_to_req -= amount;
1350 if (amount_left_to_req == 0)
1351 get_some_more = 0;
1352
1353 /* amount is always divisible by 512, hence by
1354 * the bulk-out maxpacket size */
1355 bh->outreq->length = bh->bulk_out_intended_length =
1356 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001357 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001358 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1359 &bh->outreq_busy, &bh->state);
1360 fsg->next_buffhd_to_fill = bh->next;
1361 continue;
1362 }
1363
1364 /* Write the received data to the backing file */
1365 bh = fsg->next_buffhd_to_drain;
1366 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1367 break; // We stopped early
1368 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001369 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001370 fsg->next_buffhd_to_drain = bh->next;
1371 bh->state = BUF_STATE_EMPTY;
1372
1373 /* Did something go wrong with the transfer? */
1374 if (bh->outreq->status != 0) {
1375 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1376 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001377 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001378 break;
1379 }
1380
1381 amount = bh->outreq->actual;
1382 if (curlun->file_length - file_offset < amount) {
1383 LERROR(curlun,
1384 "write %u @ %llu beyond end %llu\n",
1385 amount, (unsigned long long) file_offset,
1386 (unsigned long long) curlun->file_length);
1387 amount = curlun->file_length - file_offset;
1388 }
1389
1390 /* Perform the write */
1391 file_offset_tmp = file_offset;
1392 nwritten = vfs_write(curlun->filp,
1393 (char __user *) bh->buf,
1394 amount, &file_offset_tmp);
1395 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1396 (unsigned long long) file_offset,
1397 (int) nwritten);
1398 if (signal_pending(current))
1399 return -EINTR; // Interrupted!
1400
1401 if (nwritten < 0) {
1402 LDBG(curlun, "error in file write: %d\n",
1403 (int) nwritten);
1404 nwritten = 0;
1405 } else if (nwritten < amount) {
1406 LDBG(curlun, "partial file write: %d/%u\n",
1407 (int) nwritten, amount);
1408 nwritten -= (nwritten & 511);
1409 // Round down to a block
1410 }
1411 file_offset += nwritten;
1412 amount_left_to_write -= nwritten;
1413 fsg->residue -= nwritten;
1414
1415 /* If an error occurred, report it and its position */
1416 if (nwritten < amount) {
1417 curlun->sense_data = SS_WRITE_ERROR;
1418 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001419 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001420 break;
1421 }
1422
1423 /* Did the host decide to stop early? */
1424 if (bh->outreq->actual != bh->outreq->length) {
1425 fsg->short_packet_received = 1;
1426 break;
1427 }
1428 continue;
1429 }
1430
1431 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001432 rc = sleep_thread(fsg);
1433 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001434 return rc;
1435 }
1436
1437 return -EIO; // No default reply
1438}
1439
1440
1441/*-------------------------------------------------------------------------*/
1442
Linus Torvalds1da177e2005-04-16 15:20:36 -07001443static int do_synchronize_cache(struct fsg_dev *fsg)
1444{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001445 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001446 int rc;
1447
1448 /* We ignore the requested LBA and write out all file's
1449 * dirty data buffers. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001450 rc = fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001451 if (rc)
1452 curlun->sense_data = SS_WRITE_ERROR;
1453 return 0;
1454}
1455
1456
1457/*-------------------------------------------------------------------------*/
1458
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001459static void invalidate_sub(struct fsg_lun *curlun)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001460{
1461 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001462 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001463 unsigned long rc;
1464
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001465 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01001466 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001467}
1468
1469static int do_verify(struct fsg_dev *fsg)
1470{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001471 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001472 u32 lba;
1473 u32 verification_length;
1474 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1475 loff_t file_offset, file_offset_tmp;
1476 u32 amount_left;
1477 unsigned int amount;
1478 ssize_t nread;
1479
1480 /* Get the starting Logical Block Address and check that it's
1481 * not too big */
Alan Stern604eb892009-04-27 13:19:41 -04001482 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001483 if (lba >= curlun->num_sectors) {
1484 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1485 return -EINVAL;
1486 }
1487
1488 /* We allow DPO (Disable Page Out = don't save data in the
1489 * cache) but we don't implement it. */
1490 if ((fsg->cmnd[1] & ~0x10) != 0) {
1491 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1492 return -EINVAL;
1493 }
1494
Alan Stern604eb892009-04-27 13:19:41 -04001495 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001496 if (unlikely(verification_length == 0))
1497 return -EIO; // No default reply
1498
1499 /* Prepare to carry out the file verify */
1500 amount_left = verification_length << 9;
1501 file_offset = ((loff_t) lba) << 9;
1502
1503 /* Write out all the dirty buffers before invalidating them */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001504 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001505 if (signal_pending(current))
1506 return -EINTR;
1507
1508 invalidate_sub(curlun);
1509 if (signal_pending(current))
1510 return -EINTR;
1511
1512 /* Just try to read the requested blocks */
1513 while (amount_left > 0) {
1514
1515 /* Figure out how much we need to read:
1516 * Try to read the remaining amount, but not more than
1517 * the buffer size.
1518 * And don't try to read past the end of the file.
1519 * If this means reading 0 then we were asked to read
1520 * past the end of file. */
1521 amount = min((unsigned int) amount_left, mod_data.buflen);
1522 amount = min((loff_t) amount,
1523 curlun->file_length - file_offset);
1524 if (amount == 0) {
1525 curlun->sense_data =
1526 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1527 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001528 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001529 break;
1530 }
1531
1532 /* Perform the read */
1533 file_offset_tmp = file_offset;
1534 nread = vfs_read(curlun->filp,
1535 (char __user *) bh->buf,
1536 amount, &file_offset_tmp);
1537 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1538 (unsigned long long) file_offset,
1539 (int) nread);
1540 if (signal_pending(current))
1541 return -EINTR;
1542
1543 if (nread < 0) {
1544 LDBG(curlun, "error in file verify: %d\n",
1545 (int) nread);
1546 nread = 0;
1547 } else if (nread < amount) {
1548 LDBG(curlun, "partial file verify: %d/%u\n",
1549 (int) nread, amount);
1550 nread -= (nread & 511); // Round down to a sector
1551 }
1552 if (nread == 0) {
1553 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1554 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001555 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556 break;
1557 }
1558 file_offset += nread;
1559 amount_left -= nread;
1560 }
1561 return 0;
1562}
1563
1564
1565/*-------------------------------------------------------------------------*/
1566
1567static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1568{
1569 u8 *buf = (u8 *) bh->buf;
1570
1571 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05001572 static char product_disk_id[] = "File-Stor Gadget";
1573 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07001574
1575 if (!fsg->curlun) { // Unsupported LUNs are okay
1576 fsg->bad_lun_okay = 1;
1577 memset(buf, 0, 36);
1578 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05001579 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07001580 return 36;
1581 }
1582
Alan Stern12aae682008-11-20 14:13:12 -05001583 memset(buf, 0, 8);
1584 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001585 if (mod_data.removable)
1586 buf[1] = 0x80;
1587 buf[2] = 2; // ANSI SCSI level 2
1588 buf[3] = 2; // SCSI-2 INQUIRY data format
1589 buf[4] = 31; // Additional length
1590 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05001591 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1592 (mod_data.cdrom ? product_cdrom_id :
1593 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001594 mod_data.release);
1595 return 36;
1596}
1597
1598
1599static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1600{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001601 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001602 u8 *buf = (u8 *) bh->buf;
1603 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04001604 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001605
1606 /*
1607 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1608 *
1609 * If a REQUEST SENSE command is received from an initiator
1610 * with a pending unit attention condition (before the target
1611 * generates the contingent allegiance condition), then the
1612 * target shall either:
1613 * a) report any pending sense data and preserve the unit
1614 * attention condition on the logical unit, or,
1615 * b) report the unit attention condition, may discard any
1616 * pending sense data, and clear the unit attention
1617 * condition on the logical unit for that initiator.
1618 *
1619 * FSG normally uses option a); enable this code to use option b).
1620 */
1621#if 0
1622 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1623 curlun->sense_data = curlun->unit_attention_data;
1624 curlun->unit_attention_data = SS_NO_SENSE;
1625 }
1626#endif
1627
1628 if (!curlun) { // Unsupported LUNs are okay
1629 fsg->bad_lun_okay = 1;
1630 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1631 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001632 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001633 } else {
1634 sd = curlun->sense_data;
1635 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04001636 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001637 curlun->sense_data = SS_NO_SENSE;
1638 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001639 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001640 }
1641
1642 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04001643 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07001644 buf[2] = SK(sd);
Alan Stern604eb892009-04-27 13:19:41 -04001645 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001646 buf[7] = 18 - 8; // Additional sense length
1647 buf[12] = ASC(sd);
1648 buf[13] = ASCQ(sd);
1649 return 18;
1650}
1651
1652
1653static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1654{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001655 struct fsg_lun *curlun = fsg->curlun;
Alan Stern604eb892009-04-27 13:19:41 -04001656 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001657 int pmi = fsg->cmnd[8];
1658 u8 *buf = (u8 *) bh->buf;
1659
1660 /* Check the PMI and LBA fields */
1661 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1662 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1663 return -EINVAL;
1664 }
1665
Alan Stern604eb892009-04-27 13:19:41 -04001666 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1667 /* Max logical block */
1668 put_unaligned_be32(512, &buf[4]); /* Block length */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001669 return 8;
1670}
1671
1672
Alan Stern12aae682008-11-20 14:13:12 -05001673static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1674{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001675 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001676 int msf = fsg->cmnd[1] & 0x02;
Alan Stern604eb892009-04-27 13:19:41 -04001677 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Alan Stern12aae682008-11-20 14:13:12 -05001678 u8 *buf = (u8 *) bh->buf;
1679
1680 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1681 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1682 return -EINVAL;
1683 }
1684 if (lba >= curlun->num_sectors) {
1685 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1686 return -EINVAL;
1687 }
1688
1689 memset(buf, 0, 8);
1690 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1691 store_cdrom_address(&buf[4], msf, lba);
1692 return 8;
1693}
1694
1695
1696static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1697{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001698 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001699 int msf = fsg->cmnd[1] & 0x02;
1700 int start_track = fsg->cmnd[6];
1701 u8 *buf = (u8 *) bh->buf;
1702
1703 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1704 start_track > 1) {
1705 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1706 return -EINVAL;
1707 }
1708
1709 memset(buf, 0, 20);
1710 buf[1] = (20-2); /* TOC data length */
1711 buf[2] = 1; /* First track number */
1712 buf[3] = 1; /* Last track number */
1713 buf[5] = 0x16; /* Data track, copying allowed */
1714 buf[6] = 0x01; /* Only track is number 1 */
1715 store_cdrom_address(&buf[8], msf, 0);
1716
1717 buf[13] = 0x16; /* Lead-out track is data */
1718 buf[14] = 0xAA; /* Lead-out track number */
1719 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1720 return 20;
1721}
1722
1723
Linus Torvalds1da177e2005-04-16 15:20:36 -07001724static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1725{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001726 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001727 int mscmnd = fsg->cmnd[0];
1728 u8 *buf = (u8 *) bh->buf;
1729 u8 *buf0 = buf;
1730 int pc, page_code;
1731 int changeable_values, all_pages;
1732 int valid_page = 0;
1733 int len, limit;
1734
1735 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1736 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1737 return -EINVAL;
1738 }
1739 pc = fsg->cmnd[2] >> 6;
1740 page_code = fsg->cmnd[2] & 0x3f;
1741 if (pc == 3) {
1742 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1743 return -EINVAL;
1744 }
1745 changeable_values = (pc == 1);
1746 all_pages = (page_code == 0x3f);
1747
1748 /* Write the mode parameter header. Fixed values are: default
1749 * medium type, no cache control (DPOFUA), and no block descriptors.
1750 * The only variable value is the WriteProtect bit. We will fill in
1751 * the mode data length later. */
1752 memset(buf, 0, 8);
1753 if (mscmnd == SC_MODE_SENSE_6) {
1754 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1755 buf += 4;
1756 limit = 255;
1757 } else { // SC_MODE_SENSE_10
1758 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1759 buf += 8;
1760 limit = 65535; // Should really be mod_data.buflen
1761 }
1762
1763 /* No block descriptors */
1764
1765 /* The mode pages, in numerical order. The only page we support
1766 * is the Caching page. */
1767 if (page_code == 0x08 || all_pages) {
1768 valid_page = 1;
1769 buf[0] = 0x08; // Page code
1770 buf[1] = 10; // Page length
1771 memset(buf+2, 0, 10); // None of the fields are changeable
1772
1773 if (!changeable_values) {
1774 buf[2] = 0x04; // Write cache enable,
1775 // Read cache not disabled
1776 // No cache retention priorities
Alan Stern604eb892009-04-27 13:19:41 -04001777 put_unaligned_be16(0xffff, &buf[4]);
1778 /* Don't disable prefetch */
1779 /* Minimum prefetch = 0 */
1780 put_unaligned_be16(0xffff, &buf[8]);
1781 /* Maximum prefetch */
1782 put_unaligned_be16(0xffff, &buf[10]);
1783 /* Maximum prefetch ceiling */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001784 }
1785 buf += 12;
1786 }
1787
1788 /* Check that a valid page was requested and the mode data length
1789 * isn't too long. */
1790 len = buf - buf0;
1791 if (!valid_page || len > limit) {
1792 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1793 return -EINVAL;
1794 }
1795
1796 /* Store the mode data length */
1797 if (mscmnd == SC_MODE_SENSE_6)
1798 buf0[0] = len - 1;
1799 else
Alan Stern604eb892009-04-27 13:19:41 -04001800 put_unaligned_be16(len - 2, buf0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001801 return len;
1802}
1803
1804
1805static int do_start_stop(struct fsg_dev *fsg)
1806{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001807 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001808 int loej, start;
1809
1810 if (!mod_data.removable) {
1811 curlun->sense_data = SS_INVALID_COMMAND;
1812 return -EINVAL;
1813 }
1814
1815 // int immed = fsg->cmnd[1] & 0x01;
1816 loej = fsg->cmnd[4] & 0x02;
1817 start = fsg->cmnd[4] & 0x01;
1818
1819#ifdef CONFIG_USB_FILE_STORAGE_TEST
1820 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1821 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1822 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1823 return -EINVAL;
1824 }
1825
1826 if (!start) {
1827
1828 /* Are we allowed to unload the media? */
1829 if (curlun->prevent_medium_removal) {
1830 LDBG(curlun, "unload attempt prevented\n");
1831 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1832 return -EINVAL;
1833 }
1834 if (loej) { // Simulate an unload/eject
1835 up_read(&fsg->filesem);
1836 down_write(&fsg->filesem);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001837 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001838 up_write(&fsg->filesem);
1839 down_read(&fsg->filesem);
1840 }
1841 } else {
1842
1843 /* Our emulation doesn't support mounting; the medium is
1844 * available for use as soon as it is loaded. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001845 if (!fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001846 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1847 return -EINVAL;
1848 }
1849 }
1850#endif
1851 return 0;
1852}
1853
1854
1855static int do_prevent_allow(struct fsg_dev *fsg)
1856{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001857 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001858 int prevent;
1859
1860 if (!mod_data.removable) {
1861 curlun->sense_data = SS_INVALID_COMMAND;
1862 return -EINVAL;
1863 }
1864
1865 prevent = fsg->cmnd[4] & 0x01;
1866 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1867 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1868 return -EINVAL;
1869 }
1870
1871 if (curlun->prevent_medium_removal && !prevent)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001872 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001873 curlun->prevent_medium_removal = prevent;
1874 return 0;
1875}
1876
1877
1878static int do_read_format_capacities(struct fsg_dev *fsg,
1879 struct fsg_buffhd *bh)
1880{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001881 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001882 u8 *buf = (u8 *) bh->buf;
1883
1884 buf[0] = buf[1] = buf[2] = 0;
1885 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1886 buf += 4;
1887
Alan Stern604eb892009-04-27 13:19:41 -04001888 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1889 /* Number of blocks */
1890 put_unaligned_be32(512, &buf[4]); /* Block length */
1891 buf[4] = 0x02; /* Current capacity */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001892 return 12;
1893}
1894
1895
1896static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1897{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001898 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001899
1900 /* We don't support MODE SELECT */
1901 curlun->sense_data = SS_INVALID_COMMAND;
1902 return -EINVAL;
1903}
1904
1905
1906/*-------------------------------------------------------------------------*/
1907
1908static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1909{
1910 int rc;
1911
1912 rc = fsg_set_halt(fsg, fsg->bulk_in);
1913 if (rc == -EAGAIN)
1914 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1915 while (rc != 0) {
1916 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001917 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001918 rc = 0;
1919 break;
1920 }
1921
1922 /* Wait for a short time and then try again */
1923 if (msleep_interruptible(100) != 0)
1924 return -EINTR;
1925 rc = usb_ep_set_halt(fsg->bulk_in);
1926 }
1927 return rc;
1928}
1929
David Lopo62fd2ca2008-04-29 10:14:38 +01001930static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1931{
1932 int rc;
1933
1934 DBG(fsg, "bulk-in set wedge\n");
1935 rc = usb_ep_set_wedge(fsg->bulk_in);
1936 if (rc == -EAGAIN)
1937 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1938 while (rc != 0) {
1939 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001940 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01001941 rc = 0;
1942 break;
1943 }
1944
1945 /* Wait for a short time and then try again */
1946 if (msleep_interruptible(100) != 0)
1947 return -EINTR;
1948 rc = usb_ep_set_wedge(fsg->bulk_in);
1949 }
1950 return rc;
1951}
1952
Linus Torvalds1da177e2005-04-16 15:20:36 -07001953static int pad_with_zeros(struct fsg_dev *fsg)
1954{
1955 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1956 u32 nkeep = bh->inreq->length;
1957 u32 nsend;
1958 int rc;
1959
1960 bh->state = BUF_STATE_EMPTY; // For the first iteration
1961 fsg->usb_amount_left = nkeep + fsg->residue;
1962 while (fsg->usb_amount_left > 0) {
1963
1964 /* Wait for the next buffer to be free */
1965 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001966 rc = sleep_thread(fsg);
1967 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001968 return rc;
1969 }
1970
1971 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
1972 memset(bh->buf + nkeep, 0, nsend - nkeep);
1973 bh->inreq->length = nsend;
1974 bh->inreq->zero = 0;
1975 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1976 &bh->inreq_busy, &bh->state);
1977 bh = fsg->next_buffhd_to_fill = bh->next;
1978 fsg->usb_amount_left -= nsend;
1979 nkeep = 0;
1980 }
1981 return 0;
1982}
1983
1984static int throw_away_data(struct fsg_dev *fsg)
1985{
1986 struct fsg_buffhd *bh;
1987 u32 amount;
1988 int rc;
1989
1990 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1991 fsg->usb_amount_left > 0) {
1992
1993 /* Throw away the data in a filled buffer */
1994 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001995 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001996 bh->state = BUF_STATE_EMPTY;
1997 fsg->next_buffhd_to_drain = bh->next;
1998
1999 /* A short packet or an error ends everything */
2000 if (bh->outreq->actual != bh->outreq->length ||
2001 bh->outreq->status != 0) {
2002 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2003 return -EINTR;
2004 }
2005 continue;
2006 }
2007
2008 /* Try to submit another request if we need one */
2009 bh = fsg->next_buffhd_to_fill;
2010 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2011 amount = min(fsg->usb_amount_left,
2012 (u32) mod_data.buflen);
2013
2014 /* amount is always divisible by 512, hence by
2015 * the bulk-out maxpacket size */
2016 bh->outreq->length = bh->bulk_out_intended_length =
2017 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05002018 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002019 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2020 &bh->outreq_busy, &bh->state);
2021 fsg->next_buffhd_to_fill = bh->next;
2022 fsg->usb_amount_left -= amount;
2023 continue;
2024 }
2025
2026 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04002027 rc = sleep_thread(fsg);
2028 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002029 return rc;
2030 }
2031 return 0;
2032}
2033
2034
2035static int finish_reply(struct fsg_dev *fsg)
2036{
2037 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2038 int rc = 0;
2039
2040 switch (fsg->data_dir) {
2041 case DATA_DIR_NONE:
2042 break; // Nothing to send
2043
2044 /* If we don't know whether the host wants to read or write,
2045 * this must be CB or CBI with an unknown command. We mustn't
2046 * try to send or receive any data. So stall both bulk pipes
2047 * if we can and wait for a reset. */
2048 case DATA_DIR_UNKNOWN:
2049 if (mod_data.can_stall) {
2050 fsg_set_halt(fsg, fsg->bulk_out);
2051 rc = halt_bulk_in_endpoint(fsg);
2052 }
2053 break;
2054
2055 /* All but the last buffer of data must have already been sent */
2056 case DATA_DIR_TO_HOST:
2057 if (fsg->data_size == 0)
2058 ; // Nothing to send
2059
2060 /* If there's no residue, simply send the last buffer */
2061 else if (fsg->residue == 0) {
2062 bh->inreq->zero = 0;
2063 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2064 &bh->inreq_busy, &bh->state);
2065 fsg->next_buffhd_to_fill = bh->next;
2066 }
2067
2068 /* There is a residue. For CB and CBI, simply mark the end
2069 * of the data with a short packet. However, if we are
2070 * allowed to stall, there was no data at all (residue ==
2071 * data_size), and the command failed (invalid LUN or
2072 * sense data is set), then halt the bulk-in endpoint
2073 * instead. */
2074 else if (!transport_is_bbb()) {
2075 if (mod_data.can_stall &&
2076 fsg->residue == fsg->data_size &&
2077 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2078 bh->state = BUF_STATE_EMPTY;
2079 rc = halt_bulk_in_endpoint(fsg);
2080 } else {
2081 bh->inreq->zero = 1;
2082 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2083 &bh->inreq_busy, &bh->state);
2084 fsg->next_buffhd_to_fill = bh->next;
2085 }
2086 }
2087
2088 /* For Bulk-only, if we're allowed to stall then send the
2089 * short packet and halt the bulk-in endpoint. If we can't
2090 * stall, pad out the remaining data with 0's. */
2091 else {
2092 if (mod_data.can_stall) {
2093 bh->inreq->zero = 1;
2094 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2095 &bh->inreq_busy, &bh->state);
2096 fsg->next_buffhd_to_fill = bh->next;
2097 rc = halt_bulk_in_endpoint(fsg);
2098 } else
2099 rc = pad_with_zeros(fsg);
2100 }
2101 break;
2102
2103 /* We have processed all we want from the data the host has sent.
2104 * There may still be outstanding bulk-out requests. */
2105 case DATA_DIR_FROM_HOST:
2106 if (fsg->residue == 0)
2107 ; // Nothing to receive
2108
2109 /* Did the host stop sending unexpectedly early? */
2110 else if (fsg->short_packet_received) {
2111 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2112 rc = -EINTR;
2113 }
2114
2115 /* We haven't processed all the incoming data. Even though
2116 * we may be allowed to stall, doing so would cause a race.
2117 * The controller may already have ACK'ed all the remaining
2118 * bulk-out packets, in which case the host wouldn't see a
2119 * STALL. Not realizing the endpoint was halted, it wouldn't
2120 * clear the halt -- leading to problems later on. */
2121#if 0
2122 else if (mod_data.can_stall) {
2123 fsg_set_halt(fsg, fsg->bulk_out);
2124 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2125 rc = -EINTR;
2126 }
2127#endif
2128
2129 /* We can't stall. Read in the excess data and throw it
2130 * all away. */
2131 else
2132 rc = throw_away_data(fsg);
2133 break;
2134 }
2135 return rc;
2136}
2137
2138
2139static int send_status(struct fsg_dev *fsg)
2140{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002141 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002142 struct fsg_buffhd *bh;
2143 int rc;
2144 u8 status = USB_STATUS_PASS;
2145 u32 sd, sdinfo = 0;
2146
2147 /* Wait for the next buffer to become available */
2148 bh = fsg->next_buffhd_to_fill;
2149 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002150 rc = sleep_thread(fsg);
2151 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002152 return rc;
2153 }
2154
2155 if (curlun) {
2156 sd = curlun->sense_data;
2157 sdinfo = curlun->sense_data_info;
2158 } else if (fsg->bad_lun_okay)
2159 sd = SS_NO_SENSE;
2160 else
2161 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2162
2163 if (fsg->phase_error) {
2164 DBG(fsg, "sending phase-error status\n");
2165 status = USB_STATUS_PHASE_ERROR;
2166 sd = SS_INVALID_COMMAND;
2167 } else if (sd != SS_NO_SENSE) {
2168 DBG(fsg, "sending command-failure status\n");
2169 status = USB_STATUS_FAIL;
2170 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2171 " info x%x\n",
2172 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2173 }
2174
2175 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002176 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002177
2178 /* Store and send the Bulk-only CSW */
Harvey Harrison551509d2009-02-11 14:11:36 -08002179 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002180 csw->Tag = fsg->tag;
2181 csw->Residue = cpu_to_le32(fsg->residue);
2182 csw->Status = status;
2183
2184 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2185 bh->inreq->zero = 0;
2186 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2187 &bh->inreq_busy, &bh->state);
2188
2189 } else if (mod_data.transport_type == USB_PR_CB) {
2190
2191 /* Control-Bulk transport has no status phase! */
2192 return 0;
2193
2194 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002195 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002196
2197 /* Store and send the Interrupt data. UFI sends the ASC
2198 * and ASCQ bytes. Everything else sends a Type (which
2199 * is always 0) and the status Value. */
2200 if (mod_data.protocol_type == USB_SC_UFI) {
2201 buf->bType = ASC(sd);
2202 buf->bValue = ASCQ(sd);
2203 } else {
2204 buf->bType = 0;
2205 buf->bValue = status;
2206 }
2207 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2208
2209 fsg->intr_buffhd = bh; // Point to the right buffhd
2210 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002211 fsg->intreq->context = bh;
2212 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2213 &fsg->intreq_busy, &bh->state);
2214 }
2215
2216 fsg->next_buffhd_to_fill = bh->next;
2217 return 0;
2218}
2219
2220
2221/*-------------------------------------------------------------------------*/
2222
2223/* Check whether the command is properly formed and whether its data size
2224 * and direction agree with the values we already have. */
2225static int check_command(struct fsg_dev *fsg, int cmnd_size,
2226 enum data_direction data_dir, unsigned int mask,
2227 int needs_medium, const char *name)
2228{
2229 int i;
2230 int lun = fsg->cmnd[1] >> 5;
2231 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2232 char hdlen[20];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002233 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002234
2235 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2236 * Transparent SCSI doesn't pad. */
2237 if (protocol_is_scsi())
2238 ;
2239
2240 /* There's some disagreement as to whether RBC pads commands or not.
2241 * We'll play it safe and accept either form. */
2242 else if (mod_data.protocol_type == USB_SC_RBC) {
2243 if (fsg->cmnd_size == 12)
2244 cmnd_size = 12;
2245
2246 /* All the other protocols pad to 12 bytes */
2247 } else
2248 cmnd_size = 12;
2249
2250 hdlen[0] = 0;
2251 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2252 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2253 fsg->data_size);
2254 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2255 name, cmnd_size, dirletter[(int) data_dir],
2256 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2257
2258 /* We can't reply at all until we know the correct data direction
2259 * and size. */
2260 if (fsg->data_size_from_cmnd == 0)
2261 data_dir = DATA_DIR_NONE;
2262 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2263 fsg->data_dir = data_dir;
2264 fsg->data_size = fsg->data_size_from_cmnd;
2265
2266 } else { // Bulk-only
2267 if (fsg->data_size < fsg->data_size_from_cmnd) {
2268
2269 /* Host data size < Device data size is a phase error.
2270 * Carry out the command, but only transfer as much
2271 * as we are allowed. */
2272 fsg->data_size_from_cmnd = fsg->data_size;
2273 fsg->phase_error = 1;
2274 }
2275 }
2276 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2277
2278 /* Conflicting data directions is a phase error */
2279 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2280 fsg->phase_error = 1;
2281 return -EINVAL;
2282 }
2283
2284 /* Verify the length of the command itself */
2285 if (cmnd_size != fsg->cmnd_size) {
2286
Felipe Balbi549c41e2008-09-19 02:00:02 +03002287 /* Special case workaround: There are plenty of buggy SCSI
2288 * implementations. Many have issues with cbw->Length
2289 * field passing a wrong command size. For those cases we
2290 * always try to work around the problem by using the length
2291 * sent by the host side provided it is at least as large
2292 * as the correct command length.
2293 * Examples of such cases would be MS-Windows, which issues
2294 * REQUEST SENSE with cbw->Length == 12 where it should
2295 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2296 * REQUEST SENSE with cbw->Length == 10 where it should
2297 * be 6 as well.
2298 */
2299 if (cmnd_size <= fsg->cmnd_size) {
2300 DBG(fsg, "%s is buggy! Expected length %d "
2301 "but we got %d\n", name,
2302 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002303 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002304 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002305 fsg->phase_error = 1;
2306 return -EINVAL;
2307 }
2308 }
2309
Alan Sternd794ac72005-04-18 12:43:25 -04002310 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002311 if (transport_is_bbb()) {
2312 if (fsg->lun != lun)
2313 DBG(fsg, "using LUN %d from CBW, "
2314 "not LUN %d from CDB\n",
2315 fsg->lun, lun);
2316 } else
2317 fsg->lun = lun; // Use LUN from the command
2318
2319 /* Check the LUN */
2320 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2321 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2322 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2323 curlun->sense_data = SS_NO_SENSE;
2324 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002325 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002326 }
2327 } else {
2328 fsg->curlun = curlun = NULL;
2329 fsg->bad_lun_okay = 0;
2330
2331 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2332 * to use unsupported LUNs; all others may not. */
2333 if (fsg->cmnd[0] != SC_INQUIRY &&
2334 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2335 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2336 return -EINVAL;
2337 }
2338 }
2339
2340 /* If a unit attention condition exists, only INQUIRY and
2341 * REQUEST SENSE commands are allowed; anything else must fail. */
2342 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2343 fsg->cmnd[0] != SC_INQUIRY &&
2344 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2345 curlun->sense_data = curlun->unit_attention_data;
2346 curlun->unit_attention_data = SS_NO_SENSE;
2347 return -EINVAL;
2348 }
2349
2350 /* Check that only command bytes listed in the mask are non-zero */
2351 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2352 for (i = 1; i < cmnd_size; ++i) {
2353 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2354 if (curlun)
2355 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2356 return -EINVAL;
2357 }
2358 }
2359
2360 /* If the medium isn't mounted and the command needs to access
2361 * it, return an error. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002362 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002363 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2364 return -EINVAL;
2365 }
2366
2367 return 0;
2368}
2369
2370
2371static int do_scsi_command(struct fsg_dev *fsg)
2372{
2373 struct fsg_buffhd *bh;
2374 int rc;
2375 int reply = -EINVAL;
2376 int i;
2377 static char unknown[16];
2378
2379 dump_cdb(fsg);
2380
2381 /* Wait for the next buffer to become available for data or status */
2382 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2383 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002384 rc = sleep_thread(fsg);
2385 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002386 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002387 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002388 fsg->phase_error = 0;
2389 fsg->short_packet_received = 0;
2390
2391 down_read(&fsg->filesem); // We're using the backing file
2392 switch (fsg->cmnd[0]) {
2393
2394 case SC_INQUIRY:
2395 fsg->data_size_from_cmnd = fsg->cmnd[4];
2396 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2397 (1<<4), 0,
2398 "INQUIRY")) == 0)
2399 reply = do_inquiry(fsg, bh);
2400 break;
2401
2402 case SC_MODE_SELECT_6:
2403 fsg->data_size_from_cmnd = fsg->cmnd[4];
2404 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2405 (1<<1) | (1<<4), 0,
2406 "MODE SELECT(6)")) == 0)
2407 reply = do_mode_select(fsg, bh);
2408 break;
2409
2410 case SC_MODE_SELECT_10:
Alan Stern604eb892009-04-27 13:19:41 -04002411 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002412 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2413 (1<<1) | (3<<7), 0,
2414 "MODE SELECT(10)")) == 0)
2415 reply = do_mode_select(fsg, bh);
2416 break;
2417
2418 case SC_MODE_SENSE_6:
2419 fsg->data_size_from_cmnd = fsg->cmnd[4];
2420 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2421 (1<<1) | (1<<2) | (1<<4), 0,
2422 "MODE SENSE(6)")) == 0)
2423 reply = do_mode_sense(fsg, bh);
2424 break;
2425
2426 case SC_MODE_SENSE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002427 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002428 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2429 (1<<1) | (1<<2) | (3<<7), 0,
2430 "MODE SENSE(10)")) == 0)
2431 reply = do_mode_sense(fsg, bh);
2432 break;
2433
2434 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2435 fsg->data_size_from_cmnd = 0;
2436 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2437 (1<<4), 0,
2438 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2439 reply = do_prevent_allow(fsg);
2440 break;
2441
2442 case SC_READ_6:
2443 i = fsg->cmnd[4];
2444 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2445 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2446 (7<<1) | (1<<4), 1,
2447 "READ(6)")) == 0)
2448 reply = do_read(fsg);
2449 break;
2450
2451 case SC_READ_10:
Alan Stern604eb892009-04-27 13:19:41 -04002452 fsg->data_size_from_cmnd =
2453 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002454 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2455 (1<<1) | (0xf<<2) | (3<<7), 1,
2456 "READ(10)")) == 0)
2457 reply = do_read(fsg);
2458 break;
2459
2460 case SC_READ_12:
Alan Stern604eb892009-04-27 13:19:41 -04002461 fsg->data_size_from_cmnd =
2462 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002463 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2464 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2465 "READ(12)")) == 0)
2466 reply = do_read(fsg);
2467 break;
2468
2469 case SC_READ_CAPACITY:
2470 fsg->data_size_from_cmnd = 8;
2471 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2472 (0xf<<2) | (1<<8), 1,
2473 "READ CAPACITY")) == 0)
2474 reply = do_read_capacity(fsg, bh);
2475 break;
2476
Alan Stern12aae682008-11-20 14:13:12 -05002477 case SC_READ_HEADER:
2478 if (!mod_data.cdrom)
2479 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002480 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002481 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2482 (3<<7) | (0x1f<<1), 1,
2483 "READ HEADER")) == 0)
2484 reply = do_read_header(fsg, bh);
2485 break;
2486
2487 case SC_READ_TOC:
2488 if (!mod_data.cdrom)
2489 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002490 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002491 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2492 (7<<6) | (1<<1), 1,
2493 "READ TOC")) == 0)
2494 reply = do_read_toc(fsg, bh);
2495 break;
2496
Linus Torvalds1da177e2005-04-16 15:20:36 -07002497 case SC_READ_FORMAT_CAPACITIES:
Alan Stern604eb892009-04-27 13:19:41 -04002498 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002499 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2500 (3<<7), 1,
2501 "READ FORMAT CAPACITIES")) == 0)
2502 reply = do_read_format_capacities(fsg, bh);
2503 break;
2504
2505 case SC_REQUEST_SENSE:
2506 fsg->data_size_from_cmnd = fsg->cmnd[4];
2507 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2508 (1<<4), 0,
2509 "REQUEST SENSE")) == 0)
2510 reply = do_request_sense(fsg, bh);
2511 break;
2512
2513 case SC_START_STOP_UNIT:
2514 fsg->data_size_from_cmnd = 0;
2515 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2516 (1<<1) | (1<<4), 0,
2517 "START-STOP UNIT")) == 0)
2518 reply = do_start_stop(fsg);
2519 break;
2520
2521 case SC_SYNCHRONIZE_CACHE:
2522 fsg->data_size_from_cmnd = 0;
2523 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2524 (0xf<<2) | (3<<7), 1,
2525 "SYNCHRONIZE CACHE")) == 0)
2526 reply = do_synchronize_cache(fsg);
2527 break;
2528
2529 case SC_TEST_UNIT_READY:
2530 fsg->data_size_from_cmnd = 0;
2531 reply = check_command(fsg, 6, DATA_DIR_NONE,
2532 0, 1,
2533 "TEST UNIT READY");
2534 break;
2535
2536 /* Although optional, this command is used by MS-Windows. We
2537 * support a minimal version: BytChk must be 0. */
2538 case SC_VERIFY:
2539 fsg->data_size_from_cmnd = 0;
2540 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2541 (1<<1) | (0xf<<2) | (3<<7), 1,
2542 "VERIFY")) == 0)
2543 reply = do_verify(fsg);
2544 break;
2545
2546 case SC_WRITE_6:
2547 i = fsg->cmnd[4];
2548 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2549 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2550 (7<<1) | (1<<4), 1,
2551 "WRITE(6)")) == 0)
2552 reply = do_write(fsg);
2553 break;
2554
2555 case SC_WRITE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002556 fsg->data_size_from_cmnd =
2557 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002558 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2559 (1<<1) | (0xf<<2) | (3<<7), 1,
2560 "WRITE(10)")) == 0)
2561 reply = do_write(fsg);
2562 break;
2563
2564 case SC_WRITE_12:
Alan Stern604eb892009-04-27 13:19:41 -04002565 fsg->data_size_from_cmnd =
2566 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002567 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2568 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2569 "WRITE(12)")) == 0)
2570 reply = do_write(fsg);
2571 break;
2572
2573 /* Some mandatory commands that we recognize but don't implement.
2574 * They don't mean much in this setting. It's left as an exercise
2575 * for anyone interested to implement RESERVE and RELEASE in terms
2576 * of Posix locks. */
2577 case SC_FORMAT_UNIT:
2578 case SC_RELEASE:
2579 case SC_RESERVE:
2580 case SC_SEND_DIAGNOSTIC:
2581 // Fall through
2582
2583 default:
Alan Stern12aae682008-11-20 14:13:12 -05002584 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002585 fsg->data_size_from_cmnd = 0;
2586 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2587 if ((reply = check_command(fsg, fsg->cmnd_size,
2588 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2589 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2590 reply = -EINVAL;
2591 }
2592 break;
2593 }
2594 up_read(&fsg->filesem);
2595
2596 if (reply == -EINTR || signal_pending(current))
2597 return -EINTR;
2598
2599 /* Set up the single reply buffer for finish_reply() */
2600 if (reply == -EINVAL)
2601 reply = 0; // Error reply length
2602 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2603 reply = min((u32) reply, fsg->data_size_from_cmnd);
2604 bh->inreq->length = reply;
2605 bh->state = BUF_STATE_FULL;
2606 fsg->residue -= reply;
2607 } // Otherwise it's already set
2608
2609 return 0;
2610}
2611
2612
2613/*-------------------------------------------------------------------------*/
2614
2615static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2616{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002617 struct usb_request *req = bh->outreq;
2618 struct fsg_bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002619
Alan Sternb950bdb2008-04-14 11:45:29 -04002620 /* Was this a real packet? Should it be ignored? */
2621 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002622 return -EINVAL;
2623
2624 /* Is the CBW valid? */
2625 if (req->actual != USB_BULK_CB_WRAP_LEN ||
Harvey Harrison551509d2009-02-11 14:11:36 -08002626 cbw->Signature != cpu_to_le32(
Linus Torvalds1da177e2005-04-16 15:20:36 -07002627 USB_BULK_CB_SIG)) {
2628 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2629 req->actual,
2630 le32_to_cpu(cbw->Signature));
2631
Alan Sternb950bdb2008-04-14 11:45:29 -04002632 /* The Bulk-only spec says we MUST stall the IN endpoint
2633 * (6.6.1), so it's unavoidable. It also says we must
2634 * retain this state until the next reset, but there's
2635 * no way to tell the controller driver it should ignore
2636 * Clear-Feature(HALT) requests.
2637 *
2638 * We aren't required to halt the OUT endpoint; instead
2639 * we can simply accept and discard any data received
2640 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01002641 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04002642 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002643 return -EINVAL;
2644 }
2645
2646 /* Is the CBW meaningful? */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002647 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04002648 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002649 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2650 "cmdlen %u\n",
2651 cbw->Lun, cbw->Flags, cbw->Length);
2652
2653 /* We can do anything we want here, so let's stall the
2654 * bulk pipes if we are allowed to. */
2655 if (mod_data.can_stall) {
2656 fsg_set_halt(fsg, fsg->bulk_out);
2657 halt_bulk_in_endpoint(fsg);
2658 }
2659 return -EINVAL;
2660 }
2661
2662 /* Save the command for later */
2663 fsg->cmnd_size = cbw->Length;
2664 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2665 if (cbw->Flags & USB_BULK_IN_FLAG)
2666 fsg->data_dir = DATA_DIR_TO_HOST;
2667 else
2668 fsg->data_dir = DATA_DIR_FROM_HOST;
2669 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2670 if (fsg->data_size == 0)
2671 fsg->data_dir = DATA_DIR_NONE;
2672 fsg->lun = cbw->Lun;
2673 fsg->tag = cbw->Tag;
2674 return 0;
2675}
2676
2677
2678static int get_next_command(struct fsg_dev *fsg)
2679{
2680 struct fsg_buffhd *bh;
2681 int rc = 0;
2682
2683 if (transport_is_bbb()) {
2684
2685 /* Wait for the next buffer to become available */
2686 bh = fsg->next_buffhd_to_fill;
2687 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002688 rc = sleep_thread(fsg);
2689 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002690 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002691 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002692
2693 /* Queue a request to read a Bulk-only CBW */
2694 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
Alan Stern70ffe6e2006-03-23 15:05:16 -05002695 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002696 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2697 &bh->outreq_busy, &bh->state);
2698
2699 /* We will drain the buffer in software, which means we
2700 * can reuse it for the next filling. No need to advance
2701 * next_buffhd_to_fill. */
2702
2703 /* Wait for the CBW to arrive */
2704 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002705 rc = sleep_thread(fsg);
2706 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002707 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002708 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05002709 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002710 rc = received_cbw(fsg, bh);
2711 bh->state = BUF_STATE_EMPTY;
2712
2713 } else { // USB_PR_CB or USB_PR_CBI
2714
2715 /* Wait for the next command to arrive */
2716 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002717 rc = sleep_thread(fsg);
2718 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002719 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002720 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002721
2722 /* Is the previous status interrupt request still busy?
2723 * The host is allowed to skip reading the status,
2724 * so we must cancel it. */
2725 if (fsg->intreq_busy)
2726 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2727
2728 /* Copy the command and mark the buffer empty */
2729 fsg->data_dir = DATA_DIR_UNKNOWN;
2730 spin_lock_irq(&fsg->lock);
2731 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2732 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2733 fsg->cbbuf_cmnd_size = 0;
2734 spin_unlock_irq(&fsg->lock);
2735 }
2736 return rc;
2737}
2738
2739
2740/*-------------------------------------------------------------------------*/
2741
2742static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2743 const struct usb_endpoint_descriptor *d)
2744{
2745 int rc;
2746
2747 ep->driver_data = fsg;
2748 rc = usb_ep_enable(ep, d);
2749 if (rc)
2750 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2751 return rc;
2752}
2753
2754static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2755 struct usb_request **preq)
2756{
2757 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2758 if (*preq)
2759 return 0;
2760 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2761 return -ENOMEM;
2762}
2763
2764/*
2765 * Reset interface setting and re-init endpoint state (toggle etc).
2766 * Call with altsetting < 0 to disable the interface. The only other
2767 * available altsetting is 0, which enables the interface.
2768 */
2769static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2770{
2771 int rc = 0;
2772 int i;
2773 const struct usb_endpoint_descriptor *d;
2774
2775 if (fsg->running)
2776 DBG(fsg, "reset interface\n");
2777
2778reset:
2779 /* Deallocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002780 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002781 struct fsg_buffhd *bh = &fsg->buffhds[i];
2782
2783 if (bh->inreq) {
2784 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2785 bh->inreq = NULL;
2786 }
2787 if (bh->outreq) {
2788 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2789 bh->outreq = NULL;
2790 }
2791 }
2792 if (fsg->intreq) {
2793 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2794 fsg->intreq = NULL;
2795 }
2796
2797 /* Disable the endpoints */
2798 if (fsg->bulk_in_enabled) {
2799 usb_ep_disable(fsg->bulk_in);
2800 fsg->bulk_in_enabled = 0;
2801 }
2802 if (fsg->bulk_out_enabled) {
2803 usb_ep_disable(fsg->bulk_out);
2804 fsg->bulk_out_enabled = 0;
2805 }
2806 if (fsg->intr_in_enabled) {
2807 usb_ep_disable(fsg->intr_in);
2808 fsg->intr_in_enabled = 0;
2809 }
2810
2811 fsg->running = 0;
2812 if (altsetting < 0 || rc != 0)
2813 return rc;
2814
2815 DBG(fsg, "set interface %d\n", altsetting);
2816
2817 /* Enable the endpoints */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002818 d = fsg_ep_desc(fsg->gadget,
2819 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002820 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2821 goto reset;
2822 fsg->bulk_in_enabled = 1;
2823
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002824 d = fsg_ep_desc(fsg->gadget,
2825 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002826 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2827 goto reset;
2828 fsg->bulk_out_enabled = 1;
2829 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
Alan Sternb950bdb2008-04-14 11:45:29 -04002830 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002831
2832 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002833 d = fsg_ep_desc(fsg->gadget,
2834 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002835 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2836 goto reset;
2837 fsg->intr_in_enabled = 1;
2838 }
2839
2840 /* Allocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002841 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002842 struct fsg_buffhd *bh = &fsg->buffhds[i];
2843
2844 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2845 goto reset;
2846 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2847 goto reset;
2848 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002849 bh->inreq->context = bh->outreq->context = bh;
2850 bh->inreq->complete = bulk_in_complete;
2851 bh->outreq->complete = bulk_out_complete;
2852 }
2853 if (transport_is_cbi()) {
2854 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2855 goto reset;
2856 fsg->intreq->complete = intr_in_complete;
2857 }
2858
2859 fsg->running = 1;
2860 for (i = 0; i < fsg->nluns; ++i)
2861 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2862 return rc;
2863}
2864
2865
2866/*
2867 * Change our operational configuration. This code must agree with the code
2868 * that returns config descriptors, and with interface altsetting code.
2869 *
2870 * It's also responsible for power management interactions. Some
2871 * configurations might not work with our current power sources.
2872 * For now we just assume the gadget is always self-powered.
2873 */
2874static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2875{
2876 int rc = 0;
2877
2878 /* Disable the single interface */
2879 if (fsg->config != 0) {
2880 DBG(fsg, "reset config\n");
2881 fsg->config = 0;
2882 rc = do_set_interface(fsg, -1);
2883 }
2884
2885 /* Enable the interface */
2886 if (new_config != 0) {
2887 fsg->config = new_config;
2888 if ((rc = do_set_interface(fsg, 0)) != 0)
2889 fsg->config = 0; // Reset on errors
2890 else {
2891 char *speed;
2892
2893 switch (fsg->gadget->speed) {
2894 case USB_SPEED_LOW: speed = "low"; break;
2895 case USB_SPEED_FULL: speed = "full"; break;
2896 case USB_SPEED_HIGH: speed = "high"; break;
2897 default: speed = "?"; break;
2898 }
2899 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2900 }
2901 }
2902 return rc;
2903}
2904
2905
2906/*-------------------------------------------------------------------------*/
2907
2908static void handle_exception(struct fsg_dev *fsg)
2909{
2910 siginfo_t info;
2911 int sig;
2912 int i;
2913 int num_active;
2914 struct fsg_buffhd *bh;
2915 enum fsg_state old_state;
2916 u8 new_config;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002917 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002918 unsigned int exception_req_tag;
2919 int rc;
2920
2921 /* Clear the existing signals. Anything but SIGUSR1 is converted
2922 * into a high-priority EXIT exception. */
2923 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04002924 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002925 if (!sig)
2926 break;
2927 if (sig != SIGUSR1) {
2928 if (fsg->state < FSG_STATE_EXIT)
2929 DBG(fsg, "Main thread exiting on signal\n");
2930 raise_exception(fsg, FSG_STATE_EXIT);
2931 }
2932 }
2933
2934 /* Cancel all the pending transfers */
2935 if (fsg->intreq_busy)
2936 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002937 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002938 bh = &fsg->buffhds[i];
2939 if (bh->inreq_busy)
2940 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2941 if (bh->outreq_busy)
2942 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2943 }
2944
2945 /* Wait until everything is idle */
2946 for (;;) {
2947 num_active = fsg->intreq_busy;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002948 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002949 bh = &fsg->buffhds[i];
2950 num_active += bh->inreq_busy + bh->outreq_busy;
2951 }
2952 if (num_active == 0)
2953 break;
2954 if (sleep_thread(fsg))
2955 return;
2956 }
2957
2958 /* Clear out the controller's fifos */
2959 if (fsg->bulk_in_enabled)
2960 usb_ep_fifo_flush(fsg->bulk_in);
2961 if (fsg->bulk_out_enabled)
2962 usb_ep_fifo_flush(fsg->bulk_out);
2963 if (fsg->intr_in_enabled)
2964 usb_ep_fifo_flush(fsg->intr_in);
2965
2966 /* Reset the I/O buffer states and pointers, the SCSI
2967 * state, and the exception. Then invoke the handler. */
2968 spin_lock_irq(&fsg->lock);
2969
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002970 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002971 bh = &fsg->buffhds[i];
2972 bh->state = BUF_STATE_EMPTY;
2973 }
2974 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2975 &fsg->buffhds[0];
2976
2977 exception_req_tag = fsg->exception_req_tag;
2978 new_config = fsg->new_config;
2979 old_state = fsg->state;
2980
2981 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2982 fsg->state = FSG_STATE_STATUS_PHASE;
2983 else {
2984 for (i = 0; i < fsg->nluns; ++i) {
2985 curlun = &fsg->luns[i];
2986 curlun->prevent_medium_removal = 0;
2987 curlun->sense_data = curlun->unit_attention_data =
2988 SS_NO_SENSE;
2989 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002990 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002991 }
2992 fsg->state = FSG_STATE_IDLE;
2993 }
2994 spin_unlock_irq(&fsg->lock);
2995
2996 /* Carry out any extra actions required for the exception */
2997 switch (old_state) {
2998 default:
2999 break;
3000
3001 case FSG_STATE_ABORT_BULK_OUT:
3002 send_status(fsg);
3003 spin_lock_irq(&fsg->lock);
3004 if (fsg->state == FSG_STATE_STATUS_PHASE)
3005 fsg->state = FSG_STATE_IDLE;
3006 spin_unlock_irq(&fsg->lock);
3007 break;
3008
3009 case FSG_STATE_RESET:
3010 /* In case we were forced against our will to halt a
3011 * bulk endpoint, clear the halt now. (The SuperH UDC
3012 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04003013 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003014 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003015
3016 if (transport_is_bbb()) {
3017 if (fsg->ep0_req_tag == exception_req_tag)
3018 ep0_queue(fsg); // Complete the status stage
3019
3020 } else if (transport_is_cbi())
3021 send_status(fsg); // Status by interrupt pipe
3022
3023 /* Technically this should go here, but it would only be
3024 * a waste of time. Ditto for the INTERFACE_CHANGE and
3025 * CONFIG_CHANGE cases. */
3026 // for (i = 0; i < fsg->nluns; ++i)
3027 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3028 break;
3029
3030 case FSG_STATE_INTERFACE_CHANGE:
3031 rc = do_set_interface(fsg, 0);
3032 if (fsg->ep0_req_tag != exception_req_tag)
3033 break;
3034 if (rc != 0) // STALL on errors
3035 fsg_set_halt(fsg, fsg->ep0);
3036 else // Complete the status stage
3037 ep0_queue(fsg);
3038 break;
3039
3040 case FSG_STATE_CONFIG_CHANGE:
3041 rc = do_set_config(fsg, new_config);
3042 if (fsg->ep0_req_tag != exception_req_tag)
3043 break;
3044 if (rc != 0) // STALL on errors
3045 fsg_set_halt(fsg, fsg->ep0);
3046 else // Complete the status stage
3047 ep0_queue(fsg);
3048 break;
3049
3050 case FSG_STATE_DISCONNECT:
Michal Nazarewiczb6058d02009-10-28 16:57:14 +01003051 for (i = 0; i < fsg->nluns; ++i)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003052 fsg_lun_fsync_sub(fsg->luns + i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003053 do_set_config(fsg, 0); // Unconfigured state
3054 break;
3055
3056 case FSG_STATE_EXIT:
3057 case FSG_STATE_TERMINATED:
3058 do_set_config(fsg, 0); // Free resources
3059 spin_lock_irq(&fsg->lock);
3060 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3061 spin_unlock_irq(&fsg->lock);
3062 break;
3063 }
3064}
3065
3066
3067/*-------------------------------------------------------------------------*/
3068
3069static int fsg_main_thread(void *fsg_)
3070{
John Daiker7ca46b82006-12-29 19:02:06 -08003071 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003072
Linus Torvalds1da177e2005-04-16 15:20:36 -07003073 /* Allow the thread to be killed by a signal, but set the signal mask
3074 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003075 allow_signal(SIGINT);
3076 allow_signal(SIGTERM);
3077 allow_signal(SIGKILL);
3078 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003079
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003080 /* Allow the thread to be frozen */
3081 set_freezable();
3082
Linus Torvalds1da177e2005-04-16 15:20:36 -07003083 /* Arrange for userspace references to be interpreted as kernel
3084 * pointers. That way we can pass a kernel pointer to a routine
3085 * that expects a __user pointer and it will work okay. */
3086 set_fs(get_ds());
3087
Linus Torvalds1da177e2005-04-16 15:20:36 -07003088 /* The main loop */
3089 while (fsg->state != FSG_STATE_TERMINATED) {
3090 if (exception_in_progress(fsg) || signal_pending(current)) {
3091 handle_exception(fsg);
3092 continue;
3093 }
3094
3095 if (!fsg->running) {
3096 sleep_thread(fsg);
3097 continue;
3098 }
3099
3100 if (get_next_command(fsg))
3101 continue;
3102
3103 spin_lock_irq(&fsg->lock);
3104 if (!exception_in_progress(fsg))
3105 fsg->state = FSG_STATE_DATA_PHASE;
3106 spin_unlock_irq(&fsg->lock);
3107
3108 if (do_scsi_command(fsg) || finish_reply(fsg))
3109 continue;
3110
3111 spin_lock_irq(&fsg->lock);
3112 if (!exception_in_progress(fsg))
3113 fsg->state = FSG_STATE_STATUS_PHASE;
3114 spin_unlock_irq(&fsg->lock);
3115
3116 if (send_status(fsg))
3117 continue;
3118
3119 spin_lock_irq(&fsg->lock);
3120 if (!exception_in_progress(fsg))
3121 fsg->state = FSG_STATE_IDLE;
3122 spin_unlock_irq(&fsg->lock);
3123 }
3124
Alan Stern22efcf42005-09-26 16:12:02 -04003125 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003126 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003127 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003128
Alan Stern82a10a82009-04-16 15:37:28 -04003129 /* If we are exiting because of a signal, unregister the
3130 * gadget driver. */
3131 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003132 usb_gadget_unregister_driver(&fsg_driver);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003133
3134 /* Let the unbind and cleanup routines know the thread has exited */
3135 complete_and_exit(&fsg->thread_notifier, 0);
3136}
3137
3138
3139/*-------------------------------------------------------------------------*/
3140
Linus Torvalds1da177e2005-04-16 15:20:36 -07003141
3142/* The write permissions and store_xxx pointers are set in fsg_bind() */
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003143static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003144static DEVICE_ATTR(nofua, 0644, fsg_show_nofua, NULL);
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003145static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003146
3147
3148/*-------------------------------------------------------------------------*/
3149
Alan Stern87c42522005-11-09 16:59:56 -05003150static void fsg_release(struct kref *ref)
3151{
3152 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3153
3154 kfree(fsg->luns);
3155 kfree(fsg);
3156}
3157
Linus Torvalds1da177e2005-04-16 15:20:36 -07003158static void lun_release(struct device *dev)
3159{
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003160 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3161 struct fsg_dev *fsg =
3162 container_of(filesem, struct fsg_dev, filesem);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003163
Alan Stern87c42522005-11-09 16:59:56 -05003164 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003165}
3166
David Brownella3536782006-07-06 15:48:53 -07003167static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003168{
3169 struct fsg_dev *fsg = get_gadget_data(gadget);
3170 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003171 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003172 struct usb_request *req = fsg->ep0req;
3173
3174 DBG(fsg, "unbind\n");
3175 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3176
3177 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003178 for (i = 0; i < fsg->nluns; ++i) {
3179 curlun = &fsg->luns[i];
3180 if (curlun->registered) {
Michal Nazarewicz452ee0e2010-08-12 17:43:50 +02003181 device_remove_file(&curlun->dev, &dev_attr_nofua);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003182 device_remove_file(&curlun->dev, &dev_attr_ro);
3183 device_remove_file(&curlun->dev, &dev_attr_file);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003184 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003185 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003186 curlun->registered = 0;
3187 }
3188 }
3189
3190 /* If the thread isn't already dead, tell it to exit now */
3191 if (fsg->state != FSG_STATE_TERMINATED) {
3192 raise_exception(fsg, FSG_STATE_EXIT);
3193 wait_for_completion(&fsg->thread_notifier);
3194
3195 /* The cleanup routine waits for this completion also */
3196 complete(&fsg->thread_notifier);
3197 }
3198
3199 /* Free the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003200 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
David Brownell9d8bab52007-07-01 11:04:54 -07003201 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003202
3203 /* Free the request and buffer for endpoint 0 */
3204 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003205 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003206 usb_ep_free_request(fsg->ep0, req);
3207 }
3208
3209 set_gadget_data(gadget, NULL);
3210}
3211
3212
3213static int __init check_parameters(struct fsg_dev *fsg)
3214{
3215 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003216 int gcnum;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003217 int i;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003218
3219 /* Store the default values */
3220 mod_data.transport_type = USB_PR_BULK;
3221 mod_data.transport_name = "Bulk-only";
3222 mod_data.protocol_type = USB_SC_SCSI;
3223 mod_data.protocol_name = "Transparent SCSI";
3224
Alan Sternce459ec2009-02-24 16:19:47 -05003225 /* Some peripheral controllers are known not to be able to
3226 * halt bulk endpoints correctly. If one of them is present,
3227 * disable stalls.
3228 */
Christoph Egger90f79762010-02-05 13:24:12 +01003229 if (gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003230 mod_data.can_stall = 0;
3231
3232 if (mod_data.release == 0xffff) { // Parameter wasn't set
Christoph Egger90f79762010-02-05 13:24:12 +01003233 gcnum = usb_gadget_controller_number(fsg->gadget);
David Brownell91e79c92005-07-13 15:18:30 -07003234 if (gcnum >= 0)
3235 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003236 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003237 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003238 fsg->gadget->name);
3239 mod_data.release = 0x0399;
3240 }
3241 }
3242
3243 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3244
3245#ifdef CONFIG_USB_FILE_STORAGE_TEST
3246 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3247 ; // Use default setting
3248 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3249 mod_data.transport_type = USB_PR_CB;
3250 mod_data.transport_name = "Control-Bulk";
3251 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3252 mod_data.transport_type = USB_PR_CBI;
3253 mod_data.transport_name = "Control-Bulk-Interrupt";
3254 } else {
3255 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3256 return -EINVAL;
3257 }
3258
3259 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3260 prot == USB_SC_SCSI) {
3261 ; // Use default setting
3262 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3263 prot == USB_SC_RBC) {
3264 mod_data.protocol_type = USB_SC_RBC;
3265 mod_data.protocol_name = "RBC";
3266 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3267 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3268 prot == USB_SC_8020) {
3269 mod_data.protocol_type = USB_SC_8020;
3270 mod_data.protocol_name = "8020i (ATAPI)";
3271 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3272 prot == USB_SC_QIC) {
3273 mod_data.protocol_type = USB_SC_QIC;
3274 mod_data.protocol_name = "QIC-157";
3275 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3276 prot == USB_SC_UFI) {
3277 mod_data.protocol_type = USB_SC_UFI;
3278 mod_data.protocol_name = "UFI";
3279 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3280 prot == USB_SC_8070) {
3281 mod_data.protocol_type = USB_SC_8070;
3282 mod_data.protocol_name = "8070i";
3283 } else {
3284 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3285 return -EINVAL;
3286 }
3287
3288 mod_data.buflen &= PAGE_CACHE_MASK;
3289 if (mod_data.buflen <= 0) {
3290 ERROR(fsg, "invalid buflen\n");
3291 return -ETOOSMALL;
3292 }
Yann Cantin87eb1be2010-06-05 23:06:31 +02003293
Michal Nazarewicz56706492010-07-22 14:16:37 +02003294#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3295
Yann Cantin87eb1be2010-06-05 23:06:31 +02003296 /* Serial string handling.
3297 * On a real device, the serial string would be loaded
3298 * from permanent storage. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003299 if (mod_data.serial) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003300 const char *ch;
3301 unsigned len = 0;
3302
3303 /* Sanity check :
3304 * The CB[I] specification limits the serial string to
3305 * 12 uppercase hexadecimal characters.
3306 * BBB need at least 12 uppercase hexadecimal characters,
3307 * with a maximum of 126. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003308 for (ch = mod_data.serial; *ch; ++ch) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003309 ++len;
3310 if ((*ch < '0' || *ch > '9') &&
3311 (*ch < 'A' || *ch > 'F')) { /* not uppercase hex */
3312 WARNING(fsg,
3313 "Invalid serial string character: %c; "
3314 "Failing back to default\n",
3315 *ch);
3316 goto fill_serial;
3317 }
3318 }
3319 if (len > 126 ||
3320 (mod_data.transport_type == USB_PR_BULK && len < 12) ||
3321 (mod_data.transport_type != USB_PR_BULK && len > 12)) {
3322 WARNING(fsg,
3323 "Invalid serial string length; "
3324 "Failing back to default\n");
3325 goto fill_serial;
3326 }
Michal Nazarewicz56706492010-07-22 14:16:37 +02003327 fsg_strings[FSG_STRING_SERIAL - 1].s = mod_data.serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003328 } else {
Michal Nazarewicz56706492010-07-22 14:16:37 +02003329 WARNING(fsg,
3330 "Userspace failed to provide serial number; "
3331 "Failing back to default\n");
Yann Cantin87eb1be2010-06-05 23:06:31 +02003332fill_serial:
3333 /* Serial number not specified or invalid, make our own.
3334 * We just encode it from the driver version string,
3335 * 12 characters to comply with both CB[I] and BBB spec.
3336 * Warning : Two devices running the same kernel will have
3337 * the same fallback serial number. */
3338 for (i = 0; i < 12; i += 2) {
3339 unsigned char c = DRIVER_VERSION[i / 2];
3340
3341 if (!c)
3342 break;
3343 sprintf(&fsg_string_serial[i], "%02X", c);
3344 }
3345 }
3346
Linus Torvalds1da177e2005-04-16 15:20:36 -07003347 return 0;
3348}
3349
3350
Michal Nazarewicze12995e2010-08-12 17:43:52 +02003351static int __init fsg_bind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003352{
3353 struct fsg_dev *fsg = the_fsg;
3354 int rc;
3355 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003356 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003357 struct usb_ep *ep;
3358 struct usb_request *req;
3359 char *pathbuf, *p;
3360
3361 fsg->gadget = gadget;
3362 set_gadget_data(gadget, fsg);
3363 fsg->ep0 = gadget->ep0;
3364 fsg->ep0->driver_data = fsg;
3365
3366 if ((rc = check_parameters(fsg)) != 0)
3367 goto out;
3368
3369 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003370 dev_attr_file.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003371 dev_attr_file.store = fsg_store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003372 if (!mod_data.cdrom) {
3373 dev_attr_ro.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003374 dev_attr_ro.store = fsg_store_ro;
Alan Stern12aae682008-11-20 14:13:12 -05003375 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003376 }
3377
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003378 /* Only for removable media? */
3379 dev_attr_nofua.attr.mode = 0644;
3380 dev_attr_nofua.store = fsg_store_nofua;
3381
Linus Torvalds1da177e2005-04-16 15:20:36 -07003382 /* Find out how many LUNs there should be */
3383 i = mod_data.nluns;
3384 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003385 i = max(mod_data.num_filenames, 1u);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003386 if (i > FSG_MAX_LUNS) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003387 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3388 rc = -EINVAL;
3389 goto out;
3390 }
3391
3392 /* Create the LUNs, open their backing files, and register the
3393 * LUN devices in sysfs. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003394 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003395 if (!fsg->luns) {
3396 rc = -ENOMEM;
3397 goto out;
3398 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003399 fsg->nluns = i;
3400
3401 for (i = 0; i < fsg->nluns; ++i) {
3402 curlun = &fsg->luns[i];
Michal Nazarewicze909ef52009-10-28 16:57:16 +01003403 curlun->cdrom = !!mod_data.cdrom;
3404 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3405 curlun->initially_ro = curlun->ro;
3406 curlun->removable = mod_data.removable;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003407 curlun->nofua = mod_data.nofua[i];
Alan Stern2de9eae2006-09-25 14:31:15 -04003408 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003409 curlun->dev.parent = &gadget->dev;
3410 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003411 dev_set_drvdata(&curlun->dev, &fsg->filesem);
Kay Sievers0031a062008-05-02 06:02:41 +02003412 dev_set_name(&curlun->dev,"%s-lun%d",
3413 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003414
Alan Stern2de9eae2006-09-25 14:31:15 -04003415 if ((rc = device_register(&curlun->dev)) != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003416 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Alan Stern2de9eae2006-09-25 14:31:15 -04003417 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003418 }
Alan Stern2de9eae2006-09-25 14:31:15 -04003419 if ((rc = device_create_file(&curlun->dev,
3420 &dev_attr_ro)) != 0 ||
3421 (rc = device_create_file(&curlun->dev,
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003422 &dev_attr_nofua)) != 0 ||
3423 (rc = device_create_file(&curlun->dev,
Alan Stern2de9eae2006-09-25 14:31:15 -04003424 &dev_attr_file)) != 0) {
3425 device_unregister(&curlun->dev);
3426 goto out;
3427 }
3428 curlun->registered = 1;
3429 kref_get(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003430
Alan Sternaafe5bd2006-03-31 11:46:43 -05003431 if (mod_data.file[i] && *mod_data.file[i]) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003432 if ((rc = fsg_lun_open(curlun,
Alan Sternaafe5bd2006-03-31 11:46:43 -05003433 mod_data.file[i])) != 0)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003434 goto out;
3435 } else if (!mod_data.removable) {
3436 ERROR(fsg, "no file given for LUN%d\n", i);
3437 rc = -EINVAL;
3438 goto out;
3439 }
3440 }
3441
3442 /* Find all the endpoints we will use */
3443 usb_ep_autoconfig_reset(gadget);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003444 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003445 if (!ep)
3446 goto autoconf_fail;
3447 ep->driver_data = fsg; // claim the endpoint
3448 fsg->bulk_in = ep;
3449
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003450 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003451 if (!ep)
3452 goto autoconf_fail;
3453 ep->driver_data = fsg; // claim the endpoint
3454 fsg->bulk_out = ep;
3455
3456 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003457 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003458 if (!ep)
3459 goto autoconf_fail;
3460 ep->driver_data = fsg; // claim the endpoint
3461 fsg->intr_in = ep;
3462 }
3463
3464 /* Fix up the descriptors */
3465 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3466 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3467 device_desc.idProduct = cpu_to_le16(mod_data.product);
3468 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3469
3470 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003471 fsg_intf_desc.bNumEndpoints = i;
3472 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3473 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3474 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003475
David Brownell2e806f62007-08-02 00:03:39 -07003476 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003477 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003478
David Brownell2e806f62007-08-02 00:03:39 -07003479 /* Assume ep0 uses the same maxpacket value for both speeds */
3480 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003481
David Brownell2e806f62007-08-02 00:03:39 -07003482 /* Assume endpoint addresses are the same for both speeds */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003483 fsg_hs_bulk_in_desc.bEndpointAddress =
3484 fsg_fs_bulk_in_desc.bEndpointAddress;
3485 fsg_hs_bulk_out_desc.bEndpointAddress =
3486 fsg_fs_bulk_out_desc.bEndpointAddress;
3487 fsg_hs_intr_in_desc.bEndpointAddress =
3488 fsg_fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003489 }
3490
David Brownell2e806f62007-08-02 00:03:39 -07003491 if (gadget_is_otg(gadget))
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003492 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
David Brownell2e806f62007-08-02 00:03:39 -07003493
Linus Torvalds1da177e2005-04-16 15:20:36 -07003494 rc = -ENOMEM;
3495
3496 /* Allocate the request and buffer for endpoint 0 */
3497 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3498 if (!req)
3499 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003500 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003501 if (!req->buf)
3502 goto out;
3503 req->complete = ep0_complete;
3504
3505 /* Allocate the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003506 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003507 struct fsg_buffhd *bh = &fsg->buffhds[i];
3508
Alan Stern14cd5f82006-03-23 15:07:25 -05003509 /* Allocate for the bulk-in endpoint. We assume that
3510 * the buffer will also work with the bulk-out (and
3511 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003512 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003513 if (!bh->buf)
3514 goto out;
3515 bh->next = bh + 1;
3516 }
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003517 fsg->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->buffhds[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07003518
3519 /* This should reflect the actual gadget power source */
3520 usb_gadget_set_selfpowered(gadget);
3521
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003522 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3523 "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003524 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003525 gadget->name);
3526
Alan Stern22efcf42005-09-26 16:12:02 -04003527 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3528 "file-storage-gadget");
3529 if (IS_ERR(fsg->thread_task)) {
3530 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003531 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04003532 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003533
3534 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3535 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3536
3537 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3538 for (i = 0; i < fsg->nluns; ++i) {
3539 curlun = &fsg->luns[i];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003540 if (fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003541 p = NULL;
3542 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08003543 p = d_path(&curlun->filp->f_path,
3544 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003545 if (IS_ERR(p))
3546 p = NULL;
3547 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003548 LINFO(curlun, "ro=%d, nofua=%d, file: %s\n",
3549 curlun->ro, curlun->nofua, (p ? p : "(error)"));
Linus Torvalds1da177e2005-04-16 15:20:36 -07003550 }
3551 }
3552 kfree(pathbuf);
3553
3554 DBG(fsg, "transport=%s (x%02x)\n",
3555 mod_data.transport_name, mod_data.transport_type);
3556 DBG(fsg, "protocol=%s (x%02x)\n",
3557 mod_data.protocol_name, mod_data.protocol_type);
3558 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3559 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05003560 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003561 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05003562 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07003563 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04003564
3565 set_bit(REGISTERED, &fsg->atomic_bitflags);
3566
3567 /* Tell the thread to start working */
3568 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003569 return 0;
3570
3571autoconf_fail:
3572 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3573 rc = -ENOTSUPP;
3574
3575out:
3576 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3577 fsg_unbind(gadget);
Felipe Balbi889394b2008-12-08 13:50:27 +02003578 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003579 return rc;
3580}
3581
3582
3583/*-------------------------------------------------------------------------*/
3584
3585static void fsg_suspend(struct usb_gadget *gadget)
3586{
3587 struct fsg_dev *fsg = get_gadget_data(gadget);
3588
3589 DBG(fsg, "suspend\n");
3590 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3591}
3592
3593static void fsg_resume(struct usb_gadget *gadget)
3594{
3595 struct fsg_dev *fsg = get_gadget_data(gadget);
3596
3597 DBG(fsg, "resume\n");
3598 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3599}
3600
3601
3602/*-------------------------------------------------------------------------*/
3603
3604static struct usb_gadget_driver fsg_driver = {
3605#ifdef CONFIG_USB_GADGET_DUALSPEED
3606 .speed = USB_SPEED_HIGH,
3607#else
3608 .speed = USB_SPEED_FULL,
3609#endif
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003610 .function = (char *) fsg_string_product,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003611 .bind = fsg_bind,
David Brownell6bea4762006-12-05 03:15:33 -08003612 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003613 .disconnect = fsg_disconnect,
3614 .setup = fsg_setup,
3615 .suspend = fsg_suspend,
3616 .resume = fsg_resume,
3617
3618 .driver = {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003619 .name = DRIVER_NAME,
Ben Dooksd0d50492005-10-10 10:52:33 +01003620 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003621 // .release = ...
3622 // .suspend = ...
3623 // .resume = ...
3624 },
3625};
3626
3627
3628static int __init fsg_alloc(void)
3629{
3630 struct fsg_dev *fsg;
3631
Alan Sterna922c682005-10-06 16:38:45 -04003632 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003633 if (!fsg)
3634 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003635 spin_lock_init(&fsg->lock);
3636 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05003637 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003638 init_completion(&fsg->thread_notifier);
3639
3640 the_fsg = fsg;
3641 return 0;
3642}
3643
3644
Linus Torvalds1da177e2005-04-16 15:20:36 -07003645static int __init fsg_init(void)
3646{
3647 int rc;
3648 struct fsg_dev *fsg;
3649
3650 if ((rc = fsg_alloc()) != 0)
3651 return rc;
3652 fsg = the_fsg;
Alan Sterna922c682005-10-06 16:38:45 -04003653 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05003654 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04003655 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003656}
3657module_init(fsg_init);
3658
3659
3660static void __exit fsg_cleanup(void)
3661{
3662 struct fsg_dev *fsg = the_fsg;
3663
3664 /* Unregister the driver iff the thread hasn't already done so */
3665 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3666 usb_gadget_unregister_driver(&fsg_driver);
3667
3668 /* Wait for the thread to finish up */
3669 wait_for_completion(&fsg->thread_notifier);
3670
Alan Stern87c42522005-11-09 16:59:56 -05003671 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003672}
3673module_exit(fsg_cleanup);