blob: 5779549d7dc6cc873d89d015038829430179dae5 [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
Peiyu Li3f565a32011-08-17 22:52:59 -070072 * need be only one backing file per LUN.
Linus Torvalds1da177e2005-04-16 15:20:36 -070073 *
74 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
75 * needed (an interrupt-out endpoint is also needed for CBI). The memory
76 * requirement amounts to two 16K buffers, size configurable by a parameter.
77 * Support is included for both full-speed and high-speed operation.
78 *
Alan Stern14cd5f82006-03-23 15:07:25 -050079 * Note that the driver is slightly non-portable in that it assumes a
80 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
81 * interrupt-in endpoints. With most device controllers this isn't an
82 * issue, but there may be some with hardware restrictions that prevent
83 * a buffer from being used by more than one endpoint.
84 *
Linus Torvalds1da177e2005-04-16 15:20:36 -070085 * Module options:
86 *
87 * file=filename[,filename...]
88 * Required if "removable" is not set, names of
89 * the files or block devices used for
90 * backing storage
Alan Sternd8087422010-09-03 11:15:41 -040091 * serial=HHHH... Required serial number (string of hex chars)
Linus Torvalds1da177e2005-04-16 15:20:36 -070092 * ro=b[,b...] Default false, booleans for read-only access
93 * removable Default false, boolean for removable media
94 * luns=N Default N = number of filenames, number of
95 * LUNs to support
Andy Shevchenkoa93917d2010-07-22 17:53:56 +030096 * nofua=b[,b...] Default false, booleans for ignore FUA flag
97 * in SCSI WRITE(10,12) commands
Alan Sternd794ac72005-04-18 12:43:25 -040098 * stall Default determined according to the type of
99 * USB device controller (usually true),
100 * boolean to permit the driver to halt
101 * bulk endpoints
Alan Stern12aae682008-11-20 14:13:12 -0500102 * cdrom Default false, boolean for whether to emulate
103 * a CD-ROM drive
Linus Torvalds1da177e2005-04-16 15:20:36 -0700104 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
105 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
106 * ATAPI, QIC, UFI, 8070, or SCSI;
107 * also 1 - 6)
108 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
109 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
110 * release=0xRRRR Override the USB release number (bcdDevice)
111 * buflen=N Default N=16384, buffer size used (will be
112 * rounded down to a multiple of
113 * PAGE_CACHE_SIZE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700114 *
Alan Sternd8087422010-09-03 11:15:41 -0400115 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "serial", "ro",
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300116 * "removable", "luns", "nofua", "stall", and "cdrom" options are available;
117 * default values are used for everything else.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700118 *
119 * The pathnames of the backing files and the ro settings are available in
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300120 * the attribute files "file", "nofua", and "ro" in the lun<n> subdirectory of
121 * the gadget's sysfs directory. If the "removable" option is set, writing to
Linus Torvalds1da177e2005-04-16 15:20:36 -0700122 * these files will simulate ejecting/loading the medium (writing an empty
123 * line means eject) and adjusting a write-enable tab. Changes to the ro
Alan Stern12aae682008-11-20 14:13:12 -0500124 * setting are not allowed when the medium is loaded or if CD-ROM emulation
125 * is being used.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700126 *
127 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
Alan Sternaafe5bd2006-03-31 11:46:43 -0500128 * The driver's SCSI command interface was based on the "Information
129 * technology - Small Computer System Interface - 2" document from
130 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
131 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
132 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
133 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
134 * document, Revision 1.0, December 14, 1998, available at
135 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700136 */
137
138
139/*
140 * Driver Design
141 *
142 * The FSG driver is fairly straightforward. There is a main kernel
143 * thread that handles most of the work. Interrupt routines field
144 * callbacks from the controller driver: bulk- and interrupt-request
145 * completion notifications, endpoint-0 events, and disconnect events.
146 * Completion events are passed to the main thread by wakeup calls. Many
147 * ep0 requests are handled at interrupt time, but SetInterface,
148 * SetConfiguration, and device reset requests are forwarded to the
149 * thread in the form of "exceptions" using SIGUSR1 signals (since they
150 * should interrupt any ongoing file I/O operations).
151 *
152 * The thread's main routine implements the standard command/data/status
153 * parts of a SCSI interaction. It and its subroutines are full of tests
154 * for pending signals/exceptions -- all this polling is necessary since
155 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
156 * indication that the driver really wants to be running in userspace.)
157 * An important point is that so long as the thread is alive it keeps an
158 * open reference to the backing file. This will prevent unmounting
159 * the backing file's underlying filesystem and could cause problems
160 * during system shutdown, for example. To prevent such problems, the
161 * thread catches INT, TERM, and KILL signals and converts them into
162 * an EXIT exception.
163 *
164 * In normal operation the main thread is started during the gadget's
165 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
166 * exit when it receives a signal, and there's no point leaving the
167 * gadget running when the thread is dead. So just before the thread
168 * exits, it deregisters the gadget driver. This makes things a little
169 * tricky: The driver is deregistered at two places, and the exiting
170 * thread can indirectly call fsg_unbind() which in turn can tell the
171 * thread to exit. The first problem is resolved through the use of the
172 * REGISTERED atomic bitflag; the driver will only be deregistered once.
173 * The second problem is resolved by having fsg_unbind() check
174 * fsg->state; it won't try to stop the thread if the state is already
175 * FSG_STATE_TERMINATED.
176 *
177 * To provide maximum throughput, the driver uses a circular pipeline of
178 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
179 * arbitrarily long; in practice the benefits don't justify having more
180 * than 2 stages (i.e., double buffering). But it helps to think of the
181 * pipeline as being a long one. Each buffer head contains a bulk-in and
182 * a bulk-out request pointer (since the buffer can be used for both
183 * output and input -- directions always are given from the host's
184 * point of view) as well as a pointer to the buffer and various state
185 * variables.
186 *
187 * Use of the pipeline follows a simple protocol. There is a variable
188 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
189 * At any time that buffer head may still be in use from an earlier
190 * request, so each buffer head has a state variable indicating whether
191 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
192 * buffer head to be EMPTY, filling the buffer either by file I/O or by
193 * USB I/O (during which the buffer head is BUSY), and marking the buffer
194 * head FULL when the I/O is complete. Then the buffer will be emptied
195 * (again possibly by USB I/O, during which it is marked BUSY) and
196 * finally marked EMPTY again (possibly by a completion routine).
197 *
198 * A module parameter tells the driver to avoid stalling the bulk
199 * endpoints wherever the transport specification allows. This is
200 * necessary for some UDCs like the SuperH, which cannot reliably clear a
201 * halt on a bulk endpoint. However, under certain circumstances the
202 * Bulk-only specification requires a stall. In such cases the driver
203 * will halt the endpoint and set a flag indicating that it should clear
204 * the halt in software during the next device reset. Hopefully this
205 * will permit everything to work correctly. Furthermore, although the
206 * specification allows the bulk-out endpoint to halt when the host sends
207 * too much data, implementing this would cause an unavoidable race.
208 * The driver will always use the "no-stall" approach for OUT transfers.
209 *
210 * One subtle point concerns sending status-stage responses for ep0
211 * requests. Some of these requests, such as device reset, can involve
212 * interrupting an ongoing file I/O operation, which might take an
213 * arbitrarily long time. During that delay the host might give up on
214 * the original ep0 request and issue a new one. When that happens the
215 * driver should not notify the host about completion of the original
216 * request, as the host will no longer be waiting for it. So the driver
217 * assigns to each ep0 request a unique tag, and it keeps track of the
218 * tag value of the request associated with a long-running exception
219 * (device-reset, interface-change, or configuration-change). When the
220 * exception handler is finished, the status-stage response is submitted
221 * only if the current ep0 request tag is equal to the exception request
222 * tag. Thus only the most recently received ep0 request will get a
223 * status-stage response.
224 *
225 * Warning: This driver source file is too long. It ought to be split up
226 * into a header file plus about 3 separate .c files, to handle the details
227 * of the Gadget, USB Mass Storage, and SCSI protocols.
228 */
229
230
David Brownell2e806f62007-08-02 00:03:39 -0700231/* #define VERBOSE_DEBUG */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400232/* #define DUMP_MSGS */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700233
Linus Torvalds1da177e2005-04-16 15:20:36 -0700234
Linus Torvalds1da177e2005-04-16 15:20:36 -0700235#include <linux/blkdev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700236#include <linux/completion.h>
237#include <linux/dcache.h>
238#include <linux/delay.h>
239#include <linux/device.h>
240#include <linux/fcntl.h>
241#include <linux/file.h>
242#include <linux/fs.h>
Alan Stern87c42522005-11-09 16:59:56 -0500243#include <linux/kref.h>
Alan Stern22efcf42005-09-26 16:12:02 -0400244#include <linux/kthread.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700245#include <linux/limits.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700246#include <linux/rwsem.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700247#include <linux/slab.h>
248#include <linux/spinlock.h>
249#include <linux/string.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -0800250#include <linux/freezer.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700251#include <linux/utsname.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700252
David Brownell5f848132006-12-16 15:34:53 -0800253#include <linux/usb/ch9.h>
David Brownell9454a572007-10-04 18:05:17 -0700254#include <linux/usb/gadget.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700255
256#include "gadget_chips.h"
257
258
David Brownell352e2b92008-08-18 17:43:25 -0700259
260/*
261 * Kbuild is not very cooperative with respect to linking separately
262 * compiled library objects into one module. So for now we won't use
263 * separate compilation ... ensuring init/exit sections work to shrink
264 * the runtime footprint, and giving us at least some parts of what
265 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
266 */
267#include "usbstring.c"
268#include "config.c"
269#include "epautoconf.c"
270
Linus Torvalds1da177e2005-04-16 15:20:36 -0700271/*-------------------------------------------------------------------------*/
272
273#define DRIVER_DESC "File-backed Storage Gadget"
274#define DRIVER_NAME "g_file_storage"
Alan Sternd8087422010-09-03 11:15:41 -0400275#define DRIVER_VERSION "1 September 2010"
Linus Torvalds1da177e2005-04-16 15:20:36 -0700276
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100277static char fsg_string_manufacturer[64];
278static const char fsg_string_product[] = DRIVER_DESC;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100279static const char fsg_string_config[] = "Self-powered";
280static const char fsg_string_interface[] = "Mass Storage";
Linus Torvalds1da177e2005-04-16 15:20:36 -0700281
Michal Nazarewicz93f93742009-10-28 16:57:17 +0100282
283#include "storage_common.c"
284
285
Linus Torvalds1da177e2005-04-16 15:20:36 -0700286MODULE_DESCRIPTION(DRIVER_DESC);
287MODULE_AUTHOR("Alan Stern");
288MODULE_LICENSE("Dual BSD/GPL");
289
Linus Torvalds1da177e2005-04-16 15:20:36 -0700290/*
291 * This driver assumes self-powered hardware and has no way for users to
292 * trigger remote wakeup. It uses autoconfiguration to select endpoints
293 * and endpoint addresses.
294 */
295
296
297/*-------------------------------------------------------------------------*/
298
Linus Torvalds1da177e2005-04-16 15:20:36 -0700299
300/* Encapsulate the module parameter settings */
301
Linus Torvalds1da177e2005-04-16 15:20:36 -0700302static struct {
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100303 char *file[FSG_MAX_LUNS];
Alan Sternd8087422010-09-03 11:15:41 -0400304 char *serial;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100305 int ro[FSG_MAX_LUNS];
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300306 int nofua[FSG_MAX_LUNS];
David Brownell2e806f62007-08-02 00:03:39 -0700307 unsigned int num_filenames;
308 unsigned int num_ros;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300309 unsigned int num_nofuas;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700310 unsigned int nluns;
311
Alan Sternd794ac72005-04-18 12:43:25 -0400312 int removable;
313 int can_stall;
Alan Stern12aae682008-11-20 14:13:12 -0500314 int cdrom;
Alan Sternd794ac72005-04-18 12:43:25 -0400315
Linus Torvalds1da177e2005-04-16 15:20:36 -0700316 char *transport_parm;
317 char *protocol_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700318 unsigned short vendor;
319 unsigned short product;
320 unsigned short release;
321 unsigned int buflen;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700322
323 int transport_type;
324 char *transport_name;
325 int protocol_type;
326 char *protocol_name;
327
328} mod_data = { // Default values
329 .transport_parm = "BBB",
330 .protocol_parm = "SCSI",
331 .removable = 0,
Alan Sternd794ac72005-04-18 12:43:25 -0400332 .can_stall = 1,
Alan Stern12aae682008-11-20 14:13:12 -0500333 .cdrom = 0,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100334 .vendor = FSG_VENDOR_ID,
335 .product = FSG_PRODUCT_ID,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700336 .release = 0xffff, // Use controller chip type
337 .buflen = 16384,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700338 };
339
340
Alan Sternaafe5bd2006-03-31 11:46:43 -0500341module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
342 S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700343MODULE_PARM_DESC(file, "names of backing files or devices");
344
Alan Sternd8087422010-09-03 11:15:41 -0400345module_param_named(serial, mod_data.serial, charp, S_IRUGO);
346MODULE_PARM_DESC(serial, "USB serial number");
347
Alan Sternaafe5bd2006-03-31 11:46:43 -0500348module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700349MODULE_PARM_DESC(ro, "true to force read-only");
350
Andy Shevchenkoa93917d2010-07-22 17:53:56 +0300351module_param_array_named(nofua, mod_data.nofua, bool, &mod_data.num_nofuas,
352 S_IRUGO);
353MODULE_PARM_DESC(nofua, "true to ignore SCSI WRITE(10,12) FUA bit");
354
Linus Torvalds1da177e2005-04-16 15:20:36 -0700355module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
356MODULE_PARM_DESC(luns, "number of LUNs");
357
358module_param_named(removable, mod_data.removable, bool, S_IRUGO);
359MODULE_PARM_DESC(removable, "true to simulate removable media");
360
Alan Sternd794ac72005-04-18 12:43:25 -0400361module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
362MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
363
Alan Stern12aae682008-11-20 14:13:12 -0500364module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
365MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
366
Linus Torvalds1da177e2005-04-16 15:20:36 -0700367/* In the non-TEST version, only the module parameters listed above
368 * are available. */
369#ifdef CONFIG_USB_FILE_STORAGE_TEST
370
371module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
372MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
373
374module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
375MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
376 "8070, or SCSI)");
377
378module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
379MODULE_PARM_DESC(vendor, "USB Vendor ID");
380
381module_param_named(product, mod_data.product, ushort, S_IRUGO);
382MODULE_PARM_DESC(product, "USB Product ID");
383
384module_param_named(release, mod_data.release, ushort, S_IRUGO);
385MODULE_PARM_DESC(release, "USB release number");
386
387module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
388MODULE_PARM_DESC(buflen, "I/O buffer size");
389
Linus Torvalds1da177e2005-04-16 15:20:36 -0700390#endif /* CONFIG_USB_FILE_STORAGE_TEST */
391
392
Linus Torvalds1da177e2005-04-16 15:20:36 -0700393/*
394 * These definitions will permit the compiler to avoid generating code for
395 * parts of the driver that aren't used in the non-TEST version. Even gcc
396 * can recognize when a test of a constant expression yields a dead code
397 * path.
398 */
399
400#ifdef CONFIG_USB_FILE_STORAGE_TEST
401
402#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
403#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
404#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
405
406#else
407
408#define transport_is_bbb() 1
409#define transport_is_cbi() 0
410#define protocol_is_scsi() 1
411
412#endif /* CONFIG_USB_FILE_STORAGE_TEST */
413
414
Michal Nazarewiczb6058d02009-10-28 16:57:14 +0100415/*-------------------------------------------------------------------------*/
Linus Torvalds1da177e2005-04-16 15:20:36 -0700416
Linus Torvalds1da177e2005-04-16 15:20:36 -0700417
418struct fsg_dev {
419 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
420 spinlock_t lock;
421 struct usb_gadget *gadget;
422
423 /* filesem protects: backing files in use */
424 struct rw_semaphore filesem;
425
Alan Stern87c42522005-11-09 16:59:56 -0500426 /* reference counting: wait until all LUNs are released */
427 struct kref ref;
428
Linus Torvalds1da177e2005-04-16 15:20:36 -0700429 struct usb_ep *ep0; // Handy copy of gadget->ep0
430 struct usb_request *ep0req; // For control responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500431 unsigned int ep0_req_tag;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700432 const char *ep0req_name;
433
434 struct usb_request *intreq; // For interrupt responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500435 int intreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700436 struct fsg_buffhd *intr_buffhd;
437
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100438 unsigned int bulk_out_maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700439 enum fsg_state state; // For exception handling
440 unsigned int exception_req_tag;
441
442 u8 config, new_config;
443
444 unsigned int running : 1;
445 unsigned int bulk_in_enabled : 1;
446 unsigned int bulk_out_enabled : 1;
447 unsigned int intr_in_enabled : 1;
448 unsigned int phase_error : 1;
449 unsigned int short_packet_received : 1;
450 unsigned int bad_lun_okay : 1;
451
452 unsigned long atomic_bitflags;
453#define REGISTERED 0
Alan Sternb950bdb2008-04-14 11:45:29 -0400454#define IGNORE_BULK_OUT 1
Linus Torvalds1da177e2005-04-16 15:20:36 -0700455#define SUSPENDED 2
456
457 struct usb_ep *bulk_in;
458 struct usb_ep *bulk_out;
459 struct usb_ep *intr_in;
460
461 struct fsg_buffhd *next_buffhd_to_fill;
462 struct fsg_buffhd *next_buffhd_to_drain;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700463
Linus Torvalds1da177e2005-04-16 15:20:36 -0700464 int thread_wakeup_needed;
465 struct completion thread_notifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700466 struct task_struct *thread_task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700467
468 int cmnd_size;
469 u8 cmnd[MAX_COMMAND_SIZE];
470 enum data_direction data_dir;
471 u32 data_size;
472 u32 data_size_from_cmnd;
473 u32 tag;
474 unsigned int lun;
475 u32 residue;
476 u32 usb_amount_left;
477
478 /* The CB protocol offers no way for a host to know when a command
479 * has completed. As a result the next command may arrive early,
480 * and we will still have to handle it. For that reason we need
481 * a buffer to store new commands when using CB (or CBI, which
482 * does not oblige a host to wait for command completion either). */
483 int cbbuf_cmnd_size;
484 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
485
486 unsigned int nluns;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100487 struct fsg_lun *luns;
488 struct fsg_lun *curlun;
Per Forlin6532c7f2011-08-19 21:21:27 +0200489 /* Must be the last entry */
490 struct fsg_buffhd buffhds[];
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
Felipe Balbi4bb99b72011-08-03 14:33:27 +0300589static int populate_bos(struct fsg_dev *fsg, u8 *buf)
590{
591 memcpy(buf, &fsg_bos_desc, USB_DT_BOS_SIZE);
592 buf += USB_DT_BOS_SIZE;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700593
Felipe Balbi4bb99b72011-08-03 14:33:27 +0300594 memcpy(buf, &fsg_ext_cap_desc, USB_DT_USB_EXT_CAP_SIZE);
595 buf += USB_DT_USB_EXT_CAP_SIZE;
596
597 memcpy(buf, &fsg_ss_cap_desc, USB_DT_USB_SS_CAP_SIZE);
598
599 return USB_DT_BOS_SIZE + USB_DT_USB_SS_CAP_SIZE
600 + USB_DT_USB_EXT_CAP_SIZE;
601}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700602
603/*
604 * Config descriptors must agree with the code that sets configurations
605 * and with code managing interfaces and their altsettings. They must
606 * also handle different speeds and other-speed requests.
607 */
608static int populate_config_buf(struct usb_gadget *gadget,
609 u8 *buf, u8 type, unsigned index)
610{
Linus Torvalds1da177e2005-04-16 15:20:36 -0700611 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700612 int len;
613 const struct usb_descriptor_header **function;
614
615 if (index > 0)
616 return -EINVAL;
617
David Brownell2e806f62007-08-02 00:03:39 -0700618 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700619 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
Michal Nazarewiczd23b0f02009-11-09 14:15:20 +0100620 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
621 ? (const struct usb_descriptor_header **)fsg_hs_function
622 : (const struct usb_descriptor_header **)fsg_fs_function;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700623
624 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -0700625 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626 function++;
627
628 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
629 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
630 return len;
631}
632
633
634/*-------------------------------------------------------------------------*/
635
636/* These routines may be called in process context or in_irq */
637
Alan Sterna21d4fe2005-11-29 12:04:24 -0500638/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700639static void wakeup_thread(struct fsg_dev *fsg)
640{
641 /* Tell the main thread that something has happened */
642 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500643 if (fsg->thread_task)
644 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700645}
646
647
648static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
649{
650 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700651
652 /* Do nothing if a higher-priority exception is already in progress.
653 * If a lower-or-equal priority exception is in progress, preempt it
654 * and notify the main thread by sending it a signal. */
655 spin_lock_irqsave(&fsg->lock, flags);
656 if (fsg->state <= new_state) {
657 fsg->exception_req_tag = fsg->ep0_req_tag;
658 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -0400659 if (fsg->thread_task)
660 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
661 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700662 }
663 spin_unlock_irqrestore(&fsg->lock, flags);
664}
665
666
667/*-------------------------------------------------------------------------*/
668
669/* The disconnect callback and ep0 routines. These always run in_irq,
670 * except that ep0_queue() is called in the main thread to acknowledge
671 * completion of various requests: set config, set interface, and
672 * Bulk-only device reset. */
673
674static void fsg_disconnect(struct usb_gadget *gadget)
675{
676 struct fsg_dev *fsg = get_gadget_data(gadget);
677
678 DBG(fsg, "disconnect or port reset\n");
679 raise_exception(fsg, FSG_STATE_DISCONNECT);
680}
681
682
683static int ep0_queue(struct fsg_dev *fsg)
684{
685 int rc;
686
687 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
688 if (rc != 0 && rc != -ESHUTDOWN) {
689
690 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -0700691 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692 fsg->ep0->name, rc);
693 }
694 return rc;
695}
696
697static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
698{
John Daiker7ca46b82006-12-29 19:02:06 -0800699 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700700
701 if (req->actual > 0)
702 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
703 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800704 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700705 req->status, req->actual, req->length);
706 if (req->status == -ECONNRESET) // Request was cancelled
707 usb_ep_fifo_flush(ep);
708
709 if (req->status == 0 && req->context)
710 ((fsg_routine_t) (req->context))(fsg);
711}
712
713
714/*-------------------------------------------------------------------------*/
715
716/* Bulk and interrupt endpoint completion handlers.
717 * These always run in_irq. */
718
719static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
720{
John Daiker7ca46b82006-12-29 19:02:06 -0800721 struct fsg_dev *fsg = ep->driver_data;
722 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700723
724 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800725 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700726 req->status, req->actual, req->length);
727 if (req->status == -ECONNRESET) // Request was cancelled
728 usb_ep_fifo_flush(ep);
729
730 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500731 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700732 spin_lock(&fsg->lock);
733 bh->inreq_busy = 0;
734 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700735 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500736 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700737}
738
739static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
740{
John Daiker7ca46b82006-12-29 19:02:06 -0800741 struct fsg_dev *fsg = ep->driver_data;
742 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700743
744 dump_msg(fsg, "bulk-out", req->buf, req->actual);
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -0700745 if (req->status || req->actual != bh->bulk_out_intended_length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800746 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -0700747 req->status, req->actual,
748 bh->bulk_out_intended_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700749 if (req->status == -ECONNRESET) // Request was cancelled
750 usb_ep_fifo_flush(ep);
751
752 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500753 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700754 spin_lock(&fsg->lock);
755 bh->outreq_busy = 0;
756 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700757 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500758 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700759}
760
761
762#ifdef CONFIG_USB_FILE_STORAGE_TEST
763static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
764{
John Daiker7ca46b82006-12-29 19:02:06 -0800765 struct fsg_dev *fsg = ep->driver_data;
766 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700767
768 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800769 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700770 req->status, req->actual, req->length);
771 if (req->status == -ECONNRESET) // Request was cancelled
772 usb_ep_fifo_flush(ep);
773
774 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500775 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700776 spin_lock(&fsg->lock);
777 fsg->intreq_busy = 0;
778 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700779 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500780 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700781}
782
783#else
784static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
785{}
786#endif /* CONFIG_USB_FILE_STORAGE_TEST */
787
788
789/*-------------------------------------------------------------------------*/
790
791/* Ep0 class-specific handlers. These always run in_irq. */
792
793#ifdef CONFIG_USB_FILE_STORAGE_TEST
794static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
795{
796 struct usb_request *req = fsg->ep0req;
797 static u8 cbi_reset_cmnd[6] = {
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +0200798 SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
Linus Torvalds1da177e2005-04-16 15:20:36 -0700799
800 /* Error in command transfer? */
801 if (req->status || req->length != req->actual ||
802 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
803
804 /* Not all controllers allow a protocol stall after
805 * receiving control-out data, but we'll try anyway. */
806 fsg_set_halt(fsg, fsg->ep0);
807 return; // Wait for reset
808 }
809
810 /* Is it the special reset command? */
811 if (req->actual >= sizeof cbi_reset_cmnd &&
812 memcmp(req->buf, cbi_reset_cmnd,
813 sizeof cbi_reset_cmnd) == 0) {
814
815 /* Raise an exception to stop the current operation
816 * and reinitialize our state. */
817 DBG(fsg, "cbi reset request\n");
818 raise_exception(fsg, FSG_STATE_RESET);
819 return;
820 }
821
822 VDBG(fsg, "CB[I] accept device-specific command\n");
823 spin_lock(&fsg->lock);
824
825 /* Save the command for later */
826 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700827 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700828 fsg->cbbuf_cmnd_size = req->actual;
829 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
830
Linus Torvalds1da177e2005-04-16 15:20:36 -0700831 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500832 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700833}
834
835#else
836static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
837{}
838#endif /* CONFIG_USB_FILE_STORAGE_TEST */
839
840
841static int class_setup_req(struct fsg_dev *fsg,
842 const struct usb_ctrlrequest *ctrl)
843{
844 struct usb_request *req = fsg->ep0req;
845 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700846 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -0400847 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -0700848 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700849
850 if (!fsg->config)
851 return value;
852
853 /* Handle Bulk-only class-specific requests */
854 if (transport_is_bbb()) {
855 switch (ctrl->bRequest) {
856
857 case USB_BULK_RESET_REQUEST:
858 if (ctrl->bRequestType != (USB_DIR_OUT |
859 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
860 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400861 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700862 value = -EDOM;
863 break;
864 }
865
866 /* Raise an exception to stop the current operation
867 * and reinitialize our state. */
868 DBG(fsg, "bulk reset request\n");
869 raise_exception(fsg, FSG_STATE_RESET);
870 value = DELAYED_STATUS;
871 break;
872
873 case USB_BULK_GET_MAX_LUN_REQUEST:
874 if (ctrl->bRequestType != (USB_DIR_IN |
875 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
876 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400877 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700878 value = -EDOM;
879 break;
880 }
881 VDBG(fsg, "get max LUN\n");
882 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -0400883 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700884 break;
885 }
886 }
887
888 /* Handle CBI class-specific requests */
889 else {
890 switch (ctrl->bRequest) {
891
892 case USB_CBI_ADSC_REQUEST:
893 if (ctrl->bRequestType != (USB_DIR_OUT |
894 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
895 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400896 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897 value = -EDOM;
898 break;
899 }
900 if (w_length > MAX_COMMAND_SIZE) {
901 value = -EOVERFLOW;
902 break;
903 }
904 value = w_length;
905 fsg->ep0req->context = received_cbi_adsc;
906 break;
907 }
908 }
909
910 if (value == -EOPNOTSUPP)
911 VDBG(fsg,
912 "unknown class-specific control req "
913 "%02x.%02x v%04x i%04x l%u\n",
914 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -0700915 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700916 return value;
917}
918
919
920/*-------------------------------------------------------------------------*/
921
922/* Ep0 standard request handlers. These always run in_irq. */
923
924static int standard_setup_req(struct fsg_dev *fsg,
925 const struct usb_ctrlrequest *ctrl)
926{
927 struct usb_request *req = fsg->ep0req;
928 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700929 u16 w_index = le16_to_cpu(ctrl->wIndex);
930 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700931
932 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
933 * but config change events will also reconfigure hardware. */
934 switch (ctrl->bRequest) {
935
936 case USB_REQ_GET_DESCRIPTOR:
937 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
938 USB_RECIP_DEVICE))
939 break;
940 switch (w_value >> 8) {
941
942 case USB_DT_DEVICE:
943 VDBG(fsg, "get device descriptor\n");
Sebastian Andrzej Siewior765f5b82011-06-23 14:26:11 +0200944 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
Alan Stern76f4af82005-04-05 11:56:54 -0400945 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700946 memcpy(req->buf, &device_desc, value);
947 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700948 case USB_DT_DEVICE_QUALIFIER:
949 VDBG(fsg, "get device qualifier\n");
Felipe Balbi4bb99b72011-08-03 14:33:27 +0300950 if (!gadget_is_dualspeed(fsg->gadget) ||
951 fsg->gadget->speed == USB_SPEED_SUPER)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700952 break;
Sebastian Andrzej Siewior765f5b82011-06-23 14:26:11 +0200953 /*
954 * Assume ep0 uses the same maxpacket value for both
955 * speeds
956 */
957 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Alan Stern76f4af82005-04-05 11:56:54 -0400958 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959 memcpy(req->buf, &dev_qualifier, value);
960 break;
961
962 case USB_DT_OTHER_SPEED_CONFIG:
963 VDBG(fsg, "get other-speed config descriptor\n");
Felipe Balbi4bb99b72011-08-03 14:33:27 +0300964 if (!gadget_is_dualspeed(fsg->gadget) ||
965 fsg->gadget->speed == USB_SPEED_SUPER)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700966 break;
967 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700968 case USB_DT_CONFIG:
969 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700970get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700971 value = populate_config_buf(fsg->gadget,
972 req->buf,
973 w_value >> 8,
974 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700975 break;
976
977 case USB_DT_STRING:
978 VDBG(fsg, "get string descriptor\n");
979
980 /* wIndex == language code */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100981 value = usb_gadget_get_string(&fsg_stringtab,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700982 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700983 break;
Felipe Balbi4bb99b72011-08-03 14:33:27 +0300984
985 case USB_DT_BOS:
986 VDBG(fsg, "get bos descriptor\n");
987
988 if (gadget_is_superspeed(fsg->gadget))
989 value = populate_bos(fsg, req->buf);
990 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700991 }
Felipe Balbi4bb99b72011-08-03 14:33:27 +0300992
Linus Torvalds1da177e2005-04-16 15:20:36 -0700993 break;
994
995 /* One config, two speeds */
996 case USB_REQ_SET_CONFIGURATION:
997 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
998 USB_RECIP_DEVICE))
999 break;
1000 VDBG(fsg, "set configuration\n");
1001 if (w_value == CONFIG_VALUE || w_value == 0) {
1002 fsg->new_config = w_value;
1003
1004 /* Raise an exception to wipe out previous transaction
1005 * state (queued bufs, etc) and set the new config. */
1006 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1007 value = DELAYED_STATUS;
1008 }
1009 break;
1010 case USB_REQ_GET_CONFIGURATION:
1011 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1012 USB_RECIP_DEVICE))
1013 break;
1014 VDBG(fsg, "get configuration\n");
1015 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -04001016 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001017 break;
1018
1019 case USB_REQ_SET_INTERFACE:
1020 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1021 USB_RECIP_INTERFACE))
1022 break;
1023 if (fsg->config && w_index == 0) {
1024
1025 /* Raise an exception to wipe out previous transaction
1026 * state (queued bufs, etc) and install the new
1027 * interface altsetting. */
1028 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1029 value = DELAYED_STATUS;
1030 }
1031 break;
1032 case USB_REQ_GET_INTERFACE:
1033 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1034 USB_RECIP_INTERFACE))
1035 break;
1036 if (!fsg->config)
1037 break;
1038 if (w_index != 0) {
1039 value = -EDOM;
1040 break;
1041 }
1042 VDBG(fsg, "get interface\n");
1043 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001044 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045 break;
1046
1047 default:
1048 VDBG(fsg,
1049 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1050 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001051 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001052 }
1053
1054 return value;
1055}
1056
1057
1058static int fsg_setup(struct usb_gadget *gadget,
1059 const struct usb_ctrlrequest *ctrl)
1060{
1061 struct fsg_dev *fsg = get_gadget_data(gadget);
1062 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001063 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001064
1065 ++fsg->ep0_req_tag; // Record arrival of a new request
1066 fsg->ep0req->context = NULL;
1067 fsg->ep0req->length = 0;
1068 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1069
1070 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1071 rc = class_setup_req(fsg, ctrl);
1072 else
1073 rc = standard_setup_req(fsg, ctrl);
1074
1075 /* Respond with data/status or defer until later? */
1076 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001077 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001078 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001079 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001080 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1081 "ep0-in" : "ep0-out");
1082 rc = ep0_queue(fsg);
1083 }
1084
1085 /* Device either stalls (rc < 0) or reports success */
1086 return rc;
1087}
1088
1089
1090/*-------------------------------------------------------------------------*/
1091
1092/* All the following routines run in process context */
1093
1094
1095/* Use this for bulk or interrupt transfers, not ep0 */
1096static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001097 struct usb_request *req, int *pbusy,
1098 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001099{
1100 int rc;
1101
1102 if (ep == fsg->bulk_in)
1103 dump_msg(fsg, "bulk-in", req->buf, req->length);
1104 else if (ep == fsg->intr_in)
1105 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001106
1107 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001108 *pbusy = 1;
1109 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001110 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001111 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1112 if (rc != 0) {
1113 *pbusy = 0;
1114 *state = BUF_STATE_EMPTY;
1115
1116 /* We can't do much more than wait for a reset */
1117
1118 /* Note: currently the net2280 driver fails zero-length
1119 * submissions if DMA is enabled. */
1120 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1121 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001122 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001123 ep->name, rc);
1124 }
1125}
1126
1127
1128static int sleep_thread(struct fsg_dev *fsg)
1129{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001130 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001131
1132 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001133 for (;;) {
1134 try_to_freeze();
1135 set_current_state(TASK_INTERRUPTIBLE);
1136 if (signal_pending(current)) {
1137 rc = -EINTR;
1138 break;
1139 }
1140 if (fsg->thread_wakeup_needed)
1141 break;
1142 schedule();
1143 }
1144 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001145 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001146 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001147}
1148
1149
1150/*-------------------------------------------------------------------------*/
1151
1152static int do_read(struct fsg_dev *fsg)
1153{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001154 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001155 u32 lba;
1156 struct fsg_buffhd *bh;
1157 int rc;
1158 u32 amount_left;
1159 loff_t file_offset, file_offset_tmp;
1160 unsigned int amount;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001161 ssize_t nread;
1162
1163 /* Get the starting Logical Block Address and check that it's
1164 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001165 if (fsg->cmnd[0] == READ_6)
Alan Stern604eb892009-04-27 13:19:41 -04001166 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001167 else {
Alan Stern604eb892009-04-27 13:19:41 -04001168 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001169
1170 /* We allow DPO (Disable Page Out = don't save data in the
1171 * cache) and FUA (Force Unit Access = don't read from the
1172 * cache), but we don't implement them. */
1173 if ((fsg->cmnd[1] & ~0x18) != 0) {
1174 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1175 return -EINVAL;
1176 }
1177 }
1178 if (lba >= curlun->num_sectors) {
1179 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1180 return -EINVAL;
1181 }
Peiyu Li3f565a32011-08-17 22:52:59 -07001182 file_offset = ((loff_t) lba) << curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001183
1184 /* Carry out the file reads */
1185 amount_left = fsg->data_size_from_cmnd;
1186 if (unlikely(amount_left == 0))
1187 return -EIO; // No default reply
1188
1189 for (;;) {
1190
1191 /* Figure out how much we need to read:
1192 * Try to read the remaining amount.
1193 * But don't read more than the buffer size.
1194 * And don't try to read past the end of the file.
Alan Stern04eee252011-08-18 14:29:00 -04001195 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001196 amount = min((unsigned int) amount_left, mod_data.buflen);
1197 amount = min((loff_t) amount,
1198 curlun->file_length - file_offset);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001199
1200 /* Wait for the next buffer to become available */
1201 bh = fsg->next_buffhd_to_fill;
1202 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001203 rc = sleep_thread(fsg);
1204 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001205 return rc;
1206 }
1207
1208 /* If we were asked to read past the end of file,
1209 * end with an empty buffer. */
1210 if (amount == 0) {
1211 curlun->sense_data =
1212 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001213 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001214 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001215 bh->inreq->length = 0;
1216 bh->state = BUF_STATE_FULL;
1217 break;
1218 }
1219
1220 /* Perform the read */
1221 file_offset_tmp = file_offset;
1222 nread = vfs_read(curlun->filp,
1223 (char __user *) bh->buf,
1224 amount, &file_offset_tmp);
1225 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1226 (unsigned long long) file_offset,
1227 (int) nread);
1228 if (signal_pending(current))
1229 return -EINTR;
1230
1231 if (nread < 0) {
1232 LDBG(curlun, "error in file read: %d\n",
1233 (int) nread);
1234 nread = 0;
1235 } else if (nread < amount) {
1236 LDBG(curlun, "partial file read: %d/%u\n",
1237 (int) nread, amount);
Peiyu Li3f565a32011-08-17 22:52:59 -07001238 nread = round_down(nread, curlun->blksize);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001239 }
1240 file_offset += nread;
1241 amount_left -= nread;
1242 fsg->residue -= nread;
Alan Stern04eee252011-08-18 14:29:00 -04001243
1244 /* Except at the end of the transfer, nread will be
1245 * equal to the buffer size, which is divisible by the
1246 * bulk-in maxpacket size.
1247 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001248 bh->inreq->length = nread;
1249 bh->state = BUF_STATE_FULL;
1250
1251 /* If an error occurred, report it and its position */
1252 if (nread < amount) {
1253 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
Peiyu Li3f565a32011-08-17 22:52:59 -07001254 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001255 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001256 break;
1257 }
1258
1259 if (amount_left == 0)
1260 break; // No more left to read
1261
1262 /* Send this buffer and go read some more */
1263 bh->inreq->zero = 0;
1264 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1265 &bh->inreq_busy, &bh->state);
1266 fsg->next_buffhd_to_fill = bh->next;
1267 }
1268
1269 return -EIO; // No default reply
1270}
1271
1272
1273/*-------------------------------------------------------------------------*/
1274
1275static int do_write(struct fsg_dev *fsg)
1276{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001277 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001278 u32 lba;
1279 struct fsg_buffhd *bh;
1280 int get_some_more;
1281 u32 amount_left_to_req, amount_left_to_write;
1282 loff_t usb_offset, file_offset, file_offset_tmp;
1283 unsigned int amount;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001284 ssize_t nwritten;
1285 int rc;
1286
1287 if (curlun->ro) {
1288 curlun->sense_data = SS_WRITE_PROTECTED;
1289 return -EINVAL;
1290 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001291 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001292 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001293 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001294
1295 /* Get the starting Logical Block Address and check that it's
1296 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001297 if (fsg->cmnd[0] == WRITE_6)
Alan Stern604eb892009-04-27 13:19:41 -04001298 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001299 else {
Alan Stern604eb892009-04-27 13:19:41 -04001300 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001301
1302 /* We allow DPO (Disable Page Out = don't save data in the
1303 * cache) and FUA (Force Unit Access = write directly to the
1304 * medium). We don't implement DPO; we implement FUA by
1305 * performing synchronous output. */
1306 if ((fsg->cmnd[1] & ~0x18) != 0) {
1307 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1308 return -EINVAL;
1309 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03001310 /* FUA */
1311 if (!curlun->nofua && (fsg->cmnd[1] & 0x08)) {
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001312 spin_lock(&curlun->filp->f_lock);
Christoph Hellwig6b2f3d12009-10-27 11:05:28 +01001313 curlun->filp->f_flags |= O_DSYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001314 spin_unlock(&curlun->filp->f_lock);
1315 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001316 }
1317 if (lba >= curlun->num_sectors) {
1318 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1319 return -EINVAL;
1320 }
1321
1322 /* Carry out the file writes */
1323 get_some_more = 1;
Peiyu Li3f565a32011-08-17 22:52:59 -07001324 file_offset = usb_offset = ((loff_t) lba) << curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001325 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1326
1327 while (amount_left_to_write > 0) {
1328
1329 /* Queue a request for more data from the host */
1330 bh = fsg->next_buffhd_to_fill;
1331 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1332
1333 /* Figure out how much we want to get:
Alan Stern04eee252011-08-18 14:29:00 -04001334 * Try to get the remaining amount,
1335 * but not more than the buffer size.
1336 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001337 amount = min(amount_left_to_req, mod_data.buflen);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001338
Alan Stern04eee252011-08-18 14:29:00 -04001339 /* Beyond the end of the backing file? */
1340 if (usb_offset >= curlun->file_length) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001341 get_some_more = 0;
1342 curlun->sense_data =
1343 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001344 curlun->sense_data_info = usb_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001345 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001346 continue;
1347 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001348
1349 /* Get the next buffer */
1350 usb_offset += amount;
1351 fsg->usb_amount_left -= amount;
1352 amount_left_to_req -= amount;
1353 if (amount_left_to_req == 0)
1354 get_some_more = 0;
1355
Alan Stern04eee252011-08-18 14:29:00 -04001356 /* Except at the end of the transfer, amount will be
1357 * equal to the buffer size, which is divisible by
1358 * the bulk-out maxpacket size.
1359 */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001360 set_bulk_out_req_length(fsg, bh, amount);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001361 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1362 &bh->outreq_busy, &bh->state);
1363 fsg->next_buffhd_to_fill = bh->next;
1364 continue;
1365 }
1366
1367 /* Write the received data to the backing file */
1368 bh = fsg->next_buffhd_to_drain;
1369 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1370 break; // We stopped early
1371 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001372 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001373 fsg->next_buffhd_to_drain = bh->next;
1374 bh->state = BUF_STATE_EMPTY;
1375
1376 /* Did something go wrong with the transfer? */
1377 if (bh->outreq->status != 0) {
1378 curlun->sense_data = SS_COMMUNICATION_FAILURE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001379 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001380 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001381 break;
1382 }
1383
1384 amount = bh->outreq->actual;
1385 if (curlun->file_length - file_offset < amount) {
1386 LERROR(curlun,
1387 "write %u @ %llu beyond end %llu\n",
1388 amount, (unsigned long long) file_offset,
1389 (unsigned long long) curlun->file_length);
1390 amount = curlun->file_length - file_offset;
1391 }
1392
Paul Zimmermanfe696762011-09-30 15:26:06 -07001393 /* Don't accept excess data. The spec doesn't say
1394 * what to do in this case. We'll ignore the error.
1395 */
1396 amount = min(amount, bh->bulk_out_intended_length);
1397
Alan Stern04eee252011-08-18 14:29:00 -04001398 /* Don't write a partial block */
1399 amount = round_down(amount, curlun->blksize);
1400 if (amount == 0)
1401 goto empty_write;
1402
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403 /* Perform the write */
1404 file_offset_tmp = file_offset;
1405 nwritten = vfs_write(curlun->filp,
1406 (char __user *) bh->buf,
1407 amount, &file_offset_tmp);
1408 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1409 (unsigned long long) file_offset,
1410 (int) nwritten);
1411 if (signal_pending(current))
1412 return -EINTR; // Interrupted!
1413
1414 if (nwritten < 0) {
1415 LDBG(curlun, "error in file write: %d\n",
1416 (int) nwritten);
1417 nwritten = 0;
1418 } else if (nwritten < amount) {
1419 LDBG(curlun, "partial file write: %d/%u\n",
1420 (int) nwritten, amount);
Peiyu Li3f565a32011-08-17 22:52:59 -07001421 nwritten = round_down(nwritten, curlun->blksize);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001422 }
1423 file_offset += nwritten;
1424 amount_left_to_write -= nwritten;
1425 fsg->residue -= nwritten;
1426
1427 /* If an error occurred, report it and its position */
1428 if (nwritten < amount) {
1429 curlun->sense_data = SS_WRITE_ERROR;
Peiyu Li3f565a32011-08-17 22:52:59 -07001430 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001431 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001432 break;
1433 }
1434
Alan Stern04eee252011-08-18 14:29:00 -04001435 empty_write:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001436 /* Did the host decide to stop early? */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001437 if (bh->outreq->actual < bh->bulk_out_intended_length) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001438 fsg->short_packet_received = 1;
1439 break;
1440 }
1441 continue;
1442 }
1443
1444 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001445 rc = sleep_thread(fsg);
1446 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001447 return rc;
1448 }
1449
1450 return -EIO; // No default reply
1451}
1452
1453
1454/*-------------------------------------------------------------------------*/
1455
Linus Torvalds1da177e2005-04-16 15:20:36 -07001456static int do_synchronize_cache(struct fsg_dev *fsg)
1457{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001458 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001459 int rc;
1460
1461 /* We ignore the requested LBA and write out all file's
1462 * dirty data buffers. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001463 rc = fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001464 if (rc)
1465 curlun->sense_data = SS_WRITE_ERROR;
1466 return 0;
1467}
1468
1469
1470/*-------------------------------------------------------------------------*/
1471
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001472static void invalidate_sub(struct fsg_lun *curlun)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001473{
1474 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001475 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001476 unsigned long rc;
1477
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001478 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01001479 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001480}
1481
1482static int do_verify(struct fsg_dev *fsg)
1483{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001484 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001485 u32 lba;
1486 u32 verification_length;
1487 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1488 loff_t file_offset, file_offset_tmp;
1489 u32 amount_left;
1490 unsigned int amount;
1491 ssize_t nread;
1492
1493 /* Get the starting Logical Block Address and check that it's
1494 * not too big */
Alan Stern604eb892009-04-27 13:19:41 -04001495 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001496 if (lba >= curlun->num_sectors) {
1497 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1498 return -EINVAL;
1499 }
1500
1501 /* We allow DPO (Disable Page Out = don't save data in the
1502 * cache) but we don't implement it. */
1503 if ((fsg->cmnd[1] & ~0x10) != 0) {
1504 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1505 return -EINVAL;
1506 }
1507
Alan Stern604eb892009-04-27 13:19:41 -04001508 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001509 if (unlikely(verification_length == 0))
1510 return -EIO; // No default reply
1511
1512 /* Prepare to carry out the file verify */
Peiyu Li3f565a32011-08-17 22:52:59 -07001513 amount_left = verification_length << curlun->blkbits;
1514 file_offset = ((loff_t) lba) << curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001515
1516 /* Write out all the dirty buffers before invalidating them */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001517 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001518 if (signal_pending(current))
1519 return -EINTR;
1520
1521 invalidate_sub(curlun);
1522 if (signal_pending(current))
1523 return -EINTR;
1524
1525 /* Just try to read the requested blocks */
1526 while (amount_left > 0) {
1527
1528 /* Figure out how much we need to read:
1529 * Try to read the remaining amount, but not more than
1530 * the buffer size.
1531 * And don't try to read past the end of the file.
Alan Stern04eee252011-08-18 14:29:00 -04001532 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001533 amount = min((unsigned int) amount_left, mod_data.buflen);
1534 amount = min((loff_t) amount,
1535 curlun->file_length - file_offset);
1536 if (amount == 0) {
1537 curlun->sense_data =
1538 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001539 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001540 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001541 break;
1542 }
1543
1544 /* Perform the read */
1545 file_offset_tmp = file_offset;
1546 nread = vfs_read(curlun->filp,
1547 (char __user *) bh->buf,
1548 amount, &file_offset_tmp);
1549 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1550 (unsigned long long) file_offset,
1551 (int) nread);
1552 if (signal_pending(current))
1553 return -EINTR;
1554
1555 if (nread < 0) {
1556 LDBG(curlun, "error in file verify: %d\n",
1557 (int) nread);
1558 nread = 0;
1559 } else if (nread < amount) {
1560 LDBG(curlun, "partial file verify: %d/%u\n",
1561 (int) nread, amount);
Peiyu Li3f565a32011-08-17 22:52:59 -07001562 nread = round_down(nread, curlun->blksize);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001563 }
1564 if (nread == 0) {
1565 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
Peiyu Li3f565a32011-08-17 22:52:59 -07001566 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001567 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001568 break;
1569 }
1570 file_offset += nread;
1571 amount_left -= nread;
1572 }
1573 return 0;
1574}
1575
1576
1577/*-------------------------------------------------------------------------*/
1578
1579static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1580{
1581 u8 *buf = (u8 *) bh->buf;
1582
1583 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05001584 static char product_disk_id[] = "File-Stor Gadget";
1585 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07001586
1587 if (!fsg->curlun) { // Unsupported LUNs are okay
1588 fsg->bad_lun_okay = 1;
1589 memset(buf, 0, 36);
1590 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05001591 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07001592 return 36;
1593 }
1594
Alan Stern12aae682008-11-20 14:13:12 -05001595 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001596 buf[0] = (mod_data.cdrom ? TYPE_ROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001597 if (mod_data.removable)
1598 buf[1] = 0x80;
1599 buf[2] = 2; // ANSI SCSI level 2
1600 buf[3] = 2; // SCSI-2 INQUIRY data format
1601 buf[4] = 31; // Additional length
1602 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05001603 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1604 (mod_data.cdrom ? product_cdrom_id :
1605 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001606 mod_data.release);
1607 return 36;
1608}
1609
1610
1611static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1612{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001613 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001614 u8 *buf = (u8 *) bh->buf;
1615 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04001616 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001617
1618 /*
1619 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1620 *
1621 * If a REQUEST SENSE command is received from an initiator
1622 * with a pending unit attention condition (before the target
1623 * generates the contingent allegiance condition), then the
1624 * target shall either:
1625 * a) report any pending sense data and preserve the unit
1626 * attention condition on the logical unit, or,
1627 * b) report the unit attention condition, may discard any
1628 * pending sense data, and clear the unit attention
1629 * condition on the logical unit for that initiator.
1630 *
1631 * FSG normally uses option a); enable this code to use option b).
1632 */
1633#if 0
1634 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1635 curlun->sense_data = curlun->unit_attention_data;
1636 curlun->unit_attention_data = SS_NO_SENSE;
1637 }
1638#endif
1639
1640 if (!curlun) { // Unsupported LUNs are okay
1641 fsg->bad_lun_okay = 1;
1642 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1643 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001644 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001645 } else {
1646 sd = curlun->sense_data;
1647 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04001648 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001649 curlun->sense_data = SS_NO_SENSE;
1650 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001651 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001652 }
1653
1654 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04001655 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07001656 buf[2] = SK(sd);
Alan Stern604eb892009-04-27 13:19:41 -04001657 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001658 buf[7] = 18 - 8; // Additional sense length
1659 buf[12] = ASC(sd);
1660 buf[13] = ASCQ(sd);
1661 return 18;
1662}
1663
1664
1665static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1666{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001667 struct fsg_lun *curlun = fsg->curlun;
Alan Stern604eb892009-04-27 13:19:41 -04001668 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001669 int pmi = fsg->cmnd[8];
1670 u8 *buf = (u8 *) bh->buf;
1671
1672 /* Check the PMI and LBA fields */
1673 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1674 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1675 return -EINVAL;
1676 }
1677
Alan Stern604eb892009-04-27 13:19:41 -04001678 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1679 /* Max logical block */
Peiyu Li3f565a32011-08-17 22:52:59 -07001680 put_unaligned_be32(curlun->blksize, &buf[4]); /* Block length */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001681 return 8;
1682}
1683
1684
Alan Stern12aae682008-11-20 14:13:12 -05001685static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1686{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001687 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001688 int msf = fsg->cmnd[1] & 0x02;
Alan Stern604eb892009-04-27 13:19:41 -04001689 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Alan Stern12aae682008-11-20 14:13:12 -05001690 u8 *buf = (u8 *) bh->buf;
1691
1692 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1693 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1694 return -EINVAL;
1695 }
1696 if (lba >= curlun->num_sectors) {
1697 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1698 return -EINVAL;
1699 }
1700
1701 memset(buf, 0, 8);
1702 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1703 store_cdrom_address(&buf[4], msf, lba);
1704 return 8;
1705}
1706
1707
1708static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1709{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001710 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001711 int msf = fsg->cmnd[1] & 0x02;
1712 int start_track = fsg->cmnd[6];
1713 u8 *buf = (u8 *) bh->buf;
1714
1715 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1716 start_track > 1) {
1717 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1718 return -EINVAL;
1719 }
1720
1721 memset(buf, 0, 20);
1722 buf[1] = (20-2); /* TOC data length */
1723 buf[2] = 1; /* First track number */
1724 buf[3] = 1; /* Last track number */
1725 buf[5] = 0x16; /* Data track, copying allowed */
1726 buf[6] = 0x01; /* Only track is number 1 */
1727 store_cdrom_address(&buf[8], msf, 0);
1728
1729 buf[13] = 0x16; /* Lead-out track is data */
1730 buf[14] = 0xAA; /* Lead-out track number */
1731 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1732 return 20;
1733}
1734
1735
Linus Torvalds1da177e2005-04-16 15:20:36 -07001736static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1737{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001738 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001739 int mscmnd = fsg->cmnd[0];
1740 u8 *buf = (u8 *) bh->buf;
1741 u8 *buf0 = buf;
1742 int pc, page_code;
1743 int changeable_values, all_pages;
1744 int valid_page = 0;
1745 int len, limit;
1746
1747 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1748 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1749 return -EINVAL;
1750 }
1751 pc = fsg->cmnd[2] >> 6;
1752 page_code = fsg->cmnd[2] & 0x3f;
1753 if (pc == 3) {
1754 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1755 return -EINVAL;
1756 }
1757 changeable_values = (pc == 1);
1758 all_pages = (page_code == 0x3f);
1759
1760 /* Write the mode parameter header. Fixed values are: default
1761 * medium type, no cache control (DPOFUA), and no block descriptors.
1762 * The only variable value is the WriteProtect bit. We will fill in
1763 * the mode data length later. */
1764 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001765 if (mscmnd == MODE_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001766 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1767 buf += 4;
1768 limit = 255;
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001769 } else { // MODE_SENSE_10
Linus Torvalds1da177e2005-04-16 15:20:36 -07001770 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1771 buf += 8;
1772 limit = 65535; // Should really be mod_data.buflen
1773 }
1774
1775 /* No block descriptors */
1776
1777 /* The mode pages, in numerical order. The only page we support
1778 * is the Caching page. */
1779 if (page_code == 0x08 || all_pages) {
1780 valid_page = 1;
1781 buf[0] = 0x08; // Page code
1782 buf[1] = 10; // Page length
1783 memset(buf+2, 0, 10); // None of the fields are changeable
1784
1785 if (!changeable_values) {
1786 buf[2] = 0x04; // Write cache enable,
1787 // Read cache not disabled
1788 // No cache retention priorities
Alan Stern604eb892009-04-27 13:19:41 -04001789 put_unaligned_be16(0xffff, &buf[4]);
1790 /* Don't disable prefetch */
1791 /* Minimum prefetch = 0 */
1792 put_unaligned_be16(0xffff, &buf[8]);
1793 /* Maximum prefetch */
1794 put_unaligned_be16(0xffff, &buf[10]);
1795 /* Maximum prefetch ceiling */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001796 }
1797 buf += 12;
1798 }
1799
1800 /* Check that a valid page was requested and the mode data length
1801 * isn't too long. */
1802 len = buf - buf0;
1803 if (!valid_page || len > limit) {
1804 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1805 return -EINVAL;
1806 }
1807
1808 /* Store the mode data length */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001809 if (mscmnd == MODE_SENSE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001810 buf0[0] = len - 1;
1811 else
Alan Stern604eb892009-04-27 13:19:41 -04001812 put_unaligned_be16(len - 2, buf0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001813 return len;
1814}
1815
1816
1817static int do_start_stop(struct fsg_dev *fsg)
1818{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001819 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001820 int loej, start;
1821
1822 if (!mod_data.removable) {
1823 curlun->sense_data = SS_INVALID_COMMAND;
1824 return -EINVAL;
1825 }
1826
1827 // int immed = fsg->cmnd[1] & 0x01;
1828 loej = fsg->cmnd[4] & 0x02;
1829 start = fsg->cmnd[4] & 0x01;
1830
1831#ifdef CONFIG_USB_FILE_STORAGE_TEST
1832 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1833 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1834 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1835 return -EINVAL;
1836 }
1837
1838 if (!start) {
1839
1840 /* Are we allowed to unload the media? */
1841 if (curlun->prevent_medium_removal) {
1842 LDBG(curlun, "unload attempt prevented\n");
1843 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1844 return -EINVAL;
1845 }
1846 if (loej) { // Simulate an unload/eject
1847 up_read(&fsg->filesem);
1848 down_write(&fsg->filesem);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001849 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001850 up_write(&fsg->filesem);
1851 down_read(&fsg->filesem);
1852 }
1853 } else {
1854
1855 /* Our emulation doesn't support mounting; the medium is
1856 * available for use as soon as it is loaded. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001857 if (!fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001858 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1859 return -EINVAL;
1860 }
1861 }
1862#endif
1863 return 0;
1864}
1865
1866
1867static int do_prevent_allow(struct fsg_dev *fsg)
1868{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001869 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001870 int prevent;
1871
1872 if (!mod_data.removable) {
1873 curlun->sense_data = SS_INVALID_COMMAND;
1874 return -EINVAL;
1875 }
1876
1877 prevent = fsg->cmnd[4] & 0x01;
1878 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1879 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1880 return -EINVAL;
1881 }
1882
1883 if (curlun->prevent_medium_removal && !prevent)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001884 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001885 curlun->prevent_medium_removal = prevent;
1886 return 0;
1887}
1888
1889
1890static int do_read_format_capacities(struct fsg_dev *fsg,
1891 struct fsg_buffhd *bh)
1892{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001893 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001894 u8 *buf = (u8 *) bh->buf;
1895
1896 buf[0] = buf[1] = buf[2] = 0;
1897 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1898 buf += 4;
1899
Alan Stern604eb892009-04-27 13:19:41 -04001900 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1901 /* Number of blocks */
Peiyu Li3f565a32011-08-17 22:52:59 -07001902 put_unaligned_be32(curlun->blksize, &buf[4]); /* Block length */
Alan Stern604eb892009-04-27 13:19:41 -04001903 buf[4] = 0x02; /* Current capacity */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001904 return 12;
1905}
1906
1907
1908static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1909{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001910 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001911
1912 /* We don't support MODE SELECT */
1913 curlun->sense_data = SS_INVALID_COMMAND;
1914 return -EINVAL;
1915}
1916
1917
1918/*-------------------------------------------------------------------------*/
1919
1920static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1921{
1922 int rc;
1923
1924 rc = fsg_set_halt(fsg, fsg->bulk_in);
1925 if (rc == -EAGAIN)
1926 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1927 while (rc != 0) {
1928 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001929 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001930 rc = 0;
1931 break;
1932 }
1933
1934 /* Wait for a short time and then try again */
1935 if (msleep_interruptible(100) != 0)
1936 return -EINTR;
1937 rc = usb_ep_set_halt(fsg->bulk_in);
1938 }
1939 return rc;
1940}
1941
David Lopo62fd2ca2008-04-29 10:14:38 +01001942static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1943{
1944 int rc;
1945
1946 DBG(fsg, "bulk-in set wedge\n");
1947 rc = usb_ep_set_wedge(fsg->bulk_in);
1948 if (rc == -EAGAIN)
1949 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1950 while (rc != 0) {
1951 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001952 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01001953 rc = 0;
1954 break;
1955 }
1956
1957 /* Wait for a short time and then try again */
1958 if (msleep_interruptible(100) != 0)
1959 return -EINTR;
1960 rc = usb_ep_set_wedge(fsg->bulk_in);
1961 }
1962 return rc;
1963}
1964
Linus Torvalds1da177e2005-04-16 15:20:36 -07001965static int throw_away_data(struct fsg_dev *fsg)
1966{
1967 struct fsg_buffhd *bh;
1968 u32 amount;
1969 int rc;
1970
1971 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1972 fsg->usb_amount_left > 0) {
1973
1974 /* Throw away the data in a filled buffer */
1975 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001976 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001977 bh->state = BUF_STATE_EMPTY;
1978 fsg->next_buffhd_to_drain = bh->next;
1979
1980 /* A short packet or an error ends everything */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001981 if (bh->outreq->actual < bh->bulk_out_intended_length ||
Linus Torvalds1da177e2005-04-16 15:20:36 -07001982 bh->outreq->status != 0) {
1983 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1984 return -EINTR;
1985 }
1986 continue;
1987 }
1988
1989 /* Try to submit another request if we need one */
1990 bh = fsg->next_buffhd_to_fill;
1991 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1992 amount = min(fsg->usb_amount_left,
1993 (u32) mod_data.buflen);
1994
Alan Stern04eee252011-08-18 14:29:00 -04001995 /* Except at the end of the transfer, amount will be
1996 * equal to the buffer size, which is divisible by
1997 * the bulk-out maxpacket size.
1998 */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001999 set_bulk_out_req_length(fsg, bh, amount);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002000 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2001 &bh->outreq_busy, &bh->state);
2002 fsg->next_buffhd_to_fill = bh->next;
2003 fsg->usb_amount_left -= amount;
2004 continue;
2005 }
2006
2007 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04002008 rc = sleep_thread(fsg);
2009 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002010 return rc;
2011 }
2012 return 0;
2013}
2014
2015
2016static int finish_reply(struct fsg_dev *fsg)
2017{
2018 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2019 int rc = 0;
2020
2021 switch (fsg->data_dir) {
2022 case DATA_DIR_NONE:
2023 break; // Nothing to send
2024
2025 /* If we don't know whether the host wants to read or write,
2026 * this must be CB or CBI with an unknown command. We mustn't
2027 * try to send or receive any data. So stall both bulk pipes
2028 * if we can and wait for a reset. */
2029 case DATA_DIR_UNKNOWN:
2030 if (mod_data.can_stall) {
2031 fsg_set_halt(fsg, fsg->bulk_out);
2032 rc = halt_bulk_in_endpoint(fsg);
2033 }
2034 break;
2035
2036 /* All but the last buffer of data must have already been sent */
2037 case DATA_DIR_TO_HOST:
2038 if (fsg->data_size == 0)
2039 ; // Nothing to send
2040
2041 /* If there's no residue, simply send the last buffer */
2042 else if (fsg->residue == 0) {
2043 bh->inreq->zero = 0;
2044 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2045 &bh->inreq_busy, &bh->state);
2046 fsg->next_buffhd_to_fill = bh->next;
2047 }
2048
2049 /* There is a residue. For CB and CBI, simply mark the end
2050 * of the data with a short packet. However, if we are
2051 * allowed to stall, there was no data at all (residue ==
2052 * data_size), and the command failed (invalid LUN or
2053 * sense data is set), then halt the bulk-in endpoint
2054 * instead. */
2055 else if (!transport_is_bbb()) {
2056 if (mod_data.can_stall &&
2057 fsg->residue == fsg->data_size &&
2058 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2059 bh->state = BUF_STATE_EMPTY;
2060 rc = halt_bulk_in_endpoint(fsg);
2061 } else {
2062 bh->inreq->zero = 1;
2063 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2064 &bh->inreq_busy, &bh->state);
2065 fsg->next_buffhd_to_fill = bh->next;
2066 }
2067 }
2068
Alan Sternee81b3e2011-03-25 11:46:27 -04002069 /*
2070 * For Bulk-only, mark the end of the data with a short
2071 * packet. If we are allowed to stall, halt the bulk-in
2072 * endpoint. (Note: This violates the Bulk-Only Transport
2073 * specification, which requires us to pad the data if we
2074 * don't halt the endpoint. Presumably nobody will mind.)
2075 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002076 else {
Alan Sternee81b3e2011-03-25 11:46:27 -04002077 bh->inreq->zero = 1;
2078 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2079 &bh->inreq_busy, &bh->state);
2080 fsg->next_buffhd_to_fill = bh->next;
2081 if (mod_data.can_stall)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002082 rc = halt_bulk_in_endpoint(fsg);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002083 }
2084 break;
2085
2086 /* We have processed all we want from the data the host has sent.
2087 * There may still be outstanding bulk-out requests. */
2088 case DATA_DIR_FROM_HOST:
2089 if (fsg->residue == 0)
2090 ; // Nothing to receive
2091
2092 /* Did the host stop sending unexpectedly early? */
2093 else if (fsg->short_packet_received) {
2094 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2095 rc = -EINTR;
2096 }
2097
2098 /* We haven't processed all the incoming data. Even though
2099 * we may be allowed to stall, doing so would cause a race.
2100 * The controller may already have ACK'ed all the remaining
2101 * bulk-out packets, in which case the host wouldn't see a
2102 * STALL. Not realizing the endpoint was halted, it wouldn't
2103 * clear the halt -- leading to problems later on. */
2104#if 0
2105 else if (mod_data.can_stall) {
2106 fsg_set_halt(fsg, fsg->bulk_out);
2107 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2108 rc = -EINTR;
2109 }
2110#endif
2111
2112 /* We can't stall. Read in the excess data and throw it
2113 * all away. */
2114 else
2115 rc = throw_away_data(fsg);
2116 break;
2117 }
2118 return rc;
2119}
2120
2121
2122static int send_status(struct fsg_dev *fsg)
2123{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002124 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002125 struct fsg_buffhd *bh;
2126 int rc;
2127 u8 status = USB_STATUS_PASS;
2128 u32 sd, sdinfo = 0;
2129
2130 /* Wait for the next buffer to become available */
2131 bh = fsg->next_buffhd_to_fill;
2132 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002133 rc = sleep_thread(fsg);
2134 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002135 return rc;
2136 }
2137
2138 if (curlun) {
2139 sd = curlun->sense_data;
2140 sdinfo = curlun->sense_data_info;
2141 } else if (fsg->bad_lun_okay)
2142 sd = SS_NO_SENSE;
2143 else
2144 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2145
2146 if (fsg->phase_error) {
2147 DBG(fsg, "sending phase-error status\n");
2148 status = USB_STATUS_PHASE_ERROR;
2149 sd = SS_INVALID_COMMAND;
2150 } else if (sd != SS_NO_SENSE) {
2151 DBG(fsg, "sending command-failure status\n");
2152 status = USB_STATUS_FAIL;
2153 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2154 " info x%x\n",
2155 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2156 }
2157
2158 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002159 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002160
2161 /* Store and send the Bulk-only CSW */
Harvey Harrison551509d2009-02-11 14:11:36 -08002162 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002163 csw->Tag = fsg->tag;
2164 csw->Residue = cpu_to_le32(fsg->residue);
2165 csw->Status = status;
2166
2167 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2168 bh->inreq->zero = 0;
2169 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2170 &bh->inreq_busy, &bh->state);
2171
2172 } else if (mod_data.transport_type == USB_PR_CB) {
2173
2174 /* Control-Bulk transport has no status phase! */
2175 return 0;
2176
2177 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002178 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002179
2180 /* Store and send the Interrupt data. UFI sends the ASC
2181 * and ASCQ bytes. Everything else sends a Type (which
2182 * is always 0) and the status Value. */
2183 if (mod_data.protocol_type == USB_SC_UFI) {
2184 buf->bType = ASC(sd);
2185 buf->bValue = ASCQ(sd);
2186 } else {
2187 buf->bType = 0;
2188 buf->bValue = status;
2189 }
2190 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2191
2192 fsg->intr_buffhd = bh; // Point to the right buffhd
2193 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002194 fsg->intreq->context = bh;
2195 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2196 &fsg->intreq_busy, &bh->state);
2197 }
2198
2199 fsg->next_buffhd_to_fill = bh->next;
2200 return 0;
2201}
2202
2203
2204/*-------------------------------------------------------------------------*/
2205
2206/* Check whether the command is properly formed and whether its data size
2207 * and direction agree with the values we already have. */
2208static int check_command(struct fsg_dev *fsg, int cmnd_size,
2209 enum data_direction data_dir, unsigned int mask,
2210 int needs_medium, const char *name)
2211{
2212 int i;
2213 int lun = fsg->cmnd[1] >> 5;
2214 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2215 char hdlen[20];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002216 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002217
2218 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2219 * Transparent SCSI doesn't pad. */
2220 if (protocol_is_scsi())
2221 ;
2222
2223 /* There's some disagreement as to whether RBC pads commands or not.
2224 * We'll play it safe and accept either form. */
2225 else if (mod_data.protocol_type == USB_SC_RBC) {
2226 if (fsg->cmnd_size == 12)
2227 cmnd_size = 12;
2228
2229 /* All the other protocols pad to 12 bytes */
2230 } else
2231 cmnd_size = 12;
2232
2233 hdlen[0] = 0;
2234 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2235 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2236 fsg->data_size);
2237 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2238 name, cmnd_size, dirletter[(int) data_dir],
2239 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2240
2241 /* We can't reply at all until we know the correct data direction
2242 * and size. */
2243 if (fsg->data_size_from_cmnd == 0)
2244 data_dir = DATA_DIR_NONE;
2245 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2246 fsg->data_dir = data_dir;
2247 fsg->data_size = fsg->data_size_from_cmnd;
2248
2249 } else { // Bulk-only
2250 if (fsg->data_size < fsg->data_size_from_cmnd) {
2251
2252 /* Host data size < Device data size is a phase error.
2253 * Carry out the command, but only transfer as much
2254 * as we are allowed. */
2255 fsg->data_size_from_cmnd = fsg->data_size;
2256 fsg->phase_error = 1;
2257 }
2258 }
2259 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2260
2261 /* Conflicting data directions is a phase error */
2262 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2263 fsg->phase_error = 1;
2264 return -EINVAL;
2265 }
2266
2267 /* Verify the length of the command itself */
2268 if (cmnd_size != fsg->cmnd_size) {
2269
Felipe Balbi549c41e2008-09-19 02:00:02 +03002270 /* Special case workaround: There are plenty of buggy SCSI
2271 * implementations. Many have issues with cbw->Length
2272 * field passing a wrong command size. For those cases we
2273 * always try to work around the problem by using the length
2274 * sent by the host side provided it is at least as large
2275 * as the correct command length.
2276 * Examples of such cases would be MS-Windows, which issues
2277 * REQUEST SENSE with cbw->Length == 12 where it should
2278 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2279 * REQUEST SENSE with cbw->Length == 10 where it should
2280 * be 6 as well.
2281 */
2282 if (cmnd_size <= fsg->cmnd_size) {
2283 DBG(fsg, "%s is buggy! Expected length %d "
2284 "but we got %d\n", name,
2285 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002286 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002287 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002288 fsg->phase_error = 1;
2289 return -EINVAL;
2290 }
2291 }
2292
Alan Sternd794ac72005-04-18 12:43:25 -04002293 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002294 if (transport_is_bbb()) {
2295 if (fsg->lun != lun)
2296 DBG(fsg, "using LUN %d from CBW, "
2297 "not LUN %d from CDB\n",
2298 fsg->lun, lun);
2299 } else
2300 fsg->lun = lun; // Use LUN from the command
2301
2302 /* Check the LUN */
Maxin B John849426c2011-05-08 15:56:17 +03002303 if (fsg->lun < fsg->nluns) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002304 fsg->curlun = curlun = &fsg->luns[fsg->lun];
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002305 if (fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002306 curlun->sense_data = SS_NO_SENSE;
2307 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002308 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002309 }
2310 } else {
2311 fsg->curlun = curlun = NULL;
2312 fsg->bad_lun_okay = 0;
2313
2314 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2315 * to use unsupported LUNs; all others may not. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002316 if (fsg->cmnd[0] != INQUIRY &&
2317 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002318 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2319 return -EINVAL;
2320 }
2321 }
2322
2323 /* If a unit attention condition exists, only INQUIRY and
2324 * REQUEST SENSE commands are allowed; anything else must fail. */
2325 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002326 fsg->cmnd[0] != INQUIRY &&
2327 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002328 curlun->sense_data = curlun->unit_attention_data;
2329 curlun->unit_attention_data = SS_NO_SENSE;
2330 return -EINVAL;
2331 }
2332
2333 /* Check that only command bytes listed in the mask are non-zero */
2334 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2335 for (i = 1; i < cmnd_size; ++i) {
2336 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2337 if (curlun)
2338 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2339 return -EINVAL;
2340 }
2341 }
2342
2343 /* If the medium isn't mounted and the command needs to access
2344 * it, return an error. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002345 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002346 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2347 return -EINVAL;
2348 }
2349
2350 return 0;
2351}
2352
2353
2354static int do_scsi_command(struct fsg_dev *fsg)
2355{
2356 struct fsg_buffhd *bh;
2357 int rc;
2358 int reply = -EINVAL;
2359 int i;
2360 static char unknown[16];
2361
2362 dump_cdb(fsg);
2363
2364 /* Wait for the next buffer to become available for data or status */
2365 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2366 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002367 rc = sleep_thread(fsg);
2368 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002369 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002370 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002371 fsg->phase_error = 0;
2372 fsg->short_packet_received = 0;
2373
2374 down_read(&fsg->filesem); // We're using the backing file
2375 switch (fsg->cmnd[0]) {
2376
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002377 case INQUIRY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002378 fsg->data_size_from_cmnd = fsg->cmnd[4];
2379 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2380 (1<<4), 0,
2381 "INQUIRY")) == 0)
2382 reply = do_inquiry(fsg, bh);
2383 break;
2384
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002385 case MODE_SELECT:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002386 fsg->data_size_from_cmnd = fsg->cmnd[4];
2387 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2388 (1<<1) | (1<<4), 0,
2389 "MODE SELECT(6)")) == 0)
2390 reply = do_mode_select(fsg, bh);
2391 break;
2392
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002393 case MODE_SELECT_10:
Alan Stern604eb892009-04-27 13:19:41 -04002394 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002395 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2396 (1<<1) | (3<<7), 0,
2397 "MODE SELECT(10)")) == 0)
2398 reply = do_mode_select(fsg, bh);
2399 break;
2400
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002401 case MODE_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002402 fsg->data_size_from_cmnd = fsg->cmnd[4];
2403 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2404 (1<<1) | (1<<2) | (1<<4), 0,
2405 "MODE SENSE(6)")) == 0)
2406 reply = do_mode_sense(fsg, bh);
2407 break;
2408
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002409 case MODE_SENSE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002410 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002411 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2412 (1<<1) | (1<<2) | (3<<7), 0,
2413 "MODE SENSE(10)")) == 0)
2414 reply = do_mode_sense(fsg, bh);
2415 break;
2416
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002417 case ALLOW_MEDIUM_REMOVAL:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002418 fsg->data_size_from_cmnd = 0;
2419 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2420 (1<<4), 0,
2421 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2422 reply = do_prevent_allow(fsg);
2423 break;
2424
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002425 case READ_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002426 i = fsg->cmnd[4];
Peiyu Li3f565a32011-08-17 22:52:59 -07002427 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002428 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2429 (7<<1) | (1<<4), 1,
2430 "READ(6)")) == 0)
2431 reply = do_read(fsg);
2432 break;
2433
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002434 case READ_10:
Alan Stern604eb892009-04-27 13:19:41 -04002435 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002436 get_unaligned_be16(&fsg->cmnd[7]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002437 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2438 (1<<1) | (0xf<<2) | (3<<7), 1,
2439 "READ(10)")) == 0)
2440 reply = do_read(fsg);
2441 break;
2442
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002443 case READ_12:
Alan Stern604eb892009-04-27 13:19:41 -04002444 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002445 get_unaligned_be32(&fsg->cmnd[6]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002446 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2447 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2448 "READ(12)")) == 0)
2449 reply = do_read(fsg);
2450 break;
2451
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002452 case READ_CAPACITY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002453 fsg->data_size_from_cmnd = 8;
2454 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2455 (0xf<<2) | (1<<8), 1,
2456 "READ CAPACITY")) == 0)
2457 reply = do_read_capacity(fsg, bh);
2458 break;
2459
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002460 case READ_HEADER:
Alan Stern12aae682008-11-20 14:13:12 -05002461 if (!mod_data.cdrom)
2462 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002463 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002464 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2465 (3<<7) | (0x1f<<1), 1,
2466 "READ HEADER")) == 0)
2467 reply = do_read_header(fsg, bh);
2468 break;
2469
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002470 case READ_TOC:
Alan Stern12aae682008-11-20 14:13:12 -05002471 if (!mod_data.cdrom)
2472 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002473 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002474 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2475 (7<<6) | (1<<1), 1,
2476 "READ TOC")) == 0)
2477 reply = do_read_toc(fsg, bh);
2478 break;
2479
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002480 case READ_FORMAT_CAPACITIES:
Alan Stern604eb892009-04-27 13:19:41 -04002481 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002482 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2483 (3<<7), 1,
2484 "READ FORMAT CAPACITIES")) == 0)
2485 reply = do_read_format_capacities(fsg, bh);
2486 break;
2487
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002488 case REQUEST_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002489 fsg->data_size_from_cmnd = fsg->cmnd[4];
2490 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2491 (1<<4), 0,
2492 "REQUEST SENSE")) == 0)
2493 reply = do_request_sense(fsg, bh);
2494 break;
2495
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002496 case START_STOP:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002497 fsg->data_size_from_cmnd = 0;
2498 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2499 (1<<1) | (1<<4), 0,
2500 "START-STOP UNIT")) == 0)
2501 reply = do_start_stop(fsg);
2502 break;
2503
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002504 case SYNCHRONIZE_CACHE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002505 fsg->data_size_from_cmnd = 0;
2506 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2507 (0xf<<2) | (3<<7), 1,
2508 "SYNCHRONIZE CACHE")) == 0)
2509 reply = do_synchronize_cache(fsg);
2510 break;
2511
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002512 case TEST_UNIT_READY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002513 fsg->data_size_from_cmnd = 0;
2514 reply = check_command(fsg, 6, DATA_DIR_NONE,
2515 0, 1,
2516 "TEST UNIT READY");
2517 break;
2518
2519 /* Although optional, this command is used by MS-Windows. We
2520 * support a minimal version: BytChk must be 0. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002521 case VERIFY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002522 fsg->data_size_from_cmnd = 0;
2523 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2524 (1<<1) | (0xf<<2) | (3<<7), 1,
2525 "VERIFY")) == 0)
2526 reply = do_verify(fsg);
2527 break;
2528
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002529 case WRITE_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002530 i = fsg->cmnd[4];
Peiyu Li3f565a32011-08-17 22:52:59 -07002531 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002532 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2533 (7<<1) | (1<<4), 1,
2534 "WRITE(6)")) == 0)
2535 reply = do_write(fsg);
2536 break;
2537
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002538 case WRITE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002539 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002540 get_unaligned_be16(&fsg->cmnd[7]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002541 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2542 (1<<1) | (0xf<<2) | (3<<7), 1,
2543 "WRITE(10)")) == 0)
2544 reply = do_write(fsg);
2545 break;
2546
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002547 case WRITE_12:
Alan Stern604eb892009-04-27 13:19:41 -04002548 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002549 get_unaligned_be32(&fsg->cmnd[6]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002550 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2551 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2552 "WRITE(12)")) == 0)
2553 reply = do_write(fsg);
2554 break;
2555
2556 /* Some mandatory commands that we recognize but don't implement.
2557 * They don't mean much in this setting. It's left as an exercise
2558 * for anyone interested to implement RESERVE and RELEASE in terms
2559 * of Posix locks. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002560 case FORMAT_UNIT:
2561 case RELEASE:
2562 case RESERVE:
2563 case SEND_DIAGNOSTIC:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002564 // Fall through
2565
2566 default:
Alan Stern12aae682008-11-20 14:13:12 -05002567 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002568 fsg->data_size_from_cmnd = 0;
2569 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2570 if ((reply = check_command(fsg, fsg->cmnd_size,
2571 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2572 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2573 reply = -EINVAL;
2574 }
2575 break;
2576 }
2577 up_read(&fsg->filesem);
2578
2579 if (reply == -EINTR || signal_pending(current))
2580 return -EINTR;
2581
2582 /* Set up the single reply buffer for finish_reply() */
2583 if (reply == -EINVAL)
2584 reply = 0; // Error reply length
2585 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2586 reply = min((u32) reply, fsg->data_size_from_cmnd);
2587 bh->inreq->length = reply;
2588 bh->state = BUF_STATE_FULL;
2589 fsg->residue -= reply;
2590 } // Otherwise it's already set
2591
2592 return 0;
2593}
2594
2595
2596/*-------------------------------------------------------------------------*/
2597
2598static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2599{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002600 struct usb_request *req = bh->outreq;
2601 struct fsg_bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002602
Alan Sternb950bdb2008-04-14 11:45:29 -04002603 /* Was this a real packet? Should it be ignored? */
2604 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002605 return -EINVAL;
2606
2607 /* Is the CBW valid? */
2608 if (req->actual != USB_BULK_CB_WRAP_LEN ||
Harvey Harrison551509d2009-02-11 14:11:36 -08002609 cbw->Signature != cpu_to_le32(
Linus Torvalds1da177e2005-04-16 15:20:36 -07002610 USB_BULK_CB_SIG)) {
2611 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2612 req->actual,
2613 le32_to_cpu(cbw->Signature));
2614
Alan Sternb950bdb2008-04-14 11:45:29 -04002615 /* The Bulk-only spec says we MUST stall the IN endpoint
2616 * (6.6.1), so it's unavoidable. It also says we must
2617 * retain this state until the next reset, but there's
2618 * no way to tell the controller driver it should ignore
2619 * Clear-Feature(HALT) requests.
2620 *
2621 * We aren't required to halt the OUT endpoint; instead
2622 * we can simply accept and discard any data received
2623 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01002624 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04002625 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002626 return -EINVAL;
2627 }
2628
2629 /* Is the CBW meaningful? */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002630 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04002631 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002632 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2633 "cmdlen %u\n",
2634 cbw->Lun, cbw->Flags, cbw->Length);
2635
2636 /* We can do anything we want here, so let's stall the
2637 * bulk pipes if we are allowed to. */
2638 if (mod_data.can_stall) {
2639 fsg_set_halt(fsg, fsg->bulk_out);
2640 halt_bulk_in_endpoint(fsg);
2641 }
2642 return -EINVAL;
2643 }
2644
2645 /* Save the command for later */
2646 fsg->cmnd_size = cbw->Length;
2647 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2648 if (cbw->Flags & USB_BULK_IN_FLAG)
2649 fsg->data_dir = DATA_DIR_TO_HOST;
2650 else
2651 fsg->data_dir = DATA_DIR_FROM_HOST;
2652 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2653 if (fsg->data_size == 0)
2654 fsg->data_dir = DATA_DIR_NONE;
2655 fsg->lun = cbw->Lun;
2656 fsg->tag = cbw->Tag;
2657 return 0;
2658}
2659
2660
2661static int get_next_command(struct fsg_dev *fsg)
2662{
2663 struct fsg_buffhd *bh;
2664 int rc = 0;
2665
2666 if (transport_is_bbb()) {
2667
2668 /* Wait for the next buffer to become available */
2669 bh = fsg->next_buffhd_to_fill;
2670 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002671 rc = sleep_thread(fsg);
2672 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002673 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002674 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002675
2676 /* Queue a request to read a Bulk-only CBW */
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -07002677 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002678 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2679 &bh->outreq_busy, &bh->state);
2680
2681 /* We will drain the buffer in software, which means we
2682 * can reuse it for the next filling. No need to advance
2683 * next_buffhd_to_fill. */
2684
2685 /* Wait for the CBW to arrive */
2686 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002687 rc = sleep_thread(fsg);
2688 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002689 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002690 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05002691 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002692 rc = received_cbw(fsg, bh);
2693 bh->state = BUF_STATE_EMPTY;
2694
2695 } else { // USB_PR_CB or USB_PR_CBI
2696
2697 /* Wait for the next command to arrive */
2698 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002699 rc = sleep_thread(fsg);
2700 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002701 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002702 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002703
2704 /* Is the previous status interrupt request still busy?
2705 * The host is allowed to skip reading the status,
2706 * so we must cancel it. */
2707 if (fsg->intreq_busy)
2708 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2709
2710 /* Copy the command and mark the buffer empty */
2711 fsg->data_dir = DATA_DIR_UNKNOWN;
2712 spin_lock_irq(&fsg->lock);
2713 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2714 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2715 fsg->cbbuf_cmnd_size = 0;
2716 spin_unlock_irq(&fsg->lock);
2717 }
2718 return rc;
2719}
2720
2721
2722/*-------------------------------------------------------------------------*/
2723
2724static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2725 const struct usb_endpoint_descriptor *d)
2726{
2727 int rc;
2728
2729 ep->driver_data = fsg;
Tatyana Brokhman72c973d2011-06-28 16:33:48 +03002730 ep->desc = d;
2731 rc = usb_ep_enable(ep);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002732 if (rc)
2733 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2734 return rc;
2735}
2736
2737static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2738 struct usb_request **preq)
2739{
2740 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2741 if (*preq)
2742 return 0;
2743 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2744 return -ENOMEM;
2745}
2746
2747/*
2748 * Reset interface setting and re-init endpoint state (toggle etc).
2749 * Call with altsetting < 0 to disable the interface. The only other
2750 * available altsetting is 0, which enables the interface.
2751 */
2752static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2753{
2754 int rc = 0;
2755 int i;
2756 const struct usb_endpoint_descriptor *d;
2757
2758 if (fsg->running)
2759 DBG(fsg, "reset interface\n");
2760
2761reset:
2762 /* Deallocate the requests */
Per Forlin6532c7f2011-08-19 21:21:27 +02002763 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002764 struct fsg_buffhd *bh = &fsg->buffhds[i];
2765
2766 if (bh->inreq) {
2767 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2768 bh->inreq = NULL;
2769 }
2770 if (bh->outreq) {
2771 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2772 bh->outreq = NULL;
2773 }
2774 }
2775 if (fsg->intreq) {
2776 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2777 fsg->intreq = NULL;
2778 }
2779
2780 /* Disable the endpoints */
2781 if (fsg->bulk_in_enabled) {
2782 usb_ep_disable(fsg->bulk_in);
2783 fsg->bulk_in_enabled = 0;
2784 }
2785 if (fsg->bulk_out_enabled) {
2786 usb_ep_disable(fsg->bulk_out);
2787 fsg->bulk_out_enabled = 0;
2788 }
2789 if (fsg->intr_in_enabled) {
2790 usb_ep_disable(fsg->intr_in);
2791 fsg->intr_in_enabled = 0;
2792 }
2793
2794 fsg->running = 0;
2795 if (altsetting < 0 || rc != 0)
2796 return rc;
2797
2798 DBG(fsg, "set interface %d\n", altsetting);
2799
2800 /* Enable the endpoints */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002801 d = fsg_ep_desc(fsg->gadget,
Felipe Balbi4bb99b72011-08-03 14:33:27 +03002802 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc,
2803 &fsg_ss_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002804 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2805 goto reset;
2806 fsg->bulk_in_enabled = 1;
2807
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002808 d = fsg_ep_desc(fsg->gadget,
Felipe Balbi4bb99b72011-08-03 14:33:27 +03002809 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc,
2810 &fsg_ss_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002811 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2812 goto reset;
2813 fsg->bulk_out_enabled = 1;
Kuninori Morimoto29cc8892011-08-23 03:12:03 -07002814 fsg->bulk_out_maxpacket = usb_endpoint_maxp(d);
Alan Sternb950bdb2008-04-14 11:45:29 -04002815 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002816
2817 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002818 d = fsg_ep_desc(fsg->gadget,
Felipe Balbi4bb99b72011-08-03 14:33:27 +03002819 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc,
2820 &fsg_ss_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002821 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2822 goto reset;
2823 fsg->intr_in_enabled = 1;
2824 }
2825
2826 /* Allocate the requests */
Per Forlin6532c7f2011-08-19 21:21:27 +02002827 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002828 struct fsg_buffhd *bh = &fsg->buffhds[i];
2829
2830 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2831 goto reset;
2832 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2833 goto reset;
2834 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002835 bh->inreq->context = bh->outreq->context = bh;
2836 bh->inreq->complete = bulk_in_complete;
2837 bh->outreq->complete = bulk_out_complete;
2838 }
2839 if (transport_is_cbi()) {
2840 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2841 goto reset;
2842 fsg->intreq->complete = intr_in_complete;
2843 }
2844
2845 fsg->running = 1;
2846 for (i = 0; i < fsg->nluns; ++i)
2847 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2848 return rc;
2849}
2850
2851
2852/*
2853 * Change our operational configuration. This code must agree with the code
2854 * that returns config descriptors, and with interface altsetting code.
2855 *
2856 * It's also responsible for power management interactions. Some
2857 * configurations might not work with our current power sources.
2858 * For now we just assume the gadget is always self-powered.
2859 */
2860static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2861{
2862 int rc = 0;
2863
2864 /* Disable the single interface */
2865 if (fsg->config != 0) {
2866 DBG(fsg, "reset config\n");
2867 fsg->config = 0;
2868 rc = do_set_interface(fsg, -1);
2869 }
2870
2871 /* Enable the interface */
2872 if (new_config != 0) {
2873 fsg->config = new_config;
2874 if ((rc = do_set_interface(fsg, 0)) != 0)
2875 fsg->config = 0; // Reset on errors
Michal Nazarewicze538dfd2011-08-30 17:11:19 +02002876 else
2877 INFO(fsg, "%s config #%d\n",
2878 usb_speed_string(fsg->gadget->speed),
2879 fsg->config);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002880 }
2881 return rc;
2882}
2883
2884
2885/*-------------------------------------------------------------------------*/
2886
2887static void handle_exception(struct fsg_dev *fsg)
2888{
2889 siginfo_t info;
2890 int sig;
2891 int i;
2892 int num_active;
2893 struct fsg_buffhd *bh;
2894 enum fsg_state old_state;
2895 u8 new_config;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002896 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002897 unsigned int exception_req_tag;
2898 int rc;
2899
2900 /* Clear the existing signals. Anything but SIGUSR1 is converted
2901 * into a high-priority EXIT exception. */
2902 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04002903 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002904 if (!sig)
2905 break;
2906 if (sig != SIGUSR1) {
2907 if (fsg->state < FSG_STATE_EXIT)
2908 DBG(fsg, "Main thread exiting on signal\n");
2909 raise_exception(fsg, FSG_STATE_EXIT);
2910 }
2911 }
2912
2913 /* Cancel all the pending transfers */
2914 if (fsg->intreq_busy)
2915 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
Per Forlin6532c7f2011-08-19 21:21:27 +02002916 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002917 bh = &fsg->buffhds[i];
2918 if (bh->inreq_busy)
2919 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2920 if (bh->outreq_busy)
2921 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2922 }
2923
2924 /* Wait until everything is idle */
2925 for (;;) {
2926 num_active = fsg->intreq_busy;
Per Forlin6532c7f2011-08-19 21:21:27 +02002927 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002928 bh = &fsg->buffhds[i];
2929 num_active += bh->inreq_busy + bh->outreq_busy;
2930 }
2931 if (num_active == 0)
2932 break;
2933 if (sleep_thread(fsg))
2934 return;
2935 }
2936
2937 /* Clear out the controller's fifos */
2938 if (fsg->bulk_in_enabled)
2939 usb_ep_fifo_flush(fsg->bulk_in);
2940 if (fsg->bulk_out_enabled)
2941 usb_ep_fifo_flush(fsg->bulk_out);
2942 if (fsg->intr_in_enabled)
2943 usb_ep_fifo_flush(fsg->intr_in);
2944
2945 /* Reset the I/O buffer states and pointers, the SCSI
2946 * state, and the exception. Then invoke the handler. */
2947 spin_lock_irq(&fsg->lock);
2948
Per Forlin6532c7f2011-08-19 21:21:27 +02002949 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002950 bh = &fsg->buffhds[i];
2951 bh->state = BUF_STATE_EMPTY;
2952 }
2953 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2954 &fsg->buffhds[0];
2955
2956 exception_req_tag = fsg->exception_req_tag;
2957 new_config = fsg->new_config;
2958 old_state = fsg->state;
2959
2960 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2961 fsg->state = FSG_STATE_STATUS_PHASE;
2962 else {
2963 for (i = 0; i < fsg->nluns; ++i) {
2964 curlun = &fsg->luns[i];
2965 curlun->prevent_medium_removal = 0;
2966 curlun->sense_data = curlun->unit_attention_data =
2967 SS_NO_SENSE;
2968 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002969 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002970 }
2971 fsg->state = FSG_STATE_IDLE;
2972 }
2973 spin_unlock_irq(&fsg->lock);
2974
2975 /* Carry out any extra actions required for the exception */
2976 switch (old_state) {
2977 default:
2978 break;
2979
2980 case FSG_STATE_ABORT_BULK_OUT:
2981 send_status(fsg);
2982 spin_lock_irq(&fsg->lock);
2983 if (fsg->state == FSG_STATE_STATUS_PHASE)
2984 fsg->state = FSG_STATE_IDLE;
2985 spin_unlock_irq(&fsg->lock);
2986 break;
2987
2988 case FSG_STATE_RESET:
2989 /* In case we were forced against our will to halt a
2990 * bulk endpoint, clear the halt now. (The SuperH UDC
2991 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04002992 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002993 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002994
2995 if (transport_is_bbb()) {
2996 if (fsg->ep0_req_tag == exception_req_tag)
2997 ep0_queue(fsg); // Complete the status stage
2998
2999 } else if (transport_is_cbi())
3000 send_status(fsg); // Status by interrupt pipe
3001
3002 /* Technically this should go here, but it would only be
3003 * a waste of time. Ditto for the INTERFACE_CHANGE and
3004 * CONFIG_CHANGE cases. */
3005 // for (i = 0; i < fsg->nluns; ++i)
3006 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3007 break;
3008
3009 case FSG_STATE_INTERFACE_CHANGE:
3010 rc = do_set_interface(fsg, 0);
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_CONFIG_CHANGE:
3020 rc = do_set_config(fsg, new_config);
3021 if (fsg->ep0_req_tag != exception_req_tag)
3022 break;
3023 if (rc != 0) // STALL on errors
3024 fsg_set_halt(fsg, fsg->ep0);
3025 else // Complete the status stage
3026 ep0_queue(fsg);
3027 break;
3028
3029 case FSG_STATE_DISCONNECT:
Michal Nazarewiczb6058d02009-10-28 16:57:14 +01003030 for (i = 0; i < fsg->nluns; ++i)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003031 fsg_lun_fsync_sub(fsg->luns + i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003032 do_set_config(fsg, 0); // Unconfigured state
3033 break;
3034
3035 case FSG_STATE_EXIT:
3036 case FSG_STATE_TERMINATED:
3037 do_set_config(fsg, 0); // Free resources
3038 spin_lock_irq(&fsg->lock);
3039 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3040 spin_unlock_irq(&fsg->lock);
3041 break;
3042 }
3043}
3044
3045
3046/*-------------------------------------------------------------------------*/
3047
3048static int fsg_main_thread(void *fsg_)
3049{
John Daiker7ca46b82006-12-29 19:02:06 -08003050 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003051
Linus Torvalds1da177e2005-04-16 15:20:36 -07003052 /* Allow the thread to be killed by a signal, but set the signal mask
3053 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003054 allow_signal(SIGINT);
3055 allow_signal(SIGTERM);
3056 allow_signal(SIGKILL);
3057 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003058
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003059 /* Allow the thread to be frozen */
3060 set_freezable();
3061
Linus Torvalds1da177e2005-04-16 15:20:36 -07003062 /* Arrange for userspace references to be interpreted as kernel
3063 * pointers. That way we can pass a kernel pointer to a routine
3064 * that expects a __user pointer and it will work okay. */
3065 set_fs(get_ds());
3066
Linus Torvalds1da177e2005-04-16 15:20:36 -07003067 /* The main loop */
3068 while (fsg->state != FSG_STATE_TERMINATED) {
3069 if (exception_in_progress(fsg) || signal_pending(current)) {
3070 handle_exception(fsg);
3071 continue;
3072 }
3073
3074 if (!fsg->running) {
3075 sleep_thread(fsg);
3076 continue;
3077 }
3078
3079 if (get_next_command(fsg))
3080 continue;
3081
3082 spin_lock_irq(&fsg->lock);
3083 if (!exception_in_progress(fsg))
3084 fsg->state = FSG_STATE_DATA_PHASE;
3085 spin_unlock_irq(&fsg->lock);
3086
3087 if (do_scsi_command(fsg) || finish_reply(fsg))
3088 continue;
3089
3090 spin_lock_irq(&fsg->lock);
3091 if (!exception_in_progress(fsg))
3092 fsg->state = FSG_STATE_STATUS_PHASE;
3093 spin_unlock_irq(&fsg->lock);
3094
3095 if (send_status(fsg))
3096 continue;
3097
3098 spin_lock_irq(&fsg->lock);
3099 if (!exception_in_progress(fsg))
3100 fsg->state = FSG_STATE_IDLE;
3101 spin_unlock_irq(&fsg->lock);
3102 }
3103
Alan Stern22efcf42005-09-26 16:12:02 -04003104 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003105 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003106 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003107
Alan Stern82a10a82009-04-16 15:37:28 -04003108 /* If we are exiting because of a signal, unregister the
3109 * gadget driver. */
3110 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003111 usb_gadget_unregister_driver(&fsg_driver);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003112
3113 /* Let the unbind and cleanup routines know the thread has exited */
3114 complete_and_exit(&fsg->thread_notifier, 0);
3115}
3116
3117
3118/*-------------------------------------------------------------------------*/
3119
Linus Torvalds1da177e2005-04-16 15:20:36 -07003120
3121/* The write permissions and store_xxx pointers are set in fsg_bind() */
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003122static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003123static DEVICE_ATTR(nofua, 0644, fsg_show_nofua, NULL);
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003124static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003125
3126
3127/*-------------------------------------------------------------------------*/
3128
Alan Stern87c42522005-11-09 16:59:56 -05003129static void fsg_release(struct kref *ref)
3130{
3131 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3132
3133 kfree(fsg->luns);
3134 kfree(fsg);
3135}
3136
Linus Torvalds1da177e2005-04-16 15:20:36 -07003137static void lun_release(struct device *dev)
3138{
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003139 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3140 struct fsg_dev *fsg =
3141 container_of(filesem, struct fsg_dev, filesem);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003142
Alan Stern87c42522005-11-09 16:59:56 -05003143 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003144}
3145
David Brownella3536782006-07-06 15:48:53 -07003146static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003147{
3148 struct fsg_dev *fsg = get_gadget_data(gadget);
3149 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003150 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003151 struct usb_request *req = fsg->ep0req;
3152
3153 DBG(fsg, "unbind\n");
3154 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3155
3156 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003157 for (i = 0; i < fsg->nluns; ++i) {
3158 curlun = &fsg->luns[i];
3159 if (curlun->registered) {
Michal Nazarewicz452ee0e2010-08-12 17:43:50 +02003160 device_remove_file(&curlun->dev, &dev_attr_nofua);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003161 device_remove_file(&curlun->dev, &dev_attr_ro);
3162 device_remove_file(&curlun->dev, &dev_attr_file);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003163 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003164 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003165 curlun->registered = 0;
3166 }
3167 }
3168
3169 /* If the thread isn't already dead, tell it to exit now */
3170 if (fsg->state != FSG_STATE_TERMINATED) {
3171 raise_exception(fsg, FSG_STATE_EXIT);
3172 wait_for_completion(&fsg->thread_notifier);
3173
3174 /* The cleanup routine waits for this completion also */
3175 complete(&fsg->thread_notifier);
3176 }
3177
3178 /* Free the data buffers */
Per Forlin6532c7f2011-08-19 21:21:27 +02003179 for (i = 0; i < fsg_num_buffers; ++i)
David Brownell9d8bab52007-07-01 11:04:54 -07003180 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003181
3182 /* Free the request and buffer for endpoint 0 */
3183 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003184 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003185 usb_ep_free_request(fsg->ep0, req);
3186 }
3187
3188 set_gadget_data(gadget, NULL);
3189}
3190
3191
3192static int __init check_parameters(struct fsg_dev *fsg)
3193{
3194 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003195 int gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003196
3197 /* Store the default values */
3198 mod_data.transport_type = USB_PR_BULK;
3199 mod_data.transport_name = "Bulk-only";
3200 mod_data.protocol_type = USB_SC_SCSI;
3201 mod_data.protocol_name = "Transparent SCSI";
3202
Alan Sternce459ec2009-02-24 16:19:47 -05003203 /* Some peripheral controllers are known not to be able to
3204 * halt bulk endpoints correctly. If one of them is present,
3205 * disable stalls.
3206 */
Christoph Egger90f79762010-02-05 13:24:12 +01003207 if (gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003208 mod_data.can_stall = 0;
3209
3210 if (mod_data.release == 0xffff) { // Parameter wasn't set
Christoph Egger90f79762010-02-05 13:24:12 +01003211 gcnum = usb_gadget_controller_number(fsg->gadget);
David Brownell91e79c92005-07-13 15:18:30 -07003212 if (gcnum >= 0)
3213 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003214 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003215 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003216 fsg->gadget->name);
3217 mod_data.release = 0x0399;
3218 }
3219 }
3220
3221 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3222
3223#ifdef CONFIG_USB_FILE_STORAGE_TEST
3224 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3225 ; // Use default setting
3226 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3227 mod_data.transport_type = USB_PR_CB;
3228 mod_data.transport_name = "Control-Bulk";
3229 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3230 mod_data.transport_type = USB_PR_CBI;
3231 mod_data.transport_name = "Control-Bulk-Interrupt";
3232 } else {
3233 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3234 return -EINVAL;
3235 }
3236
3237 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3238 prot == USB_SC_SCSI) {
3239 ; // Use default setting
3240 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3241 prot == USB_SC_RBC) {
3242 mod_data.protocol_type = USB_SC_RBC;
3243 mod_data.protocol_name = "RBC";
3244 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3245 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3246 prot == USB_SC_8020) {
3247 mod_data.protocol_type = USB_SC_8020;
3248 mod_data.protocol_name = "8020i (ATAPI)";
3249 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3250 prot == USB_SC_QIC) {
3251 mod_data.protocol_type = USB_SC_QIC;
3252 mod_data.protocol_name = "QIC-157";
3253 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3254 prot == USB_SC_UFI) {
3255 mod_data.protocol_type = USB_SC_UFI;
3256 mod_data.protocol_name = "UFI";
3257 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3258 prot == USB_SC_8070) {
3259 mod_data.protocol_type = USB_SC_8070;
3260 mod_data.protocol_name = "8070i";
3261 } else {
3262 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3263 return -EINVAL;
3264 }
3265
3266 mod_data.buflen &= PAGE_CACHE_MASK;
3267 if (mod_data.buflen <= 0) {
3268 ERROR(fsg, "invalid buflen\n");
3269 return -ETOOSMALL;
3270 }
Yann Cantin87eb1be2010-06-05 23:06:31 +02003271
Michal Nazarewicz56706492010-07-22 14:16:37 +02003272#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3273
Yann Cantin87eb1be2010-06-05 23:06:31 +02003274 /* Serial string handling.
3275 * On a real device, the serial string would be loaded
3276 * from permanent storage. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003277 if (mod_data.serial) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003278 const char *ch;
3279 unsigned len = 0;
3280
3281 /* Sanity check :
3282 * The CB[I] specification limits the serial string to
3283 * 12 uppercase hexadecimal characters.
3284 * BBB need at least 12 uppercase hexadecimal characters,
3285 * with a maximum of 126. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003286 for (ch = mod_data.serial; *ch; ++ch) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003287 ++len;
3288 if ((*ch < '0' || *ch > '9') &&
3289 (*ch < 'A' || *ch > 'F')) { /* not uppercase hex */
3290 WARNING(fsg,
Alan Sternd8087422010-09-03 11:15:41 -04003291 "Invalid serial string character: %c\n",
Yann Cantin87eb1be2010-06-05 23:06:31 +02003292 *ch);
Alan Sternd8087422010-09-03 11:15:41 -04003293 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003294 }
3295 }
3296 if (len > 126 ||
3297 (mod_data.transport_type == USB_PR_BULK && len < 12) ||
3298 (mod_data.transport_type != USB_PR_BULK && len > 12)) {
Alan Sternd8087422010-09-03 11:15:41 -04003299 WARNING(fsg, "Invalid serial string length!\n");
3300 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003301 }
Michal Nazarewicz56706492010-07-22 14:16:37 +02003302 fsg_strings[FSG_STRING_SERIAL - 1].s = mod_data.serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003303 } else {
Alan Sternd8087422010-09-03 11:15:41 -04003304 WARNING(fsg, "No serial-number string provided!\n");
3305 no_serial:
3306 device_desc.iSerialNumber = 0;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003307 }
3308
Linus Torvalds1da177e2005-04-16 15:20:36 -07003309 return 0;
3310}
3311
3312
Michal Nazarewicze12995e2010-08-12 17:43:52 +02003313static int __init fsg_bind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003314{
3315 struct fsg_dev *fsg = the_fsg;
3316 int rc;
3317 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003318 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003319 struct usb_ep *ep;
3320 struct usb_request *req;
3321 char *pathbuf, *p;
3322
3323 fsg->gadget = gadget;
3324 set_gadget_data(gadget, fsg);
3325 fsg->ep0 = gadget->ep0;
3326 fsg->ep0->driver_data = fsg;
3327
3328 if ((rc = check_parameters(fsg)) != 0)
3329 goto out;
3330
3331 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003332 dev_attr_file.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003333 dev_attr_file.store = fsg_store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003334 if (!mod_data.cdrom) {
3335 dev_attr_ro.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003336 dev_attr_ro.store = fsg_store_ro;
Alan Stern12aae682008-11-20 14:13:12 -05003337 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003338 }
3339
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003340 /* Only for removable media? */
3341 dev_attr_nofua.attr.mode = 0644;
3342 dev_attr_nofua.store = fsg_store_nofua;
3343
Linus Torvalds1da177e2005-04-16 15:20:36 -07003344 /* Find out how many LUNs there should be */
3345 i = mod_data.nluns;
3346 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003347 i = max(mod_data.num_filenames, 1u);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003348 if (i > FSG_MAX_LUNS) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003349 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3350 rc = -EINVAL;
3351 goto out;
3352 }
3353
3354 /* Create the LUNs, open their backing files, and register the
3355 * LUN devices in sysfs. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003356 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003357 if (!fsg->luns) {
3358 rc = -ENOMEM;
3359 goto out;
3360 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003361 fsg->nluns = i;
3362
3363 for (i = 0; i < fsg->nluns; ++i) {
3364 curlun = &fsg->luns[i];
Michal Nazarewicze909ef52009-10-28 16:57:16 +01003365 curlun->cdrom = !!mod_data.cdrom;
3366 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3367 curlun->initially_ro = curlun->ro;
3368 curlun->removable = mod_data.removable;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003369 curlun->nofua = mod_data.nofua[i];
Alan Stern2de9eae2006-09-25 14:31:15 -04003370 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003371 curlun->dev.parent = &gadget->dev;
3372 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003373 dev_set_drvdata(&curlun->dev, &fsg->filesem);
Kay Sievers0031a062008-05-02 06:02:41 +02003374 dev_set_name(&curlun->dev,"%s-lun%d",
3375 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003376
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003377 kref_get(&fsg->ref);
3378 rc = device_register(&curlun->dev);
3379 if (rc) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003380 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003381 put_device(&curlun->dev);
Alan Stern2de9eae2006-09-25 14:31:15 -04003382 goto out;
3383 }
3384 curlun->registered = 1;
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003385
3386 rc = device_create_file(&curlun->dev, &dev_attr_ro);
3387 if (rc)
3388 goto out;
3389 rc = device_create_file(&curlun->dev, &dev_attr_nofua);
3390 if (rc)
3391 goto out;
3392 rc = device_create_file(&curlun->dev, &dev_attr_file);
3393 if (rc)
3394 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003395
Alan Sternaafe5bd2006-03-31 11:46:43 -05003396 if (mod_data.file[i] && *mod_data.file[i]) {
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003397 rc = fsg_lun_open(curlun, mod_data.file[i]);
3398 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003399 goto out;
3400 } else if (!mod_data.removable) {
3401 ERROR(fsg, "no file given for LUN%d\n", i);
3402 rc = -EINVAL;
3403 goto out;
3404 }
3405 }
3406
3407 /* Find all the endpoints we will use */
3408 usb_ep_autoconfig_reset(gadget);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003409 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003410 if (!ep)
3411 goto autoconf_fail;
3412 ep->driver_data = fsg; // claim the endpoint
3413 fsg->bulk_in = ep;
3414
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003415 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003416 if (!ep)
3417 goto autoconf_fail;
3418 ep->driver_data = fsg; // claim the endpoint
3419 fsg->bulk_out = ep;
3420
3421 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003422 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003423 if (!ep)
3424 goto autoconf_fail;
3425 ep->driver_data = fsg; // claim the endpoint
3426 fsg->intr_in = ep;
3427 }
3428
3429 /* Fix up the descriptors */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003430 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3431 device_desc.idProduct = cpu_to_le16(mod_data.product);
3432 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3433
3434 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003435 fsg_intf_desc.bNumEndpoints = i;
3436 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3437 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3438 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003439
David Brownell2e806f62007-08-02 00:03:39 -07003440 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003441 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003442
David Brownell2e806f62007-08-02 00:03:39 -07003443 /* Assume endpoint addresses are the same for both speeds */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003444 fsg_hs_bulk_in_desc.bEndpointAddress =
3445 fsg_fs_bulk_in_desc.bEndpointAddress;
3446 fsg_hs_bulk_out_desc.bEndpointAddress =
3447 fsg_fs_bulk_out_desc.bEndpointAddress;
3448 fsg_hs_intr_in_desc.bEndpointAddress =
3449 fsg_fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003450 }
3451
Felipe Balbi4bb99b72011-08-03 14:33:27 +03003452 if (gadget_is_superspeed(gadget)) {
3453 unsigned max_burst;
3454
3455 fsg_ss_function[i + FSG_SS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3456
3457 /* Calculate bMaxBurst, we know packet size is 1024 */
3458 max_burst = min_t(unsigned, mod_data.buflen / 1024, 15);
3459
3460 /* Assume endpoint addresses are the same for both speeds */
3461 fsg_ss_bulk_in_desc.bEndpointAddress =
3462 fsg_fs_bulk_in_desc.bEndpointAddress;
3463 fsg_ss_bulk_in_comp_desc.bMaxBurst = max_burst;
3464
3465 fsg_ss_bulk_out_desc.bEndpointAddress =
3466 fsg_fs_bulk_out_desc.bEndpointAddress;
3467 fsg_ss_bulk_out_comp_desc.bMaxBurst = max_burst;
3468 }
3469
David Brownell2e806f62007-08-02 00:03:39 -07003470 if (gadget_is_otg(gadget))
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003471 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
David Brownell2e806f62007-08-02 00:03:39 -07003472
Linus Torvalds1da177e2005-04-16 15:20:36 -07003473 rc = -ENOMEM;
3474
3475 /* Allocate the request and buffer for endpoint 0 */
3476 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3477 if (!req)
3478 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003479 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003480 if (!req->buf)
3481 goto out;
3482 req->complete = ep0_complete;
3483
3484 /* Allocate the data buffers */
Per Forlin6532c7f2011-08-19 21:21:27 +02003485 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003486 struct fsg_buffhd *bh = &fsg->buffhds[i];
3487
Alan Stern14cd5f82006-03-23 15:07:25 -05003488 /* Allocate for the bulk-in endpoint. We assume that
3489 * the buffer will also work with the bulk-out (and
3490 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003491 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003492 if (!bh->buf)
3493 goto out;
3494 bh->next = bh + 1;
3495 }
Per Forlin6532c7f2011-08-19 21:21:27 +02003496 fsg->buffhds[fsg_num_buffers - 1].next = &fsg->buffhds[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07003497
3498 /* This should reflect the actual gadget power source */
3499 usb_gadget_set_selfpowered(gadget);
3500
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003501 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3502 "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003503 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003504 gadget->name);
3505
Alan Stern22efcf42005-09-26 16:12:02 -04003506 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3507 "file-storage-gadget");
3508 if (IS_ERR(fsg->thread_task)) {
3509 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003510 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04003511 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003512
3513 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
Alan Stern664a51a2011-06-15 16:31:37 -04003514 INFO(fsg, "NOTE: This driver is deprecated. "
3515 "Consider using g_mass_storage instead.\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -07003516 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3517
3518 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3519 for (i = 0; i < fsg->nluns; ++i) {
3520 curlun = &fsg->luns[i];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003521 if (fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003522 p = NULL;
3523 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08003524 p = d_path(&curlun->filp->f_path,
3525 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003526 if (IS_ERR(p))
3527 p = NULL;
3528 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003529 LINFO(curlun, "ro=%d, nofua=%d, file: %s\n",
3530 curlun->ro, curlun->nofua, (p ? p : "(error)"));
Linus Torvalds1da177e2005-04-16 15:20:36 -07003531 }
3532 }
3533 kfree(pathbuf);
3534
3535 DBG(fsg, "transport=%s (x%02x)\n",
3536 mod_data.transport_name, mod_data.transport_type);
3537 DBG(fsg, "protocol=%s (x%02x)\n",
3538 mod_data.protocol_name, mod_data.protocol_type);
3539 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3540 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05003541 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003542 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05003543 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07003544 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04003545
3546 set_bit(REGISTERED, &fsg->atomic_bitflags);
3547
3548 /* Tell the thread to start working */
3549 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003550 return 0;
3551
3552autoconf_fail:
3553 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3554 rc = -ENOTSUPP;
3555
3556out:
3557 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3558 fsg_unbind(gadget);
Felipe Balbi889394b2008-12-08 13:50:27 +02003559 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003560 return rc;
3561}
3562
3563
3564/*-------------------------------------------------------------------------*/
3565
3566static void fsg_suspend(struct usb_gadget *gadget)
3567{
3568 struct fsg_dev *fsg = get_gadget_data(gadget);
3569
3570 DBG(fsg, "suspend\n");
3571 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3572}
3573
3574static void fsg_resume(struct usb_gadget *gadget)
3575{
3576 struct fsg_dev *fsg = get_gadget_data(gadget);
3577
3578 DBG(fsg, "resume\n");
3579 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3580}
3581
3582
3583/*-------------------------------------------------------------------------*/
3584
3585static struct usb_gadget_driver fsg_driver = {
Felipe Balbi4bb99b72011-08-03 14:33:27 +03003586 .speed = USB_SPEED_SUPER,
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003587 .function = (char *) fsg_string_product,
David Brownell6bea4762006-12-05 03:15:33 -08003588 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003589 .disconnect = fsg_disconnect,
3590 .setup = fsg_setup,
3591 .suspend = fsg_suspend,
3592 .resume = fsg_resume,
3593
3594 .driver = {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003595 .name = DRIVER_NAME,
Ben Dooksd0d50492005-10-10 10:52:33 +01003596 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003597 // .release = ...
3598 // .suspend = ...
3599 // .resume = ...
3600 },
3601};
3602
3603
3604static int __init fsg_alloc(void)
3605{
3606 struct fsg_dev *fsg;
3607
Per Forlin6532c7f2011-08-19 21:21:27 +02003608 fsg = kzalloc(sizeof *fsg +
3609 fsg_num_buffers * sizeof *(fsg->buffhds), GFP_KERNEL);
3610
Linus Torvalds1da177e2005-04-16 15:20:36 -07003611 if (!fsg)
3612 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003613 spin_lock_init(&fsg->lock);
3614 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05003615 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003616 init_completion(&fsg->thread_notifier);
3617
3618 the_fsg = fsg;
3619 return 0;
3620}
3621
3622
Linus Torvalds1da177e2005-04-16 15:20:36 -07003623static int __init fsg_init(void)
3624{
3625 int rc;
3626 struct fsg_dev *fsg;
3627
Per Forlin6532c7f2011-08-19 21:21:27 +02003628 rc = fsg_num_buffers_validate();
3629 if (rc != 0)
3630 return rc;
3631
Linus Torvalds1da177e2005-04-16 15:20:36 -07003632 if ((rc = fsg_alloc()) != 0)
3633 return rc;
3634 fsg = the_fsg;
Uwe Kleine-Königb0fca502010-08-12 17:43:53 +02003635 if ((rc = usb_gadget_probe_driver(&fsg_driver, fsg_bind)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05003636 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04003637 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003638}
3639module_init(fsg_init);
3640
3641
3642static void __exit fsg_cleanup(void)
3643{
3644 struct fsg_dev *fsg = the_fsg;
3645
3646 /* Unregister the driver iff the thread hasn't already done so */
3647 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3648 usb_gadget_unregister_driver(&fsg_driver);
3649
3650 /* Wait for the thread to finish up */
3651 wait_for_completion(&fsg->thread_notifier);
3652
Alan Stern87c42522005-11-09 16:59:56 -05003653 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003654}
3655module_exit(fsg_cleanup);