blob: a230009db7347ef8562e5ee240aecf75f7661f8e [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
Linus Torvalds1da177e2005-04-16 15:20:36 -0700589
590
591/*
592 * Config descriptors must agree with the code that sets configurations
593 * and with code managing interfaces and their altsettings. They must
594 * also handle different speeds and other-speed requests.
595 */
596static int populate_config_buf(struct usb_gadget *gadget,
597 u8 *buf, u8 type, unsigned index)
598{
Linus Torvalds1da177e2005-04-16 15:20:36 -0700599 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700600 int len;
601 const struct usb_descriptor_header **function;
602
603 if (index > 0)
604 return -EINVAL;
605
David Brownell2e806f62007-08-02 00:03:39 -0700606 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700607 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
Michal Nazarewiczd23b0f02009-11-09 14:15:20 +0100608 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
609 ? (const struct usb_descriptor_header **)fsg_hs_function
610 : (const struct usb_descriptor_header **)fsg_fs_function;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700611
612 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -0700613 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700614 function++;
615
616 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
617 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
618 return len;
619}
620
621
622/*-------------------------------------------------------------------------*/
623
624/* These routines may be called in process context or in_irq */
625
Alan Sterna21d4fe2005-11-29 12:04:24 -0500626/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627static void wakeup_thread(struct fsg_dev *fsg)
628{
629 /* Tell the main thread that something has happened */
630 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500631 if (fsg->thread_task)
632 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700633}
634
635
636static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
637{
638 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700639
640 /* Do nothing if a higher-priority exception is already in progress.
641 * If a lower-or-equal priority exception is in progress, preempt it
642 * and notify the main thread by sending it a signal. */
643 spin_lock_irqsave(&fsg->lock, flags);
644 if (fsg->state <= new_state) {
645 fsg->exception_req_tag = fsg->ep0_req_tag;
646 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -0400647 if (fsg->thread_task)
648 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
649 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700650 }
651 spin_unlock_irqrestore(&fsg->lock, flags);
652}
653
654
655/*-------------------------------------------------------------------------*/
656
657/* The disconnect callback and ep0 routines. These always run in_irq,
658 * except that ep0_queue() is called in the main thread to acknowledge
659 * completion of various requests: set config, set interface, and
660 * Bulk-only device reset. */
661
662static void fsg_disconnect(struct usb_gadget *gadget)
663{
664 struct fsg_dev *fsg = get_gadget_data(gadget);
665
666 DBG(fsg, "disconnect or port reset\n");
667 raise_exception(fsg, FSG_STATE_DISCONNECT);
668}
669
670
671static int ep0_queue(struct fsg_dev *fsg)
672{
673 int rc;
674
675 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
676 if (rc != 0 && rc != -ESHUTDOWN) {
677
678 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -0700679 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680 fsg->ep0->name, rc);
681 }
682 return rc;
683}
684
685static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
686{
John Daiker7ca46b82006-12-29 19:02:06 -0800687 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688
689 if (req->actual > 0)
690 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
691 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800692 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700693 req->status, req->actual, req->length);
694 if (req->status == -ECONNRESET) // Request was cancelled
695 usb_ep_fifo_flush(ep);
696
697 if (req->status == 0 && req->context)
698 ((fsg_routine_t) (req->context))(fsg);
699}
700
701
702/*-------------------------------------------------------------------------*/
703
704/* Bulk and interrupt endpoint completion handlers.
705 * These always run in_irq. */
706
707static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
708{
John Daiker7ca46b82006-12-29 19:02:06 -0800709 struct fsg_dev *fsg = ep->driver_data;
710 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700711
712 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800713 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700714 req->status, req->actual, req->length);
715 if (req->status == -ECONNRESET) // Request was cancelled
716 usb_ep_fifo_flush(ep);
717
718 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500719 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700720 spin_lock(&fsg->lock);
721 bh->inreq_busy = 0;
722 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700723 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500724 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700725}
726
727static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
728{
John Daiker7ca46b82006-12-29 19:02:06 -0800729 struct fsg_dev *fsg = ep->driver_data;
730 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700731
732 dump_msg(fsg, "bulk-out", req->buf, req->actual);
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -0700733 if (req->status || req->actual != bh->bulk_out_intended_length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800734 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -0700735 req->status, req->actual,
736 bh->bulk_out_intended_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700737 if (req->status == -ECONNRESET) // Request was cancelled
738 usb_ep_fifo_flush(ep);
739
740 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500741 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700742 spin_lock(&fsg->lock);
743 bh->outreq_busy = 0;
744 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700745 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500746 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700747}
748
749
750#ifdef CONFIG_USB_FILE_STORAGE_TEST
751static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
752{
John Daiker7ca46b82006-12-29 19:02:06 -0800753 struct fsg_dev *fsg = ep->driver_data;
754 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700755
756 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800757 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700758 req->status, req->actual, req->length);
759 if (req->status == -ECONNRESET) // Request was cancelled
760 usb_ep_fifo_flush(ep);
761
762 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500763 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700764 spin_lock(&fsg->lock);
765 fsg->intreq_busy = 0;
766 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700767 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500768 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700769}
770
771#else
772static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
773{}
774#endif /* CONFIG_USB_FILE_STORAGE_TEST */
775
776
777/*-------------------------------------------------------------------------*/
778
779/* Ep0 class-specific handlers. These always run in_irq. */
780
781#ifdef CONFIG_USB_FILE_STORAGE_TEST
782static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
783{
784 struct usb_request *req = fsg->ep0req;
785 static u8 cbi_reset_cmnd[6] = {
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +0200786 SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
Linus Torvalds1da177e2005-04-16 15:20:36 -0700787
788 /* Error in command transfer? */
789 if (req->status || req->length != req->actual ||
790 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
791
792 /* Not all controllers allow a protocol stall after
793 * receiving control-out data, but we'll try anyway. */
794 fsg_set_halt(fsg, fsg->ep0);
795 return; // Wait for reset
796 }
797
798 /* Is it the special reset command? */
799 if (req->actual >= sizeof cbi_reset_cmnd &&
800 memcmp(req->buf, cbi_reset_cmnd,
801 sizeof cbi_reset_cmnd) == 0) {
802
803 /* Raise an exception to stop the current operation
804 * and reinitialize our state. */
805 DBG(fsg, "cbi reset request\n");
806 raise_exception(fsg, FSG_STATE_RESET);
807 return;
808 }
809
810 VDBG(fsg, "CB[I] accept device-specific command\n");
811 spin_lock(&fsg->lock);
812
813 /* Save the command for later */
814 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700815 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700816 fsg->cbbuf_cmnd_size = req->actual;
817 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
818
Linus Torvalds1da177e2005-04-16 15:20:36 -0700819 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500820 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700821}
822
823#else
824static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
825{}
826#endif /* CONFIG_USB_FILE_STORAGE_TEST */
827
828
829static int class_setup_req(struct fsg_dev *fsg,
830 const struct usb_ctrlrequest *ctrl)
831{
832 struct usb_request *req = fsg->ep0req;
833 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700834 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -0400835 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -0700836 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700837
838 if (!fsg->config)
839 return value;
840
841 /* Handle Bulk-only class-specific requests */
842 if (transport_is_bbb()) {
843 switch (ctrl->bRequest) {
844
845 case USB_BULK_RESET_REQUEST:
846 if (ctrl->bRequestType != (USB_DIR_OUT |
847 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
848 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400849 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700850 value = -EDOM;
851 break;
852 }
853
854 /* Raise an exception to stop the current operation
855 * and reinitialize our state. */
856 DBG(fsg, "bulk reset request\n");
857 raise_exception(fsg, FSG_STATE_RESET);
858 value = DELAYED_STATUS;
859 break;
860
861 case USB_BULK_GET_MAX_LUN_REQUEST:
862 if (ctrl->bRequestType != (USB_DIR_IN |
863 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
864 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400865 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700866 value = -EDOM;
867 break;
868 }
869 VDBG(fsg, "get max LUN\n");
870 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -0400871 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700872 break;
873 }
874 }
875
876 /* Handle CBI class-specific requests */
877 else {
878 switch (ctrl->bRequest) {
879
880 case USB_CBI_ADSC_REQUEST:
881 if (ctrl->bRequestType != (USB_DIR_OUT |
882 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
883 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400884 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700885 value = -EDOM;
886 break;
887 }
888 if (w_length > MAX_COMMAND_SIZE) {
889 value = -EOVERFLOW;
890 break;
891 }
892 value = w_length;
893 fsg->ep0req->context = received_cbi_adsc;
894 break;
895 }
896 }
897
898 if (value == -EOPNOTSUPP)
899 VDBG(fsg,
900 "unknown class-specific control req "
901 "%02x.%02x v%04x i%04x l%u\n",
902 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -0700903 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700904 return value;
905}
906
907
908/*-------------------------------------------------------------------------*/
909
910/* Ep0 standard request handlers. These always run in_irq. */
911
912static int standard_setup_req(struct fsg_dev *fsg,
913 const struct usb_ctrlrequest *ctrl)
914{
915 struct usb_request *req = fsg->ep0req;
916 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700917 u16 w_index = le16_to_cpu(ctrl->wIndex);
918 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700919
920 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
921 * but config change events will also reconfigure hardware. */
922 switch (ctrl->bRequest) {
923
924 case USB_REQ_GET_DESCRIPTOR:
925 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
926 USB_RECIP_DEVICE))
927 break;
928 switch (w_value >> 8) {
929
930 case USB_DT_DEVICE:
931 VDBG(fsg, "get device descriptor\n");
Sebastian Andrzej Siewior765f5b82011-06-23 14:26:11 +0200932 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
Alan Stern76f4af82005-04-05 11:56:54 -0400933 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700934 memcpy(req->buf, &device_desc, value);
935 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936 case USB_DT_DEVICE_QUALIFIER:
937 VDBG(fsg, "get device qualifier\n");
David Brownell2e806f62007-08-02 00:03:39 -0700938 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700939 break;
Sebastian Andrzej Siewior765f5b82011-06-23 14:26:11 +0200940 /*
941 * Assume ep0 uses the same maxpacket value for both
942 * speeds
943 */
944 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Alan Stern76f4af82005-04-05 11:56:54 -0400945 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700946 memcpy(req->buf, &dev_qualifier, value);
947 break;
948
949 case USB_DT_OTHER_SPEED_CONFIG:
950 VDBG(fsg, "get other-speed config descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700951 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700952 break;
953 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700954 case USB_DT_CONFIG:
955 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700956get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700957 value = populate_config_buf(fsg->gadget,
958 req->buf,
959 w_value >> 8,
960 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700961 break;
962
963 case USB_DT_STRING:
964 VDBG(fsg, "get string descriptor\n");
965
966 /* wIndex == language code */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100967 value = usb_gadget_get_string(&fsg_stringtab,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700968 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700969 break;
970 }
971 break;
972
973 /* One config, two speeds */
974 case USB_REQ_SET_CONFIGURATION:
975 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
976 USB_RECIP_DEVICE))
977 break;
978 VDBG(fsg, "set configuration\n");
979 if (w_value == CONFIG_VALUE || w_value == 0) {
980 fsg->new_config = w_value;
981
982 /* Raise an exception to wipe out previous transaction
983 * state (queued bufs, etc) and set the new config. */
984 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
985 value = DELAYED_STATUS;
986 }
987 break;
988 case USB_REQ_GET_CONFIGURATION:
989 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
990 USB_RECIP_DEVICE))
991 break;
992 VDBG(fsg, "get configuration\n");
993 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -0400994 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700995 break;
996
997 case USB_REQ_SET_INTERFACE:
998 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
999 USB_RECIP_INTERFACE))
1000 break;
1001 if (fsg->config && w_index == 0) {
1002
1003 /* Raise an exception to wipe out previous transaction
1004 * state (queued bufs, etc) and install the new
1005 * interface altsetting. */
1006 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1007 value = DELAYED_STATUS;
1008 }
1009 break;
1010 case USB_REQ_GET_INTERFACE:
1011 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1012 USB_RECIP_INTERFACE))
1013 break;
1014 if (!fsg->config)
1015 break;
1016 if (w_index != 0) {
1017 value = -EDOM;
1018 break;
1019 }
1020 VDBG(fsg, "get interface\n");
1021 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001022 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001023 break;
1024
1025 default:
1026 VDBG(fsg,
1027 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1028 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001029 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001030 }
1031
1032 return value;
1033}
1034
1035
1036static int fsg_setup(struct usb_gadget *gadget,
1037 const struct usb_ctrlrequest *ctrl)
1038{
1039 struct fsg_dev *fsg = get_gadget_data(gadget);
1040 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001041 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001042
1043 ++fsg->ep0_req_tag; // Record arrival of a new request
1044 fsg->ep0req->context = NULL;
1045 fsg->ep0req->length = 0;
1046 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1047
1048 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1049 rc = class_setup_req(fsg, ctrl);
1050 else
1051 rc = standard_setup_req(fsg, ctrl);
1052
1053 /* Respond with data/status or defer until later? */
1054 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001055 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001056 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001057 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001058 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1059 "ep0-in" : "ep0-out");
1060 rc = ep0_queue(fsg);
1061 }
1062
1063 /* Device either stalls (rc < 0) or reports success */
1064 return rc;
1065}
1066
1067
1068/*-------------------------------------------------------------------------*/
1069
1070/* All the following routines run in process context */
1071
1072
1073/* Use this for bulk or interrupt transfers, not ep0 */
1074static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001075 struct usb_request *req, int *pbusy,
1076 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001077{
1078 int rc;
1079
1080 if (ep == fsg->bulk_in)
1081 dump_msg(fsg, "bulk-in", req->buf, req->length);
1082 else if (ep == fsg->intr_in)
1083 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001084
1085 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001086 *pbusy = 1;
1087 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001088 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001089 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1090 if (rc != 0) {
1091 *pbusy = 0;
1092 *state = BUF_STATE_EMPTY;
1093
1094 /* We can't do much more than wait for a reset */
1095
1096 /* Note: currently the net2280 driver fails zero-length
1097 * submissions if DMA is enabled. */
1098 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1099 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001100 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001101 ep->name, rc);
1102 }
1103}
1104
1105
1106static int sleep_thread(struct fsg_dev *fsg)
1107{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001108 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001109
1110 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001111 for (;;) {
1112 try_to_freeze();
1113 set_current_state(TASK_INTERRUPTIBLE);
1114 if (signal_pending(current)) {
1115 rc = -EINTR;
1116 break;
1117 }
1118 if (fsg->thread_wakeup_needed)
1119 break;
1120 schedule();
1121 }
1122 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001123 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001124 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001125}
1126
1127
1128/*-------------------------------------------------------------------------*/
1129
1130static int do_read(struct fsg_dev *fsg)
1131{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001132 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001133 u32 lba;
1134 struct fsg_buffhd *bh;
1135 int rc;
1136 u32 amount_left;
1137 loff_t file_offset, file_offset_tmp;
1138 unsigned int amount;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001139 ssize_t nread;
1140
1141 /* Get the starting Logical Block Address and check that it's
1142 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001143 if (fsg->cmnd[0] == READ_6)
Alan Stern604eb892009-04-27 13:19:41 -04001144 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001145 else {
Alan Stern604eb892009-04-27 13:19:41 -04001146 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001147
1148 /* We allow DPO (Disable Page Out = don't save data in the
1149 * cache) and FUA (Force Unit Access = don't read from the
1150 * cache), but we don't implement them. */
1151 if ((fsg->cmnd[1] & ~0x18) != 0) {
1152 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1153 return -EINVAL;
1154 }
1155 }
1156 if (lba >= curlun->num_sectors) {
1157 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1158 return -EINVAL;
1159 }
Peiyu Li3f565a32011-08-17 22:52:59 -07001160 file_offset = ((loff_t) lba) << curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001161
1162 /* Carry out the file reads */
1163 amount_left = fsg->data_size_from_cmnd;
1164 if (unlikely(amount_left == 0))
1165 return -EIO; // No default reply
1166
1167 for (;;) {
1168
1169 /* Figure out how much we need to read:
1170 * Try to read the remaining amount.
1171 * But don't read more than the buffer size.
1172 * And don't try to read past the end of the file.
Alan Stern04eee252011-08-18 14:29:00 -04001173 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001174 amount = min((unsigned int) amount_left, mod_data.buflen);
1175 amount = min((loff_t) amount,
1176 curlun->file_length - file_offset);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001177
1178 /* Wait for the next buffer to become available */
1179 bh = fsg->next_buffhd_to_fill;
1180 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001181 rc = sleep_thread(fsg);
1182 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001183 return rc;
1184 }
1185
1186 /* If we were asked to read past the end of file,
1187 * end with an empty buffer. */
1188 if (amount == 0) {
1189 curlun->sense_data =
1190 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001191 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001192 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001193 bh->inreq->length = 0;
1194 bh->state = BUF_STATE_FULL;
1195 break;
1196 }
1197
1198 /* Perform the read */
1199 file_offset_tmp = file_offset;
1200 nread = vfs_read(curlun->filp,
1201 (char __user *) bh->buf,
1202 amount, &file_offset_tmp);
1203 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1204 (unsigned long long) file_offset,
1205 (int) nread);
1206 if (signal_pending(current))
1207 return -EINTR;
1208
1209 if (nread < 0) {
1210 LDBG(curlun, "error in file read: %d\n",
1211 (int) nread);
1212 nread = 0;
1213 } else if (nread < amount) {
1214 LDBG(curlun, "partial file read: %d/%u\n",
1215 (int) nread, amount);
Peiyu Li3f565a32011-08-17 22:52:59 -07001216 nread = round_down(nread, curlun->blksize);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001217 }
1218 file_offset += nread;
1219 amount_left -= nread;
1220 fsg->residue -= nread;
Alan Stern04eee252011-08-18 14:29:00 -04001221
1222 /* Except at the end of the transfer, nread will be
1223 * equal to the buffer size, which is divisible by the
1224 * bulk-in maxpacket size.
1225 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001226 bh->inreq->length = nread;
1227 bh->state = BUF_STATE_FULL;
1228
1229 /* If an error occurred, report it and its position */
1230 if (nread < amount) {
1231 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
Peiyu Li3f565a32011-08-17 22:52:59 -07001232 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001233 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001234 break;
1235 }
1236
1237 if (amount_left == 0)
1238 break; // No more left to read
1239
1240 /* Send this buffer and go read some more */
1241 bh->inreq->zero = 0;
1242 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1243 &bh->inreq_busy, &bh->state);
1244 fsg->next_buffhd_to_fill = bh->next;
1245 }
1246
1247 return -EIO; // No default reply
1248}
1249
1250
1251/*-------------------------------------------------------------------------*/
1252
1253static int do_write(struct fsg_dev *fsg)
1254{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001255 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001256 u32 lba;
1257 struct fsg_buffhd *bh;
1258 int get_some_more;
1259 u32 amount_left_to_req, amount_left_to_write;
1260 loff_t usb_offset, file_offset, file_offset_tmp;
1261 unsigned int amount;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001262 ssize_t nwritten;
1263 int rc;
1264
1265 if (curlun->ro) {
1266 curlun->sense_data = SS_WRITE_PROTECTED;
1267 return -EINVAL;
1268 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001269 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001270 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001271 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001272
1273 /* Get the starting Logical Block Address and check that it's
1274 * not too big */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001275 if (fsg->cmnd[0] == WRITE_6)
Alan Stern604eb892009-04-27 13:19:41 -04001276 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001277 else {
Alan Stern604eb892009-04-27 13:19:41 -04001278 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001279
1280 /* We allow DPO (Disable Page Out = don't save data in the
1281 * cache) and FUA (Force Unit Access = write directly to the
1282 * medium). We don't implement DPO; we implement FUA by
1283 * performing synchronous output. */
1284 if ((fsg->cmnd[1] & ~0x18) != 0) {
1285 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1286 return -EINVAL;
1287 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03001288 /* FUA */
1289 if (!curlun->nofua && (fsg->cmnd[1] & 0x08)) {
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001290 spin_lock(&curlun->filp->f_lock);
Christoph Hellwig6b2f3d12009-10-27 11:05:28 +01001291 curlun->filp->f_flags |= O_DSYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001292 spin_unlock(&curlun->filp->f_lock);
1293 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001294 }
1295 if (lba >= curlun->num_sectors) {
1296 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1297 return -EINVAL;
1298 }
1299
1300 /* Carry out the file writes */
1301 get_some_more = 1;
Peiyu Li3f565a32011-08-17 22:52:59 -07001302 file_offset = usb_offset = ((loff_t) lba) << curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001303 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1304
1305 while (amount_left_to_write > 0) {
1306
1307 /* Queue a request for more data from the host */
1308 bh = fsg->next_buffhd_to_fill;
1309 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1310
1311 /* Figure out how much we want to get:
Alan Stern04eee252011-08-18 14:29:00 -04001312 * Try to get the remaining amount,
1313 * but not more than the buffer size.
1314 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001315 amount = min(amount_left_to_req, mod_data.buflen);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001316
Alan Stern04eee252011-08-18 14:29:00 -04001317 /* Beyond the end of the backing file? */
1318 if (usb_offset >= curlun->file_length) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001319 get_some_more = 0;
1320 curlun->sense_data =
1321 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001322 curlun->sense_data_info = usb_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001323 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001324 continue;
1325 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001326
1327 /* Get the next buffer */
1328 usb_offset += amount;
1329 fsg->usb_amount_left -= amount;
1330 amount_left_to_req -= amount;
1331 if (amount_left_to_req == 0)
1332 get_some_more = 0;
1333
Alan Stern04eee252011-08-18 14:29:00 -04001334 /* Except at the end of the transfer, amount will be
1335 * equal to the buffer size, which is divisible by
1336 * the bulk-out maxpacket size.
1337 */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001338 set_bulk_out_req_length(fsg, bh, amount);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001339 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1340 &bh->outreq_busy, &bh->state);
1341 fsg->next_buffhd_to_fill = bh->next;
1342 continue;
1343 }
1344
1345 /* Write the received data to the backing file */
1346 bh = fsg->next_buffhd_to_drain;
1347 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1348 break; // We stopped early
1349 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001350 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001351 fsg->next_buffhd_to_drain = bh->next;
1352 bh->state = BUF_STATE_EMPTY;
1353
1354 /* Did something go wrong with the transfer? */
1355 if (bh->outreq->status != 0) {
1356 curlun->sense_data = SS_COMMUNICATION_FAILURE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001357 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001358 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001359 break;
1360 }
1361
1362 amount = bh->outreq->actual;
1363 if (curlun->file_length - file_offset < amount) {
1364 LERROR(curlun,
1365 "write %u @ %llu beyond end %llu\n",
1366 amount, (unsigned long long) file_offset,
1367 (unsigned long long) curlun->file_length);
1368 amount = curlun->file_length - file_offset;
1369 }
1370
Paul Zimmermanfe696762011-09-30 15:26:06 -07001371 /* Don't accept excess data. The spec doesn't say
1372 * what to do in this case. We'll ignore the error.
1373 */
1374 amount = min(amount, bh->bulk_out_intended_length);
1375
Alan Stern04eee252011-08-18 14:29:00 -04001376 /* Don't write a partial block */
1377 amount = round_down(amount, curlun->blksize);
1378 if (amount == 0)
1379 goto empty_write;
1380
Linus Torvalds1da177e2005-04-16 15:20:36 -07001381 /* Perform the write */
1382 file_offset_tmp = file_offset;
1383 nwritten = vfs_write(curlun->filp,
1384 (char __user *) bh->buf,
1385 amount, &file_offset_tmp);
1386 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1387 (unsigned long long) file_offset,
1388 (int) nwritten);
1389 if (signal_pending(current))
1390 return -EINTR; // Interrupted!
1391
1392 if (nwritten < 0) {
1393 LDBG(curlun, "error in file write: %d\n",
1394 (int) nwritten);
1395 nwritten = 0;
1396 } else if (nwritten < amount) {
1397 LDBG(curlun, "partial file write: %d/%u\n",
1398 (int) nwritten, amount);
Peiyu Li3f565a32011-08-17 22:52:59 -07001399 nwritten = round_down(nwritten, curlun->blksize);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001400 }
1401 file_offset += nwritten;
1402 amount_left_to_write -= nwritten;
1403 fsg->residue -= nwritten;
1404
1405 /* If an error occurred, report it and its position */
1406 if (nwritten < amount) {
1407 curlun->sense_data = SS_WRITE_ERROR;
Peiyu Li3f565a32011-08-17 22:52:59 -07001408 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001409 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001410 break;
1411 }
1412
Alan Stern04eee252011-08-18 14:29:00 -04001413 empty_write:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001414 /* Did the host decide to stop early? */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001415 if (bh->outreq->actual < bh->bulk_out_intended_length) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001416 fsg->short_packet_received = 1;
1417 break;
1418 }
1419 continue;
1420 }
1421
1422 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001423 rc = sleep_thread(fsg);
1424 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001425 return rc;
1426 }
1427
1428 return -EIO; // No default reply
1429}
1430
1431
1432/*-------------------------------------------------------------------------*/
1433
Linus Torvalds1da177e2005-04-16 15:20:36 -07001434static int do_synchronize_cache(struct fsg_dev *fsg)
1435{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001436 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001437 int rc;
1438
1439 /* We ignore the requested LBA and write out all file's
1440 * dirty data buffers. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001441 rc = fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001442 if (rc)
1443 curlun->sense_data = SS_WRITE_ERROR;
1444 return 0;
1445}
1446
1447
1448/*-------------------------------------------------------------------------*/
1449
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001450static void invalidate_sub(struct fsg_lun *curlun)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001451{
1452 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001453 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001454 unsigned long rc;
1455
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001456 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01001457 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001458}
1459
1460static int do_verify(struct fsg_dev *fsg)
1461{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001462 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001463 u32 lba;
1464 u32 verification_length;
1465 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1466 loff_t file_offset, file_offset_tmp;
1467 u32 amount_left;
1468 unsigned int amount;
1469 ssize_t nread;
1470
1471 /* Get the starting Logical Block Address and check that it's
1472 * not too big */
Alan Stern604eb892009-04-27 13:19:41 -04001473 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001474 if (lba >= curlun->num_sectors) {
1475 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1476 return -EINVAL;
1477 }
1478
1479 /* We allow DPO (Disable Page Out = don't save data in the
1480 * cache) but we don't implement it. */
1481 if ((fsg->cmnd[1] & ~0x10) != 0) {
1482 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1483 return -EINVAL;
1484 }
1485
Alan Stern604eb892009-04-27 13:19:41 -04001486 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001487 if (unlikely(verification_length == 0))
1488 return -EIO; // No default reply
1489
1490 /* Prepare to carry out the file verify */
Peiyu Li3f565a32011-08-17 22:52:59 -07001491 amount_left = verification_length << curlun->blkbits;
1492 file_offset = ((loff_t) lba) << curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001493
1494 /* Write out all the dirty buffers before invalidating them */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001495 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001496 if (signal_pending(current))
1497 return -EINTR;
1498
1499 invalidate_sub(curlun);
1500 if (signal_pending(current))
1501 return -EINTR;
1502
1503 /* Just try to read the requested blocks */
1504 while (amount_left > 0) {
1505
1506 /* Figure out how much we need to read:
1507 * Try to read the remaining amount, but not more than
1508 * the buffer size.
1509 * And don't try to read past the end of the file.
Alan Stern04eee252011-08-18 14:29:00 -04001510 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001511 amount = min((unsigned int) amount_left, mod_data.buflen);
1512 amount = min((loff_t) amount,
1513 curlun->file_length - file_offset);
1514 if (amount == 0) {
1515 curlun->sense_data =
1516 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
Peiyu Li3f565a32011-08-17 22:52:59 -07001517 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001518 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001519 break;
1520 }
1521
1522 /* Perform the read */
1523 file_offset_tmp = file_offset;
1524 nread = vfs_read(curlun->filp,
1525 (char __user *) bh->buf,
1526 amount, &file_offset_tmp);
1527 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1528 (unsigned long long) file_offset,
1529 (int) nread);
1530 if (signal_pending(current))
1531 return -EINTR;
1532
1533 if (nread < 0) {
1534 LDBG(curlun, "error in file verify: %d\n",
1535 (int) nread);
1536 nread = 0;
1537 } else if (nread < amount) {
1538 LDBG(curlun, "partial file verify: %d/%u\n",
1539 (int) nread, amount);
Peiyu Li3f565a32011-08-17 22:52:59 -07001540 nread = round_down(nread, curlun->blksize);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001541 }
1542 if (nread == 0) {
1543 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
Peiyu Li3f565a32011-08-17 22:52:59 -07001544 curlun->sense_data_info = file_offset >> curlun->blkbits;
Alan Stern6174d0f2006-09-26 14:51:48 -04001545 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001546 break;
1547 }
1548 file_offset += nread;
1549 amount_left -= nread;
1550 }
1551 return 0;
1552}
1553
1554
1555/*-------------------------------------------------------------------------*/
1556
1557static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1558{
1559 u8 *buf = (u8 *) bh->buf;
1560
1561 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05001562 static char product_disk_id[] = "File-Stor Gadget";
1563 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07001564
1565 if (!fsg->curlun) { // Unsupported LUNs are okay
1566 fsg->bad_lun_okay = 1;
1567 memset(buf, 0, 36);
1568 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05001569 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07001570 return 36;
1571 }
1572
Alan Stern12aae682008-11-20 14:13:12 -05001573 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001574 buf[0] = (mod_data.cdrom ? TYPE_ROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001575 if (mod_data.removable)
1576 buf[1] = 0x80;
1577 buf[2] = 2; // ANSI SCSI level 2
1578 buf[3] = 2; // SCSI-2 INQUIRY data format
1579 buf[4] = 31; // Additional length
1580 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05001581 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1582 (mod_data.cdrom ? product_cdrom_id :
1583 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001584 mod_data.release);
1585 return 36;
1586}
1587
1588
1589static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1590{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001591 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001592 u8 *buf = (u8 *) bh->buf;
1593 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04001594 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001595
1596 /*
1597 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1598 *
1599 * If a REQUEST SENSE command is received from an initiator
1600 * with a pending unit attention condition (before the target
1601 * generates the contingent allegiance condition), then the
1602 * target shall either:
1603 * a) report any pending sense data and preserve the unit
1604 * attention condition on the logical unit, or,
1605 * b) report the unit attention condition, may discard any
1606 * pending sense data, and clear the unit attention
1607 * condition on the logical unit for that initiator.
1608 *
1609 * FSG normally uses option a); enable this code to use option b).
1610 */
1611#if 0
1612 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1613 curlun->sense_data = curlun->unit_attention_data;
1614 curlun->unit_attention_data = SS_NO_SENSE;
1615 }
1616#endif
1617
1618 if (!curlun) { // Unsupported LUNs are okay
1619 fsg->bad_lun_okay = 1;
1620 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1621 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001622 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001623 } else {
1624 sd = curlun->sense_data;
1625 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04001626 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001627 curlun->sense_data = SS_NO_SENSE;
1628 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001629 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001630 }
1631
1632 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04001633 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07001634 buf[2] = SK(sd);
Alan Stern604eb892009-04-27 13:19:41 -04001635 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001636 buf[7] = 18 - 8; // Additional sense length
1637 buf[12] = ASC(sd);
1638 buf[13] = ASCQ(sd);
1639 return 18;
1640}
1641
1642
1643static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1644{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001645 struct fsg_lun *curlun = fsg->curlun;
Alan Stern604eb892009-04-27 13:19:41 -04001646 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001647 int pmi = fsg->cmnd[8];
1648 u8 *buf = (u8 *) bh->buf;
1649
1650 /* Check the PMI and LBA fields */
1651 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1652 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1653 return -EINVAL;
1654 }
1655
Alan Stern604eb892009-04-27 13:19:41 -04001656 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1657 /* Max logical block */
Peiyu Li3f565a32011-08-17 22:52:59 -07001658 put_unaligned_be32(curlun->blksize, &buf[4]); /* Block length */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001659 return 8;
1660}
1661
1662
Alan Stern12aae682008-11-20 14:13:12 -05001663static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1664{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001665 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001666 int msf = fsg->cmnd[1] & 0x02;
Alan Stern604eb892009-04-27 13:19:41 -04001667 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Alan Stern12aae682008-11-20 14:13:12 -05001668 u8 *buf = (u8 *) bh->buf;
1669
1670 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1671 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1672 return -EINVAL;
1673 }
1674 if (lba >= curlun->num_sectors) {
1675 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1676 return -EINVAL;
1677 }
1678
1679 memset(buf, 0, 8);
1680 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1681 store_cdrom_address(&buf[4], msf, lba);
1682 return 8;
1683}
1684
1685
1686static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1687{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001688 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001689 int msf = fsg->cmnd[1] & 0x02;
1690 int start_track = fsg->cmnd[6];
1691 u8 *buf = (u8 *) bh->buf;
1692
1693 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1694 start_track > 1) {
1695 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1696 return -EINVAL;
1697 }
1698
1699 memset(buf, 0, 20);
1700 buf[1] = (20-2); /* TOC data length */
1701 buf[2] = 1; /* First track number */
1702 buf[3] = 1; /* Last track number */
1703 buf[5] = 0x16; /* Data track, copying allowed */
1704 buf[6] = 0x01; /* Only track is number 1 */
1705 store_cdrom_address(&buf[8], msf, 0);
1706
1707 buf[13] = 0x16; /* Lead-out track is data */
1708 buf[14] = 0xAA; /* Lead-out track number */
1709 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1710 return 20;
1711}
1712
1713
Linus Torvalds1da177e2005-04-16 15:20:36 -07001714static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1715{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001716 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001717 int mscmnd = fsg->cmnd[0];
1718 u8 *buf = (u8 *) bh->buf;
1719 u8 *buf0 = buf;
1720 int pc, page_code;
1721 int changeable_values, all_pages;
1722 int valid_page = 0;
1723 int len, limit;
1724
1725 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1726 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1727 return -EINVAL;
1728 }
1729 pc = fsg->cmnd[2] >> 6;
1730 page_code = fsg->cmnd[2] & 0x3f;
1731 if (pc == 3) {
1732 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1733 return -EINVAL;
1734 }
1735 changeable_values = (pc == 1);
1736 all_pages = (page_code == 0x3f);
1737
1738 /* Write the mode parameter header. Fixed values are: default
1739 * medium type, no cache control (DPOFUA), and no block descriptors.
1740 * The only variable value is the WriteProtect bit. We will fill in
1741 * the mode data length later. */
1742 memset(buf, 0, 8);
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001743 if (mscmnd == MODE_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001744 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1745 buf += 4;
1746 limit = 255;
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001747 } else { // MODE_SENSE_10
Linus Torvalds1da177e2005-04-16 15:20:36 -07001748 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1749 buf += 8;
1750 limit = 65535; // Should really be mod_data.buflen
1751 }
1752
1753 /* No block descriptors */
1754
1755 /* The mode pages, in numerical order. The only page we support
1756 * is the Caching page. */
1757 if (page_code == 0x08 || all_pages) {
1758 valid_page = 1;
1759 buf[0] = 0x08; // Page code
1760 buf[1] = 10; // Page length
1761 memset(buf+2, 0, 10); // None of the fields are changeable
1762
1763 if (!changeable_values) {
1764 buf[2] = 0x04; // Write cache enable,
1765 // Read cache not disabled
1766 // No cache retention priorities
Alan Stern604eb892009-04-27 13:19:41 -04001767 put_unaligned_be16(0xffff, &buf[4]);
1768 /* Don't disable prefetch */
1769 /* Minimum prefetch = 0 */
1770 put_unaligned_be16(0xffff, &buf[8]);
1771 /* Maximum prefetch */
1772 put_unaligned_be16(0xffff, &buf[10]);
1773 /* Maximum prefetch ceiling */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001774 }
1775 buf += 12;
1776 }
1777
1778 /* Check that a valid page was requested and the mode data length
1779 * isn't too long. */
1780 len = buf - buf0;
1781 if (!valid_page || len > limit) {
1782 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1783 return -EINVAL;
1784 }
1785
1786 /* Store the mode data length */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02001787 if (mscmnd == MODE_SENSE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001788 buf0[0] = len - 1;
1789 else
Alan Stern604eb892009-04-27 13:19:41 -04001790 put_unaligned_be16(len - 2, buf0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001791 return len;
1792}
1793
1794
1795static int do_start_stop(struct fsg_dev *fsg)
1796{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001797 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001798 int loej, start;
1799
1800 if (!mod_data.removable) {
1801 curlun->sense_data = SS_INVALID_COMMAND;
1802 return -EINVAL;
1803 }
1804
1805 // int immed = fsg->cmnd[1] & 0x01;
1806 loej = fsg->cmnd[4] & 0x02;
1807 start = fsg->cmnd[4] & 0x01;
1808
1809#ifdef CONFIG_USB_FILE_STORAGE_TEST
1810 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1811 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1812 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1813 return -EINVAL;
1814 }
1815
1816 if (!start) {
1817
1818 /* Are we allowed to unload the media? */
1819 if (curlun->prevent_medium_removal) {
1820 LDBG(curlun, "unload attempt prevented\n");
1821 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1822 return -EINVAL;
1823 }
1824 if (loej) { // Simulate an unload/eject
1825 up_read(&fsg->filesem);
1826 down_write(&fsg->filesem);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001827 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001828 up_write(&fsg->filesem);
1829 down_read(&fsg->filesem);
1830 }
1831 } else {
1832
1833 /* Our emulation doesn't support mounting; the medium is
1834 * available for use as soon as it is loaded. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001835 if (!fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001836 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1837 return -EINVAL;
1838 }
1839 }
1840#endif
1841 return 0;
1842}
1843
1844
1845static int do_prevent_allow(struct fsg_dev *fsg)
1846{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001847 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001848 int prevent;
1849
1850 if (!mod_data.removable) {
1851 curlun->sense_data = SS_INVALID_COMMAND;
1852 return -EINVAL;
1853 }
1854
1855 prevent = fsg->cmnd[4] & 0x01;
1856 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1857 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1858 return -EINVAL;
1859 }
1860
1861 if (curlun->prevent_medium_removal && !prevent)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001862 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001863 curlun->prevent_medium_removal = prevent;
1864 return 0;
1865}
1866
1867
1868static int do_read_format_capacities(struct fsg_dev *fsg,
1869 struct fsg_buffhd *bh)
1870{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001871 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001872 u8 *buf = (u8 *) bh->buf;
1873
1874 buf[0] = buf[1] = buf[2] = 0;
1875 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1876 buf += 4;
1877
Alan Stern604eb892009-04-27 13:19:41 -04001878 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1879 /* Number of blocks */
Peiyu Li3f565a32011-08-17 22:52:59 -07001880 put_unaligned_be32(curlun->blksize, &buf[4]); /* Block length */
Alan Stern604eb892009-04-27 13:19:41 -04001881 buf[4] = 0x02; /* Current capacity */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001882 return 12;
1883}
1884
1885
1886static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1887{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001888 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001889
1890 /* We don't support MODE SELECT */
1891 curlun->sense_data = SS_INVALID_COMMAND;
1892 return -EINVAL;
1893}
1894
1895
1896/*-------------------------------------------------------------------------*/
1897
1898static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1899{
1900 int rc;
1901
1902 rc = fsg_set_halt(fsg, fsg->bulk_in);
1903 if (rc == -EAGAIN)
1904 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1905 while (rc != 0) {
1906 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001907 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001908 rc = 0;
1909 break;
1910 }
1911
1912 /* Wait for a short time and then try again */
1913 if (msleep_interruptible(100) != 0)
1914 return -EINTR;
1915 rc = usb_ep_set_halt(fsg->bulk_in);
1916 }
1917 return rc;
1918}
1919
David Lopo62fd2ca2008-04-29 10:14:38 +01001920static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1921{
1922 int rc;
1923
1924 DBG(fsg, "bulk-in set wedge\n");
1925 rc = usb_ep_set_wedge(fsg->bulk_in);
1926 if (rc == -EAGAIN)
1927 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1928 while (rc != 0) {
1929 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001930 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01001931 rc = 0;
1932 break;
1933 }
1934
1935 /* Wait for a short time and then try again */
1936 if (msleep_interruptible(100) != 0)
1937 return -EINTR;
1938 rc = usb_ep_set_wedge(fsg->bulk_in);
1939 }
1940 return rc;
1941}
1942
Linus Torvalds1da177e2005-04-16 15:20:36 -07001943static int throw_away_data(struct fsg_dev *fsg)
1944{
1945 struct fsg_buffhd *bh;
1946 u32 amount;
1947 int rc;
1948
1949 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1950 fsg->usb_amount_left > 0) {
1951
1952 /* Throw away the data in a filled buffer */
1953 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001954 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001955 bh->state = BUF_STATE_EMPTY;
1956 fsg->next_buffhd_to_drain = bh->next;
1957
1958 /* A short packet or an error ends everything */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001959 if (bh->outreq->actual < bh->bulk_out_intended_length ||
Linus Torvalds1da177e2005-04-16 15:20:36 -07001960 bh->outreq->status != 0) {
1961 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1962 return -EINTR;
1963 }
1964 continue;
1965 }
1966
1967 /* Try to submit another request if we need one */
1968 bh = fsg->next_buffhd_to_fill;
1969 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1970 amount = min(fsg->usb_amount_left,
1971 (u32) mod_data.buflen);
1972
Alan Stern04eee252011-08-18 14:29:00 -04001973 /* Except at the end of the transfer, amount will be
1974 * equal to the buffer size, which is divisible by
1975 * the bulk-out maxpacket size.
1976 */
Paul Zimmermanfe696762011-09-30 15:26:06 -07001977 set_bulk_out_req_length(fsg, bh, amount);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001978 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1979 &bh->outreq_busy, &bh->state);
1980 fsg->next_buffhd_to_fill = bh->next;
1981 fsg->usb_amount_left -= amount;
1982 continue;
1983 }
1984
1985 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001986 rc = sleep_thread(fsg);
1987 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001988 return rc;
1989 }
1990 return 0;
1991}
1992
1993
1994static int finish_reply(struct fsg_dev *fsg)
1995{
1996 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1997 int rc = 0;
1998
1999 switch (fsg->data_dir) {
2000 case DATA_DIR_NONE:
2001 break; // Nothing to send
2002
2003 /* If we don't know whether the host wants to read or write,
2004 * this must be CB or CBI with an unknown command. We mustn't
2005 * try to send or receive any data. So stall both bulk pipes
2006 * if we can and wait for a reset. */
2007 case DATA_DIR_UNKNOWN:
2008 if (mod_data.can_stall) {
2009 fsg_set_halt(fsg, fsg->bulk_out);
2010 rc = halt_bulk_in_endpoint(fsg);
2011 }
2012 break;
2013
2014 /* All but the last buffer of data must have already been sent */
2015 case DATA_DIR_TO_HOST:
2016 if (fsg->data_size == 0)
2017 ; // Nothing to send
2018
2019 /* If there's no residue, simply send the last buffer */
2020 else if (fsg->residue == 0) {
2021 bh->inreq->zero = 0;
2022 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2023 &bh->inreq_busy, &bh->state);
2024 fsg->next_buffhd_to_fill = bh->next;
2025 }
2026
2027 /* There is a residue. For CB and CBI, simply mark the end
2028 * of the data with a short packet. However, if we are
2029 * allowed to stall, there was no data at all (residue ==
2030 * data_size), and the command failed (invalid LUN or
2031 * sense data is set), then halt the bulk-in endpoint
2032 * instead. */
2033 else if (!transport_is_bbb()) {
2034 if (mod_data.can_stall &&
2035 fsg->residue == fsg->data_size &&
2036 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2037 bh->state = BUF_STATE_EMPTY;
2038 rc = halt_bulk_in_endpoint(fsg);
2039 } else {
2040 bh->inreq->zero = 1;
2041 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2042 &bh->inreq_busy, &bh->state);
2043 fsg->next_buffhd_to_fill = bh->next;
2044 }
2045 }
2046
Alan Sternee81b3e2011-03-25 11:46:27 -04002047 /*
2048 * For Bulk-only, mark the end of the data with a short
2049 * packet. If we are allowed to stall, halt the bulk-in
2050 * endpoint. (Note: This violates the Bulk-Only Transport
2051 * specification, which requires us to pad the data if we
2052 * don't halt the endpoint. Presumably nobody will mind.)
2053 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002054 else {
Alan Sternee81b3e2011-03-25 11:46:27 -04002055 bh->inreq->zero = 1;
2056 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2057 &bh->inreq_busy, &bh->state);
2058 fsg->next_buffhd_to_fill = bh->next;
2059 if (mod_data.can_stall)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002060 rc = halt_bulk_in_endpoint(fsg);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002061 }
2062 break;
2063
2064 /* We have processed all we want from the data the host has sent.
2065 * There may still be outstanding bulk-out requests. */
2066 case DATA_DIR_FROM_HOST:
2067 if (fsg->residue == 0)
2068 ; // Nothing to receive
2069
2070 /* Did the host stop sending unexpectedly early? */
2071 else if (fsg->short_packet_received) {
2072 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2073 rc = -EINTR;
2074 }
2075
2076 /* We haven't processed all the incoming data. Even though
2077 * we may be allowed to stall, doing so would cause a race.
2078 * The controller may already have ACK'ed all the remaining
2079 * bulk-out packets, in which case the host wouldn't see a
2080 * STALL. Not realizing the endpoint was halted, it wouldn't
2081 * clear the halt -- leading to problems later on. */
2082#if 0
2083 else if (mod_data.can_stall) {
2084 fsg_set_halt(fsg, fsg->bulk_out);
2085 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2086 rc = -EINTR;
2087 }
2088#endif
2089
2090 /* We can't stall. Read in the excess data and throw it
2091 * all away. */
2092 else
2093 rc = throw_away_data(fsg);
2094 break;
2095 }
2096 return rc;
2097}
2098
2099
2100static int send_status(struct fsg_dev *fsg)
2101{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002102 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002103 struct fsg_buffhd *bh;
2104 int rc;
2105 u8 status = USB_STATUS_PASS;
2106 u32 sd, sdinfo = 0;
2107
2108 /* Wait for the next buffer to become available */
2109 bh = fsg->next_buffhd_to_fill;
2110 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002111 rc = sleep_thread(fsg);
2112 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002113 return rc;
2114 }
2115
2116 if (curlun) {
2117 sd = curlun->sense_data;
2118 sdinfo = curlun->sense_data_info;
2119 } else if (fsg->bad_lun_okay)
2120 sd = SS_NO_SENSE;
2121 else
2122 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2123
2124 if (fsg->phase_error) {
2125 DBG(fsg, "sending phase-error status\n");
2126 status = USB_STATUS_PHASE_ERROR;
2127 sd = SS_INVALID_COMMAND;
2128 } else if (sd != SS_NO_SENSE) {
2129 DBG(fsg, "sending command-failure status\n");
2130 status = USB_STATUS_FAIL;
2131 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2132 " info x%x\n",
2133 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2134 }
2135
2136 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002137 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002138
2139 /* Store and send the Bulk-only CSW */
Harvey Harrison551509d2009-02-11 14:11:36 -08002140 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002141 csw->Tag = fsg->tag;
2142 csw->Residue = cpu_to_le32(fsg->residue);
2143 csw->Status = status;
2144
2145 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2146 bh->inreq->zero = 0;
2147 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2148 &bh->inreq_busy, &bh->state);
2149
2150 } else if (mod_data.transport_type == USB_PR_CB) {
2151
2152 /* Control-Bulk transport has no status phase! */
2153 return 0;
2154
2155 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002156 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002157
2158 /* Store and send the Interrupt data. UFI sends the ASC
2159 * and ASCQ bytes. Everything else sends a Type (which
2160 * is always 0) and the status Value. */
2161 if (mod_data.protocol_type == USB_SC_UFI) {
2162 buf->bType = ASC(sd);
2163 buf->bValue = ASCQ(sd);
2164 } else {
2165 buf->bType = 0;
2166 buf->bValue = status;
2167 }
2168 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2169
2170 fsg->intr_buffhd = bh; // Point to the right buffhd
2171 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002172 fsg->intreq->context = bh;
2173 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2174 &fsg->intreq_busy, &bh->state);
2175 }
2176
2177 fsg->next_buffhd_to_fill = bh->next;
2178 return 0;
2179}
2180
2181
2182/*-------------------------------------------------------------------------*/
2183
2184/* Check whether the command is properly formed and whether its data size
2185 * and direction agree with the values we already have. */
2186static int check_command(struct fsg_dev *fsg, int cmnd_size,
2187 enum data_direction data_dir, unsigned int mask,
2188 int needs_medium, const char *name)
2189{
2190 int i;
2191 int lun = fsg->cmnd[1] >> 5;
2192 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2193 char hdlen[20];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002194 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002195
2196 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2197 * Transparent SCSI doesn't pad. */
2198 if (protocol_is_scsi())
2199 ;
2200
2201 /* There's some disagreement as to whether RBC pads commands or not.
2202 * We'll play it safe and accept either form. */
2203 else if (mod_data.protocol_type == USB_SC_RBC) {
2204 if (fsg->cmnd_size == 12)
2205 cmnd_size = 12;
2206
2207 /* All the other protocols pad to 12 bytes */
2208 } else
2209 cmnd_size = 12;
2210
2211 hdlen[0] = 0;
2212 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2213 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2214 fsg->data_size);
2215 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2216 name, cmnd_size, dirletter[(int) data_dir],
2217 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2218
2219 /* We can't reply at all until we know the correct data direction
2220 * and size. */
2221 if (fsg->data_size_from_cmnd == 0)
2222 data_dir = DATA_DIR_NONE;
2223 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2224 fsg->data_dir = data_dir;
2225 fsg->data_size = fsg->data_size_from_cmnd;
2226
2227 } else { // Bulk-only
2228 if (fsg->data_size < fsg->data_size_from_cmnd) {
2229
2230 /* Host data size < Device data size is a phase error.
2231 * Carry out the command, but only transfer as much
2232 * as we are allowed. */
2233 fsg->data_size_from_cmnd = fsg->data_size;
2234 fsg->phase_error = 1;
2235 }
2236 }
2237 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2238
2239 /* Conflicting data directions is a phase error */
2240 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2241 fsg->phase_error = 1;
2242 return -EINVAL;
2243 }
2244
2245 /* Verify the length of the command itself */
2246 if (cmnd_size != fsg->cmnd_size) {
2247
Felipe Balbi549c41e2008-09-19 02:00:02 +03002248 /* Special case workaround: There are plenty of buggy SCSI
2249 * implementations. Many have issues with cbw->Length
2250 * field passing a wrong command size. For those cases we
2251 * always try to work around the problem by using the length
2252 * sent by the host side provided it is at least as large
2253 * as the correct command length.
2254 * Examples of such cases would be MS-Windows, which issues
2255 * REQUEST SENSE with cbw->Length == 12 where it should
2256 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2257 * REQUEST SENSE with cbw->Length == 10 where it should
2258 * be 6 as well.
2259 */
2260 if (cmnd_size <= fsg->cmnd_size) {
2261 DBG(fsg, "%s is buggy! Expected length %d "
2262 "but we got %d\n", name,
2263 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002264 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002265 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002266 fsg->phase_error = 1;
2267 return -EINVAL;
2268 }
2269 }
2270
Alan Sternd794ac72005-04-18 12:43:25 -04002271 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002272 if (transport_is_bbb()) {
2273 if (fsg->lun != lun)
2274 DBG(fsg, "using LUN %d from CBW, "
2275 "not LUN %d from CDB\n",
2276 fsg->lun, lun);
2277 } else
2278 fsg->lun = lun; // Use LUN from the command
2279
2280 /* Check the LUN */
Maxin B John849426c2011-05-08 15:56:17 +03002281 if (fsg->lun < fsg->nluns) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002282 fsg->curlun = curlun = &fsg->luns[fsg->lun];
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002283 if (fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002284 curlun->sense_data = SS_NO_SENSE;
2285 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002286 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002287 }
2288 } else {
2289 fsg->curlun = curlun = NULL;
2290 fsg->bad_lun_okay = 0;
2291
2292 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2293 * to use unsupported LUNs; all others may not. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002294 if (fsg->cmnd[0] != INQUIRY &&
2295 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002296 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2297 return -EINVAL;
2298 }
2299 }
2300
2301 /* If a unit attention condition exists, only INQUIRY and
2302 * REQUEST SENSE commands are allowed; anything else must fail. */
2303 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002304 fsg->cmnd[0] != INQUIRY &&
2305 fsg->cmnd[0] != REQUEST_SENSE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002306 curlun->sense_data = curlun->unit_attention_data;
2307 curlun->unit_attention_data = SS_NO_SENSE;
2308 return -EINVAL;
2309 }
2310
2311 /* Check that only command bytes listed in the mask are non-zero */
2312 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2313 for (i = 1; i < cmnd_size; ++i) {
2314 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2315 if (curlun)
2316 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2317 return -EINVAL;
2318 }
2319 }
2320
2321 /* If the medium isn't mounted and the command needs to access
2322 * it, return an error. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002323 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002324 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2325 return -EINVAL;
2326 }
2327
2328 return 0;
2329}
2330
2331
2332static int do_scsi_command(struct fsg_dev *fsg)
2333{
2334 struct fsg_buffhd *bh;
2335 int rc;
2336 int reply = -EINVAL;
2337 int i;
2338 static char unknown[16];
2339
2340 dump_cdb(fsg);
2341
2342 /* Wait for the next buffer to become available for data or status */
2343 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2344 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002345 rc = sleep_thread(fsg);
2346 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002347 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002348 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002349 fsg->phase_error = 0;
2350 fsg->short_packet_received = 0;
2351
2352 down_read(&fsg->filesem); // We're using the backing file
2353 switch (fsg->cmnd[0]) {
2354
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002355 case INQUIRY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002356 fsg->data_size_from_cmnd = fsg->cmnd[4];
2357 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2358 (1<<4), 0,
2359 "INQUIRY")) == 0)
2360 reply = do_inquiry(fsg, bh);
2361 break;
2362
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002363 case MODE_SELECT:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002364 fsg->data_size_from_cmnd = fsg->cmnd[4];
2365 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2366 (1<<1) | (1<<4), 0,
2367 "MODE SELECT(6)")) == 0)
2368 reply = do_mode_select(fsg, bh);
2369 break;
2370
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002371 case MODE_SELECT_10:
Alan Stern604eb892009-04-27 13:19:41 -04002372 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002373 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2374 (1<<1) | (3<<7), 0,
2375 "MODE SELECT(10)")) == 0)
2376 reply = do_mode_select(fsg, bh);
2377 break;
2378
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002379 case MODE_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380 fsg->data_size_from_cmnd = fsg->cmnd[4];
2381 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2382 (1<<1) | (1<<2) | (1<<4), 0,
2383 "MODE SENSE(6)")) == 0)
2384 reply = do_mode_sense(fsg, bh);
2385 break;
2386
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002387 case MODE_SENSE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002388 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002389 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2390 (1<<1) | (1<<2) | (3<<7), 0,
2391 "MODE SENSE(10)")) == 0)
2392 reply = do_mode_sense(fsg, bh);
2393 break;
2394
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002395 case ALLOW_MEDIUM_REMOVAL:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002396 fsg->data_size_from_cmnd = 0;
2397 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2398 (1<<4), 0,
2399 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2400 reply = do_prevent_allow(fsg);
2401 break;
2402
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002403 case READ_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002404 i = fsg->cmnd[4];
Peiyu Li3f565a32011-08-17 22:52:59 -07002405 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002406 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2407 (7<<1) | (1<<4), 1,
2408 "READ(6)")) == 0)
2409 reply = do_read(fsg);
2410 break;
2411
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002412 case READ_10:
Alan Stern604eb892009-04-27 13:19:41 -04002413 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002414 get_unaligned_be16(&fsg->cmnd[7]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002415 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2416 (1<<1) | (0xf<<2) | (3<<7), 1,
2417 "READ(10)")) == 0)
2418 reply = do_read(fsg);
2419 break;
2420
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002421 case READ_12:
Alan Stern604eb892009-04-27 13:19:41 -04002422 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002423 get_unaligned_be32(&fsg->cmnd[6]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002424 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2425 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2426 "READ(12)")) == 0)
2427 reply = do_read(fsg);
2428 break;
2429
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002430 case READ_CAPACITY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002431 fsg->data_size_from_cmnd = 8;
2432 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2433 (0xf<<2) | (1<<8), 1,
2434 "READ CAPACITY")) == 0)
2435 reply = do_read_capacity(fsg, bh);
2436 break;
2437
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002438 case READ_HEADER:
Alan Stern12aae682008-11-20 14:13:12 -05002439 if (!mod_data.cdrom)
2440 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002441 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002442 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2443 (3<<7) | (0x1f<<1), 1,
2444 "READ HEADER")) == 0)
2445 reply = do_read_header(fsg, bh);
2446 break;
2447
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002448 case READ_TOC:
Alan Stern12aae682008-11-20 14:13:12 -05002449 if (!mod_data.cdrom)
2450 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002451 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002452 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2453 (7<<6) | (1<<1), 1,
2454 "READ TOC")) == 0)
2455 reply = do_read_toc(fsg, bh);
2456 break;
2457
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002458 case READ_FORMAT_CAPACITIES:
Alan Stern604eb892009-04-27 13:19:41 -04002459 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002460 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2461 (3<<7), 1,
2462 "READ FORMAT CAPACITIES")) == 0)
2463 reply = do_read_format_capacities(fsg, bh);
2464 break;
2465
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002466 case REQUEST_SENSE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002467 fsg->data_size_from_cmnd = fsg->cmnd[4];
2468 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2469 (1<<4), 0,
2470 "REQUEST SENSE")) == 0)
2471 reply = do_request_sense(fsg, bh);
2472 break;
2473
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002474 case START_STOP:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002475 fsg->data_size_from_cmnd = 0;
2476 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2477 (1<<1) | (1<<4), 0,
2478 "START-STOP UNIT")) == 0)
2479 reply = do_start_stop(fsg);
2480 break;
2481
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002482 case SYNCHRONIZE_CACHE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002483 fsg->data_size_from_cmnd = 0;
2484 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2485 (0xf<<2) | (3<<7), 1,
2486 "SYNCHRONIZE CACHE")) == 0)
2487 reply = do_synchronize_cache(fsg);
2488 break;
2489
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002490 case TEST_UNIT_READY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002491 fsg->data_size_from_cmnd = 0;
2492 reply = check_command(fsg, 6, DATA_DIR_NONE,
2493 0, 1,
2494 "TEST UNIT READY");
2495 break;
2496
2497 /* Although optional, this command is used by MS-Windows. We
2498 * support a minimal version: BytChk must be 0. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002499 case VERIFY:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002500 fsg->data_size_from_cmnd = 0;
2501 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2502 (1<<1) | (0xf<<2) | (3<<7), 1,
2503 "VERIFY")) == 0)
2504 reply = do_verify(fsg);
2505 break;
2506
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002507 case WRITE_6:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002508 i = fsg->cmnd[4];
Peiyu Li3f565a32011-08-17 22:52:59 -07002509 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002510 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2511 (7<<1) | (1<<4), 1,
2512 "WRITE(6)")) == 0)
2513 reply = do_write(fsg);
2514 break;
2515
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002516 case WRITE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002517 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002518 get_unaligned_be16(&fsg->cmnd[7]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002519 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2520 (1<<1) | (0xf<<2) | (3<<7), 1,
2521 "WRITE(10)")) == 0)
2522 reply = do_write(fsg);
2523 break;
2524
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002525 case WRITE_12:
Alan Stern604eb892009-04-27 13:19:41 -04002526 fsg->data_size_from_cmnd =
Peiyu Li3f565a32011-08-17 22:52:59 -07002527 get_unaligned_be32(&fsg->cmnd[6]) << fsg->curlun->blkbits;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002528 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2529 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2530 "WRITE(12)")) == 0)
2531 reply = do_write(fsg);
2532 break;
2533
2534 /* Some mandatory commands that we recognize but don't implement.
2535 * They don't mean much in this setting. It's left as an exercise
2536 * for anyone interested to implement RESERVE and RELEASE in terms
2537 * of Posix locks. */
Michal Nazarewicz0a6a7172010-10-07 14:46:15 +02002538 case FORMAT_UNIT:
2539 case RELEASE:
2540 case RESERVE:
2541 case SEND_DIAGNOSTIC:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002542 // Fall through
2543
2544 default:
Alan Stern12aae682008-11-20 14:13:12 -05002545 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002546 fsg->data_size_from_cmnd = 0;
2547 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2548 if ((reply = check_command(fsg, fsg->cmnd_size,
2549 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2550 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2551 reply = -EINVAL;
2552 }
2553 break;
2554 }
2555 up_read(&fsg->filesem);
2556
2557 if (reply == -EINTR || signal_pending(current))
2558 return -EINTR;
2559
2560 /* Set up the single reply buffer for finish_reply() */
2561 if (reply == -EINVAL)
2562 reply = 0; // Error reply length
2563 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2564 reply = min((u32) reply, fsg->data_size_from_cmnd);
2565 bh->inreq->length = reply;
2566 bh->state = BUF_STATE_FULL;
2567 fsg->residue -= reply;
2568 } // Otherwise it's already set
2569
2570 return 0;
2571}
2572
2573
2574/*-------------------------------------------------------------------------*/
2575
2576static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2577{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002578 struct usb_request *req = bh->outreq;
2579 struct fsg_bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002580
Alan Sternb950bdb2008-04-14 11:45:29 -04002581 /* Was this a real packet? Should it be ignored? */
2582 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002583 return -EINVAL;
2584
2585 /* Is the CBW valid? */
2586 if (req->actual != USB_BULK_CB_WRAP_LEN ||
Harvey Harrison551509d2009-02-11 14:11:36 -08002587 cbw->Signature != cpu_to_le32(
Linus Torvalds1da177e2005-04-16 15:20:36 -07002588 USB_BULK_CB_SIG)) {
2589 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2590 req->actual,
2591 le32_to_cpu(cbw->Signature));
2592
Alan Sternb950bdb2008-04-14 11:45:29 -04002593 /* The Bulk-only spec says we MUST stall the IN endpoint
2594 * (6.6.1), so it's unavoidable. It also says we must
2595 * retain this state until the next reset, but there's
2596 * no way to tell the controller driver it should ignore
2597 * Clear-Feature(HALT) requests.
2598 *
2599 * We aren't required to halt the OUT endpoint; instead
2600 * we can simply accept and discard any data received
2601 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01002602 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04002603 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002604 return -EINVAL;
2605 }
2606
2607 /* Is the CBW meaningful? */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002608 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04002609 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002610 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2611 "cmdlen %u\n",
2612 cbw->Lun, cbw->Flags, cbw->Length);
2613
2614 /* We can do anything we want here, so let's stall the
2615 * bulk pipes if we are allowed to. */
2616 if (mod_data.can_stall) {
2617 fsg_set_halt(fsg, fsg->bulk_out);
2618 halt_bulk_in_endpoint(fsg);
2619 }
2620 return -EINVAL;
2621 }
2622
2623 /* Save the command for later */
2624 fsg->cmnd_size = cbw->Length;
2625 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2626 if (cbw->Flags & USB_BULK_IN_FLAG)
2627 fsg->data_dir = DATA_DIR_TO_HOST;
2628 else
2629 fsg->data_dir = DATA_DIR_FROM_HOST;
2630 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2631 if (fsg->data_size == 0)
2632 fsg->data_dir = DATA_DIR_NONE;
2633 fsg->lun = cbw->Lun;
2634 fsg->tag = cbw->Tag;
2635 return 0;
2636}
2637
2638
2639static int get_next_command(struct fsg_dev *fsg)
2640{
2641 struct fsg_buffhd *bh;
2642 int rc = 0;
2643
2644 if (transport_is_bbb()) {
2645
2646 /* Wait for the next buffer to become available */
2647 bh = fsg->next_buffhd_to_fill;
2648 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002649 rc = sleep_thread(fsg);
2650 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002651 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002652 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002653
2654 /* Queue a request to read a Bulk-only CBW */
Greg Kroah-Hartman98346f72011-04-14 13:42:46 -07002655 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002656 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2657 &bh->outreq_busy, &bh->state);
2658
2659 /* We will drain the buffer in software, which means we
2660 * can reuse it for the next filling. No need to advance
2661 * next_buffhd_to_fill. */
2662
2663 /* Wait for the CBW to arrive */
2664 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002665 rc = sleep_thread(fsg);
2666 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002667 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002668 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05002669 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002670 rc = received_cbw(fsg, bh);
2671 bh->state = BUF_STATE_EMPTY;
2672
2673 } else { // USB_PR_CB or USB_PR_CBI
2674
2675 /* Wait for the next command to arrive */
2676 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002677 rc = sleep_thread(fsg);
2678 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002679 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002680 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002681
2682 /* Is the previous status interrupt request still busy?
2683 * The host is allowed to skip reading the status,
2684 * so we must cancel it. */
2685 if (fsg->intreq_busy)
2686 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2687
2688 /* Copy the command and mark the buffer empty */
2689 fsg->data_dir = DATA_DIR_UNKNOWN;
2690 spin_lock_irq(&fsg->lock);
2691 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2692 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2693 fsg->cbbuf_cmnd_size = 0;
2694 spin_unlock_irq(&fsg->lock);
2695 }
2696 return rc;
2697}
2698
2699
2700/*-------------------------------------------------------------------------*/
2701
2702static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2703 const struct usb_endpoint_descriptor *d)
2704{
2705 int rc;
2706
2707 ep->driver_data = fsg;
Tatyana Brokhman72c973d2011-06-28 16:33:48 +03002708 ep->desc = d;
2709 rc = usb_ep_enable(ep);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002710 if (rc)
2711 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2712 return rc;
2713}
2714
2715static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2716 struct usb_request **preq)
2717{
2718 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2719 if (*preq)
2720 return 0;
2721 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2722 return -ENOMEM;
2723}
2724
2725/*
2726 * Reset interface setting and re-init endpoint state (toggle etc).
2727 * Call with altsetting < 0 to disable the interface. The only other
2728 * available altsetting is 0, which enables the interface.
2729 */
2730static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2731{
2732 int rc = 0;
2733 int i;
2734 const struct usb_endpoint_descriptor *d;
2735
2736 if (fsg->running)
2737 DBG(fsg, "reset interface\n");
2738
2739reset:
2740 /* Deallocate the requests */
Per Forlin6532c7f2011-08-19 21:21:27 +02002741 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002742 struct fsg_buffhd *bh = &fsg->buffhds[i];
2743
2744 if (bh->inreq) {
2745 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2746 bh->inreq = NULL;
2747 }
2748 if (bh->outreq) {
2749 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2750 bh->outreq = NULL;
2751 }
2752 }
2753 if (fsg->intreq) {
2754 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2755 fsg->intreq = NULL;
2756 }
2757
2758 /* Disable the endpoints */
2759 if (fsg->bulk_in_enabled) {
2760 usb_ep_disable(fsg->bulk_in);
2761 fsg->bulk_in_enabled = 0;
2762 }
2763 if (fsg->bulk_out_enabled) {
2764 usb_ep_disable(fsg->bulk_out);
2765 fsg->bulk_out_enabled = 0;
2766 }
2767 if (fsg->intr_in_enabled) {
2768 usb_ep_disable(fsg->intr_in);
2769 fsg->intr_in_enabled = 0;
2770 }
2771
2772 fsg->running = 0;
2773 if (altsetting < 0 || rc != 0)
2774 return rc;
2775
2776 DBG(fsg, "set interface %d\n", altsetting);
2777
2778 /* Enable the endpoints */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002779 d = fsg_ep_desc(fsg->gadget,
2780 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002781 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2782 goto reset;
2783 fsg->bulk_in_enabled = 1;
2784
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002785 d = fsg_ep_desc(fsg->gadget,
2786 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002787 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2788 goto reset;
2789 fsg->bulk_out_enabled = 1;
Kuninori Morimoto29cc8892011-08-23 03:12:03 -07002790 fsg->bulk_out_maxpacket = usb_endpoint_maxp(d);
Alan Sternb950bdb2008-04-14 11:45:29 -04002791 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002792
2793 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002794 d = fsg_ep_desc(fsg->gadget,
2795 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002796 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2797 goto reset;
2798 fsg->intr_in_enabled = 1;
2799 }
2800
2801 /* Allocate the requests */
Per Forlin6532c7f2011-08-19 21:21:27 +02002802 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002803 struct fsg_buffhd *bh = &fsg->buffhds[i];
2804
2805 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2806 goto reset;
2807 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2808 goto reset;
2809 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002810 bh->inreq->context = bh->outreq->context = bh;
2811 bh->inreq->complete = bulk_in_complete;
2812 bh->outreq->complete = bulk_out_complete;
2813 }
2814 if (transport_is_cbi()) {
2815 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2816 goto reset;
2817 fsg->intreq->complete = intr_in_complete;
2818 }
2819
2820 fsg->running = 1;
2821 for (i = 0; i < fsg->nluns; ++i)
2822 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2823 return rc;
2824}
2825
2826
2827/*
2828 * Change our operational configuration. This code must agree with the code
2829 * that returns config descriptors, and with interface altsetting code.
2830 *
2831 * It's also responsible for power management interactions. Some
2832 * configurations might not work with our current power sources.
2833 * For now we just assume the gadget is always self-powered.
2834 */
2835static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2836{
2837 int rc = 0;
2838
2839 /* Disable the single interface */
2840 if (fsg->config != 0) {
2841 DBG(fsg, "reset config\n");
2842 fsg->config = 0;
2843 rc = do_set_interface(fsg, -1);
2844 }
2845
2846 /* Enable the interface */
2847 if (new_config != 0) {
2848 fsg->config = new_config;
2849 if ((rc = do_set_interface(fsg, 0)) != 0)
2850 fsg->config = 0; // Reset on errors
Michal Nazarewicze538dfd2011-08-30 17:11:19 +02002851 else
2852 INFO(fsg, "%s config #%d\n",
2853 usb_speed_string(fsg->gadget->speed),
2854 fsg->config);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002855 }
2856 return rc;
2857}
2858
2859
2860/*-------------------------------------------------------------------------*/
2861
2862static void handle_exception(struct fsg_dev *fsg)
2863{
2864 siginfo_t info;
2865 int sig;
2866 int i;
2867 int num_active;
2868 struct fsg_buffhd *bh;
2869 enum fsg_state old_state;
2870 u8 new_config;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002871 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002872 unsigned int exception_req_tag;
2873 int rc;
2874
2875 /* Clear the existing signals. Anything but SIGUSR1 is converted
2876 * into a high-priority EXIT exception. */
2877 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04002878 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002879 if (!sig)
2880 break;
2881 if (sig != SIGUSR1) {
2882 if (fsg->state < FSG_STATE_EXIT)
2883 DBG(fsg, "Main thread exiting on signal\n");
2884 raise_exception(fsg, FSG_STATE_EXIT);
2885 }
2886 }
2887
2888 /* Cancel all the pending transfers */
2889 if (fsg->intreq_busy)
2890 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
Per Forlin6532c7f2011-08-19 21:21:27 +02002891 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002892 bh = &fsg->buffhds[i];
2893 if (bh->inreq_busy)
2894 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2895 if (bh->outreq_busy)
2896 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2897 }
2898
2899 /* Wait until everything is idle */
2900 for (;;) {
2901 num_active = fsg->intreq_busy;
Per Forlin6532c7f2011-08-19 21:21:27 +02002902 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002903 bh = &fsg->buffhds[i];
2904 num_active += bh->inreq_busy + bh->outreq_busy;
2905 }
2906 if (num_active == 0)
2907 break;
2908 if (sleep_thread(fsg))
2909 return;
2910 }
2911
2912 /* Clear out the controller's fifos */
2913 if (fsg->bulk_in_enabled)
2914 usb_ep_fifo_flush(fsg->bulk_in);
2915 if (fsg->bulk_out_enabled)
2916 usb_ep_fifo_flush(fsg->bulk_out);
2917 if (fsg->intr_in_enabled)
2918 usb_ep_fifo_flush(fsg->intr_in);
2919
2920 /* Reset the I/O buffer states and pointers, the SCSI
2921 * state, and the exception. Then invoke the handler. */
2922 spin_lock_irq(&fsg->lock);
2923
Per Forlin6532c7f2011-08-19 21:21:27 +02002924 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002925 bh = &fsg->buffhds[i];
2926 bh->state = BUF_STATE_EMPTY;
2927 }
2928 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2929 &fsg->buffhds[0];
2930
2931 exception_req_tag = fsg->exception_req_tag;
2932 new_config = fsg->new_config;
2933 old_state = fsg->state;
2934
2935 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2936 fsg->state = FSG_STATE_STATUS_PHASE;
2937 else {
2938 for (i = 0; i < fsg->nluns; ++i) {
2939 curlun = &fsg->luns[i];
2940 curlun->prevent_medium_removal = 0;
2941 curlun->sense_data = curlun->unit_attention_data =
2942 SS_NO_SENSE;
2943 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002944 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002945 }
2946 fsg->state = FSG_STATE_IDLE;
2947 }
2948 spin_unlock_irq(&fsg->lock);
2949
2950 /* Carry out any extra actions required for the exception */
2951 switch (old_state) {
2952 default:
2953 break;
2954
2955 case FSG_STATE_ABORT_BULK_OUT:
2956 send_status(fsg);
2957 spin_lock_irq(&fsg->lock);
2958 if (fsg->state == FSG_STATE_STATUS_PHASE)
2959 fsg->state = FSG_STATE_IDLE;
2960 spin_unlock_irq(&fsg->lock);
2961 break;
2962
2963 case FSG_STATE_RESET:
2964 /* In case we were forced against our will to halt a
2965 * bulk endpoint, clear the halt now. (The SuperH UDC
2966 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04002967 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002968 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002969
2970 if (transport_is_bbb()) {
2971 if (fsg->ep0_req_tag == exception_req_tag)
2972 ep0_queue(fsg); // Complete the status stage
2973
2974 } else if (transport_is_cbi())
2975 send_status(fsg); // Status by interrupt pipe
2976
2977 /* Technically this should go here, but it would only be
2978 * a waste of time. Ditto for the INTERFACE_CHANGE and
2979 * CONFIG_CHANGE cases. */
2980 // for (i = 0; i < fsg->nluns; ++i)
2981 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2982 break;
2983
2984 case FSG_STATE_INTERFACE_CHANGE:
2985 rc = do_set_interface(fsg, 0);
2986 if (fsg->ep0_req_tag != exception_req_tag)
2987 break;
2988 if (rc != 0) // STALL on errors
2989 fsg_set_halt(fsg, fsg->ep0);
2990 else // Complete the status stage
2991 ep0_queue(fsg);
2992 break;
2993
2994 case FSG_STATE_CONFIG_CHANGE:
2995 rc = do_set_config(fsg, new_config);
2996 if (fsg->ep0_req_tag != exception_req_tag)
2997 break;
2998 if (rc != 0) // STALL on errors
2999 fsg_set_halt(fsg, fsg->ep0);
3000 else // Complete the status stage
3001 ep0_queue(fsg);
3002 break;
3003
3004 case FSG_STATE_DISCONNECT:
Michal Nazarewiczb6058d02009-10-28 16:57:14 +01003005 for (i = 0; i < fsg->nluns; ++i)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003006 fsg_lun_fsync_sub(fsg->luns + i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003007 do_set_config(fsg, 0); // Unconfigured state
3008 break;
3009
3010 case FSG_STATE_EXIT:
3011 case FSG_STATE_TERMINATED:
3012 do_set_config(fsg, 0); // Free resources
3013 spin_lock_irq(&fsg->lock);
3014 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3015 spin_unlock_irq(&fsg->lock);
3016 break;
3017 }
3018}
3019
3020
3021/*-------------------------------------------------------------------------*/
3022
3023static int fsg_main_thread(void *fsg_)
3024{
John Daiker7ca46b82006-12-29 19:02:06 -08003025 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003026
Linus Torvalds1da177e2005-04-16 15:20:36 -07003027 /* Allow the thread to be killed by a signal, but set the signal mask
3028 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003029 allow_signal(SIGINT);
3030 allow_signal(SIGTERM);
3031 allow_signal(SIGKILL);
3032 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003033
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003034 /* Allow the thread to be frozen */
3035 set_freezable();
3036
Linus Torvalds1da177e2005-04-16 15:20:36 -07003037 /* Arrange for userspace references to be interpreted as kernel
3038 * pointers. That way we can pass a kernel pointer to a routine
3039 * that expects a __user pointer and it will work okay. */
3040 set_fs(get_ds());
3041
Linus Torvalds1da177e2005-04-16 15:20:36 -07003042 /* The main loop */
3043 while (fsg->state != FSG_STATE_TERMINATED) {
3044 if (exception_in_progress(fsg) || signal_pending(current)) {
3045 handle_exception(fsg);
3046 continue;
3047 }
3048
3049 if (!fsg->running) {
3050 sleep_thread(fsg);
3051 continue;
3052 }
3053
3054 if (get_next_command(fsg))
3055 continue;
3056
3057 spin_lock_irq(&fsg->lock);
3058 if (!exception_in_progress(fsg))
3059 fsg->state = FSG_STATE_DATA_PHASE;
3060 spin_unlock_irq(&fsg->lock);
3061
3062 if (do_scsi_command(fsg) || finish_reply(fsg))
3063 continue;
3064
3065 spin_lock_irq(&fsg->lock);
3066 if (!exception_in_progress(fsg))
3067 fsg->state = FSG_STATE_STATUS_PHASE;
3068 spin_unlock_irq(&fsg->lock);
3069
3070 if (send_status(fsg))
3071 continue;
3072
3073 spin_lock_irq(&fsg->lock);
3074 if (!exception_in_progress(fsg))
3075 fsg->state = FSG_STATE_IDLE;
3076 spin_unlock_irq(&fsg->lock);
3077 }
3078
Alan Stern22efcf42005-09-26 16:12:02 -04003079 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003080 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003081 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003082
Alan Stern82a10a82009-04-16 15:37:28 -04003083 /* If we are exiting because of a signal, unregister the
3084 * gadget driver. */
3085 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003086 usb_gadget_unregister_driver(&fsg_driver);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003087
3088 /* Let the unbind and cleanup routines know the thread has exited */
3089 complete_and_exit(&fsg->thread_notifier, 0);
3090}
3091
3092
3093/*-------------------------------------------------------------------------*/
3094
Linus Torvalds1da177e2005-04-16 15:20:36 -07003095
3096/* The write permissions and store_xxx pointers are set in fsg_bind() */
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003097static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003098static DEVICE_ATTR(nofua, 0644, fsg_show_nofua, NULL);
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003099static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003100
3101
3102/*-------------------------------------------------------------------------*/
3103
Alan Stern87c42522005-11-09 16:59:56 -05003104static void fsg_release(struct kref *ref)
3105{
3106 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3107
3108 kfree(fsg->luns);
3109 kfree(fsg);
3110}
3111
Linus Torvalds1da177e2005-04-16 15:20:36 -07003112static void lun_release(struct device *dev)
3113{
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003114 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3115 struct fsg_dev *fsg =
3116 container_of(filesem, struct fsg_dev, filesem);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003117
Alan Stern87c42522005-11-09 16:59:56 -05003118 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003119}
3120
David Brownella3536782006-07-06 15:48:53 -07003121static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003122{
3123 struct fsg_dev *fsg = get_gadget_data(gadget);
3124 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003125 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003126 struct usb_request *req = fsg->ep0req;
3127
3128 DBG(fsg, "unbind\n");
3129 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3130
3131 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003132 for (i = 0; i < fsg->nluns; ++i) {
3133 curlun = &fsg->luns[i];
3134 if (curlun->registered) {
Michal Nazarewicz452ee0e2010-08-12 17:43:50 +02003135 device_remove_file(&curlun->dev, &dev_attr_nofua);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003136 device_remove_file(&curlun->dev, &dev_attr_ro);
3137 device_remove_file(&curlun->dev, &dev_attr_file);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003138 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003139 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003140 curlun->registered = 0;
3141 }
3142 }
3143
3144 /* If the thread isn't already dead, tell it to exit now */
3145 if (fsg->state != FSG_STATE_TERMINATED) {
3146 raise_exception(fsg, FSG_STATE_EXIT);
3147 wait_for_completion(&fsg->thread_notifier);
3148
3149 /* The cleanup routine waits for this completion also */
3150 complete(&fsg->thread_notifier);
3151 }
3152
3153 /* Free the data buffers */
Per Forlin6532c7f2011-08-19 21:21:27 +02003154 for (i = 0; i < fsg_num_buffers; ++i)
David Brownell9d8bab52007-07-01 11:04:54 -07003155 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003156
3157 /* Free the request and buffer for endpoint 0 */
3158 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003159 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003160 usb_ep_free_request(fsg->ep0, req);
3161 }
3162
3163 set_gadget_data(gadget, NULL);
3164}
3165
3166
3167static int __init check_parameters(struct fsg_dev *fsg)
3168{
3169 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003170 int gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003171
3172 /* Store the default values */
3173 mod_data.transport_type = USB_PR_BULK;
3174 mod_data.transport_name = "Bulk-only";
3175 mod_data.protocol_type = USB_SC_SCSI;
3176 mod_data.protocol_name = "Transparent SCSI";
3177
Alan Sternce459ec2009-02-24 16:19:47 -05003178 /* Some peripheral controllers are known not to be able to
3179 * halt bulk endpoints correctly. If one of them is present,
3180 * disable stalls.
3181 */
Christoph Egger90f79762010-02-05 13:24:12 +01003182 if (gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003183 mod_data.can_stall = 0;
3184
3185 if (mod_data.release == 0xffff) { // Parameter wasn't set
Christoph Egger90f79762010-02-05 13:24:12 +01003186 gcnum = usb_gadget_controller_number(fsg->gadget);
David Brownell91e79c92005-07-13 15:18:30 -07003187 if (gcnum >= 0)
3188 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003189 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003190 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003191 fsg->gadget->name);
3192 mod_data.release = 0x0399;
3193 }
3194 }
3195
3196 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3197
3198#ifdef CONFIG_USB_FILE_STORAGE_TEST
3199 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3200 ; // Use default setting
3201 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3202 mod_data.transport_type = USB_PR_CB;
3203 mod_data.transport_name = "Control-Bulk";
3204 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3205 mod_data.transport_type = USB_PR_CBI;
3206 mod_data.transport_name = "Control-Bulk-Interrupt";
3207 } else {
3208 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3209 return -EINVAL;
3210 }
3211
3212 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3213 prot == USB_SC_SCSI) {
3214 ; // Use default setting
3215 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3216 prot == USB_SC_RBC) {
3217 mod_data.protocol_type = USB_SC_RBC;
3218 mod_data.protocol_name = "RBC";
3219 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3220 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3221 prot == USB_SC_8020) {
3222 mod_data.protocol_type = USB_SC_8020;
3223 mod_data.protocol_name = "8020i (ATAPI)";
3224 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3225 prot == USB_SC_QIC) {
3226 mod_data.protocol_type = USB_SC_QIC;
3227 mod_data.protocol_name = "QIC-157";
3228 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3229 prot == USB_SC_UFI) {
3230 mod_data.protocol_type = USB_SC_UFI;
3231 mod_data.protocol_name = "UFI";
3232 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3233 prot == USB_SC_8070) {
3234 mod_data.protocol_type = USB_SC_8070;
3235 mod_data.protocol_name = "8070i";
3236 } else {
3237 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3238 return -EINVAL;
3239 }
3240
3241 mod_data.buflen &= PAGE_CACHE_MASK;
3242 if (mod_data.buflen <= 0) {
3243 ERROR(fsg, "invalid buflen\n");
3244 return -ETOOSMALL;
3245 }
Yann Cantin87eb1be2010-06-05 23:06:31 +02003246
Michal Nazarewicz56706492010-07-22 14:16:37 +02003247#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3248
Yann Cantin87eb1be2010-06-05 23:06:31 +02003249 /* Serial string handling.
3250 * On a real device, the serial string would be loaded
3251 * from permanent storage. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003252 if (mod_data.serial) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003253 const char *ch;
3254 unsigned len = 0;
3255
3256 /* Sanity check :
3257 * The CB[I] specification limits the serial string to
3258 * 12 uppercase hexadecimal characters.
3259 * BBB need at least 12 uppercase hexadecimal characters,
3260 * with a maximum of 126. */
Michal Nazarewicz56706492010-07-22 14:16:37 +02003261 for (ch = mod_data.serial; *ch; ++ch) {
Yann Cantin87eb1be2010-06-05 23:06:31 +02003262 ++len;
3263 if ((*ch < '0' || *ch > '9') &&
3264 (*ch < 'A' || *ch > 'F')) { /* not uppercase hex */
3265 WARNING(fsg,
Alan Sternd8087422010-09-03 11:15:41 -04003266 "Invalid serial string character: %c\n",
Yann Cantin87eb1be2010-06-05 23:06:31 +02003267 *ch);
Alan Sternd8087422010-09-03 11:15:41 -04003268 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003269 }
3270 }
3271 if (len > 126 ||
3272 (mod_data.transport_type == USB_PR_BULK && len < 12) ||
3273 (mod_data.transport_type != USB_PR_BULK && len > 12)) {
Alan Sternd8087422010-09-03 11:15:41 -04003274 WARNING(fsg, "Invalid serial string length!\n");
3275 goto no_serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003276 }
Michal Nazarewicz56706492010-07-22 14:16:37 +02003277 fsg_strings[FSG_STRING_SERIAL - 1].s = mod_data.serial;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003278 } else {
Alan Sternd8087422010-09-03 11:15:41 -04003279 WARNING(fsg, "No serial-number string provided!\n");
3280 no_serial:
3281 device_desc.iSerialNumber = 0;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003282 }
3283
Linus Torvalds1da177e2005-04-16 15:20:36 -07003284 return 0;
3285}
3286
3287
Michal Nazarewicze12995e2010-08-12 17:43:52 +02003288static int __init fsg_bind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003289{
3290 struct fsg_dev *fsg = the_fsg;
3291 int rc;
3292 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003293 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003294 struct usb_ep *ep;
3295 struct usb_request *req;
3296 char *pathbuf, *p;
3297
3298 fsg->gadget = gadget;
3299 set_gadget_data(gadget, fsg);
3300 fsg->ep0 = gadget->ep0;
3301 fsg->ep0->driver_data = fsg;
3302
3303 if ((rc = check_parameters(fsg)) != 0)
3304 goto out;
3305
3306 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003307 dev_attr_file.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003308 dev_attr_file.store = fsg_store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003309 if (!mod_data.cdrom) {
3310 dev_attr_ro.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003311 dev_attr_ro.store = fsg_store_ro;
Alan Stern12aae682008-11-20 14:13:12 -05003312 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003313 }
3314
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003315 /* Only for removable media? */
3316 dev_attr_nofua.attr.mode = 0644;
3317 dev_attr_nofua.store = fsg_store_nofua;
3318
Linus Torvalds1da177e2005-04-16 15:20:36 -07003319 /* Find out how many LUNs there should be */
3320 i = mod_data.nluns;
3321 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003322 i = max(mod_data.num_filenames, 1u);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003323 if (i > FSG_MAX_LUNS) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003324 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3325 rc = -EINVAL;
3326 goto out;
3327 }
3328
3329 /* Create the LUNs, open their backing files, and register the
3330 * LUN devices in sysfs. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003331 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003332 if (!fsg->luns) {
3333 rc = -ENOMEM;
3334 goto out;
3335 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003336 fsg->nluns = i;
3337
3338 for (i = 0; i < fsg->nluns; ++i) {
3339 curlun = &fsg->luns[i];
Michal Nazarewicze909ef52009-10-28 16:57:16 +01003340 curlun->cdrom = !!mod_data.cdrom;
3341 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3342 curlun->initially_ro = curlun->ro;
3343 curlun->removable = mod_data.removable;
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003344 curlun->nofua = mod_data.nofua[i];
Alan Stern2de9eae2006-09-25 14:31:15 -04003345 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003346 curlun->dev.parent = &gadget->dev;
3347 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003348 dev_set_drvdata(&curlun->dev, &fsg->filesem);
Kay Sievers0031a062008-05-02 06:02:41 +02003349 dev_set_name(&curlun->dev,"%s-lun%d",
3350 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003351
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003352 kref_get(&fsg->ref);
3353 rc = device_register(&curlun->dev);
3354 if (rc) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003355 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003356 put_device(&curlun->dev);
Alan Stern2de9eae2006-09-25 14:31:15 -04003357 goto out;
3358 }
3359 curlun->registered = 1;
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003360
3361 rc = device_create_file(&curlun->dev, &dev_attr_ro);
3362 if (rc)
3363 goto out;
3364 rc = device_create_file(&curlun->dev, &dev_attr_nofua);
3365 if (rc)
3366 goto out;
3367 rc = device_create_file(&curlun->dev, &dev_attr_file);
3368 if (rc)
3369 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003370
Alan Sternaafe5bd2006-03-31 11:46:43 -05003371 if (mod_data.file[i] && *mod_data.file[i]) {
Michal Nazarewiczd9385b62010-10-28 17:31:18 +02003372 rc = fsg_lun_open(curlun, mod_data.file[i]);
3373 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003374 goto out;
3375 } else if (!mod_data.removable) {
3376 ERROR(fsg, "no file given for LUN%d\n", i);
3377 rc = -EINVAL;
3378 goto out;
3379 }
3380 }
3381
3382 /* Find all the endpoints we will use */
3383 usb_ep_autoconfig_reset(gadget);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003384 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003385 if (!ep)
3386 goto autoconf_fail;
3387 ep->driver_data = fsg; // claim the endpoint
3388 fsg->bulk_in = ep;
3389
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003390 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003391 if (!ep)
3392 goto autoconf_fail;
3393 ep->driver_data = fsg; // claim the endpoint
3394 fsg->bulk_out = ep;
3395
3396 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003397 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003398 if (!ep)
3399 goto autoconf_fail;
3400 ep->driver_data = fsg; // claim the endpoint
3401 fsg->intr_in = ep;
3402 }
3403
3404 /* Fix up the descriptors */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003405 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3406 device_desc.idProduct = cpu_to_le16(mod_data.product);
3407 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3408
3409 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003410 fsg_intf_desc.bNumEndpoints = i;
3411 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3412 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3413 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003414
David Brownell2e806f62007-08-02 00:03:39 -07003415 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003416 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003417
David Brownell2e806f62007-08-02 00:03:39 -07003418 /* Assume endpoint addresses are the same for both speeds */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003419 fsg_hs_bulk_in_desc.bEndpointAddress =
3420 fsg_fs_bulk_in_desc.bEndpointAddress;
3421 fsg_hs_bulk_out_desc.bEndpointAddress =
3422 fsg_fs_bulk_out_desc.bEndpointAddress;
3423 fsg_hs_intr_in_desc.bEndpointAddress =
3424 fsg_fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003425 }
3426
David Brownell2e806f62007-08-02 00:03:39 -07003427 if (gadget_is_otg(gadget))
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003428 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
David Brownell2e806f62007-08-02 00:03:39 -07003429
Linus Torvalds1da177e2005-04-16 15:20:36 -07003430 rc = -ENOMEM;
3431
3432 /* Allocate the request and buffer for endpoint 0 */
3433 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3434 if (!req)
3435 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003436 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003437 if (!req->buf)
3438 goto out;
3439 req->complete = ep0_complete;
3440
3441 /* Allocate the data buffers */
Per Forlin6532c7f2011-08-19 21:21:27 +02003442 for (i = 0; i < fsg_num_buffers; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003443 struct fsg_buffhd *bh = &fsg->buffhds[i];
3444
Alan Stern14cd5f82006-03-23 15:07:25 -05003445 /* Allocate for the bulk-in endpoint. We assume that
3446 * the buffer will also work with the bulk-out (and
3447 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003448 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003449 if (!bh->buf)
3450 goto out;
3451 bh->next = bh + 1;
3452 }
Per Forlin6532c7f2011-08-19 21:21:27 +02003453 fsg->buffhds[fsg_num_buffers - 1].next = &fsg->buffhds[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07003454
3455 /* This should reflect the actual gadget power source */
3456 usb_gadget_set_selfpowered(gadget);
3457
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003458 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3459 "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003460 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003461 gadget->name);
3462
Alan Stern22efcf42005-09-26 16:12:02 -04003463 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3464 "file-storage-gadget");
3465 if (IS_ERR(fsg->thread_task)) {
3466 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003467 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04003468 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003469
3470 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
Alan Stern664a51a2011-06-15 16:31:37 -04003471 INFO(fsg, "NOTE: This driver is deprecated. "
3472 "Consider using g_mass_storage instead.\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -07003473 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3474
3475 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3476 for (i = 0; i < fsg->nluns; ++i) {
3477 curlun = &fsg->luns[i];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003478 if (fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003479 p = NULL;
3480 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08003481 p = d_path(&curlun->filp->f_path,
3482 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003483 if (IS_ERR(p))
3484 p = NULL;
3485 }
Andy Shevchenkoa93917d2010-07-22 17:53:56 +03003486 LINFO(curlun, "ro=%d, nofua=%d, file: %s\n",
3487 curlun->ro, curlun->nofua, (p ? p : "(error)"));
Linus Torvalds1da177e2005-04-16 15:20:36 -07003488 }
3489 }
3490 kfree(pathbuf);
3491
3492 DBG(fsg, "transport=%s (x%02x)\n",
3493 mod_data.transport_name, mod_data.transport_type);
3494 DBG(fsg, "protocol=%s (x%02x)\n",
3495 mod_data.protocol_name, mod_data.protocol_type);
3496 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3497 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05003498 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003499 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05003500 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07003501 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04003502
3503 set_bit(REGISTERED, &fsg->atomic_bitflags);
3504
3505 /* Tell the thread to start working */
3506 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003507 return 0;
3508
3509autoconf_fail:
3510 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3511 rc = -ENOTSUPP;
3512
3513out:
3514 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3515 fsg_unbind(gadget);
Felipe Balbi889394b2008-12-08 13:50:27 +02003516 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003517 return rc;
3518}
3519
3520
3521/*-------------------------------------------------------------------------*/
3522
3523static void fsg_suspend(struct usb_gadget *gadget)
3524{
3525 struct fsg_dev *fsg = get_gadget_data(gadget);
3526
3527 DBG(fsg, "suspend\n");
3528 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3529}
3530
3531static void fsg_resume(struct usb_gadget *gadget)
3532{
3533 struct fsg_dev *fsg = get_gadget_data(gadget);
3534
3535 DBG(fsg, "resume\n");
3536 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3537}
3538
3539
3540/*-------------------------------------------------------------------------*/
3541
3542static struct usb_gadget_driver fsg_driver = {
3543#ifdef CONFIG_USB_GADGET_DUALSPEED
3544 .speed = USB_SPEED_HIGH,
3545#else
3546 .speed = USB_SPEED_FULL,
3547#endif
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003548 .function = (char *) fsg_string_product,
David Brownell6bea4762006-12-05 03:15:33 -08003549 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003550 .disconnect = fsg_disconnect,
3551 .setup = fsg_setup,
3552 .suspend = fsg_suspend,
3553 .resume = fsg_resume,
3554
3555 .driver = {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003556 .name = DRIVER_NAME,
Ben Dooksd0d50492005-10-10 10:52:33 +01003557 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003558 // .release = ...
3559 // .suspend = ...
3560 // .resume = ...
3561 },
3562};
3563
3564
3565static int __init fsg_alloc(void)
3566{
3567 struct fsg_dev *fsg;
3568
Per Forlin6532c7f2011-08-19 21:21:27 +02003569 fsg = kzalloc(sizeof *fsg +
3570 fsg_num_buffers * sizeof *(fsg->buffhds), GFP_KERNEL);
3571
Linus Torvalds1da177e2005-04-16 15:20:36 -07003572 if (!fsg)
3573 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003574 spin_lock_init(&fsg->lock);
3575 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05003576 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003577 init_completion(&fsg->thread_notifier);
3578
3579 the_fsg = fsg;
3580 return 0;
3581}
3582
3583
Linus Torvalds1da177e2005-04-16 15:20:36 -07003584static int __init fsg_init(void)
3585{
3586 int rc;
3587 struct fsg_dev *fsg;
3588
Per Forlin6532c7f2011-08-19 21:21:27 +02003589 rc = fsg_num_buffers_validate();
3590 if (rc != 0)
3591 return rc;
3592
Linus Torvalds1da177e2005-04-16 15:20:36 -07003593 if ((rc = fsg_alloc()) != 0)
3594 return rc;
3595 fsg = the_fsg;
Uwe Kleine-Königb0fca502010-08-12 17:43:53 +02003596 if ((rc = usb_gadget_probe_driver(&fsg_driver, fsg_bind)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05003597 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04003598 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003599}
3600module_init(fsg_init);
3601
3602
3603static void __exit fsg_cleanup(void)
3604{
3605 struct fsg_dev *fsg = the_fsg;
3606
3607 /* Unregister the driver iff the thread hasn't already done so */
3608 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3609 usb_gadget_unregister_driver(&fsg_driver);
3610
3611 /* Wait for the thread to finish up */
3612 wait_for_completion(&fsg->thread_notifier);
3613
Alan Stern87c42522005-11-09 16:59:56 -05003614 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003615}
3616module_exit(fsg_cleanup);