blob: 738591a64bb4525bf45f1f7848dffa5dcb905913 [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
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -0700500/* Make bulk-out requests be divisible by the maxpacket size */
501static void set_bulk_out_req_length(struct fsg_dev *fsg,
502 struct fsg_buffhd *bh, unsigned int length)
503{
504 unsigned int rem;
505
506 bh->bulk_out_intended_length = length;
507 rem = length % fsg->bulk_out_maxpacket;
508 if (rem > 0)
509 length += fsg->bulk_out_maxpacket - rem;
510 bh->outreq->length = length;
511}
512
Linus Torvalds1da177e2005-04-16 15:20:36 -0700513static struct fsg_dev *the_fsg;
514static struct usb_gadget_driver fsg_driver;
515
Linus Torvalds1da177e2005-04-16 15:20:36 -0700516
517/*-------------------------------------------------------------------------*/
518
Linus Torvalds1da177e2005-04-16 15:20:36 -0700519static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
520{
521 const char *name;
522
523 if (ep == fsg->bulk_in)
524 name = "bulk-in";
525 else if (ep == fsg->bulk_out)
526 name = "bulk-out";
527 else
528 name = ep->name;
529 DBG(fsg, "%s set halt\n", name);
530 return usb_ep_set_halt(ep);
531}
532
533
534/*-------------------------------------------------------------------------*/
535
Linus Torvalds1da177e2005-04-16 15:20:36 -0700536/*
537 * DESCRIPTORS ... most are static, but strings and (full) configuration
538 * descriptors are built on demand. Also the (static) config and interface
539 * descriptors are adjusted during fsg_bind().
540 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700541
542/* There is only one configuration. */
543#define CONFIG_VALUE 1
544
545static struct usb_device_descriptor
546device_desc = {
547 .bLength = sizeof device_desc,
548 .bDescriptorType = USB_DT_DEVICE,
549
Harvey Harrison551509d2009-02-11 14:11:36 -0800550 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700551 .bDeviceClass = USB_CLASS_PER_INTERFACE,
552
553 /* The next three values can be overridden by module parameters */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100554 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
555 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
Harvey Harrison551509d2009-02-11 14:11:36 -0800556 .bcdDevice = cpu_to_le16(0xffff),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700557
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100558 .iManufacturer = FSG_STRING_MANUFACTURER,
559 .iProduct = FSG_STRING_PRODUCT,
560 .iSerialNumber = FSG_STRING_SERIAL,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700561 .bNumConfigurations = 1,
562};
563
564static struct usb_config_descriptor
565config_desc = {
566 .bLength = sizeof config_desc,
567 .bDescriptorType = USB_DT_CONFIG,
568
569 /* wTotalLength computed by usb_gadget_config_buf() */
570 .bNumInterfaces = 1,
571 .bConfigurationValue = CONFIG_VALUE,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100572 .iConfiguration = FSG_STRING_CONFIG,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700573 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
David Brownell36e893d2008-09-12 09:39:06 -0700574 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700575};
576
Linus Torvalds1da177e2005-04-16 15:20:36 -0700577
Linus Torvalds1da177e2005-04-16 15:20:36 -0700578static struct usb_qualifier_descriptor
579dev_qualifier = {
580 .bLength = sizeof dev_qualifier,
581 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
582
Harvey Harrison551509d2009-02-11 14:11:36 -0800583 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700584 .bDeviceClass = USB_CLASS_PER_INTERFACE,
585
586 .bNumConfigurations = 1,
587};
588
Linus Torvalds1da177e2005-04-16 15:20:36 -0700589
590
591/*
592 * Config descriptors must agree with the code that sets configurations
593 * and with code managing interfaces and their altsettings. They must
594 * also handle different speeds and other-speed requests.
595 */
596static int populate_config_buf(struct usb_gadget *gadget,
597 u8 *buf, u8 type, unsigned index)
598{
Linus Torvalds1da177e2005-04-16 15:20:36 -0700599 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700600 int len;
601 const struct usb_descriptor_header **function;
602
603 if (index > 0)
604 return -EINVAL;
605
David Brownell2e806f62007-08-02 00:03:39 -0700606 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700607 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
Michal Nazarewiczd23b0f02009-11-09 14:15:20 +0100608 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
609 ? (const struct usb_descriptor_header **)fsg_hs_function
610 : (const struct usb_descriptor_header **)fsg_fs_function;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700611
612 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -0700613 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700614 function++;
615
616 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
617 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
618 return len;
619}
620
621
622/*-------------------------------------------------------------------------*/
623
624/* These routines may be called in process context or in_irq */
625
Alan Sterna21d4fe2005-11-29 12:04:24 -0500626/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627static void wakeup_thread(struct fsg_dev *fsg)
628{
629 /* Tell the main thread that something has happened */
630 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500631 if (fsg->thread_task)
632 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700633}
634
635
636static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
637{
638 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700639
640 /* Do nothing if a higher-priority exception is already in progress.
641 * If a lower-or-equal priority exception is in progress, preempt it
642 * and notify the main thread by sending it a signal. */
643 spin_lock_irqsave(&fsg->lock, flags);
644 if (fsg->state <= new_state) {
645 fsg->exception_req_tag = fsg->ep0_req_tag;
646 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -0400647 if (fsg->thread_task)
648 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
649 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700650 }
651 spin_unlock_irqrestore(&fsg->lock, flags);
652}
653
654
655/*-------------------------------------------------------------------------*/
656
657/* The disconnect callback and ep0 routines. These always run in_irq,
658 * except that ep0_queue() is called in the main thread to acknowledge
659 * completion of various requests: set config, set interface, and
660 * Bulk-only device reset. */
661
662static void fsg_disconnect(struct usb_gadget *gadget)
663{
664 struct fsg_dev *fsg = get_gadget_data(gadget);
665
666 DBG(fsg, "disconnect or port reset\n");
667 raise_exception(fsg, FSG_STATE_DISCONNECT);
668}
669
670
671static int ep0_queue(struct fsg_dev *fsg)
672{
673 int rc;
674
675 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
676 if (rc != 0 && rc != -ESHUTDOWN) {
677
678 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -0700679 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680 fsg->ep0->name, rc);
681 }
682 return rc;
683}
684
685static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
686{
John Daiker7ca46b82006-12-29 19:02:06 -0800687 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688
689 if (req->actual > 0)
690 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
691 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800692 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700693 req->status, req->actual, req->length);
694 if (req->status == -ECONNRESET) // Request was cancelled
695 usb_ep_fifo_flush(ep);
696
697 if (req->status == 0 && req->context)
698 ((fsg_routine_t) (req->context))(fsg);
699}
700
701
702/*-------------------------------------------------------------------------*/
703
704/* Bulk and interrupt endpoint completion handlers.
705 * These always run in_irq. */
706
707static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
708{
John Daiker7ca46b82006-12-29 19:02:06 -0800709 struct fsg_dev *fsg = ep->driver_data;
710 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700711
712 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800713 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700714 req->status, req->actual, req->length);
715 if (req->status == -ECONNRESET) // Request was cancelled
716 usb_ep_fifo_flush(ep);
717
718 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500719 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700720 spin_lock(&fsg->lock);
721 bh->inreq_busy = 0;
722 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700723 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500724 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700725}
726
727static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
728{
John Daiker7ca46b82006-12-29 19:02:06 -0800729 struct fsg_dev *fsg = ep->driver_data;
730 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700731
732 dump_msg(fsg, "bulk-out", req->buf, req->actual);
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -0700733 if (req->status || req->actual != bh->bulk_out_intended_length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800734 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -0700735 req->status, req->actual,
736 bh->bulk_out_intended_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700737 if (req->status == -ECONNRESET) // Request was cancelled
738 usb_ep_fifo_flush(ep);
739
740 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500741 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700742 spin_lock(&fsg->lock);
743 bh->outreq_busy = 0;
744 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700745 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500746 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700747}
748
749
750#ifdef CONFIG_USB_FILE_STORAGE_TEST
751static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
752{
John Daiker7ca46b82006-12-29 19:02:06 -0800753 struct fsg_dev *fsg = ep->driver_data;
754 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700755
756 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800757 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700758 req->status, req->actual, req->length);
759 if (req->status == -ECONNRESET) // Request was cancelled
760 usb_ep_fifo_flush(ep);
761
762 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500763 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700764 spin_lock(&fsg->lock);
765 fsg->intreq_busy = 0;
766 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700767 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500768 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700769}
770
771#else
772static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
773{}
774#endif /* CONFIG_USB_FILE_STORAGE_TEST */
775
776
777/*-------------------------------------------------------------------------*/
778
779/* Ep0 class-specific handlers. These always run in_irq. */
780
781#ifdef CONFIG_USB_FILE_STORAGE_TEST
782static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
783{
784 struct usb_request *req = fsg->ep0req;
785 static u8 cbi_reset_cmnd[6] = {
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +0200786 SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
Linus Torvalds1da177e2005-04-16 15:20:36 -0700787
788 /* Error in command transfer? */
789 if (req->status || req->length != req->actual ||
790 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
791
792 /* Not all controllers allow a protocol stall after
793 * receiving control-out data, but we'll try anyway. */
794 fsg_set_halt(fsg, fsg->ep0);
795 return; // Wait for reset
796 }
797
798 /* Is it the special reset command? */
799 if (req->actual >= sizeof cbi_reset_cmnd &&
800 memcmp(req->buf, cbi_reset_cmnd,
801 sizeof cbi_reset_cmnd) == 0) {
802
803 /* Raise an exception to stop the current operation
804 * and reinitialize our state. */
805 DBG(fsg, "cbi reset request\n");
806 raise_exception(fsg, FSG_STATE_RESET);
807 return;
808 }
809
810 VDBG(fsg, "CB[I] accept device-specific command\n");
811 spin_lock(&fsg->lock);
812
813 /* Save the command for later */
814 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700815 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700816 fsg->cbbuf_cmnd_size = req->actual;
817 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
818
Linus Torvalds1da177e2005-04-16 15:20:36 -0700819 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500820 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700821}
822
823#else
824static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
825{}
826#endif /* CONFIG_USB_FILE_STORAGE_TEST */
827
828
829static int class_setup_req(struct fsg_dev *fsg,
830 const struct usb_ctrlrequest *ctrl)
831{
832 struct usb_request *req = fsg->ep0req;
833 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700834 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -0400835 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -0700836 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700837
838 if (!fsg->config)
839 return value;
840
841 /* Handle Bulk-only class-specific requests */
842 if (transport_is_bbb()) {
843 switch (ctrl->bRequest) {
844
845 case USB_BULK_RESET_REQUEST:
846 if (ctrl->bRequestType != (USB_DIR_OUT |
847 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
848 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400849 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700850 value = -EDOM;
851 break;
852 }
853
854 /* Raise an exception to stop the current operation
855 * and reinitialize our state. */
856 DBG(fsg, "bulk reset request\n");
857 raise_exception(fsg, FSG_STATE_RESET);
858 value = DELAYED_STATUS;
859 break;
860
861 case USB_BULK_GET_MAX_LUN_REQUEST:
862 if (ctrl->bRequestType != (USB_DIR_IN |
863 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
864 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400865 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700866 value = -EDOM;
867 break;
868 }
869 VDBG(fsg, "get max LUN\n");
870 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -0400871 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700872 break;
873 }
874 }
875
876 /* Handle CBI class-specific requests */
877 else {
878 switch (ctrl->bRequest) {
879
880 case USB_CBI_ADSC_REQUEST:
881 if (ctrl->bRequestType != (USB_DIR_OUT |
882 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
883 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400884 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700885 value = -EDOM;
886 break;
887 }
888 if (w_length > MAX_COMMAND_SIZE) {
889 value = -EOVERFLOW;
890 break;
891 }
892 value = w_length;
893 fsg->ep0req->context = received_cbi_adsc;
894 break;
895 }
896 }
897
898 if (value == -EOPNOTSUPP)
899 VDBG(fsg,
900 "unknown class-specific control req "
901 "%02x.%02x v%04x i%04x l%u\n",
902 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -0700903 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700904 return value;
905}
906
907
908/*-------------------------------------------------------------------------*/
909
910/* Ep0 standard request handlers. These always run in_irq. */
911
912static int standard_setup_req(struct fsg_dev *fsg,
913 const struct usb_ctrlrequest *ctrl)
914{
915 struct usb_request *req = fsg->ep0req;
916 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700917 u16 w_index = le16_to_cpu(ctrl->wIndex);
918 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700919
920 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
921 * but config change events will also reconfigure hardware. */
922 switch (ctrl->bRequest) {
923
924 case USB_REQ_GET_DESCRIPTOR:
925 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
926 USB_RECIP_DEVICE))
927 break;
928 switch (w_value >> 8) {
929
930 case USB_DT_DEVICE:
931 VDBG(fsg, "get device descriptor\n");
Alan Stern76f4af82005-04-05 11:56:54 -0400932 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700933 memcpy(req->buf, &device_desc, value);
934 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700935 case USB_DT_DEVICE_QUALIFIER:
936 VDBG(fsg, "get device qualifier\n");
David Brownell2e806f62007-08-02 00:03:39 -0700937 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700938 break;
Alan Stern76f4af82005-04-05 11:56:54 -0400939 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700940 memcpy(req->buf, &dev_qualifier, value);
941 break;
942
943 case USB_DT_OTHER_SPEED_CONFIG:
944 VDBG(fsg, "get other-speed config descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700945 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700946 break;
947 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700948 case USB_DT_CONFIG:
949 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700950get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951 value = populate_config_buf(fsg->gadget,
952 req->buf,
953 w_value >> 8,
954 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700955 break;
956
957 case USB_DT_STRING:
958 VDBG(fsg, "get string descriptor\n");
959
960 /* wIndex == language code */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100961 value = usb_gadget_get_string(&fsg_stringtab,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700962 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700963 break;
964 }
965 break;
966
967 /* One config, two speeds */
968 case USB_REQ_SET_CONFIGURATION:
969 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
970 USB_RECIP_DEVICE))
971 break;
972 VDBG(fsg, "set configuration\n");
973 if (w_value == CONFIG_VALUE || w_value == 0) {
974 fsg->new_config = w_value;
975
976 /* Raise an exception to wipe out previous transaction
977 * state (queued bufs, etc) and set the new config. */
978 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
979 value = DELAYED_STATUS;
980 }
981 break;
982 case USB_REQ_GET_CONFIGURATION:
983 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
984 USB_RECIP_DEVICE))
985 break;
986 VDBG(fsg, "get configuration\n");
987 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -0400988 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700989 break;
990
991 case USB_REQ_SET_INTERFACE:
992 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
993 USB_RECIP_INTERFACE))
994 break;
995 if (fsg->config && w_index == 0) {
996
997 /* Raise an exception to wipe out previous transaction
998 * state (queued bufs, etc) and install the new
999 * interface altsetting. */
1000 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1001 value = DELAYED_STATUS;
1002 }
1003 break;
1004 case USB_REQ_GET_INTERFACE:
1005 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1006 USB_RECIP_INTERFACE))
1007 break;
1008 if (!fsg->config)
1009 break;
1010 if (w_index != 0) {
1011 value = -EDOM;
1012 break;
1013 }
1014 VDBG(fsg, "get interface\n");
1015 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001016 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001017 break;
1018
1019 default:
1020 VDBG(fsg,
1021 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1022 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001023 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001024 }
1025
1026 return value;
1027}
1028
1029
1030static int fsg_setup(struct usb_gadget *gadget,
1031 const struct usb_ctrlrequest *ctrl)
1032{
1033 struct fsg_dev *fsg = get_gadget_data(gadget);
1034 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001035 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001036
1037 ++fsg->ep0_req_tag; // Record arrival of a new request
1038 fsg->ep0req->context = NULL;
1039 fsg->ep0req->length = 0;
1040 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1041
1042 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1043 rc = class_setup_req(fsg, ctrl);
1044 else
1045 rc = standard_setup_req(fsg, ctrl);
1046
1047 /* Respond with data/status or defer until later? */
1048 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001049 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001050 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001051 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001052 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1053 "ep0-in" : "ep0-out");
1054 rc = ep0_queue(fsg);
1055 }
1056
1057 /* Device either stalls (rc < 0) or reports success */
1058 return rc;
1059}
1060
1061
1062/*-------------------------------------------------------------------------*/
1063
1064/* All the following routines run in process context */
1065
1066
1067/* Use this for bulk or interrupt transfers, not ep0 */
1068static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001069 struct usb_request *req, int *pbusy,
1070 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001071{
1072 int rc;
1073
1074 if (ep == fsg->bulk_in)
1075 dump_msg(fsg, "bulk-in", req->buf, req->length);
1076 else if (ep == fsg->intr_in)
1077 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001078
1079 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001080 *pbusy = 1;
1081 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001082 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001083 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1084 if (rc != 0) {
1085 *pbusy = 0;
1086 *state = BUF_STATE_EMPTY;
1087
1088 /* We can't do much more than wait for a reset */
1089
1090 /* Note: currently the net2280 driver fails zero-length
1091 * submissions if DMA is enabled. */
1092 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1093 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001094 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001095 ep->name, rc);
1096 }
1097}
1098
1099
1100static int sleep_thread(struct fsg_dev *fsg)
1101{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001102 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001103
1104 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001105 for (;;) {
1106 try_to_freeze();
1107 set_current_state(TASK_INTERRUPTIBLE);
1108 if (signal_pending(current)) {
1109 rc = -EINTR;
1110 break;
1111 }
1112 if (fsg->thread_wakeup_needed)
1113 break;
1114 schedule();
1115 }
1116 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001117 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001118 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001119}
1120
1121
1122/*-------------------------------------------------------------------------*/
1123
1124static int do_read(struct fsg_dev *fsg)
1125{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001126 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001127 u32 lba;
1128 struct fsg_buffhd *bh;
1129 int rc;
1130 u32 amount_left;
1131 loff_t file_offset, file_offset_tmp;
1132 unsigned int amount;
1133 unsigned int partial_page;
1134 ssize_t nread;
1135
1136 /* Get the starting Logical Block Address and check that it's
1137 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001138 if (fsg->cmnd[0] == READ_6)
Alan Stern604eb892009-04-27 13:19:41 -04001139 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001140 else {
Alan Stern604eb892009-04-27 13:19:41 -04001141 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001142
1143 /* We allow DPO (Disable Page Out = don't save data in the
1144 * cache) and FUA (Force Unit Access = don't read from the
1145 * cache), but we don't implement them. */
1146 if ((fsg->cmnd[1] & ~0x18) != 0) {
1147 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1148 return -EINVAL;
1149 }
1150 }
1151 if (lba >= curlun->num_sectors) {
1152 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1153 return -EINVAL;
1154 }
1155 file_offset = ((loff_t) lba) << 9;
1156
1157 /* Carry out the file reads */
1158 amount_left = fsg->data_size_from_cmnd;
1159 if (unlikely(amount_left == 0))
1160 return -EIO; // No default reply
1161
1162 for (;;) {
1163
1164 /* Figure out how much we need to read:
1165 * Try to read the remaining amount.
1166 * But don't read more than the buffer size.
1167 * And don't try to read past the end of the file.
1168 * Finally, if we're not at a page boundary, don't read past
1169 * the next page.
1170 * If this means reading 0 then we were asked to read past
1171 * the end of file. */
1172 amount = min((unsigned int) amount_left, mod_data.buflen);
1173 amount = min((loff_t) amount,
1174 curlun->file_length - file_offset);
1175 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1176 if (partial_page > 0)
1177 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1178 partial_page);
1179
1180 /* Wait for the next buffer to become available */
1181 bh = fsg->next_buffhd_to_fill;
1182 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001183 rc = sleep_thread(fsg);
1184 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001185 return rc;
1186 }
1187
1188 /* If we were asked to read past the end of file,
1189 * end with an empty buffer. */
1190 if (amount == 0) {
1191 curlun->sense_data =
1192 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1193 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001194 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001195 bh->inreq->length = 0;
1196 bh->state = BUF_STATE_FULL;
1197 break;
1198 }
1199
1200 /* Perform the read */
1201 file_offset_tmp = file_offset;
1202 nread = vfs_read(curlun->filp,
1203 (char __user *) bh->buf,
1204 amount, &file_offset_tmp);
1205 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1206 (unsigned long long) file_offset,
1207 (int) nread);
1208 if (signal_pending(current))
1209 return -EINTR;
1210
1211 if (nread < 0) {
1212 LDBG(curlun, "error in file read: %d\n",
1213 (int) nread);
1214 nread = 0;
1215 } else if (nread < amount) {
1216 LDBG(curlun, "partial file read: %d/%u\n",
1217 (int) nread, amount);
1218 nread -= (nread & 511); // Round down to a block
1219 }
1220 file_offset += nread;
1221 amount_left -= nread;
1222 fsg->residue -= nread;
1223 bh->inreq->length = nread;
1224 bh->state = BUF_STATE_FULL;
1225
1226 /* If an error occurred, report it and its position */
1227 if (nread < amount) {
1228 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1229 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001230 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001231 break;
1232 }
1233
1234 if (amount_left == 0)
1235 break; // No more left to read
1236
1237 /* Send this buffer and go read some more */
1238 bh->inreq->zero = 0;
1239 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1240 &bh->inreq_busy, &bh->state);
1241 fsg->next_buffhd_to_fill = bh->next;
1242 }
1243
1244 return -EIO; // No default reply
1245}
1246
1247
1248/*-------------------------------------------------------------------------*/
1249
1250static int do_write(struct fsg_dev *fsg)
1251{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001252 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001253 u32 lba;
1254 struct fsg_buffhd *bh;
1255 int get_some_more;
1256 u32 amount_left_to_req, amount_left_to_write;
1257 loff_t usb_offset, file_offset, file_offset_tmp;
1258 unsigned int amount;
1259 unsigned int partial_page;
1260 ssize_t nwritten;
1261 int rc;
1262
1263 if (curlun->ro) {
1264 curlun->sense_data = SS_WRITE_PROTECTED;
1265 return -EINVAL;
1266 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001267 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001268 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001269 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001270
1271 /* Get the starting Logical Block Address and check that it's
1272 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001273 if (fsg->cmnd[0] == WRITE_6)
Alan Stern604eb892009-04-27 13:19:41 -04001274 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001275 else {
Alan Stern604eb892009-04-27 13:19:41 -04001276 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001277
1278 /* We allow DPO (Disable Page Out = don't save data in the
1279 * cache) and FUA (Force Unit Access = write directly to the
1280 * medium). We don't implement DPO; we implement FUA by
1281 * performing synchronous output. */
1282 if ((fsg->cmnd[1] & ~0x18) != 0) {
1283 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1284 return -EINVAL;
1285 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03001286 /* FUA */
1287 if (!curlun->nofua && (fsg->cmnd[1] & 0x08)) {
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001288 spin_lock(&curlun->filp->f_lock);
Christoph Hellwig6b2f3d12009-10-27 11:05:28 +01001289 curlun->filp->f_flags |= O_DSYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001290 spin_unlock(&curlun->filp->f_lock);
1291 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001292 }
1293 if (lba >= curlun->num_sectors) {
1294 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1295 return -EINVAL;
1296 }
1297
1298 /* Carry out the file writes */
1299 get_some_more = 1;
1300 file_offset = usb_offset = ((loff_t) lba) << 9;
1301 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1302
1303 while (amount_left_to_write > 0) {
1304
1305 /* Queue a request for more data from the host */
1306 bh = fsg->next_buffhd_to_fill;
1307 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1308
1309 /* Figure out how much we want to get:
1310 * Try to get the remaining amount.
1311 * But don't get more than the buffer size.
1312 * And don't try to go past the end of the file.
1313 * If we're not at a page boundary,
1314 * don't go past the next page.
1315 * If this means getting 0, then we were asked
1316 * to write past the end of file.
1317 * Finally, round down to a block boundary. */
1318 amount = min(amount_left_to_req, mod_data.buflen);
1319 amount = min((loff_t) amount, curlun->file_length -
1320 usb_offset);
1321 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1322 if (partial_page > 0)
1323 amount = min(amount,
1324 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1325
1326 if (amount == 0) {
1327 get_some_more = 0;
1328 curlun->sense_data =
1329 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1330 curlun->sense_data_info = usb_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001331 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001332 continue;
1333 }
1334 amount -= (amount & 511);
1335 if (amount == 0) {
1336
1337 /* Why were we were asked to transfer a
1338 * partial block? */
1339 get_some_more = 0;
1340 continue;
1341 }
1342
1343 /* Get the next buffer */
1344 usb_offset += amount;
1345 fsg->usb_amount_left -= amount;
1346 amount_left_to_req -= amount;
1347 if (amount_left_to_req == 0)
1348 get_some_more = 0;
1349
1350 /* amount is always divisible by 512, hence by
1351 * the bulk-out maxpacket size */
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -07001352 bh->outreq->length = bh->bulk_out_intended_length =
1353 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001354 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001355 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1356 &bh->outreq_busy, &bh->state);
1357 fsg->next_buffhd_to_fill = bh->next;
1358 continue;
1359 }
1360
1361 /* Write the received data to the backing file */
1362 bh = fsg->next_buffhd_to_drain;
1363 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1364 break; // We stopped early
1365 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001366 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001367 fsg->next_buffhd_to_drain = bh->next;
1368 bh->state = BUF_STATE_EMPTY;
1369
1370 /* Did something go wrong with the transfer? */
1371 if (bh->outreq->status != 0) {
1372 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1373 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001374 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001375 break;
1376 }
1377
1378 amount = bh->outreq->actual;
1379 if (curlun->file_length - file_offset < amount) {
1380 LERROR(curlun,
1381 "write %u @ %llu beyond end %llu\n",
1382 amount, (unsigned long long) file_offset,
1383 (unsigned long long) curlun->file_length);
1384 amount = curlun->file_length - file_offset;
1385 }
1386
1387 /* Perform the write */
1388 file_offset_tmp = file_offset;
1389 nwritten = vfs_write(curlun->filp,
1390 (char __user *) bh->buf,
1391 amount, &file_offset_tmp);
1392 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1393 (unsigned long long) file_offset,
1394 (int) nwritten);
1395 if (signal_pending(current))
1396 return -EINTR; // Interrupted!
1397
1398 if (nwritten < 0) {
1399 LDBG(curlun, "error in file write: %d\n",
1400 (int) nwritten);
1401 nwritten = 0;
1402 } else if (nwritten < amount) {
1403 LDBG(curlun, "partial file write: %d/%u\n",
1404 (int) nwritten, amount);
1405 nwritten -= (nwritten & 511);
1406 // Round down to a block
1407 }
1408 file_offset += nwritten;
1409 amount_left_to_write -= nwritten;
1410 fsg->residue -= nwritten;
1411
1412 /* If an error occurred, report it and its position */
1413 if (nwritten < amount) {
1414 curlun->sense_data = SS_WRITE_ERROR;
1415 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001416 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001417 break;
1418 }
1419
1420 /* Did the host decide to stop early? */
1421 if (bh->outreq->actual != bh->outreq->length) {
1422 fsg->short_packet_received = 1;
1423 break;
1424 }
1425 continue;
1426 }
1427
1428 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001429 rc = sleep_thread(fsg);
1430 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001431 return rc;
1432 }
1433
1434 return -EIO; // No default reply
1435}
1436
1437
1438/*-------------------------------------------------------------------------*/
1439
Linus Torvalds1da177e2005-04-16 15:20:36 -07001440static int do_synchronize_cache(struct fsg_dev *fsg)
1441{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001442 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001443 int rc;
1444
1445 /* We ignore the requested LBA and write out all file's
1446 * dirty data buffers. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001447 rc = fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001448 if (rc)
1449 curlun->sense_data = SS_WRITE_ERROR;
1450 return 0;
1451}
1452
1453
1454/*-------------------------------------------------------------------------*/
1455
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001456static void invalidate_sub(struct fsg_lun *curlun)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001457{
1458 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001459 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001460 unsigned long rc;
1461
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001462 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01001463 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001464}
1465
1466static int do_verify(struct fsg_dev *fsg)
1467{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001468 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001469 u32 lba;
1470 u32 verification_length;
1471 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1472 loff_t file_offset, file_offset_tmp;
1473 u32 amount_left;
1474 unsigned int amount;
1475 ssize_t nread;
1476
1477 /* Get the starting Logical Block Address and check that it's
1478 * not too big */
Alan Stern604eb892009-04-27 13:19:41 -04001479 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001480 if (lba >= curlun->num_sectors) {
1481 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1482 return -EINVAL;
1483 }
1484
1485 /* We allow DPO (Disable Page Out = don't save data in the
1486 * cache) but we don't implement it. */
1487 if ((fsg->cmnd[1] & ~0x10) != 0) {
1488 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1489 return -EINVAL;
1490 }
1491
Alan Stern604eb892009-04-27 13:19:41 -04001492 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001493 if (unlikely(verification_length == 0))
1494 return -EIO; // No default reply
1495
1496 /* Prepare to carry out the file verify */
1497 amount_left = verification_length << 9;
1498 file_offset = ((loff_t) lba) << 9;
1499
1500 /* Write out all the dirty buffers before invalidating them */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001501 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001502 if (signal_pending(current))
1503 return -EINTR;
1504
1505 invalidate_sub(curlun);
1506 if (signal_pending(current))
1507 return -EINTR;
1508
1509 /* Just try to read the requested blocks */
1510 while (amount_left > 0) {
1511
1512 /* Figure out how much we need to read:
1513 * Try to read the remaining amount, but not more than
1514 * the buffer size.
1515 * And don't try to read past the end of the file.
1516 * If this means reading 0 then we were asked to read
1517 * past the end of file. */
1518 amount = min((unsigned int) amount_left, mod_data.buflen);
1519 amount = min((loff_t) amount,
1520 curlun->file_length - file_offset);
1521 if (amount == 0) {
1522 curlun->sense_data =
1523 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1524 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001525 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001526 break;
1527 }
1528
1529 /* Perform the read */
1530 file_offset_tmp = file_offset;
1531 nread = vfs_read(curlun->filp,
1532 (char __user *) bh->buf,
1533 amount, &file_offset_tmp);
1534 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1535 (unsigned long long) file_offset,
1536 (int) nread);
1537 if (signal_pending(current))
1538 return -EINTR;
1539
1540 if (nread < 0) {
1541 LDBG(curlun, "error in file verify: %d\n",
1542 (int) nread);
1543 nread = 0;
1544 } else if (nread < amount) {
1545 LDBG(curlun, "partial file verify: %d/%u\n",
1546 (int) nread, amount);
1547 nread -= (nread & 511); // Round down to a sector
1548 }
1549 if (nread == 0) {
1550 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1551 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001552 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001553 break;
1554 }
1555 file_offset += nread;
1556 amount_left -= nread;
1557 }
1558 return 0;
1559}
1560
1561
1562/*-------------------------------------------------------------------------*/
1563
1564static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1565{
1566 u8 *buf = (u8 *) bh->buf;
1567
1568 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05001569 static char product_disk_id[] = "File-Stor Gadget";
1570 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07001571
1572 if (!fsg->curlun) { // Unsupported LUNs are okay
1573 fsg->bad_lun_okay = 1;
1574 memset(buf, 0, 36);
1575 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05001576 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577 return 36;
1578 }
1579
Alan Stern12aae682008-11-20 14:13:12 -05001580 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001581 buf[0] = (mod_data.cdrom ? TYPE_ROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001582 if (mod_data.removable)
1583 buf[1] = 0x80;
1584 buf[2] = 2; // ANSI SCSI level 2
1585 buf[3] = 2; // SCSI-2 INQUIRY data format
1586 buf[4] = 31; // Additional length
1587 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05001588 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1589 (mod_data.cdrom ? product_cdrom_id :
1590 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001591 mod_data.release);
1592 return 36;
1593}
1594
1595
1596static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1597{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001598 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001599 u8 *buf = (u8 *) bh->buf;
1600 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04001601 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001602
1603 /*
1604 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1605 *
1606 * If a REQUEST SENSE command is received from an initiator
1607 * with a pending unit attention condition (before the target
1608 * generates the contingent allegiance condition), then the
1609 * target shall either:
1610 * a) report any pending sense data and preserve the unit
1611 * attention condition on the logical unit, or,
1612 * b) report the unit attention condition, may discard any
1613 * pending sense data, and clear the unit attention
1614 * condition on the logical unit for that initiator.
1615 *
1616 * FSG normally uses option a); enable this code to use option b).
1617 */
1618#if 0
1619 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1620 curlun->sense_data = curlun->unit_attention_data;
1621 curlun->unit_attention_data = SS_NO_SENSE;
1622 }
1623#endif
1624
1625 if (!curlun) { // Unsupported LUNs are okay
1626 fsg->bad_lun_okay = 1;
1627 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1628 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001629 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001630 } else {
1631 sd = curlun->sense_data;
1632 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04001633 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001634 curlun->sense_data = SS_NO_SENSE;
1635 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001636 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001637 }
1638
1639 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04001640 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07001641 buf[2] = SK(sd);
Alan Stern604eb892009-04-27 13:19:41 -04001642 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001643 buf[7] = 18 - 8; // Additional sense length
1644 buf[12] = ASC(sd);
1645 buf[13] = ASCQ(sd);
1646 return 18;
1647}
1648
1649
1650static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1651{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001652 struct fsg_lun *curlun = fsg->curlun;
Alan Stern604eb892009-04-27 13:19:41 -04001653 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001654 int pmi = fsg->cmnd[8];
1655 u8 *buf = (u8 *) bh->buf;
1656
1657 /* Check the PMI and LBA fields */
1658 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1659 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1660 return -EINVAL;
1661 }
1662
Alan Stern604eb892009-04-27 13:19:41 -04001663 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1664 /* Max logical block */
1665 put_unaligned_be32(512, &buf[4]); /* Block length */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001666 return 8;
1667}
1668
1669
Alan Stern12aae682008-11-20 14:13:12 -05001670static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1671{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001672 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001673 int msf = fsg->cmnd[1] & 0x02;
Alan Stern604eb892009-04-27 13:19:41 -04001674 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Alan Stern12aae682008-11-20 14:13:12 -05001675 u8 *buf = (u8 *) bh->buf;
1676
1677 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1678 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1679 return -EINVAL;
1680 }
1681 if (lba >= curlun->num_sectors) {
1682 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1683 return -EINVAL;
1684 }
1685
1686 memset(buf, 0, 8);
1687 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1688 store_cdrom_address(&buf[4], msf, lba);
1689 return 8;
1690}
1691
1692
1693static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1694{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001695 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001696 int msf = fsg->cmnd[1] & 0x02;
1697 int start_track = fsg->cmnd[6];
1698 u8 *buf = (u8 *) bh->buf;
1699
1700 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1701 start_track > 1) {
1702 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1703 return -EINVAL;
1704 }
1705
1706 memset(buf, 0, 20);
1707 buf[1] = (20-2); /* TOC data length */
1708 buf[2] = 1; /* First track number */
1709 buf[3] = 1; /* Last track number */
1710 buf[5] = 0x16; /* Data track, copying allowed */
1711 buf[6] = 0x01; /* Only track is number 1 */
1712 store_cdrom_address(&buf[8], msf, 0);
1713
1714 buf[13] = 0x16; /* Lead-out track is data */
1715 buf[14] = 0xAA; /* Lead-out track number */
1716 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1717 return 20;
1718}
1719
1720
Linus Torvalds1da177e2005-04-16 15:20:36 -07001721static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1722{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001723 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001724 int mscmnd = fsg->cmnd[0];
1725 u8 *buf = (u8 *) bh->buf;
1726 u8 *buf0 = buf;
1727 int pc, page_code;
1728 int changeable_values, all_pages;
1729 int valid_page = 0;
1730 int len, limit;
1731
1732 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1733 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1734 return -EINVAL;
1735 }
1736 pc = fsg->cmnd[2] >> 6;
1737 page_code = fsg->cmnd[2] & 0x3f;
1738 if (pc == 3) {
1739 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1740 return -EINVAL;
1741 }
1742 changeable_values = (pc == 1);
1743 all_pages = (page_code == 0x3f);
1744
1745 /* Write the mode parameter header. Fixed values are: default
1746 * medium type, no cache control (DPOFUA), and no block descriptors.
1747 * The only variable value is the WriteProtect bit. We will fill in
1748 * the mode data length later. */
1749 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001750 if (mscmnd == MODE_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001751 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1752 buf += 4;
1753 limit = 255;
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001754 } else { // MODE_SENSE_10
Linus Torvalds1da177e2005-04-16 15:20:36 -07001755 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1756 buf += 8;
1757 limit = 65535; // Should really be mod_data.buflen
1758 }
1759
1760 /* No block descriptors */
1761
1762 /* The mode pages, in numerical order. The only page we support
1763 * is the Caching page. */
1764 if (page_code == 0x08 || all_pages) {
1765 valid_page = 1;
1766 buf[0] = 0x08; // Page code
1767 buf[1] = 10; // Page length
1768 memset(buf+2, 0, 10); // None of the fields are changeable
1769
1770 if (!changeable_values) {
1771 buf[2] = 0x04; // Write cache enable,
1772 // Read cache not disabled
1773 // No cache retention priorities
Alan Stern604eb892009-04-27 13:19:41 -04001774 put_unaligned_be16(0xffff, &buf[4]);
1775 /* Don't disable prefetch */
1776 /* Minimum prefetch = 0 */
1777 put_unaligned_be16(0xffff, &buf[8]);
1778 /* Maximum prefetch */
1779 put_unaligned_be16(0xffff, &buf[10]);
1780 /* Maximum prefetch ceiling */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001781 }
1782 buf += 12;
1783 }
1784
1785 /* Check that a valid page was requested and the mode data length
1786 * isn't too long. */
1787 len = buf - buf0;
1788 if (!valid_page || len > limit) {
1789 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1790 return -EINVAL;
1791 }
1792
1793 /* Store the mode data length */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001794 if (mscmnd == MODE_SENSE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001795 buf0[0] = len - 1;
1796 else
Alan Stern604eb892009-04-27 13:19:41 -04001797 put_unaligned_be16(len - 2, buf0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001798 return len;
1799}
1800
1801
1802static int do_start_stop(struct fsg_dev *fsg)
1803{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001804 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001805 int loej, start;
1806
1807 if (!mod_data.removable) {
1808 curlun->sense_data = SS_INVALID_COMMAND;
1809 return -EINVAL;
1810 }
1811
1812 // int immed = fsg->cmnd[1] & 0x01;
1813 loej = fsg->cmnd[4] & 0x02;
1814 start = fsg->cmnd[4] & 0x01;
1815
1816#ifdef CONFIG_USB_FILE_STORAGE_TEST
1817 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1818 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1819 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1820 return -EINVAL;
1821 }
1822
1823 if (!start) {
1824
1825 /* Are we allowed to unload the media? */
1826 if (curlun->prevent_medium_removal) {
1827 LDBG(curlun, "unload attempt prevented\n");
1828 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1829 return -EINVAL;
1830 }
1831 if (loej) { // Simulate an unload/eject
1832 up_read(&fsg->filesem);
1833 down_write(&fsg->filesem);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001834 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001835 up_write(&fsg->filesem);
1836 down_read(&fsg->filesem);
1837 }
1838 } else {
1839
1840 /* Our emulation doesn't support mounting; the medium is
1841 * available for use as soon as it is loaded. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001842 if (!fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001843 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1844 return -EINVAL;
1845 }
1846 }
1847#endif
1848 return 0;
1849}
1850
1851
1852static int do_prevent_allow(struct fsg_dev *fsg)
1853{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001854 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001855 int prevent;
1856
1857 if (!mod_data.removable) {
1858 curlun->sense_data = SS_INVALID_COMMAND;
1859 return -EINVAL;
1860 }
1861
1862 prevent = fsg->cmnd[4] & 0x01;
1863 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1864 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1865 return -EINVAL;
1866 }
1867
1868 if (curlun->prevent_medium_removal && !prevent)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001869 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001870 curlun->prevent_medium_removal = prevent;
1871 return 0;
1872}
1873
1874
1875static int do_read_format_capacities(struct fsg_dev *fsg,
1876 struct fsg_buffhd *bh)
1877{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001878 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001879 u8 *buf = (u8 *) bh->buf;
1880
1881 buf[0] = buf[1] = buf[2] = 0;
1882 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1883 buf += 4;
1884
Alan Stern604eb892009-04-27 13:19:41 -04001885 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1886 /* Number of blocks */
1887 put_unaligned_be32(512, &buf[4]); /* Block length */
1888 buf[4] = 0x02; /* Current capacity */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001889 return 12;
1890}
1891
1892
1893static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1894{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001895 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001896
1897 /* We don't support MODE SELECT */
1898 curlun->sense_data = SS_INVALID_COMMAND;
1899 return -EINVAL;
1900}
1901
1902
1903/*-------------------------------------------------------------------------*/
1904
1905static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1906{
1907 int rc;
1908
1909 rc = fsg_set_halt(fsg, fsg->bulk_in);
1910 if (rc == -EAGAIN)
1911 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1912 while (rc != 0) {
1913 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001914 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001915 rc = 0;
1916 break;
1917 }
1918
1919 /* Wait for a short time and then try again */
1920 if (msleep_interruptible(100) != 0)
1921 return -EINTR;
1922 rc = usb_ep_set_halt(fsg->bulk_in);
1923 }
1924 return rc;
1925}
1926
David Lopo62fd2ca2008-04-29 10:14:38 +01001927static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1928{
1929 int rc;
1930
1931 DBG(fsg, "bulk-in set wedge\n");
1932 rc = usb_ep_set_wedge(fsg->bulk_in);
1933 if (rc == -EAGAIN)
1934 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1935 while (rc != 0) {
1936 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001937 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01001938 rc = 0;
1939 break;
1940 }
1941
1942 /* Wait for a short time and then try again */
1943 if (msleep_interruptible(100) != 0)
1944 return -EINTR;
1945 rc = usb_ep_set_wedge(fsg->bulk_in);
1946 }
1947 return rc;
1948}
1949
Linus Torvalds1da177e2005-04-16 15:20:36 -07001950static int throw_away_data(struct fsg_dev *fsg)
1951{
1952 struct fsg_buffhd *bh;
1953 u32 amount;
1954 int rc;
1955
1956 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1957 fsg->usb_amount_left > 0) {
1958
1959 /* Throw away the data in a filled buffer */
1960 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001961 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001962 bh->state = BUF_STATE_EMPTY;
1963 fsg->next_buffhd_to_drain = bh->next;
1964
1965 /* A short packet or an error ends everything */
1966 if (bh->outreq->actual != bh->outreq->length ||
1967 bh->outreq->status != 0) {
1968 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1969 return -EINTR;
1970 }
1971 continue;
1972 }
1973
1974 /* Try to submit another request if we need one */
1975 bh = fsg->next_buffhd_to_fill;
1976 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1977 amount = min(fsg->usb_amount_left,
1978 (u32) mod_data.buflen);
1979
1980 /* amount is always divisible by 512, hence by
1981 * the bulk-out maxpacket size */
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -07001982 bh->outreq->length = bh->bulk_out_intended_length =
1983 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001984 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001985 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1986 &bh->outreq_busy, &bh->state);
1987 fsg->next_buffhd_to_fill = bh->next;
1988 fsg->usb_amount_left -= amount;
1989 continue;
1990 }
1991
1992 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001993 rc = sleep_thread(fsg);
1994 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001995 return rc;
1996 }
1997 return 0;
1998}
1999
2000
2001static int finish_reply(struct fsg_dev *fsg)
2002{
2003 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2004 int rc = 0;
2005
2006 switch (fsg->data_dir) {
2007 case DATA_DIR_NONE:
2008 break; // Nothing to send
2009
2010 /* If we don't know whether the host wants to read or write,
2011 * this must be CB or CBI with an unknown command. We mustn't
2012 * try to send or receive any data. So stall both bulk pipes
2013 * if we can and wait for a reset. */
2014 case DATA_DIR_UNKNOWN:
2015 if (mod_data.can_stall) {
2016 fsg_set_halt(fsg, fsg->bulk_out);
2017 rc = halt_bulk_in_endpoint(fsg);
2018 }
2019 break;
2020
2021 /* All but the last buffer of data must have already been sent */
2022 case DATA_DIR_TO_HOST:
2023 if (fsg->data_size == 0)
2024 ; // Nothing to send
2025
2026 /* If there's no residue, simply send the last buffer */
2027 else if (fsg->residue == 0) {
2028 bh->inreq->zero = 0;
2029 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2030 &bh->inreq_busy, &bh->state);
2031 fsg->next_buffhd_to_fill = bh->next;
2032 }
2033
2034 /* There is a residue. For CB and CBI, simply mark the end
2035 * of the data with a short packet. However, if we are
2036 * allowed to stall, there was no data at all (residue ==
2037 * data_size), and the command failed (invalid LUN or
2038 * sense data is set), then halt the bulk-in endpoint
2039 * instead. */
2040 else if (!transport_is_bbb()) {
2041 if (mod_data.can_stall &&
2042 fsg->residue == fsg->data_size &&
2043 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2044 bh->state = BUF_STATE_EMPTY;
2045 rc = halt_bulk_in_endpoint(fsg);
2046 } else {
2047 bh->inreq->zero = 1;
2048 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2049 &bh->inreq_busy, &bh->state);
2050 fsg->next_buffhd_to_fill = bh->next;
2051 }
2052 }
2053
Alan Sternee81b3e2011-03-25 11:46:27 -04002054 /*
2055 * For Bulk-only, mark the end of the data with a short
2056 * packet. If we are allowed to stall, halt the bulk-in
2057 * endpoint. (Note: This violates the Bulk-Only Transport
2058 * specification, which requires us to pad the data if we
2059 * don't halt the endpoint. Presumably nobody will mind.)
2060 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002061 else {
Alan Sternee81b3e2011-03-25 11:46:27 -04002062 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 if (mod_data.can_stall)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002067 rc = halt_bulk_in_endpoint(fsg);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002068 }
2069 break;
2070
2071 /* We have processed all we want from the data the host has sent.
2072 * There may still be outstanding bulk-out requests. */
2073 case DATA_DIR_FROM_HOST:
2074 if (fsg->residue == 0)
2075 ; // Nothing to receive
2076
2077 /* Did the host stop sending unexpectedly early? */
2078 else if (fsg->short_packet_received) {
2079 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2080 rc = -EINTR;
2081 }
2082
2083 /* We haven't processed all the incoming data. Even though
2084 * we may be allowed to stall, doing so would cause a race.
2085 * The controller may already have ACK'ed all the remaining
2086 * bulk-out packets, in which case the host wouldn't see a
2087 * STALL. Not realizing the endpoint was halted, it wouldn't
2088 * clear the halt -- leading to problems later on. */
2089#if 0
2090 else if (mod_data.can_stall) {
2091 fsg_set_halt(fsg, fsg->bulk_out);
2092 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2093 rc = -EINTR;
2094 }
2095#endif
2096
2097 /* We can't stall. Read in the excess data and throw it
2098 * all away. */
2099 else
2100 rc = throw_away_data(fsg);
2101 break;
2102 }
2103 return rc;
2104}
2105
2106
2107static int send_status(struct fsg_dev *fsg)
2108{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002109 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002110 struct fsg_buffhd *bh;
2111 int rc;
2112 u8 status = USB_STATUS_PASS;
2113 u32 sd, sdinfo = 0;
2114
2115 /* Wait for the next buffer to become available */
2116 bh = fsg->next_buffhd_to_fill;
2117 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002118 rc = sleep_thread(fsg);
2119 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002120 return rc;
2121 }
2122
2123 if (curlun) {
2124 sd = curlun->sense_data;
2125 sdinfo = curlun->sense_data_info;
2126 } else if (fsg->bad_lun_okay)
2127 sd = SS_NO_SENSE;
2128 else
2129 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2130
2131 if (fsg->phase_error) {
2132 DBG(fsg, "sending phase-error status\n");
2133 status = USB_STATUS_PHASE_ERROR;
2134 sd = SS_INVALID_COMMAND;
2135 } else if (sd != SS_NO_SENSE) {
2136 DBG(fsg, "sending command-failure status\n");
2137 status = USB_STATUS_FAIL;
2138 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2139 " info x%x\n",
2140 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2141 }
2142
2143 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002144 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002145
2146 /* Store and send the Bulk-only CSW */
Harvey Harrison551509d2009-02-11 14:11:36 -08002147 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002148 csw->Tag = fsg->tag;
2149 csw->Residue = cpu_to_le32(fsg->residue);
2150 csw->Status = status;
2151
2152 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2153 bh->inreq->zero = 0;
2154 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2155 &bh->inreq_busy, &bh->state);
2156
2157 } else if (mod_data.transport_type == USB_PR_CB) {
2158
2159 /* Control-Bulk transport has no status phase! */
2160 return 0;
2161
2162 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002163 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002164
2165 /* Store and send the Interrupt data. UFI sends the ASC
2166 * and ASCQ bytes. Everything else sends a Type (which
2167 * is always 0) and the status Value. */
2168 if (mod_data.protocol_type == USB_SC_UFI) {
2169 buf->bType = ASC(sd);
2170 buf->bValue = ASCQ(sd);
2171 } else {
2172 buf->bType = 0;
2173 buf->bValue = status;
2174 }
2175 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2176
2177 fsg->intr_buffhd = bh; // Point to the right buffhd
2178 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002179 fsg->intreq->context = bh;
2180 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2181 &fsg->intreq_busy, &bh->state);
2182 }
2183
2184 fsg->next_buffhd_to_fill = bh->next;
2185 return 0;
2186}
2187
2188
2189/*-------------------------------------------------------------------------*/
2190
2191/* Check whether the command is properly formed and whether its data size
2192 * and direction agree with the values we already have. */
2193static int check_command(struct fsg_dev *fsg, int cmnd_size,
2194 enum data_direction data_dir, unsigned int mask,
2195 int needs_medium, const char *name)
2196{
2197 int i;
2198 int lun = fsg->cmnd[1] >> 5;
2199 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2200 char hdlen[20];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002201 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002202
2203 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2204 * Transparent SCSI doesn't pad. */
2205 if (protocol_is_scsi())
2206 ;
2207
2208 /* There's some disagreement as to whether RBC pads commands or not.
2209 * We'll play it safe and accept either form. */
2210 else if (mod_data.protocol_type == USB_SC_RBC) {
2211 if (fsg->cmnd_size == 12)
2212 cmnd_size = 12;
2213
2214 /* All the other protocols pad to 12 bytes */
2215 } else
2216 cmnd_size = 12;
2217
2218 hdlen[0] = 0;
2219 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2220 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2221 fsg->data_size);
2222 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2223 name, cmnd_size, dirletter[(int) data_dir],
2224 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2225
2226 /* We can't reply at all until we know the correct data direction
2227 * and size. */
2228 if (fsg->data_size_from_cmnd == 0)
2229 data_dir = DATA_DIR_NONE;
2230 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2231 fsg->data_dir = data_dir;
2232 fsg->data_size = fsg->data_size_from_cmnd;
2233
2234 } else { // Bulk-only
2235 if (fsg->data_size < fsg->data_size_from_cmnd) {
2236
2237 /* Host data size < Device data size is a phase error.
2238 * Carry out the command, but only transfer as much
2239 * as we are allowed. */
2240 fsg->data_size_from_cmnd = fsg->data_size;
2241 fsg->phase_error = 1;
2242 }
2243 }
2244 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2245
2246 /* Conflicting data directions is a phase error */
2247 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2248 fsg->phase_error = 1;
2249 return -EINVAL;
2250 }
2251
2252 /* Verify the length of the command itself */
2253 if (cmnd_size != fsg->cmnd_size) {
2254
Felipe Balbi549c41e2008-09-19 02:00:02 +03002255 /* Special case workaround: There are plenty of buggy SCSI
2256 * implementations. Many have issues with cbw->Length
2257 * field passing a wrong command size. For those cases we
2258 * always try to work around the problem by using the length
2259 * sent by the host side provided it is at least as large
2260 * as the correct command length.
2261 * Examples of such cases would be MS-Windows, which issues
2262 * REQUEST SENSE with cbw->Length == 12 where it should
2263 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2264 * REQUEST SENSE with cbw->Length == 10 where it should
2265 * be 6 as well.
2266 */
2267 if (cmnd_size <= fsg->cmnd_size) {
2268 DBG(fsg, "%s is buggy! Expected length %d "
2269 "but we got %d\n", name,
2270 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002271 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002272 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002273 fsg->phase_error = 1;
2274 return -EINVAL;
2275 }
2276 }
2277
Alan Sternd794ac72005-04-18 12:43:25 -04002278 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002279 if (transport_is_bbb()) {
2280 if (fsg->lun != lun)
2281 DBG(fsg, "using LUN %d from CBW, "
2282 "not LUN %d from CDB\n",
2283 fsg->lun, lun);
2284 } else
2285 fsg->lun = lun; // Use LUN from the command
2286
2287 /* Check the LUN */
Maxin B John849426c2011-05-08 15:56:17 +03002288 if (fsg->lun < fsg->nluns) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002289 fsg->curlun = curlun = &fsg->luns[fsg->lun];
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002290 if (fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002291 curlun->sense_data = SS_NO_SENSE;
2292 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002293 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002294 }
2295 } else {
2296 fsg->curlun = curlun = NULL;
2297 fsg->bad_lun_okay = 0;
2298
2299 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2300 * to use unsupported LUNs; all others may not. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002301 if (fsg->cmnd[0] != INQUIRY &&
2302 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002303 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2304 return -EINVAL;
2305 }
2306 }
2307
2308 /* If a unit attention condition exists, only INQUIRY and
2309 * REQUEST SENSE commands are allowed; anything else must fail. */
2310 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002311 fsg->cmnd[0] != INQUIRY &&
2312 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002313 curlun->sense_data = curlun->unit_attention_data;
2314 curlun->unit_attention_data = SS_NO_SENSE;
2315 return -EINVAL;
2316 }
2317
2318 /* Check that only command bytes listed in the mask are non-zero */
2319 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2320 for (i = 1; i < cmnd_size; ++i) {
2321 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2322 if (curlun)
2323 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2324 return -EINVAL;
2325 }
2326 }
2327
2328 /* If the medium isn't mounted and the command needs to access
2329 * it, return an error. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002330 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002331 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2332 return -EINVAL;
2333 }
2334
2335 return 0;
2336}
2337
2338
2339static int do_scsi_command(struct fsg_dev *fsg)
2340{
2341 struct fsg_buffhd *bh;
2342 int rc;
2343 int reply = -EINVAL;
2344 int i;
2345 static char unknown[16];
2346
2347 dump_cdb(fsg);
2348
2349 /* Wait for the next buffer to become available for data or status */
2350 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2351 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002352 rc = sleep_thread(fsg);
2353 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002354 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002355 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002356 fsg->phase_error = 0;
2357 fsg->short_packet_received = 0;
2358
2359 down_read(&fsg->filesem); // We're using the backing file
2360 switch (fsg->cmnd[0]) {
2361
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002362 case INQUIRY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002363 fsg->data_size_from_cmnd = fsg->cmnd[4];
2364 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2365 (1<<4), 0,
2366 "INQUIRY")) == 0)
2367 reply = do_inquiry(fsg, bh);
2368 break;
2369
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002370 case MODE_SELECT:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002371 fsg->data_size_from_cmnd = fsg->cmnd[4];
2372 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2373 (1<<1) | (1<<4), 0,
2374 "MODE SELECT(6)")) == 0)
2375 reply = do_mode_select(fsg, bh);
2376 break;
2377
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002378 case MODE_SELECT_10:
Alan Stern604eb892009-04-27 13:19:41 -04002379 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2381 (1<<1) | (3<<7), 0,
2382 "MODE SELECT(10)")) == 0)
2383 reply = do_mode_select(fsg, bh);
2384 break;
2385
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002386 case MODE_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002387 fsg->data_size_from_cmnd = fsg->cmnd[4];
2388 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2389 (1<<1) | (1<<2) | (1<<4), 0,
2390 "MODE SENSE(6)")) == 0)
2391 reply = do_mode_sense(fsg, bh);
2392 break;
2393
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002394 case MODE_SENSE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002395 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002396 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2397 (1<<1) | (1<<2) | (3<<7), 0,
2398 "MODE SENSE(10)")) == 0)
2399 reply = do_mode_sense(fsg, bh);
2400 break;
2401
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002402 case ALLOW_MEDIUM_REMOVAL:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002403 fsg->data_size_from_cmnd = 0;
2404 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2405 (1<<4), 0,
2406 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2407 reply = do_prevent_allow(fsg);
2408 break;
2409
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002410 case READ_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002411 i = fsg->cmnd[4];
2412 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2413 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2414 (7<<1) | (1<<4), 1,
2415 "READ(6)")) == 0)
2416 reply = do_read(fsg);
2417 break;
2418
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002419 case READ_10:
Alan Stern604eb892009-04-27 13:19:41 -04002420 fsg->data_size_from_cmnd =
2421 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002422 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2423 (1<<1) | (0xf<<2) | (3<<7), 1,
2424 "READ(10)")) == 0)
2425 reply = do_read(fsg);
2426 break;
2427
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002428 case READ_12:
Alan Stern604eb892009-04-27 13:19:41 -04002429 fsg->data_size_from_cmnd =
2430 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002431 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2432 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2433 "READ(12)")) == 0)
2434 reply = do_read(fsg);
2435 break;
2436
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002437 case READ_CAPACITY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002438 fsg->data_size_from_cmnd = 8;
2439 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2440 (0xf<<2) | (1<<8), 1,
2441 "READ CAPACITY")) == 0)
2442 reply = do_read_capacity(fsg, bh);
2443 break;
2444
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002445 case READ_HEADER:
Alan Stern12aae682008-11-20 14:13:12 -05002446 if (!mod_data.cdrom)
2447 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002448 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002449 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2450 (3<<7) | (0x1f<<1), 1,
2451 "READ HEADER")) == 0)
2452 reply = do_read_header(fsg, bh);
2453 break;
2454
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002455 case READ_TOC:
Alan Stern12aae682008-11-20 14:13:12 -05002456 if (!mod_data.cdrom)
2457 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002458 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002459 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2460 (7<<6) | (1<<1), 1,
2461 "READ TOC")) == 0)
2462 reply = do_read_toc(fsg, bh);
2463 break;
2464
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002465 case READ_FORMAT_CAPACITIES:
Alan Stern604eb892009-04-27 13:19:41 -04002466 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002467 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2468 (3<<7), 1,
2469 "READ FORMAT CAPACITIES")) == 0)
2470 reply = do_read_format_capacities(fsg, bh);
2471 break;
2472
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002473 case REQUEST_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002474 fsg->data_size_from_cmnd = fsg->cmnd[4];
2475 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2476 (1<<4), 0,
2477 "REQUEST SENSE")) == 0)
2478 reply = do_request_sense(fsg, bh);
2479 break;
2480
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002481 case START_STOP:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002482 fsg->data_size_from_cmnd = 0;
2483 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2484 (1<<1) | (1<<4), 0,
2485 "START-STOP UNIT")) == 0)
2486 reply = do_start_stop(fsg);
2487 break;
2488
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002489 case SYNCHRONIZE_CACHE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002490 fsg->data_size_from_cmnd = 0;
2491 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2492 (0xf<<2) | (3<<7), 1,
2493 "SYNCHRONIZE CACHE")) == 0)
2494 reply = do_synchronize_cache(fsg);
2495 break;
2496
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002497 case TEST_UNIT_READY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002498 fsg->data_size_from_cmnd = 0;
2499 reply = check_command(fsg, 6, DATA_DIR_NONE,
2500 0, 1,
2501 "TEST UNIT READY");
2502 break;
2503
2504 /* Although optional, this command is used by MS-Windows. We
2505 * support a minimal version: BytChk must be 0. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002506 case VERIFY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002507 fsg->data_size_from_cmnd = 0;
2508 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2509 (1<<1) | (0xf<<2) | (3<<7), 1,
2510 "VERIFY")) == 0)
2511 reply = do_verify(fsg);
2512 break;
2513
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002514 case WRITE_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002515 i = fsg->cmnd[4];
2516 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2517 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2518 (7<<1) | (1<<4), 1,
2519 "WRITE(6)")) == 0)
2520 reply = do_write(fsg);
2521 break;
2522
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002523 case WRITE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002524 fsg->data_size_from_cmnd =
2525 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002526 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2527 (1<<1) | (0xf<<2) | (3<<7), 1,
2528 "WRITE(10)")) == 0)
2529 reply = do_write(fsg);
2530 break;
2531
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002532 case WRITE_12:
Alan Stern604eb892009-04-27 13:19:41 -04002533 fsg->data_size_from_cmnd =
2534 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002535 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2536 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2537 "WRITE(12)")) == 0)
2538 reply = do_write(fsg);
2539 break;
2540
2541 /* Some mandatory commands that we recognize but don't implement.
2542 * They don't mean much in this setting. It's left as an exercise
2543 * for anyone interested to implement RESERVE and RELEASE in terms
2544 * of Posix locks. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002545 case FORMAT_UNIT:
2546 case RELEASE:
2547 case RESERVE:
2548 case SEND_DIAGNOSTIC:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002549 // Fall through
2550
2551 default:
Alan Stern12aae682008-11-20 14:13:12 -05002552 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002553 fsg->data_size_from_cmnd = 0;
2554 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2555 if ((reply = check_command(fsg, fsg->cmnd_size,
2556 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2557 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2558 reply = -EINVAL;
2559 }
2560 break;
2561 }
2562 up_read(&fsg->filesem);
2563
2564 if (reply == -EINTR || signal_pending(current))
2565 return -EINTR;
2566
2567 /* Set up the single reply buffer for finish_reply() */
2568 if (reply == -EINVAL)
2569 reply = 0; // Error reply length
2570 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2571 reply = min((u32) reply, fsg->data_size_from_cmnd);
2572 bh->inreq->length = reply;
2573 bh->state = BUF_STATE_FULL;
2574 fsg->residue -= reply;
2575 } // Otherwise it's already set
2576
2577 return 0;
2578}
2579
2580
2581/*-------------------------------------------------------------------------*/
2582
2583static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2584{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002585 struct usb_request *req = bh->outreq;
2586 struct fsg_bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002587
Alan Sternb950bdb2008-04-14 11:45:29 -04002588 /* Was this a real packet? Should it be ignored? */
2589 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002590 return -EINVAL;
2591
2592 /* Is the CBW valid? */
2593 if (req->actual != USB_BULK_CB_WRAP_LEN ||
Harvey Harrison551509d2009-02-11 14:11:36 -08002594 cbw->Signature != cpu_to_le32(
Linus Torvalds1da177e2005-04-16 15:20:36 -07002595 USB_BULK_CB_SIG)) {
2596 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2597 req->actual,
2598 le32_to_cpu(cbw->Signature));
2599
Alan Sternb950bdb2008-04-14 11:45:29 -04002600 /* The Bulk-only spec says we MUST stall the IN endpoint
2601 * (6.6.1), so it's unavoidable. It also says we must
2602 * retain this state until the next reset, but there's
2603 * no way to tell the controller driver it should ignore
2604 * Clear-Feature(HALT) requests.
2605 *
2606 * We aren't required to halt the OUT endpoint; instead
2607 * we can simply accept and discard any data received
2608 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01002609 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04002610 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002611 return -EINVAL;
2612 }
2613
2614 /* Is the CBW meaningful? */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002615 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04002616 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002617 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2618 "cmdlen %u\n",
2619 cbw->Lun, cbw->Flags, cbw->Length);
2620
2621 /* We can do anything we want here, so let's stall the
2622 * bulk pipes if we are allowed to. */
2623 if (mod_data.can_stall) {
2624 fsg_set_halt(fsg, fsg->bulk_out);
2625 halt_bulk_in_endpoint(fsg);
2626 }
2627 return -EINVAL;
2628 }
2629
2630 /* Save the command for later */
2631 fsg->cmnd_size = cbw->Length;
2632 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2633 if (cbw->Flags & USB_BULK_IN_FLAG)
2634 fsg->data_dir = DATA_DIR_TO_HOST;
2635 else
2636 fsg->data_dir = DATA_DIR_FROM_HOST;
2637 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2638 if (fsg->data_size == 0)
2639 fsg->data_dir = DATA_DIR_NONE;
2640 fsg->lun = cbw->Lun;
2641 fsg->tag = cbw->Tag;
2642 return 0;
2643}
2644
2645
2646static int get_next_command(struct fsg_dev *fsg)
2647{
2648 struct fsg_buffhd *bh;
2649 int rc = 0;
2650
2651 if (transport_is_bbb()) {
2652
2653 /* Wait for the next buffer to become available */
2654 bh = fsg->next_buffhd_to_fill;
2655 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002656 rc = sleep_thread(fsg);
2657 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002658 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002659 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002660
2661 /* Queue a request to read a Bulk-only CBW */
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -07002662 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2663 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002664 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2665 &bh->outreq_busy, &bh->state);
2666
2667 /* We will drain the buffer in software, which means we
2668 * can reuse it for the next filling. No need to advance
2669 * next_buffhd_to_fill. */
2670
2671 /* Wait for the CBW to arrive */
2672 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002673 rc = sleep_thread(fsg);
2674 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002675 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002676 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05002677 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002678 rc = received_cbw(fsg, bh);
2679 bh->state = BUF_STATE_EMPTY;
2680
2681 } else { // USB_PR_CB or USB_PR_CBI
2682
2683 /* Wait for the next command to arrive */
2684 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002685 rc = sleep_thread(fsg);
2686 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002687 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002688 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002689
2690 /* Is the previous status interrupt request still busy?
2691 * The host is allowed to skip reading the status,
2692 * so we must cancel it. */
2693 if (fsg->intreq_busy)
2694 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2695
2696 /* Copy the command and mark the buffer empty */
2697 fsg->data_dir = DATA_DIR_UNKNOWN;
2698 spin_lock_irq(&fsg->lock);
2699 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2700 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2701 fsg->cbbuf_cmnd_size = 0;
2702 spin_unlock_irq(&fsg->lock);
2703 }
2704 return rc;
2705}
2706
2707
2708/*-------------------------------------------------------------------------*/
2709
2710static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2711 const struct usb_endpoint_descriptor *d)
2712{
2713 int rc;
2714
2715 ep->driver_data = fsg;
Tatyana Brokhman72c973d2011-06-28 16:33:48 +03002716 ep->desc = d;
2717 rc = usb_ep_enable(ep);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002718 if (rc)
2719 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2720 return rc;
2721}
2722
2723static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2724 struct usb_request **preq)
2725{
2726 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2727 if (*preq)
2728 return 0;
2729 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2730 return -ENOMEM;
2731}
2732
2733/*
2734 * Reset interface setting and re-init endpoint state (toggle etc).
2735 * Call with altsetting < 0 to disable the interface. The only other
2736 * available altsetting is 0, which enables the interface.
2737 */
2738static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2739{
2740 int rc = 0;
2741 int i;
2742 const struct usb_endpoint_descriptor *d;
2743
2744 if (fsg->running)
2745 DBG(fsg, "reset interface\n");
2746
2747reset:
2748 /* Deallocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002749 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002750 struct fsg_buffhd *bh = &fsg->buffhds[i];
2751
2752 if (bh->inreq) {
2753 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2754 bh->inreq = NULL;
2755 }
2756 if (bh->outreq) {
2757 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2758 bh->outreq = NULL;
2759 }
2760 }
2761 if (fsg->intreq) {
2762 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2763 fsg->intreq = NULL;
2764 }
2765
2766 /* Disable the endpoints */
2767 if (fsg->bulk_in_enabled) {
2768 usb_ep_disable(fsg->bulk_in);
2769 fsg->bulk_in_enabled = 0;
2770 }
2771 if (fsg->bulk_out_enabled) {
2772 usb_ep_disable(fsg->bulk_out);
2773 fsg->bulk_out_enabled = 0;
2774 }
2775 if (fsg->intr_in_enabled) {
2776 usb_ep_disable(fsg->intr_in);
2777 fsg->intr_in_enabled = 0;
2778 }
2779
2780 fsg->running = 0;
2781 if (altsetting < 0 || rc != 0)
2782 return rc;
2783
2784 DBG(fsg, "set interface %d\n", altsetting);
2785
2786 /* Enable the endpoints */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002787 d = fsg_ep_desc(fsg->gadget,
2788 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002789 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2790 goto reset;
2791 fsg->bulk_in_enabled = 1;
2792
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002793 d = fsg_ep_desc(fsg->gadget,
2794 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002795 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2796 goto reset;
2797 fsg->bulk_out_enabled = 1;
2798 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
Alan Sternb950bdb2008-04-14 11:45:29 -04002799 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002800
2801 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002802 d = fsg_ep_desc(fsg->gadget,
2803 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002804 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2805 goto reset;
2806 fsg->intr_in_enabled = 1;
2807 }
2808
2809 /* Allocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002810 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002811 struct fsg_buffhd *bh = &fsg->buffhds[i];
2812
2813 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2814 goto reset;
2815 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2816 goto reset;
2817 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002818 bh->inreq->context = bh->outreq->context = bh;
2819 bh->inreq->complete = bulk_in_complete;
2820 bh->outreq->complete = bulk_out_complete;
2821 }
2822 if (transport_is_cbi()) {
2823 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2824 goto reset;
2825 fsg->intreq->complete = intr_in_complete;
2826 }
2827
2828 fsg->running = 1;
2829 for (i = 0; i < fsg->nluns; ++i)
2830 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2831 return rc;
2832}
2833
2834
2835/*
2836 * Change our operational configuration. This code must agree with the code
2837 * that returns config descriptors, and with interface altsetting code.
2838 *
2839 * It's also responsible for power management interactions. Some
2840 * configurations might not work with our current power sources.
2841 * For now we just assume the gadget is always self-powered.
2842 */
2843static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2844{
2845 int rc = 0;
2846
2847 /* Disable the single interface */
2848 if (fsg->config != 0) {
2849 DBG(fsg, "reset config\n");
2850 fsg->config = 0;
2851 rc = do_set_interface(fsg, -1);
2852 }
2853
2854 /* Enable the interface */
2855 if (new_config != 0) {
2856 fsg->config = new_config;
2857 if ((rc = do_set_interface(fsg, 0)) != 0)
2858 fsg->config = 0; // Reset on errors
2859 else {
2860 char *speed;
2861
2862 switch (fsg->gadget->speed) {
2863 case USB_SPEED_LOW: speed = "low"; break;
2864 case USB_SPEED_FULL: speed = "full"; break;
2865 case USB_SPEED_HIGH: speed = "high"; break;
2866 default: speed = "?"; break;
2867 }
2868 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2869 }
2870 }
2871 return rc;
2872}
2873
2874
2875/*-------------------------------------------------------------------------*/
2876
2877static void handle_exception(struct fsg_dev *fsg)
2878{
2879 siginfo_t info;
2880 int sig;
2881 int i;
2882 int num_active;
2883 struct fsg_buffhd *bh;
2884 enum fsg_state old_state;
2885 u8 new_config;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002886 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002887 unsigned int exception_req_tag;
2888 int rc;
2889
2890 /* Clear the existing signals. Anything but SIGUSR1 is converted
2891 * into a high-priority EXIT exception. */
2892 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04002893 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002894 if (!sig)
2895 break;
2896 if (sig != SIGUSR1) {
2897 if (fsg->state < FSG_STATE_EXIT)
2898 DBG(fsg, "Main thread exiting on signal\n");
2899 raise_exception(fsg, FSG_STATE_EXIT);
2900 }
2901 }
2902
2903 /* Cancel all the pending transfers */
2904 if (fsg->intreq_busy)
2905 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002906 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002907 bh = &fsg->buffhds[i];
2908 if (bh->inreq_busy)
2909 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2910 if (bh->outreq_busy)
2911 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2912 }
2913
2914 /* Wait until everything is idle */
2915 for (;;) {
2916 num_active = fsg->intreq_busy;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002917 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002918 bh = &fsg->buffhds[i];
2919 num_active += bh->inreq_busy + bh->outreq_busy;
2920 }
2921 if (num_active == 0)
2922 break;
2923 if (sleep_thread(fsg))
2924 return;
2925 }
2926
2927 /* Clear out the controller's fifos */
2928 if (fsg->bulk_in_enabled)
2929 usb_ep_fifo_flush(fsg->bulk_in);
2930 if (fsg->bulk_out_enabled)
2931 usb_ep_fifo_flush(fsg->bulk_out);
2932 if (fsg->intr_in_enabled)
2933 usb_ep_fifo_flush(fsg->intr_in);
2934
2935 /* Reset the I/O buffer states and pointers, the SCSI
2936 * state, and the exception. Then invoke the handler. */
2937 spin_lock_irq(&fsg->lock);
2938
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002939 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002940 bh = &fsg->buffhds[i];
2941 bh->state = BUF_STATE_EMPTY;
2942 }
2943 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2944 &fsg->buffhds[0];
2945
2946 exception_req_tag = fsg->exception_req_tag;
2947 new_config = fsg->new_config;
2948 old_state = fsg->state;
2949
2950 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2951 fsg->state = FSG_STATE_STATUS_PHASE;
2952 else {
2953 for (i = 0; i < fsg->nluns; ++i) {
2954 curlun = &fsg->luns[i];
2955 curlun->prevent_medium_removal = 0;
2956 curlun->sense_data = curlun->unit_attention_data =
2957 SS_NO_SENSE;
2958 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002959 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002960 }
2961 fsg->state = FSG_STATE_IDLE;
2962 }
2963 spin_unlock_irq(&fsg->lock);
2964
2965 /* Carry out any extra actions required for the exception */
2966 switch (old_state) {
2967 default:
2968 break;
2969
2970 case FSG_STATE_ABORT_BULK_OUT:
2971 send_status(fsg);
2972 spin_lock_irq(&fsg->lock);
2973 if (fsg->state == FSG_STATE_STATUS_PHASE)
2974 fsg->state = FSG_STATE_IDLE;
2975 spin_unlock_irq(&fsg->lock);
2976 break;
2977
2978 case FSG_STATE_RESET:
2979 /* In case we were forced against our will to halt a
2980 * bulk endpoint, clear the halt now. (The SuperH UDC
2981 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04002982 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002983 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002984
2985 if (transport_is_bbb()) {
2986 if (fsg->ep0_req_tag == exception_req_tag)
2987 ep0_queue(fsg); // Complete the status stage
2988
2989 } else if (transport_is_cbi())
2990 send_status(fsg); // Status by interrupt pipe
2991
2992 /* Technically this should go here, but it would only be
2993 * a waste of time. Ditto for the INTERFACE_CHANGE and
2994 * CONFIG_CHANGE cases. */
2995 // for (i = 0; i < fsg->nluns; ++i)
2996 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2997 break;
2998
2999 case FSG_STATE_INTERFACE_CHANGE:
3000 rc = do_set_interface(fsg, 0);
3001 if (fsg->ep0_req_tag != exception_req_tag)
3002 break;
3003 if (rc != 0) // STALL on errors
3004 fsg_set_halt(fsg, fsg->ep0);
3005 else // Complete the status stage
3006 ep0_queue(fsg);
3007 break;
3008
3009 case FSG_STATE_CONFIG_CHANGE:
3010 rc = do_set_config(fsg, new_config);
3011 if (fsg->ep0_req_tag != exception_req_tag)
3012 break;
3013 if (rc != 0) // STALL on errors
3014 fsg_set_halt(fsg, fsg->ep0);
3015 else // Complete the status stage
3016 ep0_queue(fsg);
3017 break;
3018
3019 case FSG_STATE_DISCONNECT:
Michal Nazarewiczb6058d02009-10-28 16:57:14 +01003020 for (i = 0; i < fsg->nluns; ++i)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003021 fsg_lun_fsync_sub(fsg->luns + i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003022 do_set_config(fsg, 0); // Unconfigured state
3023 break;
3024
3025 case FSG_STATE_EXIT:
3026 case FSG_STATE_TERMINATED:
3027 do_set_config(fsg, 0); // Free resources
3028 spin_lock_irq(&fsg->lock);
3029 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3030 spin_unlock_irq(&fsg->lock);
3031 break;
3032 }
3033}
3034
3035
3036/*-------------------------------------------------------------------------*/
3037
3038static int fsg_main_thread(void *fsg_)
3039{
John Daiker7ca46b82006-12-29 19:02:06 -08003040 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003041
Linus Torvalds1da177e2005-04-16 15:20:36 -07003042 /* Allow the thread to be killed by a signal, but set the signal mask
3043 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003044 allow_signal(SIGINT);
3045 allow_signal(SIGTERM);
3046 allow_signal(SIGKILL);
3047 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003048
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003049 /* Allow the thread to be frozen */
3050 set_freezable();
3051
Linus Torvalds1da177e2005-04-16 15:20:36 -07003052 /* Arrange for userspace references to be interpreted as kernel
3053 * pointers. That way we can pass a kernel pointer to a routine
3054 * that expects a __user pointer and it will work okay. */
3055 set_fs(get_ds());
3056
Linus Torvalds1da177e2005-04-16 15:20:36 -07003057 /* The main loop */
3058 while (fsg->state != FSG_STATE_TERMINATED) {
3059 if (exception_in_progress(fsg) || signal_pending(current)) {
3060 handle_exception(fsg);
3061 continue;
3062 }
3063
3064 if (!fsg->running) {
3065 sleep_thread(fsg);
3066 continue;
3067 }
3068
3069 if (get_next_command(fsg))
3070 continue;
3071
3072 spin_lock_irq(&fsg->lock);
3073 if (!exception_in_progress(fsg))
3074 fsg->state = FSG_STATE_DATA_PHASE;
3075 spin_unlock_irq(&fsg->lock);
3076
3077 if (do_scsi_command(fsg) || finish_reply(fsg))
3078 continue;
3079
3080 spin_lock_irq(&fsg->lock);
3081 if (!exception_in_progress(fsg))
3082 fsg->state = FSG_STATE_STATUS_PHASE;
3083 spin_unlock_irq(&fsg->lock);
3084
3085 if (send_status(fsg))
3086 continue;
3087
3088 spin_lock_irq(&fsg->lock);
3089 if (!exception_in_progress(fsg))
3090 fsg->state = FSG_STATE_IDLE;
3091 spin_unlock_irq(&fsg->lock);
3092 }
3093
Alan Stern22efcf42005-09-26 16:12:02 -04003094 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003095 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003096 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003097
Alan Stern82a10a82009-04-16 15:37:28 -04003098 /* If we are exiting because of a signal, unregister the
3099 * gadget driver. */
3100 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003101 usb_gadget_unregister_driver(&fsg_driver);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003102
3103 /* Let the unbind and cleanup routines know the thread has exited */
3104 complete_and_exit(&fsg->thread_notifier, 0);
3105}
3106
3107
3108/*-------------------------------------------------------------------------*/
3109
Linus Torvalds1da177e2005-04-16 15:20:36 -07003110
3111/* The write permissions and store_xxx pointers are set in fsg_bind() */
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003112static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003113static DEVICE_ATTR(nofua, 0644, fsg_show_nofua, NULL);
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003114static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003115
3116
3117/*-------------------------------------------------------------------------*/
3118
Alan Stern87c42522005-11-09 16:59:56 -05003119static void fsg_release(struct kref *ref)
3120{
3121 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3122
3123 kfree(fsg->luns);
3124 kfree(fsg);
3125}
3126
Linus Torvalds1da177e2005-04-16 15:20:36 -07003127static void lun_release(struct device *dev)
3128{
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003129 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3130 struct fsg_dev *fsg =
3131 container_of(filesem, struct fsg_dev, filesem);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003132
Alan Stern87c42522005-11-09 16:59:56 -05003133 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003134}
3135
David Brownella3536782006-07-06 15:48:53 -07003136static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003137{
3138 struct fsg_dev *fsg = get_gadget_data(gadget);
3139 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003140 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003141 struct usb_request *req = fsg->ep0req;
3142
3143 DBG(fsg, "unbind\n");
3144 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3145
3146 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003147 for (i = 0; i < fsg->nluns; ++i) {
3148 curlun = &fsg->luns[i];
3149 if (curlun->registered) {
Michal Nazarewicz452ee0e2010-08-12 17:43:50 +02003150 device_remove_file(&curlun->dev, &dev_attr_nofua);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003151 device_remove_file(&curlun->dev, &dev_attr_ro);
3152 device_remove_file(&curlun->dev, &dev_attr_file);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003153 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003154 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003155 curlun->registered = 0;
3156 }
3157 }
3158
3159 /* If the thread isn't already dead, tell it to exit now */
3160 if (fsg->state != FSG_STATE_TERMINATED) {
3161 raise_exception(fsg, FSG_STATE_EXIT);
3162 wait_for_completion(&fsg->thread_notifier);
3163
3164 /* The cleanup routine waits for this completion also */
3165 complete(&fsg->thread_notifier);
3166 }
3167
3168 /* Free the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003169 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
David Brownell9d8bab52007-07-01 11:04:54 -07003170 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003171
3172 /* Free the request and buffer for endpoint 0 */
3173 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003174 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003175 usb_ep_free_request(fsg->ep0, req);
3176 }
3177
3178 set_gadget_data(gadget, NULL);
3179}
3180
3181
3182static int __init check_parameters(struct fsg_dev *fsg)
3183{
3184 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003185 int gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003186
3187 /* Store the default values */
3188 mod_data.transport_type = USB_PR_BULK;
3189 mod_data.transport_name = "Bulk-only";
3190 mod_data.protocol_type = USB_SC_SCSI;
3191 mod_data.protocol_name = "Transparent SCSI";
3192
Alan Sternce459ec2009-02-24 16:19:47 -05003193 /* Some peripheral controllers are known not to be able to
3194 * halt bulk endpoints correctly. If one of them is present,
3195 * disable stalls.
3196 */
Christoph Egger90f79762010-02-05 13:24:12 +01003197 if (gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003198 mod_data.can_stall = 0;
3199
3200 if (mod_data.release == 0xffff) { // Parameter wasn't set
Christoph Egger90f79762010-02-05 13:24:12 +01003201 gcnum = usb_gadget_controller_number(fsg->gadget);
David Brownell91e79c92005-07-13 15:18:30 -07003202 if (gcnum >= 0)
3203 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003204 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003205 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003206 fsg->gadget->name);
3207 mod_data.release = 0x0399;
3208 }
3209 }
3210
3211 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3212
3213#ifdef CONFIG_USB_FILE_STORAGE_TEST
3214 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3215 ; // Use default setting
3216 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3217 mod_data.transport_type = USB_PR_CB;
3218 mod_data.transport_name = "Control-Bulk";
3219 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3220 mod_data.transport_type = USB_PR_CBI;
3221 mod_data.transport_name = "Control-Bulk-Interrupt";
3222 } else {
3223 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3224 return -EINVAL;
3225 }
3226
3227 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3228 prot == USB_SC_SCSI) {
3229 ; // Use default setting
3230 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3231 prot == USB_SC_RBC) {
3232 mod_data.protocol_type = USB_SC_RBC;
3233 mod_data.protocol_name = "RBC";
3234 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3235 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3236 prot == USB_SC_8020) {
3237 mod_data.protocol_type = USB_SC_8020;
3238 mod_data.protocol_name = "8020i (ATAPI)";
3239 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3240 prot == USB_SC_QIC) {
3241 mod_data.protocol_type = USB_SC_QIC;
3242 mod_data.protocol_name = "QIC-157";
3243 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3244 prot == USB_SC_UFI) {
3245 mod_data.protocol_type = USB_SC_UFI;
3246 mod_data.protocol_name = "UFI";
3247 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3248 prot == USB_SC_8070) {
3249 mod_data.protocol_type = USB_SC_8070;
3250 mod_data.protocol_name = "8070i";
3251 } else {
3252 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3253 return -EINVAL;
3254 }
3255
3256 mod_data.buflen &= PAGE_CACHE_MASK;
3257 if (mod_data.buflen <= 0) {
3258 ERROR(fsg, "invalid buflen\n");
3259 return -ETOOSMALL;
3260 }
Yann Cantin87eb1be2010-06-05 23:06:31 +02003261
Michal Nazarewicz56706492010-07-22 14:16:37 +02003262#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3263
Yann Cantin87eb1be2010-06-05 23:06:31 +02003264 /* Serial string handling.
3265 * On a real device, the serial string would be loaded
3266 * from permanent storage. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003267 if (mod_data.serial) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003268 const char *ch;
3269 unsigned len = 0;
3270
3271 /* Sanity check :
3272 * The CB[I] specification limits the serial string to
3273 * 12 uppercase hexadecimal characters.
3274 * BBB need at least 12 uppercase hexadecimal characters,
3275 * with a maximum of 126. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003276 for (ch = mod_data.serial; *ch; ++ch) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003277 ++len;
3278 if ((*ch < '0' || *ch > '9') &&
3279 (*ch < 'A' || *ch > 'F')) { /* not uppercase hex */
3280 WARNING(fsg,
Alan Sternd8087422010-09-03 11:15:41 -04003281 "Invalid serial string character: %c\n",
Yann Cantin87eb1be2010-06-05 23:06:31 +02003282 *ch);
Alan Sternd8087422010-09-03 11:15:41 -04003283 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003284 }
3285 }
3286 if (len > 126 ||
3287 (mod_data.transport_type == USB_PR_BULK && len < 12) ||
3288 (mod_data.transport_type != USB_PR_BULK && len > 12)) {
Alan Sternd8087422010-09-03 11:15:41 -04003289 WARNING(fsg, "Invalid serial string length!\n");
3290 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003291 }
Michal Nazarewicz56706492010-07-22 14:16:37 +02003292 fsg_strings[FSG_STRING_SERIAL - 1].s = mod_data.serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003293 } else {
Alan Sternd8087422010-09-03 11:15:41 -04003294 WARNING(fsg, "No serial-number string provided!\n");
3295 no_serial:
3296 device_desc.iSerialNumber = 0;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003297 }
3298
Linus Torvalds1da177e2005-04-16 15:20:36 -07003299 return 0;
3300}
3301
3302
Michal Nazarewicze12995e2010-08-12 17:43:52 +02003303static int __init fsg_bind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003304{
3305 struct fsg_dev *fsg = the_fsg;
3306 int rc;
3307 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003308 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003309 struct usb_ep *ep;
3310 struct usb_request *req;
3311 char *pathbuf, *p;
3312
3313 fsg->gadget = gadget;
3314 set_gadget_data(gadget, fsg);
3315 fsg->ep0 = gadget->ep0;
3316 fsg->ep0->driver_data = fsg;
3317
3318 if ((rc = check_parameters(fsg)) != 0)
3319 goto out;
3320
3321 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003322 dev_attr_file.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003323 dev_attr_file.store = fsg_store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003324 if (!mod_data.cdrom) {
3325 dev_attr_ro.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003326 dev_attr_ro.store = fsg_store_ro;
Alan Stern12aae682008-11-20 14:13:12 -05003327 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003328 }
3329
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003330 /* Only for removable media? */
3331 dev_attr_nofua.attr.mode = 0644;
3332 dev_attr_nofua.store = fsg_store_nofua;
3333
Linus Torvalds1da177e2005-04-16 15:20:36 -07003334 /* Find out how many LUNs there should be */
3335 i = mod_data.nluns;
3336 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003337 i = max(mod_data.num_filenames, 1u);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003338 if (i > FSG_MAX_LUNS) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003339 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3340 rc = -EINVAL;
3341 goto out;
3342 }
3343
3344 /* Create the LUNs, open their backing files, and register the
3345 * LUN devices in sysfs. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003346 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003347 if (!fsg->luns) {
3348 rc = -ENOMEM;
3349 goto out;
3350 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003351 fsg->nluns = i;
3352
3353 for (i = 0; i < fsg->nluns; ++i) {
3354 curlun = &fsg->luns[i];
Michal Nazarewicze909ef52009-10-28 16:57:16 +01003355 curlun->cdrom = !!mod_data.cdrom;
3356 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3357 curlun->initially_ro = curlun->ro;
3358 curlun->removable = mod_data.removable;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003359 curlun->nofua = mod_data.nofua[i];
Alan Stern2de9eae2006-09-25 14:31:15 -04003360 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003361 curlun->dev.parent = &gadget->dev;
3362 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003363 dev_set_drvdata(&curlun->dev, &fsg->filesem);
Kay Sievers0031a062008-05-02 06:02:41 +02003364 dev_set_name(&curlun->dev,"%s-lun%d",
3365 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003366
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003367 kref_get(&fsg->ref);
3368 rc = device_register(&curlun->dev);
3369 if (rc) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003370 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003371 put_device(&curlun->dev);
Alan Stern2de9eae2006-09-25 14:31:15 -04003372 goto out;
3373 }
3374 curlun->registered = 1;
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003375
3376 rc = device_create_file(&curlun->dev, &dev_attr_ro);
3377 if (rc)
3378 goto out;
3379 rc = device_create_file(&curlun->dev, &dev_attr_nofua);
3380 if (rc)
3381 goto out;
3382 rc = device_create_file(&curlun->dev, &dev_attr_file);
3383 if (rc)
3384 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003385
Alan Sternaafe5bd2006-03-31 11:46:43 -05003386 if (mod_data.file[i] && *mod_data.file[i]) {
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003387 rc = fsg_lun_open(curlun, mod_data.file[i]);
3388 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003389 goto out;
3390 } else if (!mod_data.removable) {
3391 ERROR(fsg, "no file given for LUN%d\n", i);
3392 rc = -EINVAL;
3393 goto out;
3394 }
3395 }
3396
3397 /* Find all the endpoints we will use */
3398 usb_ep_autoconfig_reset(gadget);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003399 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003400 if (!ep)
3401 goto autoconf_fail;
3402 ep->driver_data = fsg; // claim the endpoint
3403 fsg->bulk_in = ep;
3404
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003405 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003406 if (!ep)
3407 goto autoconf_fail;
3408 ep->driver_data = fsg; // claim the endpoint
3409 fsg->bulk_out = ep;
3410
3411 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003412 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003413 if (!ep)
3414 goto autoconf_fail;
3415 ep->driver_data = fsg; // claim the endpoint
3416 fsg->intr_in = ep;
3417 }
3418
3419 /* Fix up the descriptors */
3420 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3421 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3422 device_desc.idProduct = cpu_to_le16(mod_data.product);
3423 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3424
3425 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003426 fsg_intf_desc.bNumEndpoints = i;
3427 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3428 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3429 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003430
David Brownell2e806f62007-08-02 00:03:39 -07003431 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003432 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003433
David Brownell2e806f62007-08-02 00:03:39 -07003434 /* Assume ep0 uses the same maxpacket value for both speeds */
3435 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003436
David Brownell2e806f62007-08-02 00:03:39 -07003437 /* Assume endpoint addresses are the same for both speeds */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003438 fsg_hs_bulk_in_desc.bEndpointAddress =
3439 fsg_fs_bulk_in_desc.bEndpointAddress;
3440 fsg_hs_bulk_out_desc.bEndpointAddress =
3441 fsg_fs_bulk_out_desc.bEndpointAddress;
3442 fsg_hs_intr_in_desc.bEndpointAddress =
3443 fsg_fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003444 }
3445
David Brownell2e806f62007-08-02 00:03:39 -07003446 if (gadget_is_otg(gadget))
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003447 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
David Brownell2e806f62007-08-02 00:03:39 -07003448
Linus Torvalds1da177e2005-04-16 15:20:36 -07003449 rc = -ENOMEM;
3450
3451 /* Allocate the request and buffer for endpoint 0 */
3452 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3453 if (!req)
3454 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003455 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003456 if (!req->buf)
3457 goto out;
3458 req->complete = ep0_complete;
3459
3460 /* Allocate the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003461 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003462 struct fsg_buffhd *bh = &fsg->buffhds[i];
3463
Alan Stern14cd5f82006-03-23 15:07:25 -05003464 /* Allocate for the bulk-in endpoint. We assume that
3465 * the buffer will also work with the bulk-out (and
3466 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003467 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003468 if (!bh->buf)
3469 goto out;
3470 bh->next = bh + 1;
3471 }
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003472 fsg->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->buffhds[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07003473
3474 /* This should reflect the actual gadget power source */
3475 usb_gadget_set_selfpowered(gadget);
3476
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003477 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3478 "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003479 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003480 gadget->name);
3481
Alan Stern22efcf42005-09-26 16:12:02 -04003482 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3483 "file-storage-gadget");
3484 if (IS_ERR(fsg->thread_task)) {
3485 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003486 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04003487 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003488
3489 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
Alan Stern664a51a2011-06-15 16:31:37 -04003490 INFO(fsg, "NOTE: This driver is deprecated. "
3491 "Consider using g_mass_storage instead.\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -07003492 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3493
3494 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3495 for (i = 0; i < fsg->nluns; ++i) {
3496 curlun = &fsg->luns[i];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003497 if (fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003498 p = NULL;
3499 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08003500 p = d_path(&curlun->filp->f_path,
3501 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003502 if (IS_ERR(p))
3503 p = NULL;
3504 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003505 LINFO(curlun, "ro=%d, nofua=%d, file: %s\n",
3506 curlun->ro, curlun->nofua, (p ? p : "(error)"));
Linus Torvalds1da177e2005-04-16 15:20:36 -07003507 }
3508 }
3509 kfree(pathbuf);
3510
3511 DBG(fsg, "transport=%s (x%02x)\n",
3512 mod_data.transport_name, mod_data.transport_type);
3513 DBG(fsg, "protocol=%s (x%02x)\n",
3514 mod_data.protocol_name, mod_data.protocol_type);
3515 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3516 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05003517 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003518 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05003519 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07003520 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04003521
3522 set_bit(REGISTERED, &fsg->atomic_bitflags);
3523
3524 /* Tell the thread to start working */
3525 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003526 return 0;
3527
3528autoconf_fail:
3529 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3530 rc = -ENOTSUPP;
3531
3532out:
3533 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3534 fsg_unbind(gadget);
Felipe Balbi889394b2008-12-08 13:50:27 +02003535 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003536 return rc;
3537}
3538
3539
3540/*-------------------------------------------------------------------------*/
3541
3542static void fsg_suspend(struct usb_gadget *gadget)
3543{
3544 struct fsg_dev *fsg = get_gadget_data(gadget);
3545
3546 DBG(fsg, "suspend\n");
3547 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3548}
3549
3550static void fsg_resume(struct usb_gadget *gadget)
3551{
3552 struct fsg_dev *fsg = get_gadget_data(gadget);
3553
3554 DBG(fsg, "resume\n");
3555 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3556}
3557
3558
3559/*-------------------------------------------------------------------------*/
3560
3561static struct usb_gadget_driver fsg_driver = {
3562#ifdef CONFIG_USB_GADGET_DUALSPEED
3563 .speed = USB_SPEED_HIGH,
3564#else
3565 .speed = USB_SPEED_FULL,
3566#endif
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003567 .function = (char *) fsg_string_product,
David Brownell6bea4762006-12-05 03:15:33 -08003568 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003569 .disconnect = fsg_disconnect,
3570 .setup = fsg_setup,
3571 .suspend = fsg_suspend,
3572 .resume = fsg_resume,
3573
3574 .driver = {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003575 .name = DRIVER_NAME,
Ben Dooksd0d50492005-10-10 10:52:33 +01003576 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003577 // .release = ...
3578 // .suspend = ...
3579 // .resume = ...
3580 },
3581};
3582
3583
3584static int __init fsg_alloc(void)
3585{
3586 struct fsg_dev *fsg;
3587
Alan Sterna922c682005-10-06 16:38:45 -04003588 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003589 if (!fsg)
3590 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003591 spin_lock_init(&fsg->lock);
3592 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05003593 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003594 init_completion(&fsg->thread_notifier);
3595
3596 the_fsg = fsg;
3597 return 0;
3598}
3599
3600
Linus Torvalds1da177e2005-04-16 15:20:36 -07003601static int __init fsg_init(void)
3602{
3603 int rc;
3604 struct fsg_dev *fsg;
3605
3606 if ((rc = fsg_alloc()) != 0)
3607 return rc;
3608 fsg = the_fsg;
Uwe Kleine-Königb0fca502010-08-12 17:43:53 +02003609 if ((rc = usb_gadget_probe_driver(&fsg_driver, fsg_bind)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05003610 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04003611 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003612}
3613module_init(fsg_init);
3614
3615
3616static void __exit fsg_cleanup(void)
3617{
3618 struct fsg_dev *fsg = the_fsg;
3619
3620 /* Unregister the driver iff the thread hasn't already done so */
3621 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3622 usb_gadget_unregister_driver(&fsg_driver);
3623
3624 /* Wait for the thread to finish up */
3625 wait_for_completion(&fsg->thread_notifier);
3626
Alan Stern87c42522005-11-09 16:59:56 -05003627 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003628}
3629module_exit(fsg_cleanup);