blob: 33bb76cef33c2ad78aa2c7f3b21e4d3d8a04f4c0 [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
59 * Vendor ID, Product ID, and release number can be overridden.
60 *
61 * There is support for multiple logical units (LUNs), each of which has
62 * its own backing file. The number of LUNs can be set using the optional
63 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
64 * files are specified using comma-separated lists for "file" and "ro".
65 * The default number of LUNs is taken from the number of "file" elements;
66 * it is 1 if "file" is not given. If "removable" is not set then a backing
67 * file must be specified for each LUN. If it is set, then an unspecified
Alan Stern12aae682008-11-20 14:13:12 -050068 * or empty backing filename means the LUN's medium is not loaded. Ideally
69 * each LUN would be settable independently as a disk drive or a CD-ROM
70 * drive, but currently all LUNs have to be the same type. The CD-ROM
71 * emulation includes a single data track and no audio tracks; hence there
72 * need be only one backing file per LUN. Note also that the CD-ROM block
73 * length is set to 512 rather than the more common value 2048.
Linus Torvalds1da177e2005-04-16 15:20:36 -070074 *
75 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
76 * needed (an interrupt-out endpoint is also needed for CBI). The memory
77 * requirement amounts to two 16K buffers, size configurable by a parameter.
78 * Support is included for both full-speed and high-speed operation.
79 *
Alan Stern14cd5f82006-03-23 15:07:25 -050080 * Note that the driver is slightly non-portable in that it assumes a
81 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
82 * interrupt-in endpoints. With most device controllers this isn't an
83 * issue, but there may be some with hardware restrictions that prevent
84 * a buffer from being used by more than one endpoint.
85 *
Linus Torvalds1da177e2005-04-16 15:20:36 -070086 * Module options:
87 *
88 * file=filename[,filename...]
89 * Required if "removable" is not set, names of
90 * the files or block devices used for
91 * backing storage
92 * ro=b[,b...] Default false, booleans for read-only access
93 * removable Default false, boolean for removable media
94 * luns=N Default N = number of filenames, number of
95 * LUNs to support
Alan Sternd794ac72005-04-18 12:43:25 -040096 * stall Default determined according to the type of
97 * USB device controller (usually true),
98 * boolean to permit the driver to halt
99 * bulk endpoints
Alan Stern12aae682008-11-20 14:13:12 -0500100 * cdrom Default false, boolean for whether to emulate
101 * a CD-ROM drive
Linus Torvalds1da177e2005-04-16 15:20:36 -0700102 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
103 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
104 * ATAPI, QIC, UFI, 8070, or SCSI;
105 * also 1 - 6)
106 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
107 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
108 * release=0xRRRR Override the USB release number (bcdDevice)
109 * buflen=N Default N=16384, buffer size used (will be
110 * rounded down to a multiple of
111 * PAGE_CACHE_SIZE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700112 *
113 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
Alan Stern12aae682008-11-20 14:13:12 -0500114 * "removable", "luns", "stall", and "cdrom" options are available; default
115 * values are used for everything else.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700116 *
117 * The pathnames of the backing files and the ro settings are available in
118 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
119 * gadget's sysfs directory. If the "removable" option is set, writing to
120 * these files will simulate ejecting/loading the medium (writing an empty
121 * line means eject) and adjusting a write-enable tab. Changes to the ro
Alan Stern12aae682008-11-20 14:13:12 -0500122 * setting are not allowed when the medium is loaded or if CD-ROM emulation
123 * is being used.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700124 *
125 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
Alan Sternaafe5bd2006-03-31 11:46:43 -0500126 * The driver's SCSI command interface was based on the "Information
127 * technology - Small Computer System Interface - 2" document from
128 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
129 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
130 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
131 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
132 * document, Revision 1.0, December 14, 1998, available at
133 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700134 */
135
136
137/*
138 * Driver Design
139 *
140 * The FSG driver is fairly straightforward. There is a main kernel
141 * thread that handles most of the work. Interrupt routines field
142 * callbacks from the controller driver: bulk- and interrupt-request
143 * completion notifications, endpoint-0 events, and disconnect events.
144 * Completion events are passed to the main thread by wakeup calls. Many
145 * ep0 requests are handled at interrupt time, but SetInterface,
146 * SetConfiguration, and device reset requests are forwarded to the
147 * thread in the form of "exceptions" using SIGUSR1 signals (since they
148 * should interrupt any ongoing file I/O operations).
149 *
150 * The thread's main routine implements the standard command/data/status
151 * parts of a SCSI interaction. It and its subroutines are full of tests
152 * for pending signals/exceptions -- all this polling is necessary since
153 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
154 * indication that the driver really wants to be running in userspace.)
155 * An important point is that so long as the thread is alive it keeps an
156 * open reference to the backing file. This will prevent unmounting
157 * the backing file's underlying filesystem and could cause problems
158 * during system shutdown, for example. To prevent such problems, the
159 * thread catches INT, TERM, and KILL signals and converts them into
160 * an EXIT exception.
161 *
162 * In normal operation the main thread is started during the gadget's
163 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
164 * exit when it receives a signal, and there's no point leaving the
165 * gadget running when the thread is dead. So just before the thread
166 * exits, it deregisters the gadget driver. This makes things a little
167 * tricky: The driver is deregistered at two places, and the exiting
168 * thread can indirectly call fsg_unbind() which in turn can tell the
169 * thread to exit. The first problem is resolved through the use of the
170 * REGISTERED atomic bitflag; the driver will only be deregistered once.
171 * The second problem is resolved by having fsg_unbind() check
172 * fsg->state; it won't try to stop the thread if the state is already
173 * FSG_STATE_TERMINATED.
174 *
175 * To provide maximum throughput, the driver uses a circular pipeline of
176 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
177 * arbitrarily long; in practice the benefits don't justify having more
178 * than 2 stages (i.e., double buffering). But it helps to think of the
179 * pipeline as being a long one. Each buffer head contains a bulk-in and
180 * a bulk-out request pointer (since the buffer can be used for both
181 * output and input -- directions always are given from the host's
182 * point of view) as well as a pointer to the buffer and various state
183 * variables.
184 *
185 * Use of the pipeline follows a simple protocol. There is a variable
186 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
187 * At any time that buffer head may still be in use from an earlier
188 * request, so each buffer head has a state variable indicating whether
189 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
190 * buffer head to be EMPTY, filling the buffer either by file I/O or by
191 * USB I/O (during which the buffer head is BUSY), and marking the buffer
192 * head FULL when the I/O is complete. Then the buffer will be emptied
193 * (again possibly by USB I/O, during which it is marked BUSY) and
194 * finally marked EMPTY again (possibly by a completion routine).
195 *
196 * A module parameter tells the driver to avoid stalling the bulk
197 * endpoints wherever the transport specification allows. This is
198 * necessary for some UDCs like the SuperH, which cannot reliably clear a
199 * halt on a bulk endpoint. However, under certain circumstances the
200 * Bulk-only specification requires a stall. In such cases the driver
201 * will halt the endpoint and set a flag indicating that it should clear
202 * the halt in software during the next device reset. Hopefully this
203 * will permit everything to work correctly. Furthermore, although the
204 * specification allows the bulk-out endpoint to halt when the host sends
205 * too much data, implementing this would cause an unavoidable race.
206 * The driver will always use the "no-stall" approach for OUT transfers.
207 *
208 * One subtle point concerns sending status-stage responses for ep0
209 * requests. Some of these requests, such as device reset, can involve
210 * interrupting an ongoing file I/O operation, which might take an
211 * arbitrarily long time. During that delay the host might give up on
212 * the original ep0 request and issue a new one. When that happens the
213 * driver should not notify the host about completion of the original
214 * request, as the host will no longer be waiting for it. So the driver
215 * assigns to each ep0 request a unique tag, and it keeps track of the
216 * tag value of the request associated with a long-running exception
217 * (device-reset, interface-change, or configuration-change). When the
218 * exception handler is finished, the status-stage response is submitted
219 * only if the current ep0 request tag is equal to the exception request
220 * tag. Thus only the most recently received ep0 request will get a
221 * status-stage response.
222 *
223 * Warning: This driver source file is too long. It ought to be split up
224 * into a header file plus about 3 separate .c files, to handle the details
225 * of the Gadget, USB Mass Storage, and SCSI protocols.
226 */
227
228
David Brownell2e806f62007-08-02 00:03:39 -0700229/* #define VERBOSE_DEBUG */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400230/* #define DUMP_MSGS */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700231
Linus Torvalds1da177e2005-04-16 15:20:36 -0700232
Linus Torvalds1da177e2005-04-16 15:20:36 -0700233#include <linux/blkdev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700234#include <linux/completion.h>
235#include <linux/dcache.h>
236#include <linux/delay.h>
237#include <linux/device.h>
238#include <linux/fcntl.h>
239#include <linux/file.h>
240#include <linux/fs.h>
Alan Stern87c42522005-11-09 16:59:56 -0500241#include <linux/kref.h>
Alan Stern22efcf42005-09-26 16:12:02 -0400242#include <linux/kthread.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700243#include <linux/limits.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700244#include <linux/rwsem.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700245#include <linux/slab.h>
246#include <linux/spinlock.h>
247#include <linux/string.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -0800248#include <linux/freezer.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700249#include <linux/utsname.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700250
David Brownell5f848132006-12-16 15:34:53 -0800251#include <linux/usb/ch9.h>
David Brownell9454a572007-10-04 18:05:17 -0700252#include <linux/usb/gadget.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700253
254#include "gadget_chips.h"
255
256
David Brownell352e2b92008-08-18 17:43:25 -0700257
258/*
259 * Kbuild is not very cooperative with respect to linking separately
260 * compiled library objects into one module. So for now we won't use
261 * separate compilation ... ensuring init/exit sections work to shrink
262 * the runtime footprint, and giving us at least some parts of what
263 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
264 */
265#include "usbstring.c"
266#include "config.c"
267#include "epautoconf.c"
268
Linus Torvalds1da177e2005-04-16 15:20:36 -0700269/*-------------------------------------------------------------------------*/
270
271#define DRIVER_DESC "File-backed Storage Gadget"
272#define DRIVER_NAME "g_file_storage"
Alan Stern12aae682008-11-20 14:13:12 -0500273#define DRIVER_VERSION "20 November 2008"
Linus Torvalds1da177e2005-04-16 15:20:36 -0700274
275static const char longname[] = DRIVER_DESC;
276static const char shortname[] = DRIVER_NAME;
277
278MODULE_DESCRIPTION(DRIVER_DESC);
279MODULE_AUTHOR("Alan Stern");
280MODULE_LICENSE("Dual BSD/GPL");
281
282/* Thanks to NetChip Technologies for donating this product ID.
283 *
284 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
285 * Instead: allocate your own, using normal USB-IF procedures. */
286#define DRIVER_VENDOR_ID 0x0525 // NetChip
287#define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
288
289
290/*
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#define LDBG(lun,fmt,args...) \
Alan Stern79a7d9e2007-08-08 17:10:11 -0400300 dev_dbg(&(lun)->dev , fmt , ## args)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700301#define MDBG(fmt,args...) \
David Brownell00274922007-11-19 12:58:36 -0800302 pr_debug(DRIVER_NAME ": " fmt , ## args)
303
304#ifndef DEBUG
David Brownell2e806f62007-08-02 00:03:39 -0700305#undef VERBOSE_DEBUG
Linus Torvalds1da177e2005-04-16 15:20:36 -0700306#undef DUMP_MSGS
David Brownell00274922007-11-19 12:58:36 -0800307#endif /* !DEBUG */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700308
David Brownell2e806f62007-08-02 00:03:39 -0700309#ifdef VERBOSE_DEBUG
Linus Torvalds1da177e2005-04-16 15:20:36 -0700310#define VLDBG LDBG
311#else
Linus Torvalds1da177e2005-04-16 15:20:36 -0700312#define VLDBG(lun,fmt,args...) \
313 do { } while (0)
David Brownell2e806f62007-08-02 00:03:39 -0700314#endif /* VERBOSE_DEBUG */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700315
Linus Torvalds1da177e2005-04-16 15:20:36 -0700316#define LERROR(lun,fmt,args...) \
Alan Stern79a7d9e2007-08-08 17:10:11 -0400317 dev_err(&(lun)->dev , fmt , ## args)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700318#define LWARN(lun,fmt,args...) \
Alan Stern79a7d9e2007-08-08 17:10:11 -0400319 dev_warn(&(lun)->dev , fmt , ## args)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700320#define LINFO(lun,fmt,args...) \
Alan Stern79a7d9e2007-08-08 17:10:11 -0400321 dev_info(&(lun)->dev , fmt , ## args)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700322
323#define MINFO(fmt,args...) \
David Brownell00274922007-11-19 12:58:36 -0800324 pr_info(DRIVER_NAME ": " fmt , ## args)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700325
David Brownell2e806f62007-08-02 00:03:39 -0700326#define DBG(d, fmt, args...) \
327 dev_dbg(&(d)->gadget->dev , fmt , ## args)
328#define VDBG(d, fmt, args...) \
329 dev_vdbg(&(d)->gadget->dev , fmt , ## args)
330#define ERROR(d, fmt, args...) \
331 dev_err(&(d)->gadget->dev , fmt , ## args)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700332#define WARNING(d, fmt, args...) \
David Brownell2e806f62007-08-02 00:03:39 -0700333 dev_warn(&(d)->gadget->dev , fmt , ## args)
334#define INFO(d, fmt, args...) \
335 dev_info(&(d)->gadget->dev , fmt , ## args)
336
Linus Torvalds1da177e2005-04-16 15:20:36 -0700337
338/*-------------------------------------------------------------------------*/
339
340/* Encapsulate the module parameter settings */
341
342#define MAX_LUNS 8
343
Linus Torvalds1da177e2005-04-16 15:20:36 -0700344static struct {
Alan Sternaafe5bd2006-03-31 11:46:43 -0500345 char *file[MAX_LUNS];
346 int ro[MAX_LUNS];
David Brownell2e806f62007-08-02 00:03:39 -0700347 unsigned int num_filenames;
348 unsigned int num_ros;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700349 unsigned int nluns;
350
Alan Sternd794ac72005-04-18 12:43:25 -0400351 int removable;
352 int can_stall;
Alan Stern12aae682008-11-20 14:13:12 -0500353 int cdrom;
Alan Sternd794ac72005-04-18 12:43:25 -0400354
Linus Torvalds1da177e2005-04-16 15:20:36 -0700355 char *transport_parm;
356 char *protocol_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700357 unsigned short vendor;
358 unsigned short product;
359 unsigned short release;
360 unsigned int buflen;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700361
362 int transport_type;
363 char *transport_name;
364 int protocol_type;
365 char *protocol_name;
366
367} mod_data = { // Default values
368 .transport_parm = "BBB",
369 .protocol_parm = "SCSI",
370 .removable = 0,
Alan Sternd794ac72005-04-18 12:43:25 -0400371 .can_stall = 1,
Alan Stern12aae682008-11-20 14:13:12 -0500372 .cdrom = 0,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700373 .vendor = DRIVER_VENDOR_ID,
374 .product = DRIVER_PRODUCT_ID,
375 .release = 0xffff, // Use controller chip type
376 .buflen = 16384,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700377 };
378
379
Alan Sternaafe5bd2006-03-31 11:46:43 -0500380module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
381 S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700382MODULE_PARM_DESC(file, "names of backing files or devices");
383
Alan Sternaafe5bd2006-03-31 11:46:43 -0500384module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700385MODULE_PARM_DESC(ro, "true to force read-only");
386
387module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
388MODULE_PARM_DESC(luns, "number of LUNs");
389
390module_param_named(removable, mod_data.removable, bool, S_IRUGO);
391MODULE_PARM_DESC(removable, "true to simulate removable media");
392
Alan Sternd794ac72005-04-18 12:43:25 -0400393module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
394MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
395
Alan Stern12aae682008-11-20 14:13:12 -0500396module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
397MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
398
Linus Torvalds1da177e2005-04-16 15:20:36 -0700399
400/* In the non-TEST version, only the module parameters listed above
401 * are available. */
402#ifdef CONFIG_USB_FILE_STORAGE_TEST
403
404module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
405MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
406
407module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
408MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
409 "8070, or SCSI)");
410
411module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
412MODULE_PARM_DESC(vendor, "USB Vendor ID");
413
414module_param_named(product, mod_data.product, ushort, S_IRUGO);
415MODULE_PARM_DESC(product, "USB Product ID");
416
417module_param_named(release, mod_data.release, ushort, S_IRUGO);
418MODULE_PARM_DESC(release, "USB release number");
419
420module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
421MODULE_PARM_DESC(buflen, "I/O buffer size");
422
Linus Torvalds1da177e2005-04-16 15:20:36 -0700423#endif /* CONFIG_USB_FILE_STORAGE_TEST */
424
425
426/*-------------------------------------------------------------------------*/
427
Alan Stern12aae682008-11-20 14:13:12 -0500428/* SCSI device types */
429#define TYPE_DISK 0x00
430#define TYPE_CDROM 0x05
431
Linus Torvalds1da177e2005-04-16 15:20:36 -0700432/* USB protocol value = the transport method */
433#define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
434#define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
435#define USB_PR_BULK 0x50 // Bulk-only
436
437/* USB subclass value = the protocol encapsulation */
438#define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
439#define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
440#define USB_SC_QIC 0x03 // QIC-157 (tape)
441#define USB_SC_UFI 0x04 // UFI (floppy)
442#define USB_SC_8070 0x05 // SFF-8070i (removable)
443#define USB_SC_SCSI 0x06 // Transparent SCSI
444
445/* Bulk-only data structures */
446
447/* Command Block Wrapper */
448struct bulk_cb_wrap {
449 __le32 Signature; // Contains 'USBC'
450 u32 Tag; // Unique per command id
451 __le32 DataTransferLength; // Size of the data
452 u8 Flags; // Direction in bit 7
453 u8 Lun; // LUN (normally 0)
454 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
455 u8 CDB[16]; // Command Data Block
456};
457
458#define USB_BULK_CB_WRAP_LEN 31
459#define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
460#define USB_BULK_IN_FLAG 0x80
461
462/* Command Status Wrapper */
463struct bulk_cs_wrap {
464 __le32 Signature; // Should = 'USBS'
465 u32 Tag; // Same as original command
466 __le32 Residue; // Amount not transferred
467 u8 Status; // See below
468};
469
470#define USB_BULK_CS_WRAP_LEN 13
471#define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
472#define USB_STATUS_PASS 0
473#define USB_STATUS_FAIL 1
474#define USB_STATUS_PHASE_ERROR 2
475
476/* Bulk-only class specific requests */
477#define USB_BULK_RESET_REQUEST 0xff
478#define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
479
480
481/* CBI Interrupt data structure */
482struct interrupt_data {
483 u8 bType;
484 u8 bValue;
485};
486
487#define CBI_INTERRUPT_DATA_LEN 2
488
489/* CBI Accept Device-Specific Command request */
490#define USB_CBI_ADSC_REQUEST 0x00
491
492
493#define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
494
495/* SCSI commands that we recognize */
496#define SC_FORMAT_UNIT 0x04
497#define SC_INQUIRY 0x12
498#define SC_MODE_SELECT_6 0x15
499#define SC_MODE_SELECT_10 0x55
500#define SC_MODE_SENSE_6 0x1a
501#define SC_MODE_SENSE_10 0x5a
502#define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
503#define SC_READ_6 0x08
504#define SC_READ_10 0x28
505#define SC_READ_12 0xa8
506#define SC_READ_CAPACITY 0x25
507#define SC_READ_FORMAT_CAPACITIES 0x23
Alan Stern12aae682008-11-20 14:13:12 -0500508#define SC_READ_HEADER 0x44
509#define SC_READ_TOC 0x43
Linus Torvalds1da177e2005-04-16 15:20:36 -0700510#define SC_RELEASE 0x17
511#define SC_REQUEST_SENSE 0x03
512#define SC_RESERVE 0x16
513#define SC_SEND_DIAGNOSTIC 0x1d
514#define SC_START_STOP_UNIT 0x1b
515#define SC_SYNCHRONIZE_CACHE 0x35
516#define SC_TEST_UNIT_READY 0x00
517#define SC_VERIFY 0x2f
518#define SC_WRITE_6 0x0a
519#define SC_WRITE_10 0x2a
520#define SC_WRITE_12 0xaa
521
522/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
523#define SS_NO_SENSE 0
524#define SS_COMMUNICATION_FAILURE 0x040800
525#define SS_INVALID_COMMAND 0x052000
526#define SS_INVALID_FIELD_IN_CDB 0x052400
527#define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
528#define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
529#define SS_MEDIUM_NOT_PRESENT 0x023a00
530#define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
531#define SS_NOT_READY_TO_READY_TRANSITION 0x062800
532#define SS_RESET_OCCURRED 0x062900
533#define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
534#define SS_UNRECOVERED_READ_ERROR 0x031100
535#define SS_WRITE_ERROR 0x030c02
536#define SS_WRITE_PROTECTED 0x072700
537
538#define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
539#define ASC(x) ((u8) ((x) >> 8))
540#define ASCQ(x) ((u8) (x))
541
542
543/*-------------------------------------------------------------------------*/
544
545/*
546 * These definitions will permit the compiler to avoid generating code for
547 * parts of the driver that aren't used in the non-TEST version. Even gcc
548 * can recognize when a test of a constant expression yields a dead code
549 * path.
550 */
551
552#ifdef CONFIG_USB_FILE_STORAGE_TEST
553
554#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
555#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
556#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
557
558#else
559
560#define transport_is_bbb() 1
561#define transport_is_cbi() 0
562#define protocol_is_scsi() 1
563
564#endif /* CONFIG_USB_FILE_STORAGE_TEST */
565
566
567struct lun {
568 struct file *filp;
569 loff_t file_length;
570 loff_t num_sectors;
571
572 unsigned int ro : 1;
573 unsigned int prevent_medium_removal : 1;
574 unsigned int registered : 1;
Alan Stern6174d0f2006-09-26 14:51:48 -0400575 unsigned int info_valid : 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700576
577 u32 sense_data;
578 u32 sense_data_info;
579 u32 unit_attention_data;
580
581 struct device dev;
582};
583
584#define backing_file_is_open(curlun) ((curlun)->filp != NULL)
585
Alan Stern79a7d9e2007-08-08 17:10:11 -0400586static struct lun *dev_to_lun(struct device *dev)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700587{
588 return container_of(dev, struct lun, dev);
589}
590
591
592/* Big enough to hold our biggest descriptor */
593#define EP0_BUFSIZE 256
594#define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
595
596/* Number of buffers we will use. 2 is enough for double-buffering */
597#define NUM_BUFFERS 2
598
599enum fsg_buffer_state {
600 BUF_STATE_EMPTY = 0,
601 BUF_STATE_FULL,
602 BUF_STATE_BUSY
603};
604
605struct fsg_buffhd {
606 void *buf;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500607 enum fsg_buffer_state state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700608 struct fsg_buffhd *next;
609
610 /* The NetChip 2280 is faster, and handles some protocol faults
611 * better, if we don't submit any short bulk-out read requests.
612 * So we will record the intended request length here. */
613 unsigned int bulk_out_intended_length;
614
615 struct usb_request *inreq;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500616 int inreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700617 struct usb_request *outreq;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500618 int outreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700619};
620
621enum fsg_state {
622 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
623 FSG_STATE_DATA_PHASE,
624 FSG_STATE_STATUS_PHASE,
625
626 FSG_STATE_IDLE = 0,
627 FSG_STATE_ABORT_BULK_OUT,
628 FSG_STATE_RESET,
629 FSG_STATE_INTERFACE_CHANGE,
630 FSG_STATE_CONFIG_CHANGE,
631 FSG_STATE_DISCONNECT,
632 FSG_STATE_EXIT,
633 FSG_STATE_TERMINATED
634};
635
636enum data_direction {
637 DATA_DIR_UNKNOWN = 0,
638 DATA_DIR_FROM_HOST,
639 DATA_DIR_TO_HOST,
640 DATA_DIR_NONE
641};
642
643struct fsg_dev {
644 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
645 spinlock_t lock;
646 struct usb_gadget *gadget;
647
648 /* filesem protects: backing files in use */
649 struct rw_semaphore filesem;
650
Alan Stern87c42522005-11-09 16:59:56 -0500651 /* reference counting: wait until all LUNs are released */
652 struct kref ref;
653
Linus Torvalds1da177e2005-04-16 15:20:36 -0700654 struct usb_ep *ep0; // Handy copy of gadget->ep0
655 struct usb_request *ep0req; // For control responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500656 unsigned int ep0_req_tag;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700657 const char *ep0req_name;
658
659 struct usb_request *intreq; // For interrupt responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500660 int intreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700661 struct fsg_buffhd *intr_buffhd;
662
663 unsigned int bulk_out_maxpacket;
664 enum fsg_state state; // For exception handling
665 unsigned int exception_req_tag;
666
667 u8 config, new_config;
668
669 unsigned int running : 1;
670 unsigned int bulk_in_enabled : 1;
671 unsigned int bulk_out_enabled : 1;
672 unsigned int intr_in_enabled : 1;
673 unsigned int phase_error : 1;
674 unsigned int short_packet_received : 1;
675 unsigned int bad_lun_okay : 1;
676
677 unsigned long atomic_bitflags;
678#define REGISTERED 0
Alan Sternb950bdb2008-04-14 11:45:29 -0400679#define IGNORE_BULK_OUT 1
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680#define SUSPENDED 2
681
682 struct usb_ep *bulk_in;
683 struct usb_ep *bulk_out;
684 struct usb_ep *intr_in;
685
686 struct fsg_buffhd *next_buffhd_to_fill;
687 struct fsg_buffhd *next_buffhd_to_drain;
688 struct fsg_buffhd buffhds[NUM_BUFFERS];
689
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690 int thread_wakeup_needed;
691 struct completion thread_notifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692 struct task_struct *thread_task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700693
694 int cmnd_size;
695 u8 cmnd[MAX_COMMAND_SIZE];
696 enum data_direction data_dir;
697 u32 data_size;
698 u32 data_size_from_cmnd;
699 u32 tag;
700 unsigned int lun;
701 u32 residue;
702 u32 usb_amount_left;
703
704 /* The CB protocol offers no way for a host to know when a command
705 * has completed. As a result the next command may arrive early,
706 * and we will still have to handle it. For that reason we need
707 * a buffer to store new commands when using CB (or CBI, which
708 * does not oblige a host to wait for command completion either). */
709 int cbbuf_cmnd_size;
710 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
711
712 unsigned int nluns;
713 struct lun *luns;
714 struct lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700715};
716
717typedef void (*fsg_routine_t)(struct fsg_dev *);
718
Alan Stern79a7d9e2007-08-08 17:10:11 -0400719static int exception_in_progress(struct fsg_dev *fsg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700720{
721 return (fsg->state > FSG_STATE_IDLE);
722}
723
724/* Make bulk-out requests be divisible by the maxpacket size */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400725static void set_bulk_out_req_length(struct fsg_dev *fsg,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700726 struct fsg_buffhd *bh, unsigned int length)
727{
728 unsigned int rem;
729
730 bh->bulk_out_intended_length = length;
731 rem = length % fsg->bulk_out_maxpacket;
732 if (rem > 0)
733 length += fsg->bulk_out_maxpacket - rem;
734 bh->outreq->length = length;
735}
736
737static struct fsg_dev *the_fsg;
738static struct usb_gadget_driver fsg_driver;
739
740static void close_backing_file(struct lun *curlun);
741static void close_all_backing_files(struct fsg_dev *fsg);
742
743
744/*-------------------------------------------------------------------------*/
745
746#ifdef DUMP_MSGS
747
748static void dump_msg(struct fsg_dev *fsg, const char *label,
749 const u8 *buf, unsigned int length)
750{
Alan Stern79a7d9e2007-08-08 17:10:11 -0400751 if (length < 512) {
752 DBG(fsg, "%s, length %u:\n", label, length);
753 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
754 16, 1, buf, length, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700755 }
756}
757
Alan Stern79a7d9e2007-08-08 17:10:11 -0400758static void dump_cdb(struct fsg_dev *fsg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700759{}
760
761#else
762
Alan Stern79a7d9e2007-08-08 17:10:11 -0400763static void dump_msg(struct fsg_dev *fsg, const char *label,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700764 const u8 *buf, unsigned int length)
765{}
766
Alan Stern79a7d9e2007-08-08 17:10:11 -0400767#ifdef VERBOSE_DEBUG
Linus Torvalds1da177e2005-04-16 15:20:36 -0700768
Alan Stern79a7d9e2007-08-08 17:10:11 -0400769static void dump_cdb(struct fsg_dev *fsg)
770{
771 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,
772 16, 1, fsg->cmnd, fsg->cmnd_size, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700773}
774
Alan Stern79a7d9e2007-08-08 17:10:11 -0400775#else
776
777static void dump_cdb(struct fsg_dev *fsg)
778{}
779
780#endif /* VERBOSE_DEBUG */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700781#endif /* DUMP_MSGS */
782
783
784static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
785{
786 const char *name;
787
788 if (ep == fsg->bulk_in)
789 name = "bulk-in";
790 else if (ep == fsg->bulk_out)
791 name = "bulk-out";
792 else
793 name = ep->name;
794 DBG(fsg, "%s set halt\n", name);
795 return usb_ep_set_halt(ep);
796}
797
798
799/*-------------------------------------------------------------------------*/
800
801/* Routines for unaligned data access */
802
Alan Stern79a7d9e2007-08-08 17:10:11 -0400803static u16 get_be16(u8 *buf)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700804{
805 return ((u16) buf[0] << 8) | ((u16) buf[1]);
806}
807
Alan Stern79a7d9e2007-08-08 17:10:11 -0400808static u32 get_be32(u8 *buf)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700809{
810 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
811 ((u32) buf[2] << 8) | ((u32) buf[3]);
812}
813
Alan Stern79a7d9e2007-08-08 17:10:11 -0400814static void put_be16(u8 *buf, u16 val)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700815{
816 buf[0] = val >> 8;
817 buf[1] = val;
818}
819
Alan Stern79a7d9e2007-08-08 17:10:11 -0400820static void put_be32(u8 *buf, u32 val)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700821{
822 buf[0] = val >> 24;
823 buf[1] = val >> 16;
824 buf[2] = val >> 8;
David Brownell1bbc1692005-05-07 13:05:13 -0700825 buf[3] = val & 0xff;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700826}
827
828
829/*-------------------------------------------------------------------------*/
830
831/*
832 * DESCRIPTORS ... most are static, but strings and (full) configuration
833 * descriptors are built on demand. Also the (static) config and interface
834 * descriptors are adjusted during fsg_bind().
835 */
836#define STRING_MANUFACTURER 1
837#define STRING_PRODUCT 2
838#define STRING_SERIAL 3
839#define STRING_CONFIG 4
840#define STRING_INTERFACE 5
841
842/* There is only one configuration. */
843#define CONFIG_VALUE 1
844
845static struct usb_device_descriptor
846device_desc = {
847 .bLength = sizeof device_desc,
848 .bDescriptorType = USB_DT_DEVICE,
849
850 .bcdUSB = __constant_cpu_to_le16(0x0200),
851 .bDeviceClass = USB_CLASS_PER_INTERFACE,
852
853 /* The next three values can be overridden by module parameters */
854 .idVendor = __constant_cpu_to_le16(DRIVER_VENDOR_ID),
855 .idProduct = __constant_cpu_to_le16(DRIVER_PRODUCT_ID),
856 .bcdDevice = __constant_cpu_to_le16(0xffff),
857
858 .iManufacturer = STRING_MANUFACTURER,
859 .iProduct = STRING_PRODUCT,
860 .iSerialNumber = STRING_SERIAL,
861 .bNumConfigurations = 1,
862};
863
864static struct usb_config_descriptor
865config_desc = {
866 .bLength = sizeof config_desc,
867 .bDescriptorType = USB_DT_CONFIG,
868
869 /* wTotalLength computed by usb_gadget_config_buf() */
870 .bNumInterfaces = 1,
871 .bConfigurationValue = CONFIG_VALUE,
872 .iConfiguration = STRING_CONFIG,
873 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
David Brownell36e893d2008-09-12 09:39:06 -0700874 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700875};
876
877static struct usb_otg_descriptor
878otg_desc = {
879 .bLength = sizeof(otg_desc),
880 .bDescriptorType = USB_DT_OTG,
881
882 .bmAttributes = USB_OTG_SRP,
883};
884
885/* There is only one interface. */
886
887static struct usb_interface_descriptor
888intf_desc = {
889 .bLength = sizeof intf_desc,
890 .bDescriptorType = USB_DT_INTERFACE,
891
892 .bNumEndpoints = 2, // Adjusted during fsg_bind()
893 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
894 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
895 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
896 .iInterface = STRING_INTERFACE,
897};
898
899/* Three full-speed endpoint descriptors: bulk-in, bulk-out,
900 * and interrupt-in. */
901
902static struct usb_endpoint_descriptor
903fs_bulk_in_desc = {
904 .bLength = USB_DT_ENDPOINT_SIZE,
905 .bDescriptorType = USB_DT_ENDPOINT,
906
907 .bEndpointAddress = USB_DIR_IN,
908 .bmAttributes = USB_ENDPOINT_XFER_BULK,
909 /* wMaxPacketSize set by autoconfiguration */
910};
911
912static struct usb_endpoint_descriptor
913fs_bulk_out_desc = {
914 .bLength = USB_DT_ENDPOINT_SIZE,
915 .bDescriptorType = USB_DT_ENDPOINT,
916
917 .bEndpointAddress = USB_DIR_OUT,
918 .bmAttributes = USB_ENDPOINT_XFER_BULK,
919 /* wMaxPacketSize set by autoconfiguration */
920};
921
922static struct usb_endpoint_descriptor
923fs_intr_in_desc = {
924 .bLength = USB_DT_ENDPOINT_SIZE,
925 .bDescriptorType = USB_DT_ENDPOINT,
926
927 .bEndpointAddress = USB_DIR_IN,
928 .bmAttributes = USB_ENDPOINT_XFER_INT,
929 .wMaxPacketSize = __constant_cpu_to_le16(2),
930 .bInterval = 32, // frames -> 32 ms
931};
932
933static const struct usb_descriptor_header *fs_function[] = {
934 (struct usb_descriptor_header *) &otg_desc,
935 (struct usb_descriptor_header *) &intf_desc,
936 (struct usb_descriptor_header *) &fs_bulk_in_desc,
937 (struct usb_descriptor_header *) &fs_bulk_out_desc,
938 (struct usb_descriptor_header *) &fs_intr_in_desc,
939 NULL,
940};
941#define FS_FUNCTION_PRE_EP_ENTRIES 2
942
943
Linus Torvalds1da177e2005-04-16 15:20:36 -0700944/*
945 * USB 2.0 devices need to expose both high speed and full speed
946 * descriptors, unless they only run at full speed.
947 *
948 * That means alternate endpoint descriptors (bigger packets)
949 * and a "device qualifier" ... plus more construction options
950 * for the config descriptor.
951 */
952static struct usb_qualifier_descriptor
953dev_qualifier = {
954 .bLength = sizeof dev_qualifier,
955 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
956
957 .bcdUSB = __constant_cpu_to_le16(0x0200),
958 .bDeviceClass = USB_CLASS_PER_INTERFACE,
959
960 .bNumConfigurations = 1,
961};
962
963static struct usb_endpoint_descriptor
964hs_bulk_in_desc = {
965 .bLength = USB_DT_ENDPOINT_SIZE,
966 .bDescriptorType = USB_DT_ENDPOINT,
967
968 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
969 .bmAttributes = USB_ENDPOINT_XFER_BULK,
970 .wMaxPacketSize = __constant_cpu_to_le16(512),
971};
972
973static struct usb_endpoint_descriptor
974hs_bulk_out_desc = {
975 .bLength = USB_DT_ENDPOINT_SIZE,
976 .bDescriptorType = USB_DT_ENDPOINT,
977
978 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
979 .bmAttributes = USB_ENDPOINT_XFER_BULK,
980 .wMaxPacketSize = __constant_cpu_to_le16(512),
981 .bInterval = 1, // NAK every 1 uframe
982};
983
984static struct usb_endpoint_descriptor
985hs_intr_in_desc = {
986 .bLength = USB_DT_ENDPOINT_SIZE,
987 .bDescriptorType = USB_DT_ENDPOINT,
988
989 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
990 .bmAttributes = USB_ENDPOINT_XFER_INT,
991 .wMaxPacketSize = __constant_cpu_to_le16(2),
992 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
993};
994
995static const struct usb_descriptor_header *hs_function[] = {
996 (struct usb_descriptor_header *) &otg_desc,
997 (struct usb_descriptor_header *) &intf_desc,
998 (struct usb_descriptor_header *) &hs_bulk_in_desc,
999 (struct usb_descriptor_header *) &hs_bulk_out_desc,
1000 (struct usb_descriptor_header *) &hs_intr_in_desc,
1001 NULL,
1002};
1003#define HS_FUNCTION_PRE_EP_ENTRIES 2
1004
1005/* Maxpacket and other transfer characteristics vary by speed. */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001006static struct usb_endpoint_descriptor *
David Brownell2e806f62007-08-02 00:03:39 -07001007ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
1008 struct usb_endpoint_descriptor *hs)
1009{
1010 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
1011 return hs;
1012 return fs;
1013}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001014
1015
1016/* The CBI specification limits the serial string to 12 uppercase hexadecimal
1017 * characters. */
1018static char manufacturer[64];
1019static char serial[13];
1020
1021/* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1022static struct usb_string strings[] = {
1023 {STRING_MANUFACTURER, manufacturer},
1024 {STRING_PRODUCT, longname},
1025 {STRING_SERIAL, serial},
1026 {STRING_CONFIG, "Self-powered"},
1027 {STRING_INTERFACE, "Mass Storage"},
1028 {}
1029};
1030
1031static struct usb_gadget_strings stringtab = {
1032 .language = 0x0409, // en-us
1033 .strings = strings,
1034};
1035
1036
1037/*
1038 * Config descriptors must agree with the code that sets configurations
1039 * and with code managing interfaces and their altsettings. They must
1040 * also handle different speeds and other-speed requests.
1041 */
1042static int populate_config_buf(struct usb_gadget *gadget,
1043 u8 *buf, u8 type, unsigned index)
1044{
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001046 int len;
1047 const struct usb_descriptor_header **function;
1048
1049 if (index > 0)
1050 return -EINVAL;
1051
David Brownell2e806f62007-08-02 00:03:39 -07001052 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001053 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
David Brownell2e806f62007-08-02 00:03:39 -07001054 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001055 function = hs_function;
1056 else
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057 function = fs_function;
1058
1059 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -07001060 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001061 function++;
1062
1063 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
1064 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1065 return len;
1066}
1067
1068
1069/*-------------------------------------------------------------------------*/
1070
1071/* These routines may be called in process context or in_irq */
1072
Alan Sterna21d4fe2005-11-29 12:04:24 -05001073/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001074static void wakeup_thread(struct fsg_dev *fsg)
1075{
1076 /* Tell the main thread that something has happened */
1077 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001078 if (fsg->thread_task)
1079 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001080}
1081
1082
1083static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
1084{
1085 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001086
1087 /* Do nothing if a higher-priority exception is already in progress.
1088 * If a lower-or-equal priority exception is in progress, preempt it
1089 * and notify the main thread by sending it a signal. */
1090 spin_lock_irqsave(&fsg->lock, flags);
1091 if (fsg->state <= new_state) {
1092 fsg->exception_req_tag = fsg->ep0_req_tag;
1093 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -04001094 if (fsg->thread_task)
1095 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
1096 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001097 }
1098 spin_unlock_irqrestore(&fsg->lock, flags);
1099}
1100
1101
1102/*-------------------------------------------------------------------------*/
1103
1104/* The disconnect callback and ep0 routines. These always run in_irq,
1105 * except that ep0_queue() is called in the main thread to acknowledge
1106 * completion of various requests: set config, set interface, and
1107 * Bulk-only device reset. */
1108
1109static void fsg_disconnect(struct usb_gadget *gadget)
1110{
1111 struct fsg_dev *fsg = get_gadget_data(gadget);
1112
1113 DBG(fsg, "disconnect or port reset\n");
1114 raise_exception(fsg, FSG_STATE_DISCONNECT);
1115}
1116
1117
1118static int ep0_queue(struct fsg_dev *fsg)
1119{
1120 int rc;
1121
1122 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
1123 if (rc != 0 && rc != -ESHUTDOWN) {
1124
1125 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -07001126 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001127 fsg->ep0->name, rc);
1128 }
1129 return rc;
1130}
1131
1132static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
1133{
John Daiker7ca46b82006-12-29 19:02:06 -08001134 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001135
1136 if (req->actual > 0)
1137 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
1138 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -08001139 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001140 req->status, req->actual, req->length);
1141 if (req->status == -ECONNRESET) // Request was cancelled
1142 usb_ep_fifo_flush(ep);
1143
1144 if (req->status == 0 && req->context)
1145 ((fsg_routine_t) (req->context))(fsg);
1146}
1147
1148
1149/*-------------------------------------------------------------------------*/
1150
1151/* Bulk and interrupt endpoint completion handlers.
1152 * These always run in_irq. */
1153
1154static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
1155{
John Daiker7ca46b82006-12-29 19:02:06 -08001156 struct fsg_dev *fsg = ep->driver_data;
1157 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001158
1159 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -08001160 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001161 req->status, req->actual, req->length);
1162 if (req->status == -ECONNRESET) // Request was cancelled
1163 usb_ep_fifo_flush(ep);
1164
1165 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001166 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001167 spin_lock(&fsg->lock);
1168 bh->inreq_busy = 0;
1169 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001170 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001171 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001172}
1173
1174static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
1175{
John Daiker7ca46b82006-12-29 19:02:06 -08001176 struct fsg_dev *fsg = ep->driver_data;
1177 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001178
1179 dump_msg(fsg, "bulk-out", req->buf, req->actual);
1180 if (req->status || req->actual != bh->bulk_out_intended_length)
Harvey Harrison441b62c2008-03-03 16:08:34 -08001181 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001182 req->status, req->actual,
1183 bh->bulk_out_intended_length);
1184 if (req->status == -ECONNRESET) // Request was cancelled
1185 usb_ep_fifo_flush(ep);
1186
1187 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001188 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001189 spin_lock(&fsg->lock);
1190 bh->outreq_busy = 0;
1191 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001192 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001193 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001194}
1195
1196
1197#ifdef CONFIG_USB_FILE_STORAGE_TEST
1198static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1199{
John Daiker7ca46b82006-12-29 19:02:06 -08001200 struct fsg_dev *fsg = ep->driver_data;
1201 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001202
1203 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -08001204 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001205 req->status, req->actual, req->length);
1206 if (req->status == -ECONNRESET) // Request was cancelled
1207 usb_ep_fifo_flush(ep);
1208
1209 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001210 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001211 spin_lock(&fsg->lock);
1212 fsg->intreq_busy = 0;
1213 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001214 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001215 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001216}
1217
1218#else
1219static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1220{}
1221#endif /* CONFIG_USB_FILE_STORAGE_TEST */
1222
1223
1224/*-------------------------------------------------------------------------*/
1225
1226/* Ep0 class-specific handlers. These always run in_irq. */
1227
1228#ifdef CONFIG_USB_FILE_STORAGE_TEST
1229static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1230{
1231 struct usb_request *req = fsg->ep0req;
1232 static u8 cbi_reset_cmnd[6] = {
1233 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
1234
1235 /* Error in command transfer? */
1236 if (req->status || req->length != req->actual ||
1237 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
1238
1239 /* Not all controllers allow a protocol stall after
1240 * receiving control-out data, but we'll try anyway. */
1241 fsg_set_halt(fsg, fsg->ep0);
1242 return; // Wait for reset
1243 }
1244
1245 /* Is it the special reset command? */
1246 if (req->actual >= sizeof cbi_reset_cmnd &&
1247 memcmp(req->buf, cbi_reset_cmnd,
1248 sizeof cbi_reset_cmnd) == 0) {
1249
1250 /* Raise an exception to stop the current operation
1251 * and reinitialize our state. */
1252 DBG(fsg, "cbi reset request\n");
1253 raise_exception(fsg, FSG_STATE_RESET);
1254 return;
1255 }
1256
1257 VDBG(fsg, "CB[I] accept device-specific command\n");
1258 spin_lock(&fsg->lock);
1259
1260 /* Save the command for later */
1261 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -07001262 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -07001263 fsg->cbbuf_cmnd_size = req->actual;
1264 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
1265
Linus Torvalds1da177e2005-04-16 15:20:36 -07001266 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001267 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001268}
1269
1270#else
1271static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1272{}
1273#endif /* CONFIG_USB_FILE_STORAGE_TEST */
1274
1275
1276static int class_setup_req(struct fsg_dev *fsg,
1277 const struct usb_ctrlrequest *ctrl)
1278{
1279 struct usb_request *req = fsg->ep0req;
1280 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -07001281 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -04001282 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -07001283 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001284
1285 if (!fsg->config)
1286 return value;
1287
1288 /* Handle Bulk-only class-specific requests */
1289 if (transport_is_bbb()) {
1290 switch (ctrl->bRequest) {
1291
1292 case USB_BULK_RESET_REQUEST:
1293 if (ctrl->bRequestType != (USB_DIR_OUT |
1294 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1295 break;
Luis Lloret88e45db2007-07-26 10:08:47 -04001296 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001297 value = -EDOM;
1298 break;
1299 }
1300
1301 /* Raise an exception to stop the current operation
1302 * and reinitialize our state. */
1303 DBG(fsg, "bulk reset request\n");
1304 raise_exception(fsg, FSG_STATE_RESET);
1305 value = DELAYED_STATUS;
1306 break;
1307
1308 case USB_BULK_GET_MAX_LUN_REQUEST:
1309 if (ctrl->bRequestType != (USB_DIR_IN |
1310 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1311 break;
Luis Lloret88e45db2007-07-26 10:08:47 -04001312 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001313 value = -EDOM;
1314 break;
1315 }
1316 VDBG(fsg, "get max LUN\n");
1317 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -04001318 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001319 break;
1320 }
1321 }
1322
1323 /* Handle CBI class-specific requests */
1324 else {
1325 switch (ctrl->bRequest) {
1326
1327 case USB_CBI_ADSC_REQUEST:
1328 if (ctrl->bRequestType != (USB_DIR_OUT |
1329 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1330 break;
Luis Lloret88e45db2007-07-26 10:08:47 -04001331 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001332 value = -EDOM;
1333 break;
1334 }
1335 if (w_length > MAX_COMMAND_SIZE) {
1336 value = -EOVERFLOW;
1337 break;
1338 }
1339 value = w_length;
1340 fsg->ep0req->context = received_cbi_adsc;
1341 break;
1342 }
1343 }
1344
1345 if (value == -EOPNOTSUPP)
1346 VDBG(fsg,
1347 "unknown class-specific control req "
1348 "%02x.%02x v%04x i%04x l%u\n",
1349 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001350 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001351 return value;
1352}
1353
1354
1355/*-------------------------------------------------------------------------*/
1356
1357/* Ep0 standard request handlers. These always run in_irq. */
1358
1359static int standard_setup_req(struct fsg_dev *fsg,
1360 const struct usb_ctrlrequest *ctrl)
1361{
1362 struct usb_request *req = fsg->ep0req;
1363 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -07001364 u16 w_index = le16_to_cpu(ctrl->wIndex);
1365 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001366
1367 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1368 * but config change events will also reconfigure hardware. */
1369 switch (ctrl->bRequest) {
1370
1371 case USB_REQ_GET_DESCRIPTOR:
1372 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1373 USB_RECIP_DEVICE))
1374 break;
1375 switch (w_value >> 8) {
1376
1377 case USB_DT_DEVICE:
1378 VDBG(fsg, "get device descriptor\n");
Alan Stern76f4af82005-04-05 11:56:54 -04001379 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001380 memcpy(req->buf, &device_desc, value);
1381 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001382 case USB_DT_DEVICE_QUALIFIER:
1383 VDBG(fsg, "get device qualifier\n");
David Brownell2e806f62007-08-02 00:03:39 -07001384 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001385 break;
Alan Stern76f4af82005-04-05 11:56:54 -04001386 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001387 memcpy(req->buf, &dev_qualifier, value);
1388 break;
1389
1390 case USB_DT_OTHER_SPEED_CONFIG:
1391 VDBG(fsg, "get other-speed config descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -07001392 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393 break;
1394 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001395 case USB_DT_CONFIG:
1396 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -07001397get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001398 value = populate_config_buf(fsg->gadget,
1399 req->buf,
1400 w_value >> 8,
1401 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402 break;
1403
1404 case USB_DT_STRING:
1405 VDBG(fsg, "get string descriptor\n");
1406
1407 /* wIndex == language code */
1408 value = usb_gadget_get_string(&stringtab,
1409 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001410 break;
1411 }
1412 break;
1413
1414 /* One config, two speeds */
1415 case USB_REQ_SET_CONFIGURATION:
1416 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
1417 USB_RECIP_DEVICE))
1418 break;
1419 VDBG(fsg, "set configuration\n");
1420 if (w_value == CONFIG_VALUE || w_value == 0) {
1421 fsg->new_config = w_value;
1422
1423 /* Raise an exception to wipe out previous transaction
1424 * state (queued bufs, etc) and set the new config. */
1425 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1426 value = DELAYED_STATUS;
1427 }
1428 break;
1429 case USB_REQ_GET_CONFIGURATION:
1430 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1431 USB_RECIP_DEVICE))
1432 break;
1433 VDBG(fsg, "get configuration\n");
1434 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -04001435 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001436 break;
1437
1438 case USB_REQ_SET_INTERFACE:
1439 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1440 USB_RECIP_INTERFACE))
1441 break;
1442 if (fsg->config && w_index == 0) {
1443
1444 /* Raise an exception to wipe out previous transaction
1445 * state (queued bufs, etc) and install the new
1446 * interface altsetting. */
1447 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1448 value = DELAYED_STATUS;
1449 }
1450 break;
1451 case USB_REQ_GET_INTERFACE:
1452 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1453 USB_RECIP_INTERFACE))
1454 break;
1455 if (!fsg->config)
1456 break;
1457 if (w_index != 0) {
1458 value = -EDOM;
1459 break;
1460 }
1461 VDBG(fsg, "get interface\n");
1462 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001463 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001464 break;
1465
1466 default:
1467 VDBG(fsg,
1468 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1469 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001470 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001471 }
1472
1473 return value;
1474}
1475
1476
1477static int fsg_setup(struct usb_gadget *gadget,
1478 const struct usb_ctrlrequest *ctrl)
1479{
1480 struct fsg_dev *fsg = get_gadget_data(gadget);
1481 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001482 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001483
1484 ++fsg->ep0_req_tag; // Record arrival of a new request
1485 fsg->ep0req->context = NULL;
1486 fsg->ep0req->length = 0;
1487 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1488
1489 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1490 rc = class_setup_req(fsg, ctrl);
1491 else
1492 rc = standard_setup_req(fsg, ctrl);
1493
1494 /* Respond with data/status or defer until later? */
1495 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001496 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001497 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001498 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001499 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1500 "ep0-in" : "ep0-out");
1501 rc = ep0_queue(fsg);
1502 }
1503
1504 /* Device either stalls (rc < 0) or reports success */
1505 return rc;
1506}
1507
1508
1509/*-------------------------------------------------------------------------*/
1510
1511/* All the following routines run in process context */
1512
1513
1514/* Use this for bulk or interrupt transfers, not ep0 */
1515static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001516 struct usb_request *req, int *pbusy,
1517 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001518{
1519 int rc;
1520
1521 if (ep == fsg->bulk_in)
1522 dump_msg(fsg, "bulk-in", req->buf, req->length);
1523 else if (ep == fsg->intr_in)
1524 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001525
1526 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001527 *pbusy = 1;
1528 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001529 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001530 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1531 if (rc != 0) {
1532 *pbusy = 0;
1533 *state = BUF_STATE_EMPTY;
1534
1535 /* We can't do much more than wait for a reset */
1536
1537 /* Note: currently the net2280 driver fails zero-length
1538 * submissions if DMA is enabled. */
1539 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1540 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001541 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001542 ep->name, rc);
1543 }
1544}
1545
1546
1547static int sleep_thread(struct fsg_dev *fsg)
1548{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001549 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550
1551 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001552 for (;;) {
1553 try_to_freeze();
1554 set_current_state(TASK_INTERRUPTIBLE);
1555 if (signal_pending(current)) {
1556 rc = -EINTR;
1557 break;
1558 }
1559 if (fsg->thread_wakeup_needed)
1560 break;
1561 schedule();
1562 }
1563 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001564 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001565 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001566}
1567
1568
1569/*-------------------------------------------------------------------------*/
1570
1571static int do_read(struct fsg_dev *fsg)
1572{
1573 struct lun *curlun = fsg->curlun;
1574 u32 lba;
1575 struct fsg_buffhd *bh;
1576 int rc;
1577 u32 amount_left;
1578 loff_t file_offset, file_offset_tmp;
1579 unsigned int amount;
1580 unsigned int partial_page;
1581 ssize_t nread;
1582
1583 /* Get the starting Logical Block Address and check that it's
1584 * not too big */
1585 if (fsg->cmnd[0] == SC_READ_6)
1586 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1587 else {
1588 lba = get_be32(&fsg->cmnd[2]);
1589
1590 /* We allow DPO (Disable Page Out = don't save data in the
1591 * cache) and FUA (Force Unit Access = don't read from the
1592 * cache), but we don't implement them. */
1593 if ((fsg->cmnd[1] & ~0x18) != 0) {
1594 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1595 return -EINVAL;
1596 }
1597 }
1598 if (lba >= curlun->num_sectors) {
1599 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1600 return -EINVAL;
1601 }
1602 file_offset = ((loff_t) lba) << 9;
1603
1604 /* Carry out the file reads */
1605 amount_left = fsg->data_size_from_cmnd;
1606 if (unlikely(amount_left == 0))
1607 return -EIO; // No default reply
1608
1609 for (;;) {
1610
1611 /* Figure out how much we need to read:
1612 * Try to read the remaining amount.
1613 * But don't read more than the buffer size.
1614 * And don't try to read past the end of the file.
1615 * Finally, if we're not at a page boundary, don't read past
1616 * the next page.
1617 * If this means reading 0 then we were asked to read past
1618 * the end of file. */
1619 amount = min((unsigned int) amount_left, mod_data.buflen);
1620 amount = min((loff_t) amount,
1621 curlun->file_length - file_offset);
1622 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1623 if (partial_page > 0)
1624 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1625 partial_page);
1626
1627 /* Wait for the next buffer to become available */
1628 bh = fsg->next_buffhd_to_fill;
1629 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001630 rc = sleep_thread(fsg);
1631 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001632 return rc;
1633 }
1634
1635 /* If we were asked to read past the end of file,
1636 * end with an empty buffer. */
1637 if (amount == 0) {
1638 curlun->sense_data =
1639 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1640 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001641 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001642 bh->inreq->length = 0;
1643 bh->state = BUF_STATE_FULL;
1644 break;
1645 }
1646
1647 /* Perform the read */
1648 file_offset_tmp = file_offset;
1649 nread = vfs_read(curlun->filp,
1650 (char __user *) bh->buf,
1651 amount, &file_offset_tmp);
1652 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1653 (unsigned long long) file_offset,
1654 (int) nread);
1655 if (signal_pending(current))
1656 return -EINTR;
1657
1658 if (nread < 0) {
1659 LDBG(curlun, "error in file read: %d\n",
1660 (int) nread);
1661 nread = 0;
1662 } else if (nread < amount) {
1663 LDBG(curlun, "partial file read: %d/%u\n",
1664 (int) nread, amount);
1665 nread -= (nread & 511); // Round down to a block
1666 }
1667 file_offset += nread;
1668 amount_left -= nread;
1669 fsg->residue -= nread;
1670 bh->inreq->length = nread;
1671 bh->state = BUF_STATE_FULL;
1672
1673 /* If an error occurred, report it and its position */
1674 if (nread < amount) {
1675 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1676 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001677 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001678 break;
1679 }
1680
1681 if (amount_left == 0)
1682 break; // No more left to read
1683
1684 /* Send this buffer and go read some more */
1685 bh->inreq->zero = 0;
1686 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1687 &bh->inreq_busy, &bh->state);
1688 fsg->next_buffhd_to_fill = bh->next;
1689 }
1690
1691 return -EIO; // No default reply
1692}
1693
1694
1695/*-------------------------------------------------------------------------*/
1696
1697static int do_write(struct fsg_dev *fsg)
1698{
1699 struct lun *curlun = fsg->curlun;
1700 u32 lba;
1701 struct fsg_buffhd *bh;
1702 int get_some_more;
1703 u32 amount_left_to_req, amount_left_to_write;
1704 loff_t usb_offset, file_offset, file_offset_tmp;
1705 unsigned int amount;
1706 unsigned int partial_page;
1707 ssize_t nwritten;
1708 int rc;
1709
1710 if (curlun->ro) {
1711 curlun->sense_data = SS_WRITE_PROTECTED;
1712 return -EINVAL;
1713 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001714 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001715 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001716 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001717
1718 /* Get the starting Logical Block Address and check that it's
1719 * not too big */
1720 if (fsg->cmnd[0] == SC_WRITE_6)
1721 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1722 else {
1723 lba = get_be32(&fsg->cmnd[2]);
1724
1725 /* We allow DPO (Disable Page Out = don't save data in the
1726 * cache) and FUA (Force Unit Access = write directly to the
1727 * medium). We don't implement DPO; we implement FUA by
1728 * performing synchronous output. */
1729 if ((fsg->cmnd[1] & ~0x18) != 0) {
1730 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1731 return -EINVAL;
1732 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001733 if (fsg->cmnd[1] & 0x08) { // FUA
1734 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001735 curlun->filp->f_flags |= O_SYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001736 spin_unlock(&curlun->filp->f_lock);
1737 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001738 }
1739 if (lba >= curlun->num_sectors) {
1740 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1741 return -EINVAL;
1742 }
1743
1744 /* Carry out the file writes */
1745 get_some_more = 1;
1746 file_offset = usb_offset = ((loff_t) lba) << 9;
1747 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1748
1749 while (amount_left_to_write > 0) {
1750
1751 /* Queue a request for more data from the host */
1752 bh = fsg->next_buffhd_to_fill;
1753 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1754
1755 /* Figure out how much we want to get:
1756 * Try to get the remaining amount.
1757 * But don't get more than the buffer size.
1758 * And don't try to go past the end of the file.
1759 * If we're not at a page boundary,
1760 * don't go past the next page.
1761 * If this means getting 0, then we were asked
1762 * to write past the end of file.
1763 * Finally, round down to a block boundary. */
1764 amount = min(amount_left_to_req, mod_data.buflen);
1765 amount = min((loff_t) amount, curlun->file_length -
1766 usb_offset);
1767 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1768 if (partial_page > 0)
1769 amount = min(amount,
1770 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1771
1772 if (amount == 0) {
1773 get_some_more = 0;
1774 curlun->sense_data =
1775 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1776 curlun->sense_data_info = usb_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001777 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001778 continue;
1779 }
1780 amount -= (amount & 511);
1781 if (amount == 0) {
1782
1783 /* Why were we were asked to transfer a
1784 * partial block? */
1785 get_some_more = 0;
1786 continue;
1787 }
1788
1789 /* Get the next buffer */
1790 usb_offset += amount;
1791 fsg->usb_amount_left -= amount;
1792 amount_left_to_req -= amount;
1793 if (amount_left_to_req == 0)
1794 get_some_more = 0;
1795
1796 /* amount is always divisible by 512, hence by
1797 * the bulk-out maxpacket size */
1798 bh->outreq->length = bh->bulk_out_intended_length =
1799 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001800 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001801 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1802 &bh->outreq_busy, &bh->state);
1803 fsg->next_buffhd_to_fill = bh->next;
1804 continue;
1805 }
1806
1807 /* Write the received data to the backing file */
1808 bh = fsg->next_buffhd_to_drain;
1809 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1810 break; // We stopped early
1811 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001812 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001813 fsg->next_buffhd_to_drain = bh->next;
1814 bh->state = BUF_STATE_EMPTY;
1815
1816 /* Did something go wrong with the transfer? */
1817 if (bh->outreq->status != 0) {
1818 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1819 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001820 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001821 break;
1822 }
1823
1824 amount = bh->outreq->actual;
1825 if (curlun->file_length - file_offset < amount) {
1826 LERROR(curlun,
1827 "write %u @ %llu beyond end %llu\n",
1828 amount, (unsigned long long) file_offset,
1829 (unsigned long long) curlun->file_length);
1830 amount = curlun->file_length - file_offset;
1831 }
1832
1833 /* Perform the write */
1834 file_offset_tmp = file_offset;
1835 nwritten = vfs_write(curlun->filp,
1836 (char __user *) bh->buf,
1837 amount, &file_offset_tmp);
1838 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1839 (unsigned long long) file_offset,
1840 (int) nwritten);
1841 if (signal_pending(current))
1842 return -EINTR; // Interrupted!
1843
1844 if (nwritten < 0) {
1845 LDBG(curlun, "error in file write: %d\n",
1846 (int) nwritten);
1847 nwritten = 0;
1848 } else if (nwritten < amount) {
1849 LDBG(curlun, "partial file write: %d/%u\n",
1850 (int) nwritten, amount);
1851 nwritten -= (nwritten & 511);
1852 // Round down to a block
1853 }
1854 file_offset += nwritten;
1855 amount_left_to_write -= nwritten;
1856 fsg->residue -= nwritten;
1857
1858 /* If an error occurred, report it and its position */
1859 if (nwritten < amount) {
1860 curlun->sense_data = SS_WRITE_ERROR;
1861 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001862 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001863 break;
1864 }
1865
1866 /* Did the host decide to stop early? */
1867 if (bh->outreq->actual != bh->outreq->length) {
1868 fsg->short_packet_received = 1;
1869 break;
1870 }
1871 continue;
1872 }
1873
1874 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001875 rc = sleep_thread(fsg);
1876 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001877 return rc;
1878 }
1879
1880 return -EIO; // No default reply
1881}
1882
1883
1884/*-------------------------------------------------------------------------*/
1885
1886/* Sync the file data, don't bother with the metadata.
1887 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1888static int fsync_sub(struct lun *curlun)
1889{
1890 struct file *filp = curlun->filp;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001891
1892 if (curlun->ro || !filp)
1893 return 0;
Christoph Hellwig4c728ef2008-12-22 21:11:15 +01001894 return vfs_fsync(filp, filp->f_path.dentry, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001895}
1896
1897static void fsync_all(struct fsg_dev *fsg)
1898{
1899 int i;
1900
1901 for (i = 0; i < fsg->nluns; ++i)
1902 fsync_sub(&fsg->luns[i]);
1903}
1904
1905static int do_synchronize_cache(struct fsg_dev *fsg)
1906{
1907 struct lun *curlun = fsg->curlun;
1908 int rc;
1909
1910 /* We ignore the requested LBA and write out all file's
1911 * dirty data buffers. */
1912 rc = fsync_sub(curlun);
1913 if (rc)
1914 curlun->sense_data = SS_WRITE_ERROR;
1915 return 0;
1916}
1917
1918
1919/*-------------------------------------------------------------------------*/
1920
1921static void invalidate_sub(struct lun *curlun)
1922{
1923 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001924 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001925 unsigned long rc;
1926
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001927 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001928 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1929}
1930
1931static int do_verify(struct fsg_dev *fsg)
1932{
1933 struct lun *curlun = fsg->curlun;
1934 u32 lba;
1935 u32 verification_length;
1936 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1937 loff_t file_offset, file_offset_tmp;
1938 u32 amount_left;
1939 unsigned int amount;
1940 ssize_t nread;
1941
1942 /* Get the starting Logical Block Address and check that it's
1943 * not too big */
1944 lba = get_be32(&fsg->cmnd[2]);
1945 if (lba >= curlun->num_sectors) {
1946 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1947 return -EINVAL;
1948 }
1949
1950 /* We allow DPO (Disable Page Out = don't save data in the
1951 * cache) but we don't implement it. */
1952 if ((fsg->cmnd[1] & ~0x10) != 0) {
1953 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1954 return -EINVAL;
1955 }
1956
1957 verification_length = get_be16(&fsg->cmnd[7]);
1958 if (unlikely(verification_length == 0))
1959 return -EIO; // No default reply
1960
1961 /* Prepare to carry out the file verify */
1962 amount_left = verification_length << 9;
1963 file_offset = ((loff_t) lba) << 9;
1964
1965 /* Write out all the dirty buffers before invalidating them */
1966 fsync_sub(curlun);
1967 if (signal_pending(current))
1968 return -EINTR;
1969
1970 invalidate_sub(curlun);
1971 if (signal_pending(current))
1972 return -EINTR;
1973
1974 /* Just try to read the requested blocks */
1975 while (amount_left > 0) {
1976
1977 /* Figure out how much we need to read:
1978 * Try to read the remaining amount, but not more than
1979 * the buffer size.
1980 * And don't try to read past the end of the file.
1981 * If this means reading 0 then we were asked to read
1982 * past the end of file. */
1983 amount = min((unsigned int) amount_left, mod_data.buflen);
1984 amount = min((loff_t) amount,
1985 curlun->file_length - file_offset);
1986 if (amount == 0) {
1987 curlun->sense_data =
1988 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1989 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001990 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001991 break;
1992 }
1993
1994 /* Perform the read */
1995 file_offset_tmp = file_offset;
1996 nread = vfs_read(curlun->filp,
1997 (char __user *) bh->buf,
1998 amount, &file_offset_tmp);
1999 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
2000 (unsigned long long) file_offset,
2001 (int) nread);
2002 if (signal_pending(current))
2003 return -EINTR;
2004
2005 if (nread < 0) {
2006 LDBG(curlun, "error in file verify: %d\n",
2007 (int) nread);
2008 nread = 0;
2009 } else if (nread < amount) {
2010 LDBG(curlun, "partial file verify: %d/%u\n",
2011 (int) nread, amount);
2012 nread -= (nread & 511); // Round down to a sector
2013 }
2014 if (nread == 0) {
2015 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
2016 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04002017 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002018 break;
2019 }
2020 file_offset += nread;
2021 amount_left -= nread;
2022 }
2023 return 0;
2024}
2025
2026
2027/*-------------------------------------------------------------------------*/
2028
2029static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2030{
2031 u8 *buf = (u8 *) bh->buf;
2032
2033 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05002034 static char product_disk_id[] = "File-Stor Gadget";
2035 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07002036
2037 if (!fsg->curlun) { // Unsupported LUNs are okay
2038 fsg->bad_lun_okay = 1;
2039 memset(buf, 0, 36);
2040 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05002041 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07002042 return 36;
2043 }
2044
Alan Stern12aae682008-11-20 14:13:12 -05002045 memset(buf, 0, 8);
2046 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002047 if (mod_data.removable)
2048 buf[1] = 0x80;
2049 buf[2] = 2; // ANSI SCSI level 2
2050 buf[3] = 2; // SCSI-2 INQUIRY data format
2051 buf[4] = 31; // Additional length
2052 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05002053 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
2054 (mod_data.cdrom ? product_cdrom_id :
2055 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07002056 mod_data.release);
2057 return 36;
2058}
2059
2060
2061static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2062{
2063 struct lun *curlun = fsg->curlun;
2064 u8 *buf = (u8 *) bh->buf;
2065 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04002066 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002067
2068 /*
2069 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2070 *
2071 * If a REQUEST SENSE command is received from an initiator
2072 * with a pending unit attention condition (before the target
2073 * generates the contingent allegiance condition), then the
2074 * target shall either:
2075 * a) report any pending sense data and preserve the unit
2076 * attention condition on the logical unit, or,
2077 * b) report the unit attention condition, may discard any
2078 * pending sense data, and clear the unit attention
2079 * condition on the logical unit for that initiator.
2080 *
2081 * FSG normally uses option a); enable this code to use option b).
2082 */
2083#if 0
2084 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2085 curlun->sense_data = curlun->unit_attention_data;
2086 curlun->unit_attention_data = SS_NO_SENSE;
2087 }
2088#endif
2089
2090 if (!curlun) { // Unsupported LUNs are okay
2091 fsg->bad_lun_okay = 1;
2092 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2093 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002094 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002095 } else {
2096 sd = curlun->sense_data;
2097 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04002098 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002099 curlun->sense_data = SS_NO_SENSE;
2100 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002101 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002102 }
2103
2104 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04002105 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07002106 buf[2] = SK(sd);
2107 put_be32(&buf[3], sdinfo); // Sense information
2108 buf[7] = 18 - 8; // Additional sense length
2109 buf[12] = ASC(sd);
2110 buf[13] = ASCQ(sd);
2111 return 18;
2112}
2113
2114
2115static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2116{
2117 struct lun *curlun = fsg->curlun;
2118 u32 lba = get_be32(&fsg->cmnd[2]);
2119 int pmi = fsg->cmnd[8];
2120 u8 *buf = (u8 *) bh->buf;
2121
2122 /* Check the PMI and LBA fields */
2123 if (pmi > 1 || (pmi == 0 && lba != 0)) {
2124 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2125 return -EINVAL;
2126 }
2127
2128 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block
2129 put_be32(&buf[4], 512); // Block length
2130 return 8;
2131}
2132
2133
Alan Stern12aae682008-11-20 14:13:12 -05002134static void store_cdrom_address(u8 *dest, int msf, u32 addr)
2135{
2136 if (msf) {
2137 /* Convert to Minutes-Seconds-Frames */
2138 addr >>= 2; /* Convert to 2048-byte frames */
2139 addr += 2*75; /* Lead-in occupies 2 seconds */
2140 dest[3] = addr % 75; /* Frames */
2141 addr /= 75;
2142 dest[2] = addr % 60; /* Seconds */
2143 addr /= 60;
2144 dest[1] = addr; /* Minutes */
2145 dest[0] = 0; /* Reserved */
2146 } else {
2147 /* Absolute sector */
2148 put_be32(dest, addr);
2149 }
2150}
2151
2152static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2153{
2154 struct lun *curlun = fsg->curlun;
2155 int msf = fsg->cmnd[1] & 0x02;
2156 u32 lba = get_be32(&fsg->cmnd[2]);
2157 u8 *buf = (u8 *) bh->buf;
2158
2159 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
2160 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2161 return -EINVAL;
2162 }
2163 if (lba >= curlun->num_sectors) {
2164 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
2165 return -EINVAL;
2166 }
2167
2168 memset(buf, 0, 8);
2169 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
2170 store_cdrom_address(&buf[4], msf, lba);
2171 return 8;
2172}
2173
2174
2175static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2176{
2177 struct lun *curlun = fsg->curlun;
2178 int msf = fsg->cmnd[1] & 0x02;
2179 int start_track = fsg->cmnd[6];
2180 u8 *buf = (u8 *) bh->buf;
2181
2182 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
2183 start_track > 1) {
2184 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2185 return -EINVAL;
2186 }
2187
2188 memset(buf, 0, 20);
2189 buf[1] = (20-2); /* TOC data length */
2190 buf[2] = 1; /* First track number */
2191 buf[3] = 1; /* Last track number */
2192 buf[5] = 0x16; /* Data track, copying allowed */
2193 buf[6] = 0x01; /* Only track is number 1 */
2194 store_cdrom_address(&buf[8], msf, 0);
2195
2196 buf[13] = 0x16; /* Lead-out track is data */
2197 buf[14] = 0xAA; /* Lead-out track number */
2198 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
2199 return 20;
2200}
2201
2202
Linus Torvalds1da177e2005-04-16 15:20:36 -07002203static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2204{
2205 struct lun *curlun = fsg->curlun;
2206 int mscmnd = fsg->cmnd[0];
2207 u8 *buf = (u8 *) bh->buf;
2208 u8 *buf0 = buf;
2209 int pc, page_code;
2210 int changeable_values, all_pages;
2211 int valid_page = 0;
2212 int len, limit;
2213
2214 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
2215 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2216 return -EINVAL;
2217 }
2218 pc = fsg->cmnd[2] >> 6;
2219 page_code = fsg->cmnd[2] & 0x3f;
2220 if (pc == 3) {
2221 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2222 return -EINVAL;
2223 }
2224 changeable_values = (pc == 1);
2225 all_pages = (page_code == 0x3f);
2226
2227 /* Write the mode parameter header. Fixed values are: default
2228 * medium type, no cache control (DPOFUA), and no block descriptors.
2229 * The only variable value is the WriteProtect bit. We will fill in
2230 * the mode data length later. */
2231 memset(buf, 0, 8);
2232 if (mscmnd == SC_MODE_SENSE_6) {
2233 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2234 buf += 4;
2235 limit = 255;
2236 } else { // SC_MODE_SENSE_10
2237 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2238 buf += 8;
2239 limit = 65535; // Should really be mod_data.buflen
2240 }
2241
2242 /* No block descriptors */
2243
2244 /* The mode pages, in numerical order. The only page we support
2245 * is the Caching page. */
2246 if (page_code == 0x08 || all_pages) {
2247 valid_page = 1;
2248 buf[0] = 0x08; // Page code
2249 buf[1] = 10; // Page length
2250 memset(buf+2, 0, 10); // None of the fields are changeable
2251
2252 if (!changeable_values) {
2253 buf[2] = 0x04; // Write cache enable,
2254 // Read cache not disabled
2255 // No cache retention priorities
2256 put_be16(&buf[4], 0xffff); // Don't disable prefetch
2257 // Minimum prefetch = 0
2258 put_be16(&buf[8], 0xffff); // Maximum prefetch
2259 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2260 }
2261 buf += 12;
2262 }
2263
2264 /* Check that a valid page was requested and the mode data length
2265 * isn't too long. */
2266 len = buf - buf0;
2267 if (!valid_page || len > limit) {
2268 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2269 return -EINVAL;
2270 }
2271
2272 /* Store the mode data length */
2273 if (mscmnd == SC_MODE_SENSE_6)
2274 buf0[0] = len - 1;
2275 else
2276 put_be16(buf0, len - 2);
2277 return len;
2278}
2279
2280
2281static int do_start_stop(struct fsg_dev *fsg)
2282{
2283 struct lun *curlun = fsg->curlun;
2284 int loej, start;
2285
2286 if (!mod_data.removable) {
2287 curlun->sense_data = SS_INVALID_COMMAND;
2288 return -EINVAL;
2289 }
2290
2291 // int immed = fsg->cmnd[1] & 0x01;
2292 loej = fsg->cmnd[4] & 0x02;
2293 start = fsg->cmnd[4] & 0x01;
2294
2295#ifdef CONFIG_USB_FILE_STORAGE_TEST
2296 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
2297 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
2298 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2299 return -EINVAL;
2300 }
2301
2302 if (!start) {
2303
2304 /* Are we allowed to unload the media? */
2305 if (curlun->prevent_medium_removal) {
2306 LDBG(curlun, "unload attempt prevented\n");
2307 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2308 return -EINVAL;
2309 }
2310 if (loej) { // Simulate an unload/eject
2311 up_read(&fsg->filesem);
2312 down_write(&fsg->filesem);
2313 close_backing_file(curlun);
2314 up_write(&fsg->filesem);
2315 down_read(&fsg->filesem);
2316 }
2317 } else {
2318
2319 /* Our emulation doesn't support mounting; the medium is
2320 * available for use as soon as it is loaded. */
2321 if (!backing_file_is_open(curlun)) {
2322 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2323 return -EINVAL;
2324 }
2325 }
2326#endif
2327 return 0;
2328}
2329
2330
2331static int do_prevent_allow(struct fsg_dev *fsg)
2332{
2333 struct lun *curlun = fsg->curlun;
2334 int prevent;
2335
2336 if (!mod_data.removable) {
2337 curlun->sense_data = SS_INVALID_COMMAND;
2338 return -EINVAL;
2339 }
2340
2341 prevent = fsg->cmnd[4] & 0x01;
2342 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
2343 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2344 return -EINVAL;
2345 }
2346
2347 if (curlun->prevent_medium_removal && !prevent)
2348 fsync_sub(curlun);
2349 curlun->prevent_medium_removal = prevent;
2350 return 0;
2351}
2352
2353
2354static int do_read_format_capacities(struct fsg_dev *fsg,
2355 struct fsg_buffhd *bh)
2356{
2357 struct lun *curlun = fsg->curlun;
2358 u8 *buf = (u8 *) bh->buf;
2359
2360 buf[0] = buf[1] = buf[2] = 0;
2361 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
2362 buf += 4;
2363
2364 put_be32(&buf[0], curlun->num_sectors); // Number of blocks
2365 put_be32(&buf[4], 512); // Block length
2366 buf[4] = 0x02; // Current capacity
2367 return 12;
2368}
2369
2370
2371static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2372{
2373 struct lun *curlun = fsg->curlun;
2374
2375 /* We don't support MODE SELECT */
2376 curlun->sense_data = SS_INVALID_COMMAND;
2377 return -EINVAL;
2378}
2379
2380
2381/*-------------------------------------------------------------------------*/
2382
2383static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2384{
2385 int rc;
2386
2387 rc = fsg_set_halt(fsg, fsg->bulk_in);
2388 if (rc == -EAGAIN)
2389 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2390 while (rc != 0) {
2391 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07002392 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002393 rc = 0;
2394 break;
2395 }
2396
2397 /* Wait for a short time and then try again */
2398 if (msleep_interruptible(100) != 0)
2399 return -EINTR;
2400 rc = usb_ep_set_halt(fsg->bulk_in);
2401 }
2402 return rc;
2403}
2404
David Lopo62fd2ca2008-04-29 10:14:38 +01002405static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
2406{
2407 int rc;
2408
2409 DBG(fsg, "bulk-in set wedge\n");
2410 rc = usb_ep_set_wedge(fsg->bulk_in);
2411 if (rc == -EAGAIN)
2412 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
2413 while (rc != 0) {
2414 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07002415 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01002416 rc = 0;
2417 break;
2418 }
2419
2420 /* Wait for a short time and then try again */
2421 if (msleep_interruptible(100) != 0)
2422 return -EINTR;
2423 rc = usb_ep_set_wedge(fsg->bulk_in);
2424 }
2425 return rc;
2426}
2427
Linus Torvalds1da177e2005-04-16 15:20:36 -07002428static int pad_with_zeros(struct fsg_dev *fsg)
2429{
2430 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2431 u32 nkeep = bh->inreq->length;
2432 u32 nsend;
2433 int rc;
2434
2435 bh->state = BUF_STATE_EMPTY; // For the first iteration
2436 fsg->usb_amount_left = nkeep + fsg->residue;
2437 while (fsg->usb_amount_left > 0) {
2438
2439 /* Wait for the next buffer to be free */
2440 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002441 rc = sleep_thread(fsg);
2442 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002443 return rc;
2444 }
2445
2446 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2447 memset(bh->buf + nkeep, 0, nsend - nkeep);
2448 bh->inreq->length = nsend;
2449 bh->inreq->zero = 0;
2450 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2451 &bh->inreq_busy, &bh->state);
2452 bh = fsg->next_buffhd_to_fill = bh->next;
2453 fsg->usb_amount_left -= nsend;
2454 nkeep = 0;
2455 }
2456 return 0;
2457}
2458
2459static int throw_away_data(struct fsg_dev *fsg)
2460{
2461 struct fsg_buffhd *bh;
2462 u32 amount;
2463 int rc;
2464
2465 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2466 fsg->usb_amount_left > 0) {
2467
2468 /* Throw away the data in a filled buffer */
2469 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05002470 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002471 bh->state = BUF_STATE_EMPTY;
2472 fsg->next_buffhd_to_drain = bh->next;
2473
2474 /* A short packet or an error ends everything */
2475 if (bh->outreq->actual != bh->outreq->length ||
2476 bh->outreq->status != 0) {
2477 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2478 return -EINTR;
2479 }
2480 continue;
2481 }
2482
2483 /* Try to submit another request if we need one */
2484 bh = fsg->next_buffhd_to_fill;
2485 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2486 amount = min(fsg->usb_amount_left,
2487 (u32) mod_data.buflen);
2488
2489 /* amount is always divisible by 512, hence by
2490 * the bulk-out maxpacket size */
2491 bh->outreq->length = bh->bulk_out_intended_length =
2492 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05002493 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002494 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2495 &bh->outreq_busy, &bh->state);
2496 fsg->next_buffhd_to_fill = bh->next;
2497 fsg->usb_amount_left -= amount;
2498 continue;
2499 }
2500
2501 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04002502 rc = sleep_thread(fsg);
2503 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002504 return rc;
2505 }
2506 return 0;
2507}
2508
2509
2510static int finish_reply(struct fsg_dev *fsg)
2511{
2512 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2513 int rc = 0;
2514
2515 switch (fsg->data_dir) {
2516 case DATA_DIR_NONE:
2517 break; // Nothing to send
2518
2519 /* If we don't know whether the host wants to read or write,
2520 * this must be CB or CBI with an unknown command. We mustn't
2521 * try to send or receive any data. So stall both bulk pipes
2522 * if we can and wait for a reset. */
2523 case DATA_DIR_UNKNOWN:
2524 if (mod_data.can_stall) {
2525 fsg_set_halt(fsg, fsg->bulk_out);
2526 rc = halt_bulk_in_endpoint(fsg);
2527 }
2528 break;
2529
2530 /* All but the last buffer of data must have already been sent */
2531 case DATA_DIR_TO_HOST:
2532 if (fsg->data_size == 0)
2533 ; // Nothing to send
2534
2535 /* If there's no residue, simply send the last buffer */
2536 else if (fsg->residue == 0) {
2537 bh->inreq->zero = 0;
2538 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2539 &bh->inreq_busy, &bh->state);
2540 fsg->next_buffhd_to_fill = bh->next;
2541 }
2542
2543 /* There is a residue. For CB and CBI, simply mark the end
2544 * of the data with a short packet. However, if we are
2545 * allowed to stall, there was no data at all (residue ==
2546 * data_size), and the command failed (invalid LUN or
2547 * sense data is set), then halt the bulk-in endpoint
2548 * instead. */
2549 else if (!transport_is_bbb()) {
2550 if (mod_data.can_stall &&
2551 fsg->residue == fsg->data_size &&
2552 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2553 bh->state = BUF_STATE_EMPTY;
2554 rc = halt_bulk_in_endpoint(fsg);
2555 } else {
2556 bh->inreq->zero = 1;
2557 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2558 &bh->inreq_busy, &bh->state);
2559 fsg->next_buffhd_to_fill = bh->next;
2560 }
2561 }
2562
2563 /* For Bulk-only, if we're allowed to stall then send the
2564 * short packet and halt the bulk-in endpoint. If we can't
2565 * stall, pad out the remaining data with 0's. */
2566 else {
2567 if (mod_data.can_stall) {
2568 bh->inreq->zero = 1;
2569 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2570 &bh->inreq_busy, &bh->state);
2571 fsg->next_buffhd_to_fill = bh->next;
2572 rc = halt_bulk_in_endpoint(fsg);
2573 } else
2574 rc = pad_with_zeros(fsg);
2575 }
2576 break;
2577
2578 /* We have processed all we want from the data the host has sent.
2579 * There may still be outstanding bulk-out requests. */
2580 case DATA_DIR_FROM_HOST:
2581 if (fsg->residue == 0)
2582 ; // Nothing to receive
2583
2584 /* Did the host stop sending unexpectedly early? */
2585 else if (fsg->short_packet_received) {
2586 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2587 rc = -EINTR;
2588 }
2589
2590 /* We haven't processed all the incoming data. Even though
2591 * we may be allowed to stall, doing so would cause a race.
2592 * The controller may already have ACK'ed all the remaining
2593 * bulk-out packets, in which case the host wouldn't see a
2594 * STALL. Not realizing the endpoint was halted, it wouldn't
2595 * clear the halt -- leading to problems later on. */
2596#if 0
2597 else if (mod_data.can_stall) {
2598 fsg_set_halt(fsg, fsg->bulk_out);
2599 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2600 rc = -EINTR;
2601 }
2602#endif
2603
2604 /* We can't stall. Read in the excess data and throw it
2605 * all away. */
2606 else
2607 rc = throw_away_data(fsg);
2608 break;
2609 }
2610 return rc;
2611}
2612
2613
2614static int send_status(struct fsg_dev *fsg)
2615{
2616 struct lun *curlun = fsg->curlun;
2617 struct fsg_buffhd *bh;
2618 int rc;
2619 u8 status = USB_STATUS_PASS;
2620 u32 sd, sdinfo = 0;
2621
2622 /* Wait for the next buffer to become available */
2623 bh = fsg->next_buffhd_to_fill;
2624 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002625 rc = sleep_thread(fsg);
2626 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002627 return rc;
2628 }
2629
2630 if (curlun) {
2631 sd = curlun->sense_data;
2632 sdinfo = curlun->sense_data_info;
2633 } else if (fsg->bad_lun_okay)
2634 sd = SS_NO_SENSE;
2635 else
2636 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2637
2638 if (fsg->phase_error) {
2639 DBG(fsg, "sending phase-error status\n");
2640 status = USB_STATUS_PHASE_ERROR;
2641 sd = SS_INVALID_COMMAND;
2642 } else if (sd != SS_NO_SENSE) {
2643 DBG(fsg, "sending command-failure status\n");
2644 status = USB_STATUS_FAIL;
2645 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2646 " info x%x\n",
2647 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2648 }
2649
2650 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002651 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002652
2653 /* Store and send the Bulk-only CSW */
2654 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
2655 csw->Tag = fsg->tag;
2656 csw->Residue = cpu_to_le32(fsg->residue);
2657 csw->Status = status;
2658
2659 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2660 bh->inreq->zero = 0;
2661 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2662 &bh->inreq_busy, &bh->state);
2663
2664 } else if (mod_data.transport_type == USB_PR_CB) {
2665
2666 /* Control-Bulk transport has no status phase! */
2667 return 0;
2668
2669 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002670 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002671
2672 /* Store and send the Interrupt data. UFI sends the ASC
2673 * and ASCQ bytes. Everything else sends a Type (which
2674 * is always 0) and the status Value. */
2675 if (mod_data.protocol_type == USB_SC_UFI) {
2676 buf->bType = ASC(sd);
2677 buf->bValue = ASCQ(sd);
2678 } else {
2679 buf->bType = 0;
2680 buf->bValue = status;
2681 }
2682 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2683
2684 fsg->intr_buffhd = bh; // Point to the right buffhd
2685 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002686 fsg->intreq->context = bh;
2687 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2688 &fsg->intreq_busy, &bh->state);
2689 }
2690
2691 fsg->next_buffhd_to_fill = bh->next;
2692 return 0;
2693}
2694
2695
2696/*-------------------------------------------------------------------------*/
2697
2698/* Check whether the command is properly formed and whether its data size
2699 * and direction agree with the values we already have. */
2700static int check_command(struct fsg_dev *fsg, int cmnd_size,
2701 enum data_direction data_dir, unsigned int mask,
2702 int needs_medium, const char *name)
2703{
2704 int i;
2705 int lun = fsg->cmnd[1] >> 5;
2706 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2707 char hdlen[20];
2708 struct lun *curlun;
2709
2710 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2711 * Transparent SCSI doesn't pad. */
2712 if (protocol_is_scsi())
2713 ;
2714
2715 /* There's some disagreement as to whether RBC pads commands or not.
2716 * We'll play it safe and accept either form. */
2717 else if (mod_data.protocol_type == USB_SC_RBC) {
2718 if (fsg->cmnd_size == 12)
2719 cmnd_size = 12;
2720
2721 /* All the other protocols pad to 12 bytes */
2722 } else
2723 cmnd_size = 12;
2724
2725 hdlen[0] = 0;
2726 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2727 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2728 fsg->data_size);
2729 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2730 name, cmnd_size, dirletter[(int) data_dir],
2731 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2732
2733 /* We can't reply at all until we know the correct data direction
2734 * and size. */
2735 if (fsg->data_size_from_cmnd == 0)
2736 data_dir = DATA_DIR_NONE;
2737 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2738 fsg->data_dir = data_dir;
2739 fsg->data_size = fsg->data_size_from_cmnd;
2740
2741 } else { // Bulk-only
2742 if (fsg->data_size < fsg->data_size_from_cmnd) {
2743
2744 /* Host data size < Device data size is a phase error.
2745 * Carry out the command, but only transfer as much
2746 * as we are allowed. */
2747 fsg->data_size_from_cmnd = fsg->data_size;
2748 fsg->phase_error = 1;
2749 }
2750 }
2751 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2752
2753 /* Conflicting data directions is a phase error */
2754 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2755 fsg->phase_error = 1;
2756 return -EINVAL;
2757 }
2758
2759 /* Verify the length of the command itself */
2760 if (cmnd_size != fsg->cmnd_size) {
2761
Felipe Balbi549c41e2008-09-19 02:00:02 +03002762 /* Special case workaround: There are plenty of buggy SCSI
2763 * implementations. Many have issues with cbw->Length
2764 * field passing a wrong command size. For those cases we
2765 * always try to work around the problem by using the length
2766 * sent by the host side provided it is at least as large
2767 * as the correct command length.
2768 * Examples of such cases would be MS-Windows, which issues
2769 * REQUEST SENSE with cbw->Length == 12 where it should
2770 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2771 * REQUEST SENSE with cbw->Length == 10 where it should
2772 * be 6 as well.
2773 */
2774 if (cmnd_size <= fsg->cmnd_size) {
2775 DBG(fsg, "%s is buggy! Expected length %d "
2776 "but we got %d\n", name,
2777 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002778 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002779 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002780 fsg->phase_error = 1;
2781 return -EINVAL;
2782 }
2783 }
2784
Alan Sternd794ac72005-04-18 12:43:25 -04002785 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002786 if (transport_is_bbb()) {
2787 if (fsg->lun != lun)
2788 DBG(fsg, "using LUN %d from CBW, "
2789 "not LUN %d from CDB\n",
2790 fsg->lun, lun);
2791 } else
2792 fsg->lun = lun; // Use LUN from the command
2793
2794 /* Check the LUN */
2795 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2796 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2797 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2798 curlun->sense_data = SS_NO_SENSE;
2799 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002800 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002801 }
2802 } else {
2803 fsg->curlun = curlun = NULL;
2804 fsg->bad_lun_okay = 0;
2805
2806 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2807 * to use unsupported LUNs; all others may not. */
2808 if (fsg->cmnd[0] != SC_INQUIRY &&
2809 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2810 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2811 return -EINVAL;
2812 }
2813 }
2814
2815 /* If a unit attention condition exists, only INQUIRY and
2816 * REQUEST SENSE commands are allowed; anything else must fail. */
2817 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2818 fsg->cmnd[0] != SC_INQUIRY &&
2819 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2820 curlun->sense_data = curlun->unit_attention_data;
2821 curlun->unit_attention_data = SS_NO_SENSE;
2822 return -EINVAL;
2823 }
2824
2825 /* Check that only command bytes listed in the mask are non-zero */
2826 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2827 for (i = 1; i < cmnd_size; ++i) {
2828 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2829 if (curlun)
2830 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2831 return -EINVAL;
2832 }
2833 }
2834
2835 /* If the medium isn't mounted and the command needs to access
2836 * it, return an error. */
2837 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2838 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2839 return -EINVAL;
2840 }
2841
2842 return 0;
2843}
2844
2845
2846static int do_scsi_command(struct fsg_dev *fsg)
2847{
2848 struct fsg_buffhd *bh;
2849 int rc;
2850 int reply = -EINVAL;
2851 int i;
2852 static char unknown[16];
2853
2854 dump_cdb(fsg);
2855
2856 /* Wait for the next buffer to become available for data or status */
2857 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2858 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002859 rc = sleep_thread(fsg);
2860 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002861 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002862 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002863 fsg->phase_error = 0;
2864 fsg->short_packet_received = 0;
2865
2866 down_read(&fsg->filesem); // We're using the backing file
2867 switch (fsg->cmnd[0]) {
2868
2869 case SC_INQUIRY:
2870 fsg->data_size_from_cmnd = fsg->cmnd[4];
2871 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2872 (1<<4), 0,
2873 "INQUIRY")) == 0)
2874 reply = do_inquiry(fsg, bh);
2875 break;
2876
2877 case SC_MODE_SELECT_6:
2878 fsg->data_size_from_cmnd = fsg->cmnd[4];
2879 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2880 (1<<1) | (1<<4), 0,
2881 "MODE SELECT(6)")) == 0)
2882 reply = do_mode_select(fsg, bh);
2883 break;
2884
2885 case SC_MODE_SELECT_10:
2886 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2887 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2888 (1<<1) | (3<<7), 0,
2889 "MODE SELECT(10)")) == 0)
2890 reply = do_mode_select(fsg, bh);
2891 break;
2892
2893 case SC_MODE_SENSE_6:
2894 fsg->data_size_from_cmnd = fsg->cmnd[4];
2895 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2896 (1<<1) | (1<<2) | (1<<4), 0,
2897 "MODE SENSE(6)")) == 0)
2898 reply = do_mode_sense(fsg, bh);
2899 break;
2900
2901 case SC_MODE_SENSE_10:
2902 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2903 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2904 (1<<1) | (1<<2) | (3<<7), 0,
2905 "MODE SENSE(10)")) == 0)
2906 reply = do_mode_sense(fsg, bh);
2907 break;
2908
2909 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2910 fsg->data_size_from_cmnd = 0;
2911 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2912 (1<<4), 0,
2913 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2914 reply = do_prevent_allow(fsg);
2915 break;
2916
2917 case SC_READ_6:
2918 i = fsg->cmnd[4];
2919 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2920 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2921 (7<<1) | (1<<4), 1,
2922 "READ(6)")) == 0)
2923 reply = do_read(fsg);
2924 break;
2925
2926 case SC_READ_10:
2927 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2928 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2929 (1<<1) | (0xf<<2) | (3<<7), 1,
2930 "READ(10)")) == 0)
2931 reply = do_read(fsg);
2932 break;
2933
2934 case SC_READ_12:
2935 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2936 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2937 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2938 "READ(12)")) == 0)
2939 reply = do_read(fsg);
2940 break;
2941
2942 case SC_READ_CAPACITY:
2943 fsg->data_size_from_cmnd = 8;
2944 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2945 (0xf<<2) | (1<<8), 1,
2946 "READ CAPACITY")) == 0)
2947 reply = do_read_capacity(fsg, bh);
2948 break;
2949
Alan Stern12aae682008-11-20 14:13:12 -05002950 case SC_READ_HEADER:
2951 if (!mod_data.cdrom)
2952 goto unknown_cmnd;
2953 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2954 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2955 (3<<7) | (0x1f<<1), 1,
2956 "READ HEADER")) == 0)
2957 reply = do_read_header(fsg, bh);
2958 break;
2959
2960 case SC_READ_TOC:
2961 if (!mod_data.cdrom)
2962 goto unknown_cmnd;
2963 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2964 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2965 (7<<6) | (1<<1), 1,
2966 "READ TOC")) == 0)
2967 reply = do_read_toc(fsg, bh);
2968 break;
2969
Linus Torvalds1da177e2005-04-16 15:20:36 -07002970 case SC_READ_FORMAT_CAPACITIES:
2971 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2972 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2973 (3<<7), 1,
2974 "READ FORMAT CAPACITIES")) == 0)
2975 reply = do_read_format_capacities(fsg, bh);
2976 break;
2977
2978 case SC_REQUEST_SENSE:
2979 fsg->data_size_from_cmnd = fsg->cmnd[4];
2980 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2981 (1<<4), 0,
2982 "REQUEST SENSE")) == 0)
2983 reply = do_request_sense(fsg, bh);
2984 break;
2985
2986 case SC_START_STOP_UNIT:
2987 fsg->data_size_from_cmnd = 0;
2988 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2989 (1<<1) | (1<<4), 0,
2990 "START-STOP UNIT")) == 0)
2991 reply = do_start_stop(fsg);
2992 break;
2993
2994 case SC_SYNCHRONIZE_CACHE:
2995 fsg->data_size_from_cmnd = 0;
2996 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2997 (0xf<<2) | (3<<7), 1,
2998 "SYNCHRONIZE CACHE")) == 0)
2999 reply = do_synchronize_cache(fsg);
3000 break;
3001
3002 case SC_TEST_UNIT_READY:
3003 fsg->data_size_from_cmnd = 0;
3004 reply = check_command(fsg, 6, DATA_DIR_NONE,
3005 0, 1,
3006 "TEST UNIT READY");
3007 break;
3008
3009 /* Although optional, this command is used by MS-Windows. We
3010 * support a minimal version: BytChk must be 0. */
3011 case SC_VERIFY:
3012 fsg->data_size_from_cmnd = 0;
3013 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
3014 (1<<1) | (0xf<<2) | (3<<7), 1,
3015 "VERIFY")) == 0)
3016 reply = do_verify(fsg);
3017 break;
3018
3019 case SC_WRITE_6:
3020 i = fsg->cmnd[4];
3021 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
3022 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
3023 (7<<1) | (1<<4), 1,
3024 "WRITE(6)")) == 0)
3025 reply = do_write(fsg);
3026 break;
3027
3028 case SC_WRITE_10:
3029 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
3030 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
3031 (1<<1) | (0xf<<2) | (3<<7), 1,
3032 "WRITE(10)")) == 0)
3033 reply = do_write(fsg);
3034 break;
3035
3036 case SC_WRITE_12:
3037 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
3038 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
3039 (1<<1) | (0xf<<2) | (0xf<<6), 1,
3040 "WRITE(12)")) == 0)
3041 reply = do_write(fsg);
3042 break;
3043
3044 /* Some mandatory commands that we recognize but don't implement.
3045 * They don't mean much in this setting. It's left as an exercise
3046 * for anyone interested to implement RESERVE and RELEASE in terms
3047 * of Posix locks. */
3048 case SC_FORMAT_UNIT:
3049 case SC_RELEASE:
3050 case SC_RESERVE:
3051 case SC_SEND_DIAGNOSTIC:
3052 // Fall through
3053
3054 default:
Alan Stern12aae682008-11-20 14:13:12 -05003055 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003056 fsg->data_size_from_cmnd = 0;
3057 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
3058 if ((reply = check_command(fsg, fsg->cmnd_size,
3059 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
3060 fsg->curlun->sense_data = SS_INVALID_COMMAND;
3061 reply = -EINVAL;
3062 }
3063 break;
3064 }
3065 up_read(&fsg->filesem);
3066
3067 if (reply == -EINTR || signal_pending(current))
3068 return -EINTR;
3069
3070 /* Set up the single reply buffer for finish_reply() */
3071 if (reply == -EINVAL)
3072 reply = 0; // Error reply length
3073 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
3074 reply = min((u32) reply, fsg->data_size_from_cmnd);
3075 bh->inreq->length = reply;
3076 bh->state = BUF_STATE_FULL;
3077 fsg->residue -= reply;
3078 } // Otherwise it's already set
3079
3080 return 0;
3081}
3082
3083
3084/*-------------------------------------------------------------------------*/
3085
3086static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
3087{
3088 struct usb_request *req = bh->outreq;
John Daiker7ca46b82006-12-29 19:02:06 -08003089 struct bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003090
Alan Sternb950bdb2008-04-14 11:45:29 -04003091 /* Was this a real packet? Should it be ignored? */
3092 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003093 return -EINVAL;
3094
3095 /* Is the CBW valid? */
3096 if (req->actual != USB_BULK_CB_WRAP_LEN ||
3097 cbw->Signature != __constant_cpu_to_le32(
3098 USB_BULK_CB_SIG)) {
3099 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
3100 req->actual,
3101 le32_to_cpu(cbw->Signature));
3102
Alan Sternb950bdb2008-04-14 11:45:29 -04003103 /* The Bulk-only spec says we MUST stall the IN endpoint
3104 * (6.6.1), so it's unavoidable. It also says we must
3105 * retain this state until the next reset, but there's
3106 * no way to tell the controller driver it should ignore
3107 * Clear-Feature(HALT) requests.
3108 *
3109 * We aren't required to halt the OUT endpoint; instead
3110 * we can simply accept and discard any data received
3111 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01003112 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04003113 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003114 return -EINVAL;
3115 }
3116
3117 /* Is the CBW meaningful? */
3118 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04003119 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003120 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
3121 "cmdlen %u\n",
3122 cbw->Lun, cbw->Flags, cbw->Length);
3123
3124 /* We can do anything we want here, so let's stall the
3125 * bulk pipes if we are allowed to. */
3126 if (mod_data.can_stall) {
3127 fsg_set_halt(fsg, fsg->bulk_out);
3128 halt_bulk_in_endpoint(fsg);
3129 }
3130 return -EINVAL;
3131 }
3132
3133 /* Save the command for later */
3134 fsg->cmnd_size = cbw->Length;
3135 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
3136 if (cbw->Flags & USB_BULK_IN_FLAG)
3137 fsg->data_dir = DATA_DIR_TO_HOST;
3138 else
3139 fsg->data_dir = DATA_DIR_FROM_HOST;
3140 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
3141 if (fsg->data_size == 0)
3142 fsg->data_dir = DATA_DIR_NONE;
3143 fsg->lun = cbw->Lun;
3144 fsg->tag = cbw->Tag;
3145 return 0;
3146}
3147
3148
3149static int get_next_command(struct fsg_dev *fsg)
3150{
3151 struct fsg_buffhd *bh;
3152 int rc = 0;
3153
3154 if (transport_is_bbb()) {
3155
3156 /* Wait for the next buffer to become available */
3157 bh = fsg->next_buffhd_to_fill;
3158 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04003159 rc = sleep_thread(fsg);
3160 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003161 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04003162 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003163
3164 /* Queue a request to read a Bulk-only CBW */
3165 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
Alan Stern70ffe6e2006-03-23 15:05:16 -05003166 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003167 start_transfer(fsg, fsg->bulk_out, bh->outreq,
3168 &bh->outreq_busy, &bh->state);
3169
3170 /* We will drain the buffer in software, which means we
3171 * can reuse it for the next filling. No need to advance
3172 * next_buffhd_to_fill. */
3173
3174 /* Wait for the CBW to arrive */
3175 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04003176 rc = sleep_thread(fsg);
3177 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003178 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04003179 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05003180 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07003181 rc = received_cbw(fsg, bh);
3182 bh->state = BUF_STATE_EMPTY;
3183
3184 } else { // USB_PR_CB or USB_PR_CBI
3185
3186 /* Wait for the next command to arrive */
3187 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04003188 rc = sleep_thread(fsg);
3189 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003190 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04003191 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003192
3193 /* Is the previous status interrupt request still busy?
3194 * The host is allowed to skip reading the status,
3195 * so we must cancel it. */
3196 if (fsg->intreq_busy)
3197 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3198
3199 /* Copy the command and mark the buffer empty */
3200 fsg->data_dir = DATA_DIR_UNKNOWN;
3201 spin_lock_irq(&fsg->lock);
3202 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3203 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3204 fsg->cbbuf_cmnd_size = 0;
3205 spin_unlock_irq(&fsg->lock);
3206 }
3207 return rc;
3208}
3209
3210
3211/*-------------------------------------------------------------------------*/
3212
3213static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3214 const struct usb_endpoint_descriptor *d)
3215{
3216 int rc;
3217
3218 ep->driver_data = fsg;
3219 rc = usb_ep_enable(ep, d);
3220 if (rc)
3221 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3222 return rc;
3223}
3224
3225static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3226 struct usb_request **preq)
3227{
3228 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3229 if (*preq)
3230 return 0;
3231 ERROR(fsg, "can't allocate request for %s\n", ep->name);
3232 return -ENOMEM;
3233}
3234
3235/*
3236 * Reset interface setting and re-init endpoint state (toggle etc).
3237 * Call with altsetting < 0 to disable the interface. The only other
3238 * available altsetting is 0, which enables the interface.
3239 */
3240static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3241{
3242 int rc = 0;
3243 int i;
3244 const struct usb_endpoint_descriptor *d;
3245
3246 if (fsg->running)
3247 DBG(fsg, "reset interface\n");
3248
3249reset:
3250 /* Deallocate the requests */
3251 for (i = 0; i < NUM_BUFFERS; ++i) {
3252 struct fsg_buffhd *bh = &fsg->buffhds[i];
3253
3254 if (bh->inreq) {
3255 usb_ep_free_request(fsg->bulk_in, bh->inreq);
3256 bh->inreq = NULL;
3257 }
3258 if (bh->outreq) {
3259 usb_ep_free_request(fsg->bulk_out, bh->outreq);
3260 bh->outreq = NULL;
3261 }
3262 }
3263 if (fsg->intreq) {
3264 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3265 fsg->intreq = NULL;
3266 }
3267
3268 /* Disable the endpoints */
3269 if (fsg->bulk_in_enabled) {
3270 usb_ep_disable(fsg->bulk_in);
3271 fsg->bulk_in_enabled = 0;
3272 }
3273 if (fsg->bulk_out_enabled) {
3274 usb_ep_disable(fsg->bulk_out);
3275 fsg->bulk_out_enabled = 0;
3276 }
3277 if (fsg->intr_in_enabled) {
3278 usb_ep_disable(fsg->intr_in);
3279 fsg->intr_in_enabled = 0;
3280 }
3281
3282 fsg->running = 0;
3283 if (altsetting < 0 || rc != 0)
3284 return rc;
3285
3286 DBG(fsg, "set interface %d\n", altsetting);
3287
3288 /* Enable the endpoints */
3289 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3290 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3291 goto reset;
3292 fsg->bulk_in_enabled = 1;
3293
3294 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3295 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3296 goto reset;
3297 fsg->bulk_out_enabled = 1;
3298 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
Alan Sternb950bdb2008-04-14 11:45:29 -04003299 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003300
3301 if (transport_is_cbi()) {
3302 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3303 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3304 goto reset;
3305 fsg->intr_in_enabled = 1;
3306 }
3307
3308 /* Allocate the requests */
3309 for (i = 0; i < NUM_BUFFERS; ++i) {
3310 struct fsg_buffhd *bh = &fsg->buffhds[i];
3311
3312 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3313 goto reset;
3314 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3315 goto reset;
3316 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003317 bh->inreq->context = bh->outreq->context = bh;
3318 bh->inreq->complete = bulk_in_complete;
3319 bh->outreq->complete = bulk_out_complete;
3320 }
3321 if (transport_is_cbi()) {
3322 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3323 goto reset;
3324 fsg->intreq->complete = intr_in_complete;
3325 }
3326
3327 fsg->running = 1;
3328 for (i = 0; i < fsg->nluns; ++i)
3329 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3330 return rc;
3331}
3332
3333
3334/*
3335 * Change our operational configuration. This code must agree with the code
3336 * that returns config descriptors, and with interface altsetting code.
3337 *
3338 * It's also responsible for power management interactions. Some
3339 * configurations might not work with our current power sources.
3340 * For now we just assume the gadget is always self-powered.
3341 */
3342static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3343{
3344 int rc = 0;
3345
3346 /* Disable the single interface */
3347 if (fsg->config != 0) {
3348 DBG(fsg, "reset config\n");
3349 fsg->config = 0;
3350 rc = do_set_interface(fsg, -1);
3351 }
3352
3353 /* Enable the interface */
3354 if (new_config != 0) {
3355 fsg->config = new_config;
3356 if ((rc = do_set_interface(fsg, 0)) != 0)
3357 fsg->config = 0; // Reset on errors
3358 else {
3359 char *speed;
3360
3361 switch (fsg->gadget->speed) {
3362 case USB_SPEED_LOW: speed = "low"; break;
3363 case USB_SPEED_FULL: speed = "full"; break;
3364 case USB_SPEED_HIGH: speed = "high"; break;
3365 default: speed = "?"; break;
3366 }
3367 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3368 }
3369 }
3370 return rc;
3371}
3372
3373
3374/*-------------------------------------------------------------------------*/
3375
3376static void handle_exception(struct fsg_dev *fsg)
3377{
3378 siginfo_t info;
3379 int sig;
3380 int i;
3381 int num_active;
3382 struct fsg_buffhd *bh;
3383 enum fsg_state old_state;
3384 u8 new_config;
3385 struct lun *curlun;
3386 unsigned int exception_req_tag;
3387 int rc;
3388
3389 /* Clear the existing signals. Anything but SIGUSR1 is converted
3390 * into a high-priority EXIT exception. */
3391 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003392 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003393 if (!sig)
3394 break;
3395 if (sig != SIGUSR1) {
3396 if (fsg->state < FSG_STATE_EXIT)
3397 DBG(fsg, "Main thread exiting on signal\n");
3398 raise_exception(fsg, FSG_STATE_EXIT);
3399 }
3400 }
3401
3402 /* Cancel all the pending transfers */
3403 if (fsg->intreq_busy)
3404 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3405 for (i = 0; i < NUM_BUFFERS; ++i) {
3406 bh = &fsg->buffhds[i];
3407 if (bh->inreq_busy)
3408 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3409 if (bh->outreq_busy)
3410 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3411 }
3412
3413 /* Wait until everything is idle */
3414 for (;;) {
3415 num_active = fsg->intreq_busy;
3416 for (i = 0; i < NUM_BUFFERS; ++i) {
3417 bh = &fsg->buffhds[i];
3418 num_active += bh->inreq_busy + bh->outreq_busy;
3419 }
3420 if (num_active == 0)
3421 break;
3422 if (sleep_thread(fsg))
3423 return;
3424 }
3425
3426 /* Clear out the controller's fifos */
3427 if (fsg->bulk_in_enabled)
3428 usb_ep_fifo_flush(fsg->bulk_in);
3429 if (fsg->bulk_out_enabled)
3430 usb_ep_fifo_flush(fsg->bulk_out);
3431 if (fsg->intr_in_enabled)
3432 usb_ep_fifo_flush(fsg->intr_in);
3433
3434 /* Reset the I/O buffer states and pointers, the SCSI
3435 * state, and the exception. Then invoke the handler. */
3436 spin_lock_irq(&fsg->lock);
3437
3438 for (i = 0; i < NUM_BUFFERS; ++i) {
3439 bh = &fsg->buffhds[i];
3440 bh->state = BUF_STATE_EMPTY;
3441 }
3442 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3443 &fsg->buffhds[0];
3444
3445 exception_req_tag = fsg->exception_req_tag;
3446 new_config = fsg->new_config;
3447 old_state = fsg->state;
3448
3449 if (old_state == FSG_STATE_ABORT_BULK_OUT)
3450 fsg->state = FSG_STATE_STATUS_PHASE;
3451 else {
3452 for (i = 0; i < fsg->nluns; ++i) {
3453 curlun = &fsg->luns[i];
3454 curlun->prevent_medium_removal = 0;
3455 curlun->sense_data = curlun->unit_attention_data =
3456 SS_NO_SENSE;
3457 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04003458 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003459 }
3460 fsg->state = FSG_STATE_IDLE;
3461 }
3462 spin_unlock_irq(&fsg->lock);
3463
3464 /* Carry out any extra actions required for the exception */
3465 switch (old_state) {
3466 default:
3467 break;
3468
3469 case FSG_STATE_ABORT_BULK_OUT:
3470 send_status(fsg);
3471 spin_lock_irq(&fsg->lock);
3472 if (fsg->state == FSG_STATE_STATUS_PHASE)
3473 fsg->state = FSG_STATE_IDLE;
3474 spin_unlock_irq(&fsg->lock);
3475 break;
3476
3477 case FSG_STATE_RESET:
3478 /* In case we were forced against our will to halt a
3479 * bulk endpoint, clear the halt now. (The SuperH UDC
3480 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04003481 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003482 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003483
3484 if (transport_is_bbb()) {
3485 if (fsg->ep0_req_tag == exception_req_tag)
3486 ep0_queue(fsg); // Complete the status stage
3487
3488 } else if (transport_is_cbi())
3489 send_status(fsg); // Status by interrupt pipe
3490
3491 /* Technically this should go here, but it would only be
3492 * a waste of time. Ditto for the INTERFACE_CHANGE and
3493 * CONFIG_CHANGE cases. */
3494 // for (i = 0; i < fsg->nluns; ++i)
3495 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3496 break;
3497
3498 case FSG_STATE_INTERFACE_CHANGE:
3499 rc = do_set_interface(fsg, 0);
3500 if (fsg->ep0_req_tag != exception_req_tag)
3501 break;
3502 if (rc != 0) // STALL on errors
3503 fsg_set_halt(fsg, fsg->ep0);
3504 else // Complete the status stage
3505 ep0_queue(fsg);
3506 break;
3507
3508 case FSG_STATE_CONFIG_CHANGE:
3509 rc = do_set_config(fsg, new_config);
3510 if (fsg->ep0_req_tag != exception_req_tag)
3511 break;
3512 if (rc != 0) // STALL on errors
3513 fsg_set_halt(fsg, fsg->ep0);
3514 else // Complete the status stage
3515 ep0_queue(fsg);
3516 break;
3517
3518 case FSG_STATE_DISCONNECT:
3519 fsync_all(fsg);
3520 do_set_config(fsg, 0); // Unconfigured state
3521 break;
3522
3523 case FSG_STATE_EXIT:
3524 case FSG_STATE_TERMINATED:
3525 do_set_config(fsg, 0); // Free resources
3526 spin_lock_irq(&fsg->lock);
3527 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3528 spin_unlock_irq(&fsg->lock);
3529 break;
3530 }
3531}
3532
3533
3534/*-------------------------------------------------------------------------*/
3535
3536static int fsg_main_thread(void *fsg_)
3537{
John Daiker7ca46b82006-12-29 19:02:06 -08003538 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003539
Linus Torvalds1da177e2005-04-16 15:20:36 -07003540 /* Allow the thread to be killed by a signal, but set the signal mask
3541 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003542 allow_signal(SIGINT);
3543 allow_signal(SIGTERM);
3544 allow_signal(SIGKILL);
3545 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003546
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003547 /* Allow the thread to be frozen */
3548 set_freezable();
3549
Linus Torvalds1da177e2005-04-16 15:20:36 -07003550 /* Arrange for userspace references to be interpreted as kernel
3551 * pointers. That way we can pass a kernel pointer to a routine
3552 * that expects a __user pointer and it will work okay. */
3553 set_fs(get_ds());
3554
Linus Torvalds1da177e2005-04-16 15:20:36 -07003555 /* The main loop */
3556 while (fsg->state != FSG_STATE_TERMINATED) {
3557 if (exception_in_progress(fsg) || signal_pending(current)) {
3558 handle_exception(fsg);
3559 continue;
3560 }
3561
3562 if (!fsg->running) {
3563 sleep_thread(fsg);
3564 continue;
3565 }
3566
3567 if (get_next_command(fsg))
3568 continue;
3569
3570 spin_lock_irq(&fsg->lock);
3571 if (!exception_in_progress(fsg))
3572 fsg->state = FSG_STATE_DATA_PHASE;
3573 spin_unlock_irq(&fsg->lock);
3574
3575 if (do_scsi_command(fsg) || finish_reply(fsg))
3576 continue;
3577
3578 spin_lock_irq(&fsg->lock);
3579 if (!exception_in_progress(fsg))
3580 fsg->state = FSG_STATE_STATUS_PHASE;
3581 spin_unlock_irq(&fsg->lock);
3582
3583 if (send_status(fsg))
3584 continue;
3585
3586 spin_lock_irq(&fsg->lock);
3587 if (!exception_in_progress(fsg))
3588 fsg->state = FSG_STATE_IDLE;
3589 spin_unlock_irq(&fsg->lock);
3590 }
3591
Alan Stern22efcf42005-09-26 16:12:02 -04003592 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003593 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003594 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003595
3596 /* In case we are exiting because of a signal, unregister the
3597 * gadget driver and close the backing file. */
3598 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) {
3599 usb_gadget_unregister_driver(&fsg_driver);
3600 close_all_backing_files(fsg);
3601 }
3602
3603 /* Let the unbind and cleanup routines know the thread has exited */
3604 complete_and_exit(&fsg->thread_notifier, 0);
3605}
3606
3607
3608/*-------------------------------------------------------------------------*/
3609
3610/* If the next two routines are called while the gadget is registered,
3611 * the caller must own fsg->filesem for writing. */
3612
3613static int open_backing_file(struct lun *curlun, const char *filename)
3614{
3615 int ro;
3616 struct file *filp = NULL;
3617 int rc = -EINVAL;
3618 struct inode *inode = NULL;
3619 loff_t size;
3620 loff_t num_sectors;
Alan Stern12aae682008-11-20 14:13:12 -05003621 loff_t min_sectors;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003622
3623 /* R/W if we can, R/O if we must */
3624 ro = curlun->ro;
3625 if (!ro) {
3626 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3627 if (-EROFS == PTR_ERR(filp))
3628 ro = 1;
3629 }
3630 if (ro)
3631 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3632 if (IS_ERR(filp)) {
3633 LINFO(curlun, "unable to open backing file: %s\n", filename);
3634 return PTR_ERR(filp);
3635 }
3636
3637 if (!(filp->f_mode & FMODE_WRITE))
3638 ro = 1;
3639
Josef Sipek33cb8992006-12-08 02:37:46 -08003640 if (filp->f_path.dentry)
3641 inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003642 if (inode && S_ISBLK(inode->i_mode)) {
3643 if (bdev_read_only(inode->i_bdev))
3644 ro = 1;
3645 } else if (!inode || !S_ISREG(inode->i_mode)) {
3646 LINFO(curlun, "invalid file type: %s\n", filename);
3647 goto out;
3648 }
3649
3650 /* If we can't read the file, it's no good.
3651 * If we can't write the file, use it read-only. */
3652 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3653 LINFO(curlun, "file not readable: %s\n", filename);
3654 goto out;
3655 }
3656 if (!(filp->f_op->write || filp->f_op->aio_write))
3657 ro = 1;
3658
3659 size = i_size_read(inode->i_mapping->host);
3660 if (size < 0) {
3661 LINFO(curlun, "unable to find file size: %s\n", filename);
3662 rc = (int) size;
3663 goto out;
3664 }
Alan Stern12aae682008-11-20 14:13:12 -05003665 num_sectors = size >> 9; // File size in 512-byte blocks
3666 min_sectors = 1;
3667 if (mod_data.cdrom) {
3668 num_sectors &= ~3; // Reduce to a multiple of 2048
3669 min_sectors = 300*4; // Smallest track is 300 frames
3670 if (num_sectors >= 256*60*75*4) {
3671 num_sectors = (256*60*75 - 1) * 4;
3672 LINFO(curlun, "file too big: %s\n", filename);
3673 LINFO(curlun, "using only first %d blocks\n",
3674 (int) num_sectors);
3675 }
3676 }
3677 if (num_sectors < min_sectors) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003678 LINFO(curlun, "file too small: %s\n", filename);
3679 rc = -ETOOSMALL;
3680 goto out;
3681 }
3682
3683 get_file(filp);
3684 curlun->ro = ro;
3685 curlun->filp = filp;
3686 curlun->file_length = size;
3687 curlun->num_sectors = num_sectors;
3688 LDBG(curlun, "open backing file: %s\n", filename);
3689 rc = 0;
3690
3691out:
3692 filp_close(filp, current->files);
3693 return rc;
3694}
3695
3696
3697static void close_backing_file(struct lun *curlun)
3698{
3699 if (curlun->filp) {
3700 LDBG(curlun, "close backing file\n");
3701 fput(curlun->filp);
3702 curlun->filp = NULL;
3703 }
3704}
3705
3706static void close_all_backing_files(struct fsg_dev *fsg)
3707{
3708 int i;
3709
3710 for (i = 0; i < fsg->nluns; ++i)
3711 close_backing_file(&fsg->luns[i]);
3712}
3713
3714
Yani Ioannou10523b32005-05-17 06:43:37 -04003715static ssize_t show_ro(struct device *dev, struct device_attribute *attr, char *buf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003716{
3717 struct lun *curlun = dev_to_lun(dev);
3718
3719 return sprintf(buf, "%d\n", curlun->ro);
3720}
3721
Alan Stern79a7d9e2007-08-08 17:10:11 -04003722static ssize_t show_file(struct device *dev, struct device_attribute *attr,
3723 char *buf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003724{
3725 struct lun *curlun = dev_to_lun(dev);
John Daiker7ca46b82006-12-29 19:02:06 -08003726 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003727 char *p;
3728 ssize_t rc;
3729
3730 down_read(&fsg->filesem);
3731 if (backing_file_is_open(curlun)) { // Get the complete pathname
Jan Blunckcf28b482008-02-14 19:38:44 -08003732 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003733 if (IS_ERR(p))
3734 rc = PTR_ERR(p);
3735 else {
3736 rc = strlen(p);
3737 memmove(buf, p, rc);
3738 buf[rc] = '\n'; // Add a newline
3739 buf[++rc] = 0;
3740 }
3741 } else { // No file, return 0 bytes
3742 *buf = 0;
3743 rc = 0;
3744 }
3745 up_read(&fsg->filesem);
3746 return rc;
3747}
3748
3749
Alan Stern79a7d9e2007-08-08 17:10:11 -04003750static ssize_t store_ro(struct device *dev, struct device_attribute *attr,
3751 const char *buf, size_t count)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003752{
3753 ssize_t rc = count;
3754 struct lun *curlun = dev_to_lun(dev);
John Daiker7ca46b82006-12-29 19:02:06 -08003755 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003756 int i;
3757
3758 if (sscanf(buf, "%d", &i) != 1)
3759 return -EINVAL;
3760
3761 /* Allow the write-enable status to change only while the backing file
3762 * is closed. */
3763 down_read(&fsg->filesem);
3764 if (backing_file_is_open(curlun)) {
3765 LDBG(curlun, "read-only status change prevented\n");
3766 rc = -EBUSY;
3767 } else {
3768 curlun->ro = !!i;
3769 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3770 }
3771 up_read(&fsg->filesem);
3772 return rc;
3773}
3774
Alan Stern79a7d9e2007-08-08 17:10:11 -04003775static ssize_t store_file(struct device *dev, struct device_attribute *attr,
3776 const char *buf, size_t count)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003777{
3778 struct lun *curlun = dev_to_lun(dev);
John Daiker7ca46b82006-12-29 19:02:06 -08003779 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003780 int rc = 0;
3781
3782 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3783 LDBG(curlun, "eject attempt prevented\n");
3784 return -EBUSY; // "Door is locked"
3785 }
3786
3787 /* Remove a trailing newline */
3788 if (count > 0 && buf[count-1] == '\n')
3789 ((char *) buf)[count-1] = 0; // Ugh!
3790
3791 /* Eject current medium */
3792 down_write(&fsg->filesem);
3793 if (backing_file_is_open(curlun)) {
3794 close_backing_file(curlun);
3795 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3796 }
3797
3798 /* Load new medium */
3799 if (count > 0 && buf[0]) {
3800 rc = open_backing_file(curlun, buf);
3801 if (rc == 0)
3802 curlun->unit_attention_data =
3803 SS_NOT_READY_TO_READY_TRANSITION;
3804 }
3805 up_write(&fsg->filesem);
3806 return (rc < 0 ? rc : count);
3807}
3808
3809
3810/* The write permissions and store_xxx pointers are set in fsg_bind() */
3811static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3812static DEVICE_ATTR(file, 0444, show_file, NULL);
3813
3814
3815/*-------------------------------------------------------------------------*/
3816
Alan Stern87c42522005-11-09 16:59:56 -05003817static void fsg_release(struct kref *ref)
3818{
3819 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3820
3821 kfree(fsg->luns);
3822 kfree(fsg);
3823}
3824
Linus Torvalds1da177e2005-04-16 15:20:36 -07003825static void lun_release(struct device *dev)
3826{
John Daiker7ca46b82006-12-29 19:02:06 -08003827 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003828
Alan Stern87c42522005-11-09 16:59:56 -05003829 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003830}
3831
David Brownella3536782006-07-06 15:48:53 -07003832static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003833{
3834 struct fsg_dev *fsg = get_gadget_data(gadget);
3835 int i;
3836 struct lun *curlun;
3837 struct usb_request *req = fsg->ep0req;
3838
3839 DBG(fsg, "unbind\n");
3840 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3841
3842 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003843 for (i = 0; i < fsg->nluns; ++i) {
3844 curlun = &fsg->luns[i];
3845 if (curlun->registered) {
3846 device_remove_file(&curlun->dev, &dev_attr_ro);
3847 device_remove_file(&curlun->dev, &dev_attr_file);
3848 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003849 curlun->registered = 0;
3850 }
3851 }
3852
3853 /* If the thread isn't already dead, tell it to exit now */
3854 if (fsg->state != FSG_STATE_TERMINATED) {
3855 raise_exception(fsg, FSG_STATE_EXIT);
3856 wait_for_completion(&fsg->thread_notifier);
3857
3858 /* The cleanup routine waits for this completion also */
3859 complete(&fsg->thread_notifier);
3860 }
3861
3862 /* Free the data buffers */
David Brownell9d8bab52007-07-01 11:04:54 -07003863 for (i = 0; i < NUM_BUFFERS; ++i)
3864 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003865
3866 /* Free the request and buffer for endpoint 0 */
3867 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003868 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003869 usb_ep_free_request(fsg->ep0, req);
3870 }
3871
3872 set_gadget_data(gadget, NULL);
3873}
3874
3875
3876static int __init check_parameters(struct fsg_dev *fsg)
3877{
3878 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003879 int gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003880
3881 /* Store the default values */
3882 mod_data.transport_type = USB_PR_BULK;
3883 mod_data.transport_name = "Bulk-only";
3884 mod_data.protocol_type = USB_SC_SCSI;
3885 mod_data.protocol_name = "Transparent SCSI";
3886
Alan Sternce459ec2009-02-24 16:19:47 -05003887 /* Some peripheral controllers are known not to be able to
3888 * halt bulk endpoints correctly. If one of them is present,
3889 * disable stalls.
3890 */
3891 if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003892 mod_data.can_stall = 0;
3893
3894 if (mod_data.release == 0xffff) { // Parameter wasn't set
Linus Torvalds1da177e2005-04-16 15:20:36 -07003895 /* The sa1100 controller is not supported */
David Brownell91e79c92005-07-13 15:18:30 -07003896 if (gadget_is_sa1100(fsg->gadget))
3897 gcnum = -1;
3898 else
3899 gcnum = usb_gadget_controller_number(fsg->gadget);
3900 if (gcnum >= 0)
3901 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003902 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003903 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003904 fsg->gadget->name);
3905 mod_data.release = 0x0399;
3906 }
3907 }
3908
3909 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3910
3911#ifdef CONFIG_USB_FILE_STORAGE_TEST
3912 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3913 ; // Use default setting
3914 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3915 mod_data.transport_type = USB_PR_CB;
3916 mod_data.transport_name = "Control-Bulk";
3917 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3918 mod_data.transport_type = USB_PR_CBI;
3919 mod_data.transport_name = "Control-Bulk-Interrupt";
3920 } else {
3921 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3922 return -EINVAL;
3923 }
3924
3925 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3926 prot == USB_SC_SCSI) {
3927 ; // Use default setting
3928 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3929 prot == USB_SC_RBC) {
3930 mod_data.protocol_type = USB_SC_RBC;
3931 mod_data.protocol_name = "RBC";
3932 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3933 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3934 prot == USB_SC_8020) {
3935 mod_data.protocol_type = USB_SC_8020;
3936 mod_data.protocol_name = "8020i (ATAPI)";
3937 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3938 prot == USB_SC_QIC) {
3939 mod_data.protocol_type = USB_SC_QIC;
3940 mod_data.protocol_name = "QIC-157";
3941 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3942 prot == USB_SC_UFI) {
3943 mod_data.protocol_type = USB_SC_UFI;
3944 mod_data.protocol_name = "UFI";
3945 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3946 prot == USB_SC_8070) {
3947 mod_data.protocol_type = USB_SC_8070;
3948 mod_data.protocol_name = "8070i";
3949 } else {
3950 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3951 return -EINVAL;
3952 }
3953
3954 mod_data.buflen &= PAGE_CACHE_MASK;
3955 if (mod_data.buflen <= 0) {
3956 ERROR(fsg, "invalid buflen\n");
3957 return -ETOOSMALL;
3958 }
3959#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3960
3961 return 0;
3962}
3963
3964
3965static int __init fsg_bind(struct usb_gadget *gadget)
3966{
3967 struct fsg_dev *fsg = the_fsg;
3968 int rc;
3969 int i;
3970 struct lun *curlun;
3971 struct usb_ep *ep;
3972 struct usb_request *req;
3973 char *pathbuf, *p;
3974
3975 fsg->gadget = gadget;
3976 set_gadget_data(gadget, fsg);
3977 fsg->ep0 = gadget->ep0;
3978 fsg->ep0->driver_data = fsg;
3979
3980 if ((rc = check_parameters(fsg)) != 0)
3981 goto out;
3982
3983 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003984 dev_attr_file.attr.mode = 0644;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003985 dev_attr_file.store = store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003986 if (!mod_data.cdrom) {
3987 dev_attr_ro.attr.mode = 0644;
3988 dev_attr_ro.store = store_ro;
3989 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003990 }
3991
3992 /* Find out how many LUNs there should be */
3993 i = mod_data.nluns;
3994 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003995 i = max(mod_data.num_filenames, 1u);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003996 if (i > MAX_LUNS) {
3997 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3998 rc = -EINVAL;
3999 goto out;
4000 }
4001
4002 /* Create the LUNs, open their backing files, and register the
4003 * LUN devices in sysfs. */
Alan Sterna922c682005-10-06 16:38:45 -04004004 fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004005 if (!fsg->luns) {
4006 rc = -ENOMEM;
4007 goto out;
4008 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07004009 fsg->nluns = i;
4010
4011 for (i = 0; i < fsg->nluns; ++i) {
4012 curlun = &fsg->luns[i];
Alan Sternaafe5bd2006-03-31 11:46:43 -05004013 curlun->ro = mod_data.ro[i];
Alan Stern12aae682008-11-20 14:13:12 -05004014 if (mod_data.cdrom)
4015 curlun->ro = 1;
Alan Stern2de9eae2006-09-25 14:31:15 -04004016 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004017 curlun->dev.parent = &gadget->dev;
4018 curlun->dev.driver = &fsg_driver.driver;
4019 dev_set_drvdata(&curlun->dev, fsg);
Kay Sievers0031a062008-05-02 06:02:41 +02004020 dev_set_name(&curlun->dev,"%s-lun%d",
4021 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004022
Alan Stern2de9eae2006-09-25 14:31:15 -04004023 if ((rc = device_register(&curlun->dev)) != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07004024 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Alan Stern2de9eae2006-09-25 14:31:15 -04004025 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004026 }
Alan Stern2de9eae2006-09-25 14:31:15 -04004027 if ((rc = device_create_file(&curlun->dev,
4028 &dev_attr_ro)) != 0 ||
4029 (rc = device_create_file(&curlun->dev,
4030 &dev_attr_file)) != 0) {
4031 device_unregister(&curlun->dev);
4032 goto out;
4033 }
4034 curlun->registered = 1;
4035 kref_get(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004036
Alan Sternaafe5bd2006-03-31 11:46:43 -05004037 if (mod_data.file[i] && *mod_data.file[i]) {
4038 if ((rc = open_backing_file(curlun,
4039 mod_data.file[i])) != 0)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004040 goto out;
4041 } else if (!mod_data.removable) {
4042 ERROR(fsg, "no file given for LUN%d\n", i);
4043 rc = -EINVAL;
4044 goto out;
4045 }
4046 }
4047
4048 /* Find all the endpoints we will use */
4049 usb_ep_autoconfig_reset(gadget);
4050 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
4051 if (!ep)
4052 goto autoconf_fail;
4053 ep->driver_data = fsg; // claim the endpoint
4054 fsg->bulk_in = ep;
4055
4056 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
4057 if (!ep)
4058 goto autoconf_fail;
4059 ep->driver_data = fsg; // claim the endpoint
4060 fsg->bulk_out = ep;
4061
4062 if (transport_is_cbi()) {
4063 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
4064 if (!ep)
4065 goto autoconf_fail;
4066 ep->driver_data = fsg; // claim the endpoint
4067 fsg->intr_in = ep;
4068 }
4069
4070 /* Fix up the descriptors */
4071 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
4072 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
4073 device_desc.idProduct = cpu_to_le16(mod_data.product);
4074 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
4075
4076 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
4077 intf_desc.bNumEndpoints = i;
4078 intf_desc.bInterfaceSubClass = mod_data.protocol_type;
4079 intf_desc.bInterfaceProtocol = mod_data.transport_type;
4080 fs_function[i + FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
4081
David Brownell2e806f62007-08-02 00:03:39 -07004082 if (gadget_is_dualspeed(gadget)) {
4083 hs_function[i + HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004084
David Brownell2e806f62007-08-02 00:03:39 -07004085 /* Assume ep0 uses the same maxpacket value for both speeds */
4086 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004087
David Brownell2e806f62007-08-02 00:03:39 -07004088 /* Assume endpoint addresses are the same for both speeds */
4089 hs_bulk_in_desc.bEndpointAddress =
4090 fs_bulk_in_desc.bEndpointAddress;
4091 hs_bulk_out_desc.bEndpointAddress =
4092 fs_bulk_out_desc.bEndpointAddress;
4093 hs_intr_in_desc.bEndpointAddress =
4094 fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004095 }
4096
David Brownell2e806f62007-08-02 00:03:39 -07004097 if (gadget_is_otg(gadget))
4098 otg_desc.bmAttributes |= USB_OTG_HNP;
4099
Linus Torvalds1da177e2005-04-16 15:20:36 -07004100 rc = -ENOMEM;
4101
4102 /* Allocate the request and buffer for endpoint 0 */
4103 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
4104 if (!req)
4105 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07004106 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004107 if (!req->buf)
4108 goto out;
4109 req->complete = ep0_complete;
4110
4111 /* Allocate the data buffers */
4112 for (i = 0; i < NUM_BUFFERS; ++i) {
4113 struct fsg_buffhd *bh = &fsg->buffhds[i];
4114
Alan Stern14cd5f82006-03-23 15:07:25 -05004115 /* Allocate for the bulk-in endpoint. We assume that
4116 * the buffer will also work with the bulk-out (and
4117 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07004118 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004119 if (!bh->buf)
4120 goto out;
4121 bh->next = bh + 1;
4122 }
4123 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
4124
4125 /* This should reflect the actual gadget power source */
4126 usb_gadget_set_selfpowered(gadget);
4127
4128 snprintf(manufacturer, sizeof manufacturer, "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07004129 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07004130 gadget->name);
4131
4132 /* On a real device, serial[] would be loaded from permanent
4133 * storage. We just encode it from the driver version string. */
4134 for (i = 0; i < sizeof(serial) - 2; i += 2) {
4135 unsigned char c = DRIVER_VERSION[i / 2];
4136
4137 if (!c)
4138 break;
4139 sprintf(&serial[i], "%02X", c);
4140 }
4141
Alan Stern22efcf42005-09-26 16:12:02 -04004142 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
4143 "file-storage-gadget");
4144 if (IS_ERR(fsg->thread_task)) {
4145 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004146 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04004147 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07004148
4149 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
4150 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
4151
4152 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4153 for (i = 0; i < fsg->nluns; ++i) {
4154 curlun = &fsg->luns[i];
4155 if (backing_file_is_open(curlun)) {
4156 p = NULL;
4157 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08004158 p = d_path(&curlun->filp->f_path,
4159 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004160 if (IS_ERR(p))
4161 p = NULL;
4162 }
4163 LINFO(curlun, "ro=%d, file: %s\n",
4164 curlun->ro, (p ? p : "(error)"));
4165 }
4166 }
4167 kfree(pathbuf);
4168
4169 DBG(fsg, "transport=%s (x%02x)\n",
4170 mod_data.transport_name, mod_data.transport_type);
4171 DBG(fsg, "protocol=%s (x%02x)\n",
4172 mod_data.protocol_name, mod_data.protocol_type);
4173 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
4174 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05004175 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07004176 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05004177 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07004178 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04004179
4180 set_bit(REGISTERED, &fsg->atomic_bitflags);
4181
4182 /* Tell the thread to start working */
4183 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004184 return 0;
4185
4186autoconf_fail:
4187 ERROR(fsg, "unable to autoconfigure all endpoints\n");
4188 rc = -ENOTSUPP;
4189
4190out:
4191 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
4192 fsg_unbind(gadget);
4193 close_all_backing_files(fsg);
Felipe Balbi889394b2008-12-08 13:50:27 +02004194 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004195 return rc;
4196}
4197
4198
4199/*-------------------------------------------------------------------------*/
4200
4201static void fsg_suspend(struct usb_gadget *gadget)
4202{
4203 struct fsg_dev *fsg = get_gadget_data(gadget);
4204
4205 DBG(fsg, "suspend\n");
4206 set_bit(SUSPENDED, &fsg->atomic_bitflags);
4207}
4208
4209static void fsg_resume(struct usb_gadget *gadget)
4210{
4211 struct fsg_dev *fsg = get_gadget_data(gadget);
4212
4213 DBG(fsg, "resume\n");
4214 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
4215}
4216
4217
4218/*-------------------------------------------------------------------------*/
4219
4220static struct usb_gadget_driver fsg_driver = {
4221#ifdef CONFIG_USB_GADGET_DUALSPEED
4222 .speed = USB_SPEED_HIGH,
4223#else
4224 .speed = USB_SPEED_FULL,
4225#endif
4226 .function = (char *) longname,
4227 .bind = fsg_bind,
David Brownell6bea4762006-12-05 03:15:33 -08004228 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07004229 .disconnect = fsg_disconnect,
4230 .setup = fsg_setup,
4231 .suspend = fsg_suspend,
4232 .resume = fsg_resume,
4233
4234 .driver = {
4235 .name = (char *) shortname,
Ben Dooksd0d50492005-10-10 10:52:33 +01004236 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07004237 // .release = ...
4238 // .suspend = ...
4239 // .resume = ...
4240 },
4241};
4242
4243
4244static int __init fsg_alloc(void)
4245{
4246 struct fsg_dev *fsg;
4247
Alan Sterna922c682005-10-06 16:38:45 -04004248 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004249 if (!fsg)
4250 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004251 spin_lock_init(&fsg->lock);
4252 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05004253 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004254 init_completion(&fsg->thread_notifier);
4255
4256 the_fsg = fsg;
4257 return 0;
4258}
4259
4260
Linus Torvalds1da177e2005-04-16 15:20:36 -07004261static int __init fsg_init(void)
4262{
4263 int rc;
4264 struct fsg_dev *fsg;
4265
4266 if ((rc = fsg_alloc()) != 0)
4267 return rc;
4268 fsg = the_fsg;
Alan Sterna922c682005-10-06 16:38:45 -04004269 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05004270 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04004271 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004272}
4273module_init(fsg_init);
4274
4275
4276static void __exit fsg_cleanup(void)
4277{
4278 struct fsg_dev *fsg = the_fsg;
4279
4280 /* Unregister the driver iff the thread hasn't already done so */
4281 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4282 usb_gadget_unregister_driver(&fsg_driver);
4283
4284 /* Wait for the thread to finish up */
4285 wait_for_completion(&fsg->thread_notifier);
4286
4287 close_all_backing_files(fsg);
Alan Stern87c42522005-11-09 16:59:56 -05004288 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004289}
4290module_exit(fsg_cleanup);