blob: d04e0e6b019dc9db9b8d2e00d6640fd471f3331f [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
Alan Sternd8087422010-09-03 11:15:41 -040092 * serial=HHHH... Required serial number (string of hex chars)
Linus Torvalds1da177e2005-04-16 15:20:36 -070093 * ro=b[,b...] Default false, booleans for read-only access
94 * removable Default false, boolean for removable media
95 * luns=N Default N = number of filenames, number of
96 * LUNs to support
Andy Shevchenkoa93917d2010-07-22 17:53:56 +030097 * nofua=b[,b...] Default false, booleans for ignore FUA flag
98 * in SCSI WRITE(10,12) commands
Alan Sternd794ac72005-04-18 12:43:25 -040099 * stall Default determined according to the type of
100 * USB device controller (usually true),
101 * boolean to permit the driver to halt
102 * bulk endpoints
Alan Stern12aae682008-11-20 14:13:12 -0500103 * cdrom Default false, boolean for whether to emulate
104 * a CD-ROM drive
Linus Torvalds1da177e2005-04-16 15:20:36 -0700105 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
106 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
107 * ATAPI, QIC, UFI, 8070, or SCSI;
108 * also 1 - 6)
109 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
110 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
111 * release=0xRRRR Override the USB release number (bcdDevice)
112 * buflen=N Default N=16384, buffer size used (will be
113 * rounded down to a multiple of
114 * PAGE_CACHE_SIZE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700115 *
Alan Sternd8087422010-09-03 11:15:41 -0400116 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "serial", "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"
Alan Sternd8087422010-09-03 11:15:41 -0400276#define DRIVER_VERSION "1 September 2010"
Linus Torvalds1da177e2005-04-16 15:20:36 -0700277
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100278static char fsg_string_manufacturer[64];
279static const char fsg_string_product[] = DRIVER_DESC;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100280static const char fsg_string_config[] = "Self-powered";
281static const char fsg_string_interface[] = "Mass Storage";
Linus Torvalds1da177e2005-04-16 15:20:36 -0700282
Michal Nazarewicz93f93742009-10-28 16:57:17 +0100283
284#include "storage_common.c"
285
286
Linus Torvalds1da177e2005-04-16 15:20:36 -0700287MODULE_DESCRIPTION(DRIVER_DESC);
288MODULE_AUTHOR("Alan Stern");
289MODULE_LICENSE("Dual BSD/GPL");
290
Linus Torvalds1da177e2005-04-16 15:20:36 -0700291/*
292 * This driver assumes self-powered hardware and has no way for users to
293 * trigger remote wakeup. It uses autoconfiguration to select endpoints
294 * and endpoint addresses.
295 */
296
297
298/*-------------------------------------------------------------------------*/
299
Linus Torvalds1da177e2005-04-16 15:20:36 -0700300
301/* Encapsulate the module parameter settings */
302
Linus Torvalds1da177e2005-04-16 15:20:36 -0700303static struct {
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100304 char *file[FSG_MAX_LUNS];
Alan Sternd8087422010-09-03 11:15:41 -0400305 char *serial;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100306 int ro[FSG_MAX_LUNS];
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300307 int nofua[FSG_MAX_LUNS];
David Brownell2e806f62007-08-02 00:03:39 -0700308 unsigned int num_filenames;
309 unsigned int num_ros;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300310 unsigned int num_nofuas;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700311 unsigned int nluns;
312
Alan Sternd794ac72005-04-18 12:43:25 -0400313 int removable;
314 int can_stall;
Alan Stern12aae682008-11-20 14:13:12 -0500315 int cdrom;
Alan Sternd794ac72005-04-18 12:43:25 -0400316
Linus Torvalds1da177e2005-04-16 15:20:36 -0700317 char *transport_parm;
318 char *protocol_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700319 unsigned short vendor;
320 unsigned short product;
321 unsigned short release;
322 unsigned int buflen;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700323
324 int transport_type;
325 char *transport_name;
326 int protocol_type;
327 char *protocol_name;
328
329} mod_data = { // Default values
330 .transport_parm = "BBB",
331 .protocol_parm = "SCSI",
332 .removable = 0,
Alan Sternd794ac72005-04-18 12:43:25 -0400333 .can_stall = 1,
Alan Stern12aae682008-11-20 14:13:12 -0500334 .cdrom = 0,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100335 .vendor = FSG_VENDOR_ID,
336 .product = FSG_PRODUCT_ID,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700337 .release = 0xffff, // Use controller chip type
338 .buflen = 16384,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700339 };
340
341
Alan Sternaafe5bd2006-03-31 11:46:43 -0500342module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
343 S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700344MODULE_PARM_DESC(file, "names of backing files or devices");
345
Alan Sternd8087422010-09-03 11:15:41 -0400346module_param_named(serial, mod_data.serial, charp, S_IRUGO);
347MODULE_PARM_DESC(serial, "USB serial number");
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
Linus Torvalds1da177e2005-04-16 15:20:36 -0700368/* In the non-TEST version, only the module parameters listed above
369 * are available. */
370#ifdef CONFIG_USB_FILE_STORAGE_TEST
371
372module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
373MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
374
375module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
376MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
377 "8070, or SCSI)");
378
379module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
380MODULE_PARM_DESC(vendor, "USB Vendor ID");
381
382module_param_named(product, mod_data.product, ushort, S_IRUGO);
383MODULE_PARM_DESC(product, "USB Product ID");
384
385module_param_named(release, mod_data.release, ushort, S_IRUGO);
386MODULE_PARM_DESC(release, "USB release number");
387
388module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
389MODULE_PARM_DESC(buflen, "I/O buffer size");
390
Linus Torvalds1da177e2005-04-16 15:20:36 -0700391#endif /* CONFIG_USB_FILE_STORAGE_TEST */
392
393
Linus Torvalds1da177e2005-04-16 15:20:36 -0700394/*
395 * These definitions will permit the compiler to avoid generating code for
396 * parts of the driver that aren't used in the non-TEST version. Even gcc
397 * can recognize when a test of a constant expression yields a dead code
398 * path.
399 */
400
401#ifdef CONFIG_USB_FILE_STORAGE_TEST
402
403#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
404#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
405#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
406
407#else
408
409#define transport_is_bbb() 1
410#define transport_is_cbi() 0
411#define protocol_is_scsi() 1
412
413#endif /* CONFIG_USB_FILE_STORAGE_TEST */
414
415
Michal Nazarewiczb6058d02009-10-28 16:57:14 +0100416/*-------------------------------------------------------------------------*/
Linus Torvalds1da177e2005-04-16 15:20:36 -0700417
Linus Torvalds1da177e2005-04-16 15:20:36 -0700418
419struct fsg_dev {
420 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
421 spinlock_t lock;
422 struct usb_gadget *gadget;
423
424 /* filesem protects: backing files in use */
425 struct rw_semaphore filesem;
426
Alan Stern87c42522005-11-09 16:59:56 -0500427 /* reference counting: wait until all LUNs are released */
428 struct kref ref;
429
Linus Torvalds1da177e2005-04-16 15:20:36 -0700430 struct usb_ep *ep0; // Handy copy of gadget->ep0
431 struct usb_request *ep0req; // For control responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500432 unsigned int ep0_req_tag;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700433 const char *ep0req_name;
434
435 struct usb_request *intreq; // For interrupt responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500436 int intreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700437 struct fsg_buffhd *intr_buffhd;
438
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100439 unsigned int bulk_out_maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700440 enum fsg_state state; // For exception handling
441 unsigned int exception_req_tag;
442
443 u8 config, new_config;
444
445 unsigned int running : 1;
446 unsigned int bulk_in_enabled : 1;
447 unsigned int bulk_out_enabled : 1;
448 unsigned int intr_in_enabled : 1;
449 unsigned int phase_error : 1;
450 unsigned int short_packet_received : 1;
451 unsigned int bad_lun_okay : 1;
452
453 unsigned long atomic_bitflags;
454#define REGISTERED 0
Alan Sternb950bdb2008-04-14 11:45:29 -0400455#define IGNORE_BULK_OUT 1
Linus Torvalds1da177e2005-04-16 15:20:36 -0700456#define SUSPENDED 2
457
458 struct usb_ep *bulk_in;
459 struct usb_ep *bulk_out;
460 struct usb_ep *intr_in;
461
462 struct fsg_buffhd *next_buffhd_to_fill;
463 struct fsg_buffhd *next_buffhd_to_drain;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100464 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700465
Linus Torvalds1da177e2005-04-16 15:20:36 -0700466 int thread_wakeup_needed;
467 struct completion thread_notifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700468 struct task_struct *thread_task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700469
470 int cmnd_size;
471 u8 cmnd[MAX_COMMAND_SIZE];
472 enum data_direction data_dir;
473 u32 data_size;
474 u32 data_size_from_cmnd;
475 u32 tag;
476 unsigned int lun;
477 u32 residue;
478 u32 usb_amount_left;
479
480 /* The CB protocol offers no way for a host to know when a command
481 * has completed. As a result the next command may arrive early,
482 * and we will still have to handle it. For that reason we need
483 * a buffer to store new commands when using CB (or CBI, which
484 * does not oblige a host to wait for command completion either). */
485 int cbbuf_cmnd_size;
486 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
487
488 unsigned int nluns;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100489 struct fsg_lun *luns;
490 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700491};
492
493typedef void (*fsg_routine_t)(struct fsg_dev *);
494
Alan Stern79a7d9e2007-08-08 17:10:11 -0400495static int exception_in_progress(struct fsg_dev *fsg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700496{
497 return (fsg->state > FSG_STATE_IDLE);
498}
499
Linus Torvalds1da177e2005-04-16 15:20:36 -0700500static struct fsg_dev *the_fsg;
501static struct usb_gadget_driver fsg_driver;
502
Linus Torvalds1da177e2005-04-16 15:20:36 -0700503
504/*-------------------------------------------------------------------------*/
505
Linus Torvalds1da177e2005-04-16 15:20:36 -0700506static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
507{
508 const char *name;
509
510 if (ep == fsg->bulk_in)
511 name = "bulk-in";
512 else if (ep == fsg->bulk_out)
513 name = "bulk-out";
514 else
515 name = ep->name;
516 DBG(fsg, "%s set halt\n", name);
517 return usb_ep_set_halt(ep);
518}
519
520
521/*-------------------------------------------------------------------------*/
522
Linus Torvalds1da177e2005-04-16 15:20:36 -0700523/*
524 * DESCRIPTORS ... most are static, but strings and (full) configuration
525 * descriptors are built on demand. Also the (static) config and interface
526 * descriptors are adjusted during fsg_bind().
527 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700528
529/* There is only one configuration. */
530#define CONFIG_VALUE 1
531
532static struct usb_device_descriptor
533device_desc = {
534 .bLength = sizeof device_desc,
535 .bDescriptorType = USB_DT_DEVICE,
536
Harvey Harrison551509d2009-02-11 14:11:36 -0800537 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700538 .bDeviceClass = USB_CLASS_PER_INTERFACE,
539
540 /* The next three values can be overridden by module parameters */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100541 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
542 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
Harvey Harrison551509d2009-02-11 14:11:36 -0800543 .bcdDevice = cpu_to_le16(0xffff),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700544
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100545 .iManufacturer = FSG_STRING_MANUFACTURER,
546 .iProduct = FSG_STRING_PRODUCT,
547 .iSerialNumber = FSG_STRING_SERIAL,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700548 .bNumConfigurations = 1,
549};
550
551static struct usb_config_descriptor
552config_desc = {
553 .bLength = sizeof config_desc,
554 .bDescriptorType = USB_DT_CONFIG,
555
556 /* wTotalLength computed by usb_gadget_config_buf() */
557 .bNumInterfaces = 1,
558 .bConfigurationValue = CONFIG_VALUE,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100559 .iConfiguration = FSG_STRING_CONFIG,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700560 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
David Brownell36e893d2008-09-12 09:39:06 -0700561 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700562};
563
Linus Torvalds1da177e2005-04-16 15:20:36 -0700564
Linus Torvalds1da177e2005-04-16 15:20:36 -0700565static struct usb_qualifier_descriptor
566dev_qualifier = {
567 .bLength = sizeof dev_qualifier,
568 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
569
Harvey Harrison551509d2009-02-11 14:11:36 -0800570 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700571 .bDeviceClass = USB_CLASS_PER_INTERFACE,
572
573 .bNumConfigurations = 1,
574};
575
Linus Torvalds1da177e2005-04-16 15:20:36 -0700576
577
578/*
579 * Config descriptors must agree with the code that sets configurations
580 * and with code managing interfaces and their altsettings. They must
581 * also handle different speeds and other-speed requests.
582 */
583static int populate_config_buf(struct usb_gadget *gadget,
584 u8 *buf, u8 type, unsigned index)
585{
Linus Torvalds1da177e2005-04-16 15:20:36 -0700586 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700587 int len;
588 const struct usb_descriptor_header **function;
589
590 if (index > 0)
591 return -EINVAL;
592
David Brownell2e806f62007-08-02 00:03:39 -0700593 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700594 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
Michal Nazarewiczd23b0f02009-11-09 14:15:20 +0100595 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
596 ? (const struct usb_descriptor_header **)fsg_hs_function
597 : (const struct usb_descriptor_header **)fsg_fs_function;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700598
599 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -0700600 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700601 function++;
602
603 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
604 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
605 return len;
606}
607
608
609/*-------------------------------------------------------------------------*/
610
611/* These routines may be called in process context or in_irq */
612
Alan Sterna21d4fe2005-11-29 12:04:24 -0500613/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700614static void wakeup_thread(struct fsg_dev *fsg)
615{
616 /* Tell the main thread that something has happened */
617 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500618 if (fsg->thread_task)
619 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700620}
621
622
623static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
624{
625 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626
627 /* Do nothing if a higher-priority exception is already in progress.
628 * If a lower-or-equal priority exception is in progress, preempt it
629 * and notify the main thread by sending it a signal. */
630 spin_lock_irqsave(&fsg->lock, flags);
631 if (fsg->state <= new_state) {
632 fsg->exception_req_tag = fsg->ep0_req_tag;
633 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -0400634 if (fsg->thread_task)
635 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
636 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700637 }
638 spin_unlock_irqrestore(&fsg->lock, flags);
639}
640
641
642/*-------------------------------------------------------------------------*/
643
644/* The disconnect callback and ep0 routines. These always run in_irq,
645 * except that ep0_queue() is called in the main thread to acknowledge
646 * completion of various requests: set config, set interface, and
647 * Bulk-only device reset. */
648
649static void fsg_disconnect(struct usb_gadget *gadget)
650{
651 struct fsg_dev *fsg = get_gadget_data(gadget);
652
653 DBG(fsg, "disconnect or port reset\n");
654 raise_exception(fsg, FSG_STATE_DISCONNECT);
655}
656
657
658static int ep0_queue(struct fsg_dev *fsg)
659{
660 int rc;
661
662 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
663 if (rc != 0 && rc != -ESHUTDOWN) {
664
665 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -0700666 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -0700667 fsg->ep0->name, rc);
668 }
669 return rc;
670}
671
672static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
673{
John Daiker7ca46b82006-12-29 19:02:06 -0800674 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700675
676 if (req->actual > 0)
677 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
678 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800679 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680 req->status, req->actual, req->length);
681 if (req->status == -ECONNRESET) // Request was cancelled
682 usb_ep_fifo_flush(ep);
683
684 if (req->status == 0 && req->context)
685 ((fsg_routine_t) (req->context))(fsg);
686}
687
688
689/*-------------------------------------------------------------------------*/
690
691/* Bulk and interrupt endpoint completion handlers.
692 * These always run in_irq. */
693
694static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
695{
John Daiker7ca46b82006-12-29 19:02:06 -0800696 struct fsg_dev *fsg = ep->driver_data;
697 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700698
699 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800700 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700701 req->status, req->actual, req->length);
702 if (req->status == -ECONNRESET) // Request was cancelled
703 usb_ep_fifo_flush(ep);
704
705 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500706 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700707 spin_lock(&fsg->lock);
708 bh->inreq_busy = 0;
709 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700710 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500711 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700712}
713
714static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
715{
John Daiker7ca46b82006-12-29 19:02:06 -0800716 struct fsg_dev *fsg = ep->driver_data;
717 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700718
719 dump_msg(fsg, "bulk-out", req->buf, req->actual);
Mian Yousaf Kaukab806e8f82011-03-24 12:20:13 +0100720 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800721 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Mian Yousaf Kaukab806e8f82011-03-24 12:20:13 +0100722 req->status, req->actual, req->length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700723 if (req->status == -ECONNRESET) // Request was cancelled
724 usb_ep_fifo_flush(ep);
725
726 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500727 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700728 spin_lock(&fsg->lock);
729 bh->outreq_busy = 0;
730 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700731 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500732 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700733}
734
735
736#ifdef CONFIG_USB_FILE_STORAGE_TEST
737static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
738{
John Daiker7ca46b82006-12-29 19:02:06 -0800739 struct fsg_dev *fsg = ep->driver_data;
740 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700741
742 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800743 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700744 req->status, req->actual, req->length);
745 if (req->status == -ECONNRESET) // Request was cancelled
746 usb_ep_fifo_flush(ep);
747
748 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500749 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700750 spin_lock(&fsg->lock);
751 fsg->intreq_busy = 0;
752 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700753 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500754 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700755}
756
757#else
758static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
759{}
760#endif /* CONFIG_USB_FILE_STORAGE_TEST */
761
762
763/*-------------------------------------------------------------------------*/
764
765/* Ep0 class-specific handlers. These always run in_irq. */
766
767#ifdef CONFIG_USB_FILE_STORAGE_TEST
768static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
769{
770 struct usb_request *req = fsg->ep0req;
771 static u8 cbi_reset_cmnd[6] = {
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +0200772 SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
Linus Torvalds1da177e2005-04-16 15:20:36 -0700773
774 /* Error in command transfer? */
775 if (req->status || req->length != req->actual ||
776 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
777
778 /* Not all controllers allow a protocol stall after
779 * receiving control-out data, but we'll try anyway. */
780 fsg_set_halt(fsg, fsg->ep0);
781 return; // Wait for reset
782 }
783
784 /* Is it the special reset command? */
785 if (req->actual >= sizeof cbi_reset_cmnd &&
786 memcmp(req->buf, cbi_reset_cmnd,
787 sizeof cbi_reset_cmnd) == 0) {
788
789 /* Raise an exception to stop the current operation
790 * and reinitialize our state. */
791 DBG(fsg, "cbi reset request\n");
792 raise_exception(fsg, FSG_STATE_RESET);
793 return;
794 }
795
796 VDBG(fsg, "CB[I] accept device-specific command\n");
797 spin_lock(&fsg->lock);
798
799 /* Save the command for later */
800 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700801 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700802 fsg->cbbuf_cmnd_size = req->actual;
803 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
804
Linus Torvalds1da177e2005-04-16 15:20:36 -0700805 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500806 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700807}
808
809#else
810static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
811{}
812#endif /* CONFIG_USB_FILE_STORAGE_TEST */
813
814
815static int class_setup_req(struct fsg_dev *fsg,
816 const struct usb_ctrlrequest *ctrl)
817{
818 struct usb_request *req = fsg->ep0req;
819 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700820 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -0400821 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -0700822 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700823
824 if (!fsg->config)
825 return value;
826
827 /* Handle Bulk-only class-specific requests */
828 if (transport_is_bbb()) {
829 switch (ctrl->bRequest) {
830
831 case USB_BULK_RESET_REQUEST:
832 if (ctrl->bRequestType != (USB_DIR_OUT |
833 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
834 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400835 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700836 value = -EDOM;
837 break;
838 }
839
840 /* Raise an exception to stop the current operation
841 * and reinitialize our state. */
842 DBG(fsg, "bulk reset request\n");
843 raise_exception(fsg, FSG_STATE_RESET);
844 value = DELAYED_STATUS;
845 break;
846
847 case USB_BULK_GET_MAX_LUN_REQUEST:
848 if (ctrl->bRequestType != (USB_DIR_IN |
849 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
850 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400851 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700852 value = -EDOM;
853 break;
854 }
855 VDBG(fsg, "get max LUN\n");
856 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -0400857 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700858 break;
859 }
860 }
861
862 /* Handle CBI class-specific requests */
863 else {
864 switch (ctrl->bRequest) {
865
866 case USB_CBI_ADSC_REQUEST:
867 if (ctrl->bRequestType != (USB_DIR_OUT |
868 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
869 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400870 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700871 value = -EDOM;
872 break;
873 }
874 if (w_length > MAX_COMMAND_SIZE) {
875 value = -EOVERFLOW;
876 break;
877 }
878 value = w_length;
879 fsg->ep0req->context = received_cbi_adsc;
880 break;
881 }
882 }
883
884 if (value == -EOPNOTSUPP)
885 VDBG(fsg,
886 "unknown class-specific control req "
887 "%02x.%02x v%04x i%04x l%u\n",
888 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -0700889 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700890 return value;
891}
892
893
894/*-------------------------------------------------------------------------*/
895
896/* Ep0 standard request handlers. These always run in_irq. */
897
898static int standard_setup_req(struct fsg_dev *fsg,
899 const struct usb_ctrlrequest *ctrl)
900{
901 struct usb_request *req = fsg->ep0req;
902 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700903 u16 w_index = le16_to_cpu(ctrl->wIndex);
904 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700905
906 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
907 * but config change events will also reconfigure hardware. */
908 switch (ctrl->bRequest) {
909
910 case USB_REQ_GET_DESCRIPTOR:
911 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
912 USB_RECIP_DEVICE))
913 break;
914 switch (w_value >> 8) {
915
916 case USB_DT_DEVICE:
917 VDBG(fsg, "get device descriptor\n");
Alan Stern76f4af82005-04-05 11:56:54 -0400918 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700919 memcpy(req->buf, &device_desc, value);
920 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700921 case USB_DT_DEVICE_QUALIFIER:
922 VDBG(fsg, "get device qualifier\n");
David Brownell2e806f62007-08-02 00:03:39 -0700923 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700924 break;
Alan Stern76f4af82005-04-05 11:56:54 -0400925 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700926 memcpy(req->buf, &dev_qualifier, value);
927 break;
928
929 case USB_DT_OTHER_SPEED_CONFIG:
930 VDBG(fsg, "get other-speed config descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700931 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700932 break;
933 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700934 case USB_DT_CONFIG:
935 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700936get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700937 value = populate_config_buf(fsg->gadget,
938 req->buf,
939 w_value >> 8,
940 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700941 break;
942
943 case USB_DT_STRING:
944 VDBG(fsg, "get string descriptor\n");
945
946 /* wIndex == language code */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100947 value = usb_gadget_get_string(&fsg_stringtab,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700948 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700949 break;
950 }
951 break;
952
953 /* One config, two speeds */
954 case USB_REQ_SET_CONFIGURATION:
955 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
956 USB_RECIP_DEVICE))
957 break;
958 VDBG(fsg, "set configuration\n");
959 if (w_value == CONFIG_VALUE || w_value == 0) {
960 fsg->new_config = w_value;
961
962 /* Raise an exception to wipe out previous transaction
963 * state (queued bufs, etc) and set the new config. */
964 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
965 value = DELAYED_STATUS;
966 }
967 break;
968 case USB_REQ_GET_CONFIGURATION:
969 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
970 USB_RECIP_DEVICE))
971 break;
972 VDBG(fsg, "get configuration\n");
973 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -0400974 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700975 break;
976
977 case USB_REQ_SET_INTERFACE:
978 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
979 USB_RECIP_INTERFACE))
980 break;
981 if (fsg->config && w_index == 0) {
982
983 /* Raise an exception to wipe out previous transaction
984 * state (queued bufs, etc) and install the new
985 * interface altsetting. */
986 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
987 value = DELAYED_STATUS;
988 }
989 break;
990 case USB_REQ_GET_INTERFACE:
991 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
992 USB_RECIP_INTERFACE))
993 break;
994 if (!fsg->config)
995 break;
996 if (w_index != 0) {
997 value = -EDOM;
998 break;
999 }
1000 VDBG(fsg, "get interface\n");
1001 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001002 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001003 break;
1004
1005 default:
1006 VDBG(fsg,
1007 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1008 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001009 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001010 }
1011
1012 return value;
1013}
1014
1015
1016static int fsg_setup(struct usb_gadget *gadget,
1017 const struct usb_ctrlrequest *ctrl)
1018{
1019 struct fsg_dev *fsg = get_gadget_data(gadget);
1020 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001021 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001022
1023 ++fsg->ep0_req_tag; // Record arrival of a new request
1024 fsg->ep0req->context = NULL;
1025 fsg->ep0req->length = 0;
1026 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1027
1028 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1029 rc = class_setup_req(fsg, ctrl);
1030 else
1031 rc = standard_setup_req(fsg, ctrl);
1032
1033 /* Respond with data/status or defer until later? */
1034 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001035 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001036 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001037 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001038 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1039 "ep0-in" : "ep0-out");
1040 rc = ep0_queue(fsg);
1041 }
1042
1043 /* Device either stalls (rc < 0) or reports success */
1044 return rc;
1045}
1046
1047
1048/*-------------------------------------------------------------------------*/
1049
1050/* All the following routines run in process context */
1051
1052
1053/* Use this for bulk or interrupt transfers, not ep0 */
1054static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001055 struct usb_request *req, int *pbusy,
1056 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057{
1058 int rc;
1059
1060 if (ep == fsg->bulk_in)
1061 dump_msg(fsg, "bulk-in", req->buf, req->length);
1062 else if (ep == fsg->intr_in)
1063 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001064
1065 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001066 *pbusy = 1;
1067 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001068 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001069 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1070 if (rc != 0) {
1071 *pbusy = 0;
1072 *state = BUF_STATE_EMPTY;
1073
1074 /* We can't do much more than wait for a reset */
1075
1076 /* Note: currently the net2280 driver fails zero-length
1077 * submissions if DMA is enabled. */
1078 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1079 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001080 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001081 ep->name, rc);
1082 }
1083}
1084
1085
1086static int sleep_thread(struct fsg_dev *fsg)
1087{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001088 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001089
1090 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001091 for (;;) {
1092 try_to_freeze();
1093 set_current_state(TASK_INTERRUPTIBLE);
1094 if (signal_pending(current)) {
1095 rc = -EINTR;
1096 break;
1097 }
1098 if (fsg->thread_wakeup_needed)
1099 break;
1100 schedule();
1101 }
1102 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001103 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001104 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001105}
1106
1107
1108/*-------------------------------------------------------------------------*/
1109
1110static int do_read(struct fsg_dev *fsg)
1111{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001112 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001113 u32 lba;
1114 struct fsg_buffhd *bh;
1115 int rc;
1116 u32 amount_left;
1117 loff_t file_offset, file_offset_tmp;
1118 unsigned int amount;
1119 unsigned int partial_page;
1120 ssize_t nread;
1121
1122 /* Get the starting Logical Block Address and check that it's
1123 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001124 if (fsg->cmnd[0] == READ_6)
Alan Stern604eb892009-04-27 13:19:41 -04001125 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001126 else {
Alan Stern604eb892009-04-27 13:19:41 -04001127 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001128
1129 /* We allow DPO (Disable Page Out = don't save data in the
1130 * cache) and FUA (Force Unit Access = don't read from the
1131 * cache), but we don't implement them. */
1132 if ((fsg->cmnd[1] & ~0x18) != 0) {
1133 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1134 return -EINVAL;
1135 }
1136 }
1137 if (lba >= curlun->num_sectors) {
1138 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1139 return -EINVAL;
1140 }
1141 file_offset = ((loff_t) lba) << 9;
1142
1143 /* Carry out the file reads */
1144 amount_left = fsg->data_size_from_cmnd;
1145 if (unlikely(amount_left == 0))
1146 return -EIO; // No default reply
1147
1148 for (;;) {
1149
1150 /* Figure out how much we need to read:
1151 * Try to read the remaining amount.
1152 * But don't read more than the buffer size.
1153 * And don't try to read past the end of the file.
1154 * Finally, if we're not at a page boundary, don't read past
1155 * the next page.
1156 * If this means reading 0 then we were asked to read past
1157 * the end of file. */
1158 amount = min((unsigned int) amount_left, mod_data.buflen);
1159 amount = min((loff_t) amount,
1160 curlun->file_length - file_offset);
1161 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1162 if (partial_page > 0)
1163 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1164 partial_page);
1165
1166 /* Wait for the next buffer to become available */
1167 bh = fsg->next_buffhd_to_fill;
1168 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001169 rc = sleep_thread(fsg);
1170 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001171 return rc;
1172 }
1173
1174 /* If we were asked to read past the end of file,
1175 * end with an empty buffer. */
1176 if (amount == 0) {
1177 curlun->sense_data =
1178 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1179 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001180 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001181 bh->inreq->length = 0;
1182 bh->state = BUF_STATE_FULL;
1183 break;
1184 }
1185
1186 /* Perform the read */
1187 file_offset_tmp = file_offset;
1188 nread = vfs_read(curlun->filp,
1189 (char __user *) bh->buf,
1190 amount, &file_offset_tmp);
1191 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1192 (unsigned long long) file_offset,
1193 (int) nread);
1194 if (signal_pending(current))
1195 return -EINTR;
1196
1197 if (nread < 0) {
1198 LDBG(curlun, "error in file read: %d\n",
1199 (int) nread);
1200 nread = 0;
1201 } else if (nread < amount) {
1202 LDBG(curlun, "partial file read: %d/%u\n",
1203 (int) nread, amount);
1204 nread -= (nread & 511); // Round down to a block
1205 }
1206 file_offset += nread;
1207 amount_left -= nread;
1208 fsg->residue -= nread;
1209 bh->inreq->length = nread;
1210 bh->state = BUF_STATE_FULL;
1211
1212 /* If an error occurred, report it and its position */
1213 if (nread < amount) {
1214 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1215 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001216 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001217 break;
1218 }
1219
1220 if (amount_left == 0)
1221 break; // No more left to read
1222
1223 /* Send this buffer and go read some more */
1224 bh->inreq->zero = 0;
1225 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1226 &bh->inreq_busy, &bh->state);
1227 fsg->next_buffhd_to_fill = bh->next;
1228 }
1229
1230 return -EIO; // No default reply
1231}
1232
1233
1234/*-------------------------------------------------------------------------*/
1235
1236static int do_write(struct fsg_dev *fsg)
1237{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001238 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001239 u32 lba;
1240 struct fsg_buffhd *bh;
1241 int get_some_more;
1242 u32 amount_left_to_req, amount_left_to_write;
1243 loff_t usb_offset, file_offset, file_offset_tmp;
1244 unsigned int amount;
1245 unsigned int partial_page;
1246 ssize_t nwritten;
1247 int rc;
1248
1249 if (curlun->ro) {
1250 curlun->sense_data = SS_WRITE_PROTECTED;
1251 return -EINVAL;
1252 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001253 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001254 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001255 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001256
1257 /* Get the starting Logical Block Address and check that it's
1258 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001259 if (fsg->cmnd[0] == WRITE_6)
Alan Stern604eb892009-04-27 13:19:41 -04001260 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001261 else {
Alan Stern604eb892009-04-27 13:19:41 -04001262 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001263
1264 /* We allow DPO (Disable Page Out = don't save data in the
1265 * cache) and FUA (Force Unit Access = write directly to the
1266 * medium). We don't implement DPO; we implement FUA by
1267 * performing synchronous output. */
1268 if ((fsg->cmnd[1] & ~0x18) != 0) {
1269 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1270 return -EINVAL;
1271 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03001272 /* FUA */
1273 if (!curlun->nofua && (fsg->cmnd[1] & 0x08)) {
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001274 spin_lock(&curlun->filp->f_lock);
Christoph Hellwig6b2f3d12009-10-27 11:05:28 +01001275 curlun->filp->f_flags |= O_DSYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001276 spin_unlock(&curlun->filp->f_lock);
1277 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001278 }
1279 if (lba >= curlun->num_sectors) {
1280 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1281 return -EINVAL;
1282 }
1283
1284 /* Carry out the file writes */
1285 get_some_more = 1;
1286 file_offset = usb_offset = ((loff_t) lba) << 9;
1287 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1288
1289 while (amount_left_to_write > 0) {
1290
1291 /* Queue a request for more data from the host */
1292 bh = fsg->next_buffhd_to_fill;
1293 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1294
1295 /* Figure out how much we want to get:
1296 * Try to get the remaining amount.
1297 * But don't get more than the buffer size.
1298 * And don't try to go past the end of the file.
1299 * If we're not at a page boundary,
1300 * don't go past the next page.
1301 * If this means getting 0, then we were asked
1302 * to write past the end of file.
1303 * Finally, round down to a block boundary. */
1304 amount = min(amount_left_to_req, mod_data.buflen);
1305 amount = min((loff_t) amount, curlun->file_length -
1306 usb_offset);
1307 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1308 if (partial_page > 0)
1309 amount = min(amount,
1310 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1311
1312 if (amount == 0) {
1313 get_some_more = 0;
1314 curlun->sense_data =
1315 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1316 curlun->sense_data_info = usb_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001317 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001318 continue;
1319 }
1320 amount -= (amount & 511);
1321 if (amount == 0) {
1322
1323 /* Why were we were asked to transfer a
1324 * partial block? */
1325 get_some_more = 0;
1326 continue;
1327 }
1328
1329 /* Get the next buffer */
1330 usb_offset += amount;
1331 fsg->usb_amount_left -= amount;
1332 amount_left_to_req -= amount;
1333 if (amount_left_to_req == 0)
1334 get_some_more = 0;
1335
1336 /* amount is always divisible by 512, hence by
1337 * the bulk-out maxpacket size */
Mian Yousaf Kaukab806e8f82011-03-24 12:20:13 +01001338 bh->outreq->length = amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001339 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001340 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1341 &bh->outreq_busy, &bh->state);
1342 fsg->next_buffhd_to_fill = bh->next;
1343 continue;
1344 }
1345
1346 /* Write the received data to the backing file */
1347 bh = fsg->next_buffhd_to_drain;
1348 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1349 break; // We stopped early
1350 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001351 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001352 fsg->next_buffhd_to_drain = bh->next;
1353 bh->state = BUF_STATE_EMPTY;
1354
1355 /* Did something go wrong with the transfer? */
1356 if (bh->outreq->status != 0) {
1357 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1358 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001359 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001360 break;
1361 }
1362
1363 amount = bh->outreq->actual;
1364 if (curlun->file_length - file_offset < amount) {
1365 LERROR(curlun,
1366 "write %u @ %llu beyond end %llu\n",
1367 amount, (unsigned long long) file_offset,
1368 (unsigned long long) curlun->file_length);
1369 amount = curlun->file_length - file_offset;
1370 }
1371
1372 /* Perform the write */
1373 file_offset_tmp = file_offset;
1374 nwritten = vfs_write(curlun->filp,
1375 (char __user *) bh->buf,
1376 amount, &file_offset_tmp);
1377 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1378 (unsigned long long) file_offset,
1379 (int) nwritten);
1380 if (signal_pending(current))
1381 return -EINTR; // Interrupted!
1382
1383 if (nwritten < 0) {
1384 LDBG(curlun, "error in file write: %d\n",
1385 (int) nwritten);
1386 nwritten = 0;
1387 } else if (nwritten < amount) {
1388 LDBG(curlun, "partial file write: %d/%u\n",
1389 (int) nwritten, amount);
1390 nwritten -= (nwritten & 511);
1391 // Round down to a block
1392 }
1393 file_offset += nwritten;
1394 amount_left_to_write -= nwritten;
1395 fsg->residue -= nwritten;
1396
1397 /* If an error occurred, report it and its position */
1398 if (nwritten < amount) {
1399 curlun->sense_data = SS_WRITE_ERROR;
1400 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001401 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402 break;
1403 }
1404
1405 /* Did the host decide to stop early? */
1406 if (bh->outreq->actual != bh->outreq->length) {
1407 fsg->short_packet_received = 1;
1408 break;
1409 }
1410 continue;
1411 }
1412
1413 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001414 rc = sleep_thread(fsg);
1415 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001416 return rc;
1417 }
1418
1419 return -EIO; // No default reply
1420}
1421
1422
1423/*-------------------------------------------------------------------------*/
1424
Linus Torvalds1da177e2005-04-16 15:20:36 -07001425static int do_synchronize_cache(struct fsg_dev *fsg)
1426{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001427 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001428 int rc;
1429
1430 /* We ignore the requested LBA and write out all file's
1431 * dirty data buffers. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001432 rc = fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001433 if (rc)
1434 curlun->sense_data = SS_WRITE_ERROR;
1435 return 0;
1436}
1437
1438
1439/*-------------------------------------------------------------------------*/
1440
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001441static void invalidate_sub(struct fsg_lun *curlun)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001442{
1443 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001444 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001445 unsigned long rc;
1446
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001447 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01001448 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001449}
1450
1451static int do_verify(struct fsg_dev *fsg)
1452{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001453 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001454 u32 lba;
1455 u32 verification_length;
1456 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1457 loff_t file_offset, file_offset_tmp;
1458 u32 amount_left;
1459 unsigned int amount;
1460 ssize_t nread;
1461
1462 /* Get the starting Logical Block Address and check that it's
1463 * not too big */
Alan Stern604eb892009-04-27 13:19:41 -04001464 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001465 if (lba >= curlun->num_sectors) {
1466 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1467 return -EINVAL;
1468 }
1469
1470 /* We allow DPO (Disable Page Out = don't save data in the
1471 * cache) but we don't implement it. */
1472 if ((fsg->cmnd[1] & ~0x10) != 0) {
1473 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1474 return -EINVAL;
1475 }
1476
Alan Stern604eb892009-04-27 13:19:41 -04001477 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001478 if (unlikely(verification_length == 0))
1479 return -EIO; // No default reply
1480
1481 /* Prepare to carry out the file verify */
1482 amount_left = verification_length << 9;
1483 file_offset = ((loff_t) lba) << 9;
1484
1485 /* Write out all the dirty buffers before invalidating them */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001486 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001487 if (signal_pending(current))
1488 return -EINTR;
1489
1490 invalidate_sub(curlun);
1491 if (signal_pending(current))
1492 return -EINTR;
1493
1494 /* Just try to read the requested blocks */
1495 while (amount_left > 0) {
1496
1497 /* Figure out how much we need to read:
1498 * Try to read the remaining amount, but not more than
1499 * the buffer size.
1500 * And don't try to read past the end of the file.
1501 * If this means reading 0 then we were asked to read
1502 * past the end of file. */
1503 amount = min((unsigned int) amount_left, mod_data.buflen);
1504 amount = min((loff_t) amount,
1505 curlun->file_length - file_offset);
1506 if (amount == 0) {
1507 curlun->sense_data =
1508 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1509 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001510 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001511 break;
1512 }
1513
1514 /* Perform the read */
1515 file_offset_tmp = file_offset;
1516 nread = vfs_read(curlun->filp,
1517 (char __user *) bh->buf,
1518 amount, &file_offset_tmp);
1519 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1520 (unsigned long long) file_offset,
1521 (int) nread);
1522 if (signal_pending(current))
1523 return -EINTR;
1524
1525 if (nread < 0) {
1526 LDBG(curlun, "error in file verify: %d\n",
1527 (int) nread);
1528 nread = 0;
1529 } else if (nread < amount) {
1530 LDBG(curlun, "partial file verify: %d/%u\n",
1531 (int) nread, amount);
1532 nread -= (nread & 511); // Round down to a sector
1533 }
1534 if (nread == 0) {
1535 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1536 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001537 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001538 break;
1539 }
1540 file_offset += nread;
1541 amount_left -= nread;
1542 }
1543 return 0;
1544}
1545
1546
1547/*-------------------------------------------------------------------------*/
1548
1549static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1550{
1551 u8 *buf = (u8 *) bh->buf;
1552
1553 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05001554 static char product_disk_id[] = "File-Stor Gadget";
1555 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556
1557 if (!fsg->curlun) { // Unsupported LUNs are okay
1558 fsg->bad_lun_okay = 1;
1559 memset(buf, 0, 36);
1560 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05001561 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07001562 return 36;
1563 }
1564
Alan Stern12aae682008-11-20 14:13:12 -05001565 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001566 buf[0] = (mod_data.cdrom ? TYPE_ROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001567 if (mod_data.removable)
1568 buf[1] = 0x80;
1569 buf[2] = 2; // ANSI SCSI level 2
1570 buf[3] = 2; // SCSI-2 INQUIRY data format
1571 buf[4] = 31; // Additional length
1572 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05001573 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1574 (mod_data.cdrom ? product_cdrom_id :
1575 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001576 mod_data.release);
1577 return 36;
1578}
1579
1580
1581static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1582{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001583 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001584 u8 *buf = (u8 *) bh->buf;
1585 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04001586 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001587
1588 /*
1589 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1590 *
1591 * If a REQUEST SENSE command is received from an initiator
1592 * with a pending unit attention condition (before the target
1593 * generates the contingent allegiance condition), then the
1594 * target shall either:
1595 * a) report any pending sense data and preserve the unit
1596 * attention condition on the logical unit, or,
1597 * b) report the unit attention condition, may discard any
1598 * pending sense data, and clear the unit attention
1599 * condition on the logical unit for that initiator.
1600 *
1601 * FSG normally uses option a); enable this code to use option b).
1602 */
1603#if 0
1604 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1605 curlun->sense_data = curlun->unit_attention_data;
1606 curlun->unit_attention_data = SS_NO_SENSE;
1607 }
1608#endif
1609
1610 if (!curlun) { // Unsupported LUNs are okay
1611 fsg->bad_lun_okay = 1;
1612 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1613 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001614 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001615 } else {
1616 sd = curlun->sense_data;
1617 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04001618 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001619 curlun->sense_data = SS_NO_SENSE;
1620 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001621 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001622 }
1623
1624 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04001625 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07001626 buf[2] = SK(sd);
Alan Stern604eb892009-04-27 13:19:41 -04001627 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001628 buf[7] = 18 - 8; // Additional sense length
1629 buf[12] = ASC(sd);
1630 buf[13] = ASCQ(sd);
1631 return 18;
1632}
1633
1634
1635static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1636{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001637 struct fsg_lun *curlun = fsg->curlun;
Alan Stern604eb892009-04-27 13:19:41 -04001638 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001639 int pmi = fsg->cmnd[8];
1640 u8 *buf = (u8 *) bh->buf;
1641
1642 /* Check the PMI and LBA fields */
1643 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1644 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1645 return -EINVAL;
1646 }
1647
Alan Stern604eb892009-04-27 13:19:41 -04001648 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1649 /* Max logical block */
1650 put_unaligned_be32(512, &buf[4]); /* Block length */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001651 return 8;
1652}
1653
1654
Alan Stern12aae682008-11-20 14:13:12 -05001655static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1656{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001657 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001658 int msf = fsg->cmnd[1] & 0x02;
Alan Stern604eb892009-04-27 13:19:41 -04001659 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Alan Stern12aae682008-11-20 14:13:12 -05001660 u8 *buf = (u8 *) bh->buf;
1661
1662 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1663 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1664 return -EINVAL;
1665 }
1666 if (lba >= curlun->num_sectors) {
1667 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1668 return -EINVAL;
1669 }
1670
1671 memset(buf, 0, 8);
1672 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1673 store_cdrom_address(&buf[4], msf, lba);
1674 return 8;
1675}
1676
1677
1678static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1679{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001680 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001681 int msf = fsg->cmnd[1] & 0x02;
1682 int start_track = fsg->cmnd[6];
1683 u8 *buf = (u8 *) bh->buf;
1684
1685 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1686 start_track > 1) {
1687 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1688 return -EINVAL;
1689 }
1690
1691 memset(buf, 0, 20);
1692 buf[1] = (20-2); /* TOC data length */
1693 buf[2] = 1; /* First track number */
1694 buf[3] = 1; /* Last track number */
1695 buf[5] = 0x16; /* Data track, copying allowed */
1696 buf[6] = 0x01; /* Only track is number 1 */
1697 store_cdrom_address(&buf[8], msf, 0);
1698
1699 buf[13] = 0x16; /* Lead-out track is data */
1700 buf[14] = 0xAA; /* Lead-out track number */
1701 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1702 return 20;
1703}
1704
1705
Linus Torvalds1da177e2005-04-16 15:20:36 -07001706static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1707{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001708 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001709 int mscmnd = fsg->cmnd[0];
1710 u8 *buf = (u8 *) bh->buf;
1711 u8 *buf0 = buf;
1712 int pc, page_code;
1713 int changeable_values, all_pages;
1714 int valid_page = 0;
1715 int len, limit;
1716
1717 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1718 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1719 return -EINVAL;
1720 }
1721 pc = fsg->cmnd[2] >> 6;
1722 page_code = fsg->cmnd[2] & 0x3f;
1723 if (pc == 3) {
1724 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1725 return -EINVAL;
1726 }
1727 changeable_values = (pc == 1);
1728 all_pages = (page_code == 0x3f);
1729
1730 /* Write the mode parameter header. Fixed values are: default
1731 * medium type, no cache control (DPOFUA), and no block descriptors.
1732 * The only variable value is the WriteProtect bit. We will fill in
1733 * the mode data length later. */
1734 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001735 if (mscmnd == MODE_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001736 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1737 buf += 4;
1738 limit = 255;
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001739 } else { // MODE_SENSE_10
Linus Torvalds1da177e2005-04-16 15:20:36 -07001740 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1741 buf += 8;
1742 limit = 65535; // Should really be mod_data.buflen
1743 }
1744
1745 /* No block descriptors */
1746
1747 /* The mode pages, in numerical order. The only page we support
1748 * is the Caching page. */
1749 if (page_code == 0x08 || all_pages) {
1750 valid_page = 1;
1751 buf[0] = 0x08; // Page code
1752 buf[1] = 10; // Page length
1753 memset(buf+2, 0, 10); // None of the fields are changeable
1754
1755 if (!changeable_values) {
1756 buf[2] = 0x04; // Write cache enable,
1757 // Read cache not disabled
1758 // No cache retention priorities
Alan Stern604eb892009-04-27 13:19:41 -04001759 put_unaligned_be16(0xffff, &buf[4]);
1760 /* Don't disable prefetch */
1761 /* Minimum prefetch = 0 */
1762 put_unaligned_be16(0xffff, &buf[8]);
1763 /* Maximum prefetch */
1764 put_unaligned_be16(0xffff, &buf[10]);
1765 /* Maximum prefetch ceiling */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001766 }
1767 buf += 12;
1768 }
1769
1770 /* Check that a valid page was requested and the mode data length
1771 * isn't too long. */
1772 len = buf - buf0;
1773 if (!valid_page || len > limit) {
1774 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1775 return -EINVAL;
1776 }
1777
1778 /* Store the mode data length */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001779 if (mscmnd == MODE_SENSE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001780 buf0[0] = len - 1;
1781 else
Alan Stern604eb892009-04-27 13:19:41 -04001782 put_unaligned_be16(len - 2, buf0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001783 return len;
1784}
1785
1786
1787static int do_start_stop(struct fsg_dev *fsg)
1788{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001789 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001790 int loej, start;
1791
1792 if (!mod_data.removable) {
1793 curlun->sense_data = SS_INVALID_COMMAND;
1794 return -EINVAL;
1795 }
1796
1797 // int immed = fsg->cmnd[1] & 0x01;
1798 loej = fsg->cmnd[4] & 0x02;
1799 start = fsg->cmnd[4] & 0x01;
1800
1801#ifdef CONFIG_USB_FILE_STORAGE_TEST
1802 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1803 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1804 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1805 return -EINVAL;
1806 }
1807
1808 if (!start) {
1809
1810 /* Are we allowed to unload the media? */
1811 if (curlun->prevent_medium_removal) {
1812 LDBG(curlun, "unload attempt prevented\n");
1813 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1814 return -EINVAL;
1815 }
1816 if (loej) { // Simulate an unload/eject
1817 up_read(&fsg->filesem);
1818 down_write(&fsg->filesem);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001819 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001820 up_write(&fsg->filesem);
1821 down_read(&fsg->filesem);
1822 }
1823 } else {
1824
1825 /* Our emulation doesn't support mounting; the medium is
1826 * available for use as soon as it is loaded. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001827 if (!fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001828 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1829 return -EINVAL;
1830 }
1831 }
1832#endif
1833 return 0;
1834}
1835
1836
1837static int do_prevent_allow(struct fsg_dev *fsg)
1838{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001839 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001840 int prevent;
1841
1842 if (!mod_data.removable) {
1843 curlun->sense_data = SS_INVALID_COMMAND;
1844 return -EINVAL;
1845 }
1846
1847 prevent = fsg->cmnd[4] & 0x01;
1848 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1849 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1850 return -EINVAL;
1851 }
1852
1853 if (curlun->prevent_medium_removal && !prevent)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001854 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001855 curlun->prevent_medium_removal = prevent;
1856 return 0;
1857}
1858
1859
1860static int do_read_format_capacities(struct fsg_dev *fsg,
1861 struct fsg_buffhd *bh)
1862{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001863 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001864 u8 *buf = (u8 *) bh->buf;
1865
1866 buf[0] = buf[1] = buf[2] = 0;
1867 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1868 buf += 4;
1869
Alan Stern604eb892009-04-27 13:19:41 -04001870 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1871 /* Number of blocks */
1872 put_unaligned_be32(512, &buf[4]); /* Block length */
1873 buf[4] = 0x02; /* Current capacity */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001874 return 12;
1875}
1876
1877
1878static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1879{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001880 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001881
1882 /* We don't support MODE SELECT */
1883 curlun->sense_data = SS_INVALID_COMMAND;
1884 return -EINVAL;
1885}
1886
1887
1888/*-------------------------------------------------------------------------*/
1889
1890static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1891{
1892 int rc;
1893
1894 rc = fsg_set_halt(fsg, fsg->bulk_in);
1895 if (rc == -EAGAIN)
1896 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1897 while (rc != 0) {
1898 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001899 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001900 rc = 0;
1901 break;
1902 }
1903
1904 /* Wait for a short time and then try again */
1905 if (msleep_interruptible(100) != 0)
1906 return -EINTR;
1907 rc = usb_ep_set_halt(fsg->bulk_in);
1908 }
1909 return rc;
1910}
1911
David Lopo62fd2ca2008-04-29 10:14:38 +01001912static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1913{
1914 int rc;
1915
1916 DBG(fsg, "bulk-in set wedge\n");
1917 rc = usb_ep_set_wedge(fsg->bulk_in);
1918 if (rc == -EAGAIN)
1919 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1920 while (rc != 0) {
1921 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001922 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01001923 rc = 0;
1924 break;
1925 }
1926
1927 /* Wait for a short time and then try again */
1928 if (msleep_interruptible(100) != 0)
1929 return -EINTR;
1930 rc = usb_ep_set_wedge(fsg->bulk_in);
1931 }
1932 return rc;
1933}
1934
Linus Torvalds1da177e2005-04-16 15:20:36 -07001935static int pad_with_zeros(struct fsg_dev *fsg)
1936{
1937 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1938 u32 nkeep = bh->inreq->length;
1939 u32 nsend;
1940 int rc;
1941
1942 bh->state = BUF_STATE_EMPTY; // For the first iteration
1943 fsg->usb_amount_left = nkeep + fsg->residue;
1944 while (fsg->usb_amount_left > 0) {
1945
1946 /* Wait for the next buffer to be free */
1947 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001948 rc = sleep_thread(fsg);
1949 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001950 return rc;
1951 }
1952
1953 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
1954 memset(bh->buf + nkeep, 0, nsend - nkeep);
1955 bh->inreq->length = nsend;
1956 bh->inreq->zero = 0;
1957 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1958 &bh->inreq_busy, &bh->state);
1959 bh = fsg->next_buffhd_to_fill = bh->next;
1960 fsg->usb_amount_left -= nsend;
1961 nkeep = 0;
1962 }
1963 return 0;
1964}
1965
1966static int throw_away_data(struct fsg_dev *fsg)
1967{
1968 struct fsg_buffhd *bh;
1969 u32 amount;
1970 int rc;
1971
1972 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1973 fsg->usb_amount_left > 0) {
1974
1975 /* Throw away the data in a filled buffer */
1976 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001977 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001978 bh->state = BUF_STATE_EMPTY;
1979 fsg->next_buffhd_to_drain = bh->next;
1980
1981 /* A short packet or an error ends everything */
1982 if (bh->outreq->actual != bh->outreq->length ||
1983 bh->outreq->status != 0) {
1984 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1985 return -EINTR;
1986 }
1987 continue;
1988 }
1989
1990 /* Try to submit another request if we need one */
1991 bh = fsg->next_buffhd_to_fill;
1992 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1993 amount = min(fsg->usb_amount_left,
1994 (u32) mod_data.buflen);
1995
1996 /* amount is always divisible by 512, hence by
1997 * the bulk-out maxpacket size */
Mian Yousaf Kaukab806e8f82011-03-24 12:20:13 +01001998 bh->outreq->length = amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001999 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002000 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2001 &bh->outreq_busy, &bh->state);
2002 fsg->next_buffhd_to_fill = bh->next;
2003 fsg->usb_amount_left -= amount;
2004 continue;
2005 }
2006
2007 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04002008 rc = sleep_thread(fsg);
2009 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002010 return rc;
2011 }
2012 return 0;
2013}
2014
2015
2016static int finish_reply(struct fsg_dev *fsg)
2017{
2018 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2019 int rc = 0;
2020
2021 switch (fsg->data_dir) {
2022 case DATA_DIR_NONE:
2023 break; // Nothing to send
2024
2025 /* If we don't know whether the host wants to read or write,
2026 * this must be CB or CBI with an unknown command. We mustn't
2027 * try to send or receive any data. So stall both bulk pipes
2028 * if we can and wait for a reset. */
2029 case DATA_DIR_UNKNOWN:
2030 if (mod_data.can_stall) {
2031 fsg_set_halt(fsg, fsg->bulk_out);
2032 rc = halt_bulk_in_endpoint(fsg);
2033 }
2034 break;
2035
2036 /* All but the last buffer of data must have already been sent */
2037 case DATA_DIR_TO_HOST:
2038 if (fsg->data_size == 0)
2039 ; // Nothing to send
2040
2041 /* If there's no residue, simply send the last buffer */
2042 else if (fsg->residue == 0) {
2043 bh->inreq->zero = 0;
2044 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2045 &bh->inreq_busy, &bh->state);
2046 fsg->next_buffhd_to_fill = bh->next;
2047 }
2048
2049 /* There is a residue. For CB and CBI, simply mark the end
2050 * of the data with a short packet. However, if we are
2051 * allowed to stall, there was no data at all (residue ==
2052 * data_size), and the command failed (invalid LUN or
2053 * sense data is set), then halt the bulk-in endpoint
2054 * instead. */
2055 else if (!transport_is_bbb()) {
2056 if (mod_data.can_stall &&
2057 fsg->residue == fsg->data_size &&
2058 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2059 bh->state = BUF_STATE_EMPTY;
2060 rc = halt_bulk_in_endpoint(fsg);
2061 } else {
2062 bh->inreq->zero = 1;
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
2069 /* For Bulk-only, if we're allowed to stall then send the
2070 * short packet and halt the bulk-in endpoint. If we can't
2071 * stall, pad out the remaining data with 0's. */
2072 else {
2073 if (mod_data.can_stall) {
2074 bh->inreq->zero = 1;
2075 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2076 &bh->inreq_busy, &bh->state);
2077 fsg->next_buffhd_to_fill = bh->next;
2078 rc = halt_bulk_in_endpoint(fsg);
2079 } else
2080 rc = pad_with_zeros(fsg);
2081 }
2082 break;
2083
2084 /* We have processed all we want from the data the host has sent.
2085 * There may still be outstanding bulk-out requests. */
2086 case DATA_DIR_FROM_HOST:
2087 if (fsg->residue == 0)
2088 ; // Nothing to receive
2089
2090 /* Did the host stop sending unexpectedly early? */
2091 else if (fsg->short_packet_received) {
2092 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2093 rc = -EINTR;
2094 }
2095
2096 /* We haven't processed all the incoming data. Even though
2097 * we may be allowed to stall, doing so would cause a race.
2098 * The controller may already have ACK'ed all the remaining
2099 * bulk-out packets, in which case the host wouldn't see a
2100 * STALL. Not realizing the endpoint was halted, it wouldn't
2101 * clear the halt -- leading to problems later on. */
2102#if 0
2103 else if (mod_data.can_stall) {
2104 fsg_set_halt(fsg, fsg->bulk_out);
2105 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2106 rc = -EINTR;
2107 }
2108#endif
2109
2110 /* We can't stall. Read in the excess data and throw it
2111 * all away. */
2112 else
2113 rc = throw_away_data(fsg);
2114 break;
2115 }
2116 return rc;
2117}
2118
2119
2120static int send_status(struct fsg_dev *fsg)
2121{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002122 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002123 struct fsg_buffhd *bh;
2124 int rc;
2125 u8 status = USB_STATUS_PASS;
2126 u32 sd, sdinfo = 0;
2127
2128 /* Wait for the next buffer to become available */
2129 bh = fsg->next_buffhd_to_fill;
2130 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002131 rc = sleep_thread(fsg);
2132 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002133 return rc;
2134 }
2135
2136 if (curlun) {
2137 sd = curlun->sense_data;
2138 sdinfo = curlun->sense_data_info;
2139 } else if (fsg->bad_lun_okay)
2140 sd = SS_NO_SENSE;
2141 else
2142 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2143
2144 if (fsg->phase_error) {
2145 DBG(fsg, "sending phase-error status\n");
2146 status = USB_STATUS_PHASE_ERROR;
2147 sd = SS_INVALID_COMMAND;
2148 } else if (sd != SS_NO_SENSE) {
2149 DBG(fsg, "sending command-failure status\n");
2150 status = USB_STATUS_FAIL;
2151 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2152 " info x%x\n",
2153 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2154 }
2155
2156 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002157 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002158
2159 /* Store and send the Bulk-only CSW */
Harvey Harrison551509d2009-02-11 14:11:36 -08002160 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002161 csw->Tag = fsg->tag;
2162 csw->Residue = cpu_to_le32(fsg->residue);
2163 csw->Status = status;
2164
2165 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2166 bh->inreq->zero = 0;
2167 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2168 &bh->inreq_busy, &bh->state);
2169
2170 } else if (mod_data.transport_type == USB_PR_CB) {
2171
2172 /* Control-Bulk transport has no status phase! */
2173 return 0;
2174
2175 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002176 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002177
2178 /* Store and send the Interrupt data. UFI sends the ASC
2179 * and ASCQ bytes. Everything else sends a Type (which
2180 * is always 0) and the status Value. */
2181 if (mod_data.protocol_type == USB_SC_UFI) {
2182 buf->bType = ASC(sd);
2183 buf->bValue = ASCQ(sd);
2184 } else {
2185 buf->bType = 0;
2186 buf->bValue = status;
2187 }
2188 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2189
2190 fsg->intr_buffhd = bh; // Point to the right buffhd
2191 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002192 fsg->intreq->context = bh;
2193 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2194 &fsg->intreq_busy, &bh->state);
2195 }
2196
2197 fsg->next_buffhd_to_fill = bh->next;
2198 return 0;
2199}
2200
2201
2202/*-------------------------------------------------------------------------*/
2203
2204/* Check whether the command is properly formed and whether its data size
2205 * and direction agree with the values we already have. */
2206static int check_command(struct fsg_dev *fsg, int cmnd_size,
2207 enum data_direction data_dir, unsigned int mask,
2208 int needs_medium, const char *name)
2209{
2210 int i;
2211 int lun = fsg->cmnd[1] >> 5;
2212 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2213 char hdlen[20];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002214 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002215
2216 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2217 * Transparent SCSI doesn't pad. */
2218 if (protocol_is_scsi())
2219 ;
2220
2221 /* There's some disagreement as to whether RBC pads commands or not.
2222 * We'll play it safe and accept either form. */
2223 else if (mod_data.protocol_type == USB_SC_RBC) {
2224 if (fsg->cmnd_size == 12)
2225 cmnd_size = 12;
2226
2227 /* All the other protocols pad to 12 bytes */
2228 } else
2229 cmnd_size = 12;
2230
2231 hdlen[0] = 0;
2232 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2233 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2234 fsg->data_size);
2235 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2236 name, cmnd_size, dirletter[(int) data_dir],
2237 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2238
2239 /* We can't reply at all until we know the correct data direction
2240 * and size. */
2241 if (fsg->data_size_from_cmnd == 0)
2242 data_dir = DATA_DIR_NONE;
2243 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2244 fsg->data_dir = data_dir;
2245 fsg->data_size = fsg->data_size_from_cmnd;
2246
2247 } else { // Bulk-only
2248 if (fsg->data_size < fsg->data_size_from_cmnd) {
2249
2250 /* Host data size < Device data size is a phase error.
2251 * Carry out the command, but only transfer as much
2252 * as we are allowed. */
2253 fsg->data_size_from_cmnd = fsg->data_size;
2254 fsg->phase_error = 1;
2255 }
2256 }
2257 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2258
2259 /* Conflicting data directions is a phase error */
2260 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2261 fsg->phase_error = 1;
2262 return -EINVAL;
2263 }
2264
2265 /* Verify the length of the command itself */
2266 if (cmnd_size != fsg->cmnd_size) {
2267
Felipe Balbi549c41e2008-09-19 02:00:02 +03002268 /* Special case workaround: There are plenty of buggy SCSI
2269 * implementations. Many have issues with cbw->Length
2270 * field passing a wrong command size. For those cases we
2271 * always try to work around the problem by using the length
2272 * sent by the host side provided it is at least as large
2273 * as the correct command length.
2274 * Examples of such cases would be MS-Windows, which issues
2275 * REQUEST SENSE with cbw->Length == 12 where it should
2276 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2277 * REQUEST SENSE with cbw->Length == 10 where it should
2278 * be 6 as well.
2279 */
2280 if (cmnd_size <= fsg->cmnd_size) {
2281 DBG(fsg, "%s is buggy! Expected length %d "
2282 "but we got %d\n", name,
2283 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002284 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002285 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002286 fsg->phase_error = 1;
2287 return -EINVAL;
2288 }
2289 }
2290
Alan Sternd794ac72005-04-18 12:43:25 -04002291 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002292 if (transport_is_bbb()) {
2293 if (fsg->lun != lun)
2294 DBG(fsg, "using LUN %d from CBW, "
2295 "not LUN %d from CDB\n",
2296 fsg->lun, lun);
2297 } else
2298 fsg->lun = lun; // Use LUN from the command
2299
2300 /* Check the LUN */
2301 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2302 fsg->curlun = curlun = &fsg->luns[fsg->lun];
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002303 if (fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002304 curlun->sense_data = SS_NO_SENSE;
2305 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002306 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002307 }
2308 } else {
2309 fsg->curlun = curlun = NULL;
2310 fsg->bad_lun_okay = 0;
2311
2312 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2313 * to use unsupported LUNs; all others may not. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002314 if (fsg->cmnd[0] != INQUIRY &&
2315 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002316 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2317 return -EINVAL;
2318 }
2319 }
2320
2321 /* If a unit attention condition exists, only INQUIRY and
2322 * REQUEST SENSE commands are allowed; anything else must fail. */
2323 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002324 fsg->cmnd[0] != INQUIRY &&
2325 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002326 curlun->sense_data = curlun->unit_attention_data;
2327 curlun->unit_attention_data = SS_NO_SENSE;
2328 return -EINVAL;
2329 }
2330
2331 /* Check that only command bytes listed in the mask are non-zero */
2332 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2333 for (i = 1; i < cmnd_size; ++i) {
2334 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2335 if (curlun)
2336 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2337 return -EINVAL;
2338 }
2339 }
2340
2341 /* If the medium isn't mounted and the command needs to access
2342 * it, return an error. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002343 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002344 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2345 return -EINVAL;
2346 }
2347
2348 return 0;
2349}
2350
2351
2352static int do_scsi_command(struct fsg_dev *fsg)
2353{
2354 struct fsg_buffhd *bh;
2355 int rc;
2356 int reply = -EINVAL;
2357 int i;
2358 static char unknown[16];
2359
2360 dump_cdb(fsg);
2361
2362 /* Wait for the next buffer to become available for data or status */
2363 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2364 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002365 rc = sleep_thread(fsg);
2366 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002367 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002368 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002369 fsg->phase_error = 0;
2370 fsg->short_packet_received = 0;
2371
2372 down_read(&fsg->filesem); // We're using the backing file
2373 switch (fsg->cmnd[0]) {
2374
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002375 case INQUIRY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002376 fsg->data_size_from_cmnd = fsg->cmnd[4];
2377 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2378 (1<<4), 0,
2379 "INQUIRY")) == 0)
2380 reply = do_inquiry(fsg, bh);
2381 break;
2382
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002383 case MODE_SELECT:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002384 fsg->data_size_from_cmnd = fsg->cmnd[4];
2385 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2386 (1<<1) | (1<<4), 0,
2387 "MODE SELECT(6)")) == 0)
2388 reply = do_mode_select(fsg, bh);
2389 break;
2390
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002391 case MODE_SELECT_10:
Alan Stern604eb892009-04-27 13:19:41 -04002392 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002393 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2394 (1<<1) | (3<<7), 0,
2395 "MODE SELECT(10)")) == 0)
2396 reply = do_mode_select(fsg, bh);
2397 break;
2398
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002399 case MODE_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002400 fsg->data_size_from_cmnd = fsg->cmnd[4];
2401 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2402 (1<<1) | (1<<2) | (1<<4), 0,
2403 "MODE SENSE(6)")) == 0)
2404 reply = do_mode_sense(fsg, bh);
2405 break;
2406
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002407 case MODE_SENSE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002408 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002409 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2410 (1<<1) | (1<<2) | (3<<7), 0,
2411 "MODE SENSE(10)")) == 0)
2412 reply = do_mode_sense(fsg, bh);
2413 break;
2414
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002415 case ALLOW_MEDIUM_REMOVAL:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002416 fsg->data_size_from_cmnd = 0;
2417 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2418 (1<<4), 0,
2419 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2420 reply = do_prevent_allow(fsg);
2421 break;
2422
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002423 case READ_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002424 i = fsg->cmnd[4];
2425 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2426 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2427 (7<<1) | (1<<4), 1,
2428 "READ(6)")) == 0)
2429 reply = do_read(fsg);
2430 break;
2431
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002432 case READ_10:
Alan Stern604eb892009-04-27 13:19:41 -04002433 fsg->data_size_from_cmnd =
2434 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002435 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2436 (1<<1) | (0xf<<2) | (3<<7), 1,
2437 "READ(10)")) == 0)
2438 reply = do_read(fsg);
2439 break;
2440
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002441 case READ_12:
Alan Stern604eb892009-04-27 13:19:41 -04002442 fsg->data_size_from_cmnd =
2443 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002444 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2445 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2446 "READ(12)")) == 0)
2447 reply = do_read(fsg);
2448 break;
2449
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002450 case READ_CAPACITY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002451 fsg->data_size_from_cmnd = 8;
2452 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2453 (0xf<<2) | (1<<8), 1,
2454 "READ CAPACITY")) == 0)
2455 reply = do_read_capacity(fsg, bh);
2456 break;
2457
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002458 case READ_HEADER:
Alan Stern12aae682008-11-20 14:13:12 -05002459 if (!mod_data.cdrom)
2460 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002461 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002462 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2463 (3<<7) | (0x1f<<1), 1,
2464 "READ HEADER")) == 0)
2465 reply = do_read_header(fsg, bh);
2466 break;
2467
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002468 case READ_TOC:
Alan Stern12aae682008-11-20 14:13:12 -05002469 if (!mod_data.cdrom)
2470 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002471 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002472 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2473 (7<<6) | (1<<1), 1,
2474 "READ TOC")) == 0)
2475 reply = do_read_toc(fsg, bh);
2476 break;
2477
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002478 case READ_FORMAT_CAPACITIES:
Alan Stern604eb892009-04-27 13:19:41 -04002479 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002480 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2481 (3<<7), 1,
2482 "READ FORMAT CAPACITIES")) == 0)
2483 reply = do_read_format_capacities(fsg, bh);
2484 break;
2485
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002486 case REQUEST_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002487 fsg->data_size_from_cmnd = fsg->cmnd[4];
2488 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2489 (1<<4), 0,
2490 "REQUEST SENSE")) == 0)
2491 reply = do_request_sense(fsg, bh);
2492 break;
2493
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002494 case START_STOP:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002495 fsg->data_size_from_cmnd = 0;
2496 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2497 (1<<1) | (1<<4), 0,
2498 "START-STOP UNIT")) == 0)
2499 reply = do_start_stop(fsg);
2500 break;
2501
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002502 case SYNCHRONIZE_CACHE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002503 fsg->data_size_from_cmnd = 0;
2504 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2505 (0xf<<2) | (3<<7), 1,
2506 "SYNCHRONIZE CACHE")) == 0)
2507 reply = do_synchronize_cache(fsg);
2508 break;
2509
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002510 case TEST_UNIT_READY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002511 fsg->data_size_from_cmnd = 0;
2512 reply = check_command(fsg, 6, DATA_DIR_NONE,
2513 0, 1,
2514 "TEST UNIT READY");
2515 break;
2516
2517 /* Although optional, this command is used by MS-Windows. We
2518 * support a minimal version: BytChk must be 0. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002519 case VERIFY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002520 fsg->data_size_from_cmnd = 0;
2521 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2522 (1<<1) | (0xf<<2) | (3<<7), 1,
2523 "VERIFY")) == 0)
2524 reply = do_verify(fsg);
2525 break;
2526
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002527 case WRITE_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002528 i = fsg->cmnd[4];
2529 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2530 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2531 (7<<1) | (1<<4), 1,
2532 "WRITE(6)")) == 0)
2533 reply = do_write(fsg);
2534 break;
2535
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002536 case WRITE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002537 fsg->data_size_from_cmnd =
2538 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002539 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2540 (1<<1) | (0xf<<2) | (3<<7), 1,
2541 "WRITE(10)")) == 0)
2542 reply = do_write(fsg);
2543 break;
2544
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002545 case WRITE_12:
Alan Stern604eb892009-04-27 13:19:41 -04002546 fsg->data_size_from_cmnd =
2547 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002548 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2549 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2550 "WRITE(12)")) == 0)
2551 reply = do_write(fsg);
2552 break;
2553
2554 /* Some mandatory commands that we recognize but don't implement.
2555 * They don't mean much in this setting. It's left as an exercise
2556 * for anyone interested to implement RESERVE and RELEASE in terms
2557 * of Posix locks. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002558 case FORMAT_UNIT:
2559 case RELEASE:
2560 case RESERVE:
2561 case SEND_DIAGNOSTIC:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002562 // Fall through
2563
2564 default:
Alan Stern12aae682008-11-20 14:13:12 -05002565 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002566 fsg->data_size_from_cmnd = 0;
2567 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2568 if ((reply = check_command(fsg, fsg->cmnd_size,
2569 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2570 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2571 reply = -EINVAL;
2572 }
2573 break;
2574 }
2575 up_read(&fsg->filesem);
2576
2577 if (reply == -EINTR || signal_pending(current))
2578 return -EINTR;
2579
2580 /* Set up the single reply buffer for finish_reply() */
2581 if (reply == -EINVAL)
2582 reply = 0; // Error reply length
2583 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2584 reply = min((u32) reply, fsg->data_size_from_cmnd);
2585 bh->inreq->length = reply;
2586 bh->state = BUF_STATE_FULL;
2587 fsg->residue -= reply;
2588 } // Otherwise it's already set
2589
2590 return 0;
2591}
2592
2593
2594/*-------------------------------------------------------------------------*/
2595
2596static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2597{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002598 struct usb_request *req = bh->outreq;
2599 struct fsg_bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002600
Alan Sternb950bdb2008-04-14 11:45:29 -04002601 /* Was this a real packet? Should it be ignored? */
2602 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002603 return -EINVAL;
2604
2605 /* Is the CBW valid? */
2606 if (req->actual != USB_BULK_CB_WRAP_LEN ||
Harvey Harrison551509d2009-02-11 14:11:36 -08002607 cbw->Signature != cpu_to_le32(
Linus Torvalds1da177e2005-04-16 15:20:36 -07002608 USB_BULK_CB_SIG)) {
2609 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2610 req->actual,
2611 le32_to_cpu(cbw->Signature));
2612
Alan Sternb950bdb2008-04-14 11:45:29 -04002613 /* The Bulk-only spec says we MUST stall the IN endpoint
2614 * (6.6.1), so it's unavoidable. It also says we must
2615 * retain this state until the next reset, but there's
2616 * no way to tell the controller driver it should ignore
2617 * Clear-Feature(HALT) requests.
2618 *
2619 * We aren't required to halt the OUT endpoint; instead
2620 * we can simply accept and discard any data received
2621 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01002622 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04002623 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002624 return -EINVAL;
2625 }
2626
2627 /* Is the CBW meaningful? */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002628 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04002629 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002630 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2631 "cmdlen %u\n",
2632 cbw->Lun, cbw->Flags, cbw->Length);
2633
2634 /* We can do anything we want here, so let's stall the
2635 * bulk pipes if we are allowed to. */
2636 if (mod_data.can_stall) {
2637 fsg_set_halt(fsg, fsg->bulk_out);
2638 halt_bulk_in_endpoint(fsg);
2639 }
2640 return -EINVAL;
2641 }
2642
2643 /* Save the command for later */
2644 fsg->cmnd_size = cbw->Length;
2645 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2646 if (cbw->Flags & USB_BULK_IN_FLAG)
2647 fsg->data_dir = DATA_DIR_TO_HOST;
2648 else
2649 fsg->data_dir = DATA_DIR_FROM_HOST;
2650 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2651 if (fsg->data_size == 0)
2652 fsg->data_dir = DATA_DIR_NONE;
2653 fsg->lun = cbw->Lun;
2654 fsg->tag = cbw->Tag;
2655 return 0;
2656}
2657
2658
2659static int get_next_command(struct fsg_dev *fsg)
2660{
2661 struct fsg_buffhd *bh;
2662 int rc = 0;
2663
2664 if (transport_is_bbb()) {
2665
2666 /* Wait for the next buffer to become available */
2667 bh = fsg->next_buffhd_to_fill;
2668 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002669 rc = sleep_thread(fsg);
2670 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002671 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002672 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002673
2674 /* Queue a request to read a Bulk-only CBW */
Mian Yousaf Kaukab806e8f82011-03-24 12:20:13 +01002675 bh->outreq->length = USB_BULK_CB_WRAP_LEN;
2676 bh->outreq->short_not_ok = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002677 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2678 &bh->outreq_busy, &bh->state);
2679
2680 /* We will drain the buffer in software, which means we
2681 * can reuse it for the next filling. No need to advance
2682 * next_buffhd_to_fill. */
2683
2684 /* Wait for the CBW to arrive */
2685 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002686 rc = sleep_thread(fsg);
2687 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002688 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002689 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05002690 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002691 rc = received_cbw(fsg, bh);
2692 bh->state = BUF_STATE_EMPTY;
2693
2694 } else { // USB_PR_CB or USB_PR_CBI
2695
2696 /* Wait for the next command to arrive */
2697 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002698 rc = sleep_thread(fsg);
2699 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002700 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002701 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002702
2703 /* Is the previous status interrupt request still busy?
2704 * The host is allowed to skip reading the status,
2705 * so we must cancel it. */
2706 if (fsg->intreq_busy)
2707 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2708
2709 /* Copy the command and mark the buffer empty */
2710 fsg->data_dir = DATA_DIR_UNKNOWN;
2711 spin_lock_irq(&fsg->lock);
2712 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2713 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2714 fsg->cbbuf_cmnd_size = 0;
2715 spin_unlock_irq(&fsg->lock);
2716 }
2717 return rc;
2718}
2719
2720
2721/*-------------------------------------------------------------------------*/
2722
2723static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2724 const struct usb_endpoint_descriptor *d)
2725{
2726 int rc;
2727
2728 ep->driver_data = fsg;
2729 rc = usb_ep_enable(ep, d);
2730 if (rc)
2731 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2732 return rc;
2733}
2734
2735static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2736 struct usb_request **preq)
2737{
2738 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2739 if (*preq)
2740 return 0;
2741 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2742 return -ENOMEM;
2743}
2744
2745/*
2746 * Reset interface setting and re-init endpoint state (toggle etc).
2747 * Call with altsetting < 0 to disable the interface. The only other
2748 * available altsetting is 0, which enables the interface.
2749 */
2750static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2751{
2752 int rc = 0;
2753 int i;
2754 const struct usb_endpoint_descriptor *d;
2755
2756 if (fsg->running)
2757 DBG(fsg, "reset interface\n");
2758
2759reset:
2760 /* Deallocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002761 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002762 struct fsg_buffhd *bh = &fsg->buffhds[i];
2763
2764 if (bh->inreq) {
2765 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2766 bh->inreq = NULL;
2767 }
2768 if (bh->outreq) {
2769 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2770 bh->outreq = NULL;
2771 }
2772 }
2773 if (fsg->intreq) {
2774 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2775 fsg->intreq = NULL;
2776 }
2777
2778 /* Disable the endpoints */
2779 if (fsg->bulk_in_enabled) {
2780 usb_ep_disable(fsg->bulk_in);
2781 fsg->bulk_in_enabled = 0;
2782 }
2783 if (fsg->bulk_out_enabled) {
2784 usb_ep_disable(fsg->bulk_out);
2785 fsg->bulk_out_enabled = 0;
2786 }
2787 if (fsg->intr_in_enabled) {
2788 usb_ep_disable(fsg->intr_in);
2789 fsg->intr_in_enabled = 0;
2790 }
2791
2792 fsg->running = 0;
2793 if (altsetting < 0 || rc != 0)
2794 return rc;
2795
2796 DBG(fsg, "set interface %d\n", altsetting);
2797
2798 /* Enable the endpoints */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002799 d = fsg_ep_desc(fsg->gadget,
2800 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002801 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2802 goto reset;
2803 fsg->bulk_in_enabled = 1;
2804
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002805 d = fsg_ep_desc(fsg->gadget,
2806 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002807 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2808 goto reset;
2809 fsg->bulk_out_enabled = 1;
2810 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
Alan Sternb950bdb2008-04-14 11:45:29 -04002811 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002812
2813 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002814 d = fsg_ep_desc(fsg->gadget,
2815 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002816 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2817 goto reset;
2818 fsg->intr_in_enabled = 1;
2819 }
2820
2821 /* Allocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002822 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002823 struct fsg_buffhd *bh = &fsg->buffhds[i];
2824
2825 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2826 goto reset;
2827 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2828 goto reset;
2829 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002830 bh->inreq->context = bh->outreq->context = bh;
2831 bh->inreq->complete = bulk_in_complete;
2832 bh->outreq->complete = bulk_out_complete;
2833 }
2834 if (transport_is_cbi()) {
2835 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2836 goto reset;
2837 fsg->intreq->complete = intr_in_complete;
2838 }
2839
2840 fsg->running = 1;
2841 for (i = 0; i < fsg->nluns; ++i)
2842 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2843 return rc;
2844}
2845
2846
2847/*
2848 * Change our operational configuration. This code must agree with the code
2849 * that returns config descriptors, and with interface altsetting code.
2850 *
2851 * It's also responsible for power management interactions. Some
2852 * configurations might not work with our current power sources.
2853 * For now we just assume the gadget is always self-powered.
2854 */
2855static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2856{
2857 int rc = 0;
2858
2859 /* Disable the single interface */
2860 if (fsg->config != 0) {
2861 DBG(fsg, "reset config\n");
2862 fsg->config = 0;
2863 rc = do_set_interface(fsg, -1);
2864 }
2865
2866 /* Enable the interface */
2867 if (new_config != 0) {
2868 fsg->config = new_config;
2869 if ((rc = do_set_interface(fsg, 0)) != 0)
2870 fsg->config = 0; // Reset on errors
2871 else {
2872 char *speed;
2873
2874 switch (fsg->gadget->speed) {
2875 case USB_SPEED_LOW: speed = "low"; break;
2876 case USB_SPEED_FULL: speed = "full"; break;
2877 case USB_SPEED_HIGH: speed = "high"; break;
2878 default: speed = "?"; break;
2879 }
2880 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2881 }
2882 }
2883 return rc;
2884}
2885
2886
2887/*-------------------------------------------------------------------------*/
2888
2889static void handle_exception(struct fsg_dev *fsg)
2890{
2891 siginfo_t info;
2892 int sig;
2893 int i;
2894 int num_active;
2895 struct fsg_buffhd *bh;
2896 enum fsg_state old_state;
2897 u8 new_config;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002898 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002899 unsigned int exception_req_tag;
2900 int rc;
2901
2902 /* Clear the existing signals. Anything but SIGUSR1 is converted
2903 * into a high-priority EXIT exception. */
2904 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04002905 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002906 if (!sig)
2907 break;
2908 if (sig != SIGUSR1) {
2909 if (fsg->state < FSG_STATE_EXIT)
2910 DBG(fsg, "Main thread exiting on signal\n");
2911 raise_exception(fsg, FSG_STATE_EXIT);
2912 }
2913 }
2914
2915 /* Cancel all the pending transfers */
2916 if (fsg->intreq_busy)
2917 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002918 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002919 bh = &fsg->buffhds[i];
2920 if (bh->inreq_busy)
2921 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2922 if (bh->outreq_busy)
2923 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2924 }
2925
2926 /* Wait until everything is idle */
2927 for (;;) {
2928 num_active = fsg->intreq_busy;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002929 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002930 bh = &fsg->buffhds[i];
2931 num_active += bh->inreq_busy + bh->outreq_busy;
2932 }
2933 if (num_active == 0)
2934 break;
2935 if (sleep_thread(fsg))
2936 return;
2937 }
2938
2939 /* Clear out the controller's fifos */
2940 if (fsg->bulk_in_enabled)
2941 usb_ep_fifo_flush(fsg->bulk_in);
2942 if (fsg->bulk_out_enabled)
2943 usb_ep_fifo_flush(fsg->bulk_out);
2944 if (fsg->intr_in_enabled)
2945 usb_ep_fifo_flush(fsg->intr_in);
2946
2947 /* Reset the I/O buffer states and pointers, the SCSI
2948 * state, and the exception. Then invoke the handler. */
2949 spin_lock_irq(&fsg->lock);
2950
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002951 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002952 bh = &fsg->buffhds[i];
2953 bh->state = BUF_STATE_EMPTY;
2954 }
2955 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2956 &fsg->buffhds[0];
2957
2958 exception_req_tag = fsg->exception_req_tag;
2959 new_config = fsg->new_config;
2960 old_state = fsg->state;
2961
2962 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2963 fsg->state = FSG_STATE_STATUS_PHASE;
2964 else {
2965 for (i = 0; i < fsg->nluns; ++i) {
2966 curlun = &fsg->luns[i];
2967 curlun->prevent_medium_removal = 0;
2968 curlun->sense_data = curlun->unit_attention_data =
2969 SS_NO_SENSE;
2970 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002971 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002972 }
2973 fsg->state = FSG_STATE_IDLE;
2974 }
2975 spin_unlock_irq(&fsg->lock);
2976
2977 /* Carry out any extra actions required for the exception */
2978 switch (old_state) {
2979 default:
2980 break;
2981
2982 case FSG_STATE_ABORT_BULK_OUT:
2983 send_status(fsg);
2984 spin_lock_irq(&fsg->lock);
2985 if (fsg->state == FSG_STATE_STATUS_PHASE)
2986 fsg->state = FSG_STATE_IDLE;
2987 spin_unlock_irq(&fsg->lock);
2988 break;
2989
2990 case FSG_STATE_RESET:
2991 /* In case we were forced against our will to halt a
2992 * bulk endpoint, clear the halt now. (The SuperH UDC
2993 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04002994 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002995 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002996
2997 if (transport_is_bbb()) {
2998 if (fsg->ep0_req_tag == exception_req_tag)
2999 ep0_queue(fsg); // Complete the status stage
3000
3001 } else if (transport_is_cbi())
3002 send_status(fsg); // Status by interrupt pipe
3003
3004 /* Technically this should go here, but it would only be
3005 * a waste of time. Ditto for the INTERFACE_CHANGE and
3006 * CONFIG_CHANGE cases. */
3007 // for (i = 0; i < fsg->nluns; ++i)
3008 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3009 break;
3010
3011 case FSG_STATE_INTERFACE_CHANGE:
3012 rc = do_set_interface(fsg, 0);
3013 if (fsg->ep0_req_tag != exception_req_tag)
3014 break;
3015 if (rc != 0) // STALL on errors
3016 fsg_set_halt(fsg, fsg->ep0);
3017 else // Complete the status stage
3018 ep0_queue(fsg);
3019 break;
3020
3021 case FSG_STATE_CONFIG_CHANGE:
3022 rc = do_set_config(fsg, new_config);
3023 if (fsg->ep0_req_tag != exception_req_tag)
3024 break;
3025 if (rc != 0) // STALL on errors
3026 fsg_set_halt(fsg, fsg->ep0);
3027 else // Complete the status stage
3028 ep0_queue(fsg);
3029 break;
3030
3031 case FSG_STATE_DISCONNECT:
Michal Nazarewiczb6058d02009-10-28 16:57:14 +01003032 for (i = 0; i < fsg->nluns; ++i)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003033 fsg_lun_fsync_sub(fsg->luns + i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003034 do_set_config(fsg, 0); // Unconfigured state
3035 break;
3036
3037 case FSG_STATE_EXIT:
3038 case FSG_STATE_TERMINATED:
3039 do_set_config(fsg, 0); // Free resources
3040 spin_lock_irq(&fsg->lock);
3041 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3042 spin_unlock_irq(&fsg->lock);
3043 break;
3044 }
3045}
3046
3047
3048/*-------------------------------------------------------------------------*/
3049
3050static int fsg_main_thread(void *fsg_)
3051{
John Daiker7ca46b82006-12-29 19:02:06 -08003052 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003053
Linus Torvalds1da177e2005-04-16 15:20:36 -07003054 /* Allow the thread to be killed by a signal, but set the signal mask
3055 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003056 allow_signal(SIGINT);
3057 allow_signal(SIGTERM);
3058 allow_signal(SIGKILL);
3059 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003060
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003061 /* Allow the thread to be frozen */
3062 set_freezable();
3063
Linus Torvalds1da177e2005-04-16 15:20:36 -07003064 /* Arrange for userspace references to be interpreted as kernel
3065 * pointers. That way we can pass a kernel pointer to a routine
3066 * that expects a __user pointer and it will work okay. */
3067 set_fs(get_ds());
3068
Linus Torvalds1da177e2005-04-16 15:20:36 -07003069 /* The main loop */
3070 while (fsg->state != FSG_STATE_TERMINATED) {
3071 if (exception_in_progress(fsg) || signal_pending(current)) {
3072 handle_exception(fsg);
3073 continue;
3074 }
3075
3076 if (!fsg->running) {
3077 sleep_thread(fsg);
3078 continue;
3079 }
3080
3081 if (get_next_command(fsg))
3082 continue;
3083
3084 spin_lock_irq(&fsg->lock);
3085 if (!exception_in_progress(fsg))
3086 fsg->state = FSG_STATE_DATA_PHASE;
3087 spin_unlock_irq(&fsg->lock);
3088
3089 if (do_scsi_command(fsg) || finish_reply(fsg))
3090 continue;
3091
3092 spin_lock_irq(&fsg->lock);
3093 if (!exception_in_progress(fsg))
3094 fsg->state = FSG_STATE_STATUS_PHASE;
3095 spin_unlock_irq(&fsg->lock);
3096
3097 if (send_status(fsg))
3098 continue;
3099
3100 spin_lock_irq(&fsg->lock);
3101 if (!exception_in_progress(fsg))
3102 fsg->state = FSG_STATE_IDLE;
3103 spin_unlock_irq(&fsg->lock);
3104 }
3105
Alan Stern22efcf42005-09-26 16:12:02 -04003106 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003107 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003108 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003109
Alan Stern82a10a82009-04-16 15:37:28 -04003110 /* If we are exiting because of a signal, unregister the
3111 * gadget driver. */
3112 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003113 usb_gadget_unregister_driver(&fsg_driver);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003114
3115 /* Let the unbind and cleanup routines know the thread has exited */
3116 complete_and_exit(&fsg->thread_notifier, 0);
3117}
3118
3119
3120/*-------------------------------------------------------------------------*/
3121
Linus Torvalds1da177e2005-04-16 15:20:36 -07003122
3123/* The write permissions and store_xxx pointers are set in fsg_bind() */
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003124static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003125static DEVICE_ATTR(nofua, 0644, fsg_show_nofua, NULL);
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003126static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003127
3128
3129/*-------------------------------------------------------------------------*/
3130
Alan Stern87c42522005-11-09 16:59:56 -05003131static void fsg_release(struct kref *ref)
3132{
3133 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3134
3135 kfree(fsg->luns);
3136 kfree(fsg);
3137}
3138
Linus Torvalds1da177e2005-04-16 15:20:36 -07003139static void lun_release(struct device *dev)
3140{
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003141 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3142 struct fsg_dev *fsg =
3143 container_of(filesem, struct fsg_dev, filesem);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003144
Alan Stern87c42522005-11-09 16:59:56 -05003145 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003146}
3147
David Brownella3536782006-07-06 15:48:53 -07003148static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003149{
3150 struct fsg_dev *fsg = get_gadget_data(gadget);
3151 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003152 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003153 struct usb_request *req = fsg->ep0req;
3154
3155 DBG(fsg, "unbind\n");
3156 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3157
3158 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003159 for (i = 0; i < fsg->nluns; ++i) {
3160 curlun = &fsg->luns[i];
3161 if (curlun->registered) {
Michal Nazarewicz452ee0e2010-08-12 17:43:50 +02003162 device_remove_file(&curlun->dev, &dev_attr_nofua);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003163 device_remove_file(&curlun->dev, &dev_attr_ro);
3164 device_remove_file(&curlun->dev, &dev_attr_file);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003165 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003166 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003167 curlun->registered = 0;
3168 }
3169 }
3170
3171 /* If the thread isn't already dead, tell it to exit now */
3172 if (fsg->state != FSG_STATE_TERMINATED) {
3173 raise_exception(fsg, FSG_STATE_EXIT);
3174 wait_for_completion(&fsg->thread_notifier);
3175
3176 /* The cleanup routine waits for this completion also */
3177 complete(&fsg->thread_notifier);
3178 }
3179
3180 /* Free the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003181 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
David Brownell9d8bab52007-07-01 11:04:54 -07003182 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003183
3184 /* Free the request and buffer for endpoint 0 */
3185 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003186 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003187 usb_ep_free_request(fsg->ep0, req);
3188 }
3189
3190 set_gadget_data(gadget, NULL);
3191}
3192
3193
3194static int __init check_parameters(struct fsg_dev *fsg)
3195{
3196 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003197 int gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003198
3199 /* Store the default values */
3200 mod_data.transport_type = USB_PR_BULK;
3201 mod_data.transport_name = "Bulk-only";
3202 mod_data.protocol_type = USB_SC_SCSI;
3203 mod_data.protocol_name = "Transparent SCSI";
3204
Alan Sternce459ec2009-02-24 16:19:47 -05003205 /* Some peripheral controllers are known not to be able to
3206 * halt bulk endpoints correctly. If one of them is present,
3207 * disable stalls.
3208 */
Christoph Egger90f79762010-02-05 13:24:12 +01003209 if (gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003210 mod_data.can_stall = 0;
3211
3212 if (mod_data.release == 0xffff) { // Parameter wasn't set
Christoph Egger90f79762010-02-05 13:24:12 +01003213 gcnum = usb_gadget_controller_number(fsg->gadget);
David Brownell91e79c92005-07-13 15:18:30 -07003214 if (gcnum >= 0)
3215 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003216 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003217 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003218 fsg->gadget->name);
3219 mod_data.release = 0x0399;
3220 }
3221 }
3222
3223 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3224
3225#ifdef CONFIG_USB_FILE_STORAGE_TEST
3226 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3227 ; // Use default setting
3228 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3229 mod_data.transport_type = USB_PR_CB;
3230 mod_data.transport_name = "Control-Bulk";
3231 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3232 mod_data.transport_type = USB_PR_CBI;
3233 mod_data.transport_name = "Control-Bulk-Interrupt";
3234 } else {
3235 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3236 return -EINVAL;
3237 }
3238
3239 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3240 prot == USB_SC_SCSI) {
3241 ; // Use default setting
3242 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3243 prot == USB_SC_RBC) {
3244 mod_data.protocol_type = USB_SC_RBC;
3245 mod_data.protocol_name = "RBC";
3246 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3247 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3248 prot == USB_SC_8020) {
3249 mod_data.protocol_type = USB_SC_8020;
3250 mod_data.protocol_name = "8020i (ATAPI)";
3251 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3252 prot == USB_SC_QIC) {
3253 mod_data.protocol_type = USB_SC_QIC;
3254 mod_data.protocol_name = "QIC-157";
3255 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3256 prot == USB_SC_UFI) {
3257 mod_data.protocol_type = USB_SC_UFI;
3258 mod_data.protocol_name = "UFI";
3259 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3260 prot == USB_SC_8070) {
3261 mod_data.protocol_type = USB_SC_8070;
3262 mod_data.protocol_name = "8070i";
3263 } else {
3264 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3265 return -EINVAL;
3266 }
3267
3268 mod_data.buflen &= PAGE_CACHE_MASK;
3269 if (mod_data.buflen <= 0) {
3270 ERROR(fsg, "invalid buflen\n");
3271 return -ETOOSMALL;
3272 }
Yann Cantin87eb1be2010-06-05 23:06:31 +02003273
Michal Nazarewicz56706492010-07-22 14:16:37 +02003274#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3275
Yann Cantin87eb1be2010-06-05 23:06:31 +02003276 /* Serial string handling.
3277 * On a real device, the serial string would be loaded
3278 * from permanent storage. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003279 if (mod_data.serial) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003280 const char *ch;
3281 unsigned len = 0;
3282
3283 /* Sanity check :
3284 * The CB[I] specification limits the serial string to
3285 * 12 uppercase hexadecimal characters.
3286 * BBB need at least 12 uppercase hexadecimal characters,
3287 * with a maximum of 126. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003288 for (ch = mod_data.serial; *ch; ++ch) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003289 ++len;
3290 if ((*ch < '0' || *ch > '9') &&
3291 (*ch < 'A' || *ch > 'F')) { /* not uppercase hex */
3292 WARNING(fsg,
Alan Sternd8087422010-09-03 11:15:41 -04003293 "Invalid serial string character: %c\n",
Yann Cantin87eb1be2010-06-05 23:06:31 +02003294 *ch);
Alan Sternd8087422010-09-03 11:15:41 -04003295 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003296 }
3297 }
3298 if (len > 126 ||
3299 (mod_data.transport_type == USB_PR_BULK && len < 12) ||
3300 (mod_data.transport_type != USB_PR_BULK && len > 12)) {
Alan Sternd8087422010-09-03 11:15:41 -04003301 WARNING(fsg, "Invalid serial string length!\n");
3302 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003303 }
Michal Nazarewicz56706492010-07-22 14:16:37 +02003304 fsg_strings[FSG_STRING_SERIAL - 1].s = mod_data.serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003305 } else {
Alan Sternd8087422010-09-03 11:15:41 -04003306 WARNING(fsg, "No serial-number string provided!\n");
3307 no_serial:
3308 device_desc.iSerialNumber = 0;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003309 }
3310
Linus Torvalds1da177e2005-04-16 15:20:36 -07003311 return 0;
3312}
3313
3314
Michal Nazarewicze12995e2010-08-12 17:43:52 +02003315static int __init fsg_bind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003316{
3317 struct fsg_dev *fsg = the_fsg;
3318 int rc;
3319 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003320 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003321 struct usb_ep *ep;
3322 struct usb_request *req;
3323 char *pathbuf, *p;
3324
3325 fsg->gadget = gadget;
3326 set_gadget_data(gadget, fsg);
3327 fsg->ep0 = gadget->ep0;
3328 fsg->ep0->driver_data = fsg;
3329
3330 if ((rc = check_parameters(fsg)) != 0)
3331 goto out;
3332
3333 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003334 dev_attr_file.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003335 dev_attr_file.store = fsg_store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003336 if (!mod_data.cdrom) {
3337 dev_attr_ro.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003338 dev_attr_ro.store = fsg_store_ro;
Alan Stern12aae682008-11-20 14:13:12 -05003339 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003340 }
3341
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003342 /* Only for removable media? */
3343 dev_attr_nofua.attr.mode = 0644;
3344 dev_attr_nofua.store = fsg_store_nofua;
3345
Linus Torvalds1da177e2005-04-16 15:20:36 -07003346 /* Find out how many LUNs there should be */
3347 i = mod_data.nluns;
3348 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003349 i = max(mod_data.num_filenames, 1u);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003350 if (i > FSG_MAX_LUNS) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003351 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3352 rc = -EINVAL;
3353 goto out;
3354 }
3355
3356 /* Create the LUNs, open their backing files, and register the
3357 * LUN devices in sysfs. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003358 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003359 if (!fsg->luns) {
3360 rc = -ENOMEM;
3361 goto out;
3362 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003363 fsg->nluns = i;
3364
3365 for (i = 0; i < fsg->nluns; ++i) {
3366 curlun = &fsg->luns[i];
Michal Nazarewicze909ef52009-10-28 16:57:16 +01003367 curlun->cdrom = !!mod_data.cdrom;
3368 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3369 curlun->initially_ro = curlun->ro;
3370 curlun->removable = mod_data.removable;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003371 curlun->nofua = mod_data.nofua[i];
Alan Stern2de9eae2006-09-25 14:31:15 -04003372 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003373 curlun->dev.parent = &gadget->dev;
3374 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003375 dev_set_drvdata(&curlun->dev, &fsg->filesem);
Kay Sievers0031a062008-05-02 06:02:41 +02003376 dev_set_name(&curlun->dev,"%s-lun%d",
3377 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003378
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003379 kref_get(&fsg->ref);
3380 rc = device_register(&curlun->dev);
3381 if (rc) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003382 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003383 put_device(&curlun->dev);
Alan Stern2de9eae2006-09-25 14:31:15 -04003384 goto out;
3385 }
3386 curlun->registered = 1;
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003387
3388 rc = device_create_file(&curlun->dev, &dev_attr_ro);
3389 if (rc)
3390 goto out;
3391 rc = device_create_file(&curlun->dev, &dev_attr_nofua);
3392 if (rc)
3393 goto out;
3394 rc = device_create_file(&curlun->dev, &dev_attr_file);
3395 if (rc)
3396 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003397
Alan Sternaafe5bd2006-03-31 11:46:43 -05003398 if (mod_data.file[i] && *mod_data.file[i]) {
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003399 rc = fsg_lun_open(curlun, mod_data.file[i]);
3400 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003401 goto out;
3402 } else if (!mod_data.removable) {
3403 ERROR(fsg, "no file given for LUN%d\n", i);
3404 rc = -EINVAL;
3405 goto out;
3406 }
3407 }
3408
3409 /* Find all the endpoints we will use */
3410 usb_ep_autoconfig_reset(gadget);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003411 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003412 if (!ep)
3413 goto autoconf_fail;
3414 ep->driver_data = fsg; // claim the endpoint
3415 fsg->bulk_in = ep;
3416
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003417 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003418 if (!ep)
3419 goto autoconf_fail;
3420 ep->driver_data = fsg; // claim the endpoint
3421 fsg->bulk_out = ep;
3422
3423 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003424 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003425 if (!ep)
3426 goto autoconf_fail;
3427 ep->driver_data = fsg; // claim the endpoint
3428 fsg->intr_in = ep;
3429 }
3430
3431 /* Fix up the descriptors */
3432 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3433 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3434 device_desc.idProduct = cpu_to_le16(mod_data.product);
3435 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3436
3437 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003438 fsg_intf_desc.bNumEndpoints = i;
3439 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3440 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3441 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003442
David Brownell2e806f62007-08-02 00:03:39 -07003443 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003444 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003445
David Brownell2e806f62007-08-02 00:03:39 -07003446 /* Assume ep0 uses the same maxpacket value for both speeds */
3447 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003448
David Brownell2e806f62007-08-02 00:03:39 -07003449 /* Assume endpoint addresses are the same for both speeds */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003450 fsg_hs_bulk_in_desc.bEndpointAddress =
3451 fsg_fs_bulk_in_desc.bEndpointAddress;
3452 fsg_hs_bulk_out_desc.bEndpointAddress =
3453 fsg_fs_bulk_out_desc.bEndpointAddress;
3454 fsg_hs_intr_in_desc.bEndpointAddress =
3455 fsg_fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003456 }
3457
David Brownell2e806f62007-08-02 00:03:39 -07003458 if (gadget_is_otg(gadget))
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003459 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
David Brownell2e806f62007-08-02 00:03:39 -07003460
Linus Torvalds1da177e2005-04-16 15:20:36 -07003461 rc = -ENOMEM;
3462
3463 /* Allocate the request and buffer for endpoint 0 */
3464 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3465 if (!req)
3466 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003467 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003468 if (!req->buf)
3469 goto out;
3470 req->complete = ep0_complete;
3471
3472 /* Allocate the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003473 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003474 struct fsg_buffhd *bh = &fsg->buffhds[i];
3475
Alan Stern14cd5f82006-03-23 15:07:25 -05003476 /* Allocate for the bulk-in endpoint. We assume that
3477 * the buffer will also work with the bulk-out (and
3478 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003479 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003480 if (!bh->buf)
3481 goto out;
3482 bh->next = bh + 1;
3483 }
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003484 fsg->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->buffhds[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07003485
3486 /* This should reflect the actual gadget power source */
3487 usb_gadget_set_selfpowered(gadget);
3488
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003489 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3490 "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003491 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003492 gadget->name);
3493
Alan Stern22efcf42005-09-26 16:12:02 -04003494 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3495 "file-storage-gadget");
3496 if (IS_ERR(fsg->thread_task)) {
3497 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003498 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04003499 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003500
3501 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3502 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3503
3504 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3505 for (i = 0; i < fsg->nluns; ++i) {
3506 curlun = &fsg->luns[i];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003507 if (fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003508 p = NULL;
3509 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08003510 p = d_path(&curlun->filp->f_path,
3511 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003512 if (IS_ERR(p))
3513 p = NULL;
3514 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003515 LINFO(curlun, "ro=%d, nofua=%d, file: %s\n",
3516 curlun->ro, curlun->nofua, (p ? p : "(error)"));
Linus Torvalds1da177e2005-04-16 15:20:36 -07003517 }
3518 }
3519 kfree(pathbuf);
3520
3521 DBG(fsg, "transport=%s (x%02x)\n",
3522 mod_data.transport_name, mod_data.transport_type);
3523 DBG(fsg, "protocol=%s (x%02x)\n",
3524 mod_data.protocol_name, mod_data.protocol_type);
3525 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3526 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05003527 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003528 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05003529 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07003530 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04003531
3532 set_bit(REGISTERED, &fsg->atomic_bitflags);
3533
3534 /* Tell the thread to start working */
3535 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003536 return 0;
3537
3538autoconf_fail:
3539 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3540 rc = -ENOTSUPP;
3541
3542out:
3543 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3544 fsg_unbind(gadget);
Felipe Balbi889394b2008-12-08 13:50:27 +02003545 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003546 return rc;
3547}
3548
3549
3550/*-------------------------------------------------------------------------*/
3551
3552static void fsg_suspend(struct usb_gadget *gadget)
3553{
3554 struct fsg_dev *fsg = get_gadget_data(gadget);
3555
3556 DBG(fsg, "suspend\n");
3557 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3558}
3559
3560static void fsg_resume(struct usb_gadget *gadget)
3561{
3562 struct fsg_dev *fsg = get_gadget_data(gadget);
3563
3564 DBG(fsg, "resume\n");
3565 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3566}
3567
3568
3569/*-------------------------------------------------------------------------*/
3570
3571static struct usb_gadget_driver fsg_driver = {
3572#ifdef CONFIG_USB_GADGET_DUALSPEED
3573 .speed = USB_SPEED_HIGH,
3574#else
3575 .speed = USB_SPEED_FULL,
3576#endif
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003577 .function = (char *) fsg_string_product,
David Brownell6bea4762006-12-05 03:15:33 -08003578 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003579 .disconnect = fsg_disconnect,
3580 .setup = fsg_setup,
3581 .suspend = fsg_suspend,
3582 .resume = fsg_resume,
3583
3584 .driver = {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003585 .name = DRIVER_NAME,
Ben Dooksd0d50492005-10-10 10:52:33 +01003586 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003587 // .release = ...
3588 // .suspend = ...
3589 // .resume = ...
3590 },
3591};
3592
3593
3594static int __init fsg_alloc(void)
3595{
3596 struct fsg_dev *fsg;
3597
Alan Sterna922c682005-10-06 16:38:45 -04003598 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003599 if (!fsg)
3600 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003601 spin_lock_init(&fsg->lock);
3602 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05003603 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003604 init_completion(&fsg->thread_notifier);
3605
3606 the_fsg = fsg;
3607 return 0;
3608}
3609
3610
Linus Torvalds1da177e2005-04-16 15:20:36 -07003611static int __init fsg_init(void)
3612{
3613 int rc;
3614 struct fsg_dev *fsg;
3615
3616 if ((rc = fsg_alloc()) != 0)
3617 return rc;
3618 fsg = the_fsg;
Uwe Kleine-Königb0fca502010-08-12 17:43:53 +02003619 if ((rc = usb_gadget_probe_driver(&fsg_driver, fsg_bind)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05003620 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04003621 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003622}
3623module_init(fsg_init);
3624
3625
3626static void __exit fsg_cleanup(void)
3627{
3628 struct fsg_dev *fsg = the_fsg;
3629
3630 /* Unregister the driver iff the thread hasn't already done so */
3631 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3632 usb_gadget_unregister_driver(&fsg_driver);
3633
3634 /* Wait for the thread to finish up */
3635 wait_for_completion(&fsg->thread_notifier);
3636
Alan Stern87c42522005-11-09 16:59:56 -05003637 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003638}
3639module_exit(fsg_cleanup);