blob: b49d86e3e45b639d2d3f4760d027e38a0fd52d44 [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
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100275static char fsg_string_manufacturer[64];
276static const char fsg_string_product[] = DRIVER_DESC;
277static char fsg_string_serial[13];
278static const char fsg_string_config[] = "Self-powered";
279static const char fsg_string_interface[] = "Mass Storage";
Linus Torvalds1da177e2005-04-16 15:20:36 -0700280
Michal Nazarewicz93f93742009-10-28 16:57:17 +0100281
282#include "storage_common.c"
283
284
Linus Torvalds1da177e2005-04-16 15:20:36 -0700285MODULE_DESCRIPTION(DRIVER_DESC);
286MODULE_AUTHOR("Alan Stern");
287MODULE_LICENSE("Dual BSD/GPL");
288
Linus Torvalds1da177e2005-04-16 15:20:36 -0700289/*
290 * This driver assumes self-powered hardware and has no way for users to
291 * trigger remote wakeup. It uses autoconfiguration to select endpoints
292 * and endpoint addresses.
293 */
294
295
296/*-------------------------------------------------------------------------*/
297
Linus Torvalds1da177e2005-04-16 15:20:36 -0700298
299/* Encapsulate the module parameter settings */
300
Linus Torvalds1da177e2005-04-16 15:20:36 -0700301static struct {
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100302 char *file[FSG_MAX_LUNS];
303 int ro[FSG_MAX_LUNS];
David Brownell2e806f62007-08-02 00:03:39 -0700304 unsigned int num_filenames;
305 unsigned int num_ros;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700306 unsigned int nluns;
307
Alan Sternd794ac72005-04-18 12:43:25 -0400308 int removable;
309 int can_stall;
Alan Stern12aae682008-11-20 14:13:12 -0500310 int cdrom;
Alan Sternd794ac72005-04-18 12:43:25 -0400311
Linus Torvalds1da177e2005-04-16 15:20:36 -0700312 char *transport_parm;
313 char *protocol_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700314 unsigned short vendor;
315 unsigned short product;
316 unsigned short release;
317 unsigned int buflen;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700318
319 int transport_type;
320 char *transport_name;
321 int protocol_type;
322 char *protocol_name;
323
324} mod_data = { // Default values
325 .transport_parm = "BBB",
326 .protocol_parm = "SCSI",
327 .removable = 0,
Alan Sternd794ac72005-04-18 12:43:25 -0400328 .can_stall = 1,
Alan Stern12aae682008-11-20 14:13:12 -0500329 .cdrom = 0,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100330 .vendor = FSG_VENDOR_ID,
331 .product = FSG_PRODUCT_ID,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700332 .release = 0xffff, // Use controller chip type
333 .buflen = 16384,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700334 };
335
336
Alan Sternaafe5bd2006-03-31 11:46:43 -0500337module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
338 S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700339MODULE_PARM_DESC(file, "names of backing files or devices");
340
Alan Sternaafe5bd2006-03-31 11:46:43 -0500341module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700342MODULE_PARM_DESC(ro, "true to force read-only");
343
344module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
345MODULE_PARM_DESC(luns, "number of LUNs");
346
347module_param_named(removable, mod_data.removable, bool, S_IRUGO);
348MODULE_PARM_DESC(removable, "true to simulate removable media");
349
Alan Sternd794ac72005-04-18 12:43:25 -0400350module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
351MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
352
Alan Stern12aae682008-11-20 14:13:12 -0500353module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
354MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
355
Linus Torvalds1da177e2005-04-16 15:20:36 -0700356
357/* In the non-TEST version, only the module parameters listed above
358 * are available. */
359#ifdef CONFIG_USB_FILE_STORAGE_TEST
360
361module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
362MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
363
364module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
365MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
366 "8070, or SCSI)");
367
368module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
369MODULE_PARM_DESC(vendor, "USB Vendor ID");
370
371module_param_named(product, mod_data.product, ushort, S_IRUGO);
372MODULE_PARM_DESC(product, "USB Product ID");
373
374module_param_named(release, mod_data.release, ushort, S_IRUGO);
375MODULE_PARM_DESC(release, "USB release number");
376
377module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
378MODULE_PARM_DESC(buflen, "I/O buffer size");
379
Linus Torvalds1da177e2005-04-16 15:20:36 -0700380#endif /* CONFIG_USB_FILE_STORAGE_TEST */
381
382
Linus Torvalds1da177e2005-04-16 15:20:36 -0700383/*
384 * These definitions will permit the compiler to avoid generating code for
385 * parts of the driver that aren't used in the non-TEST version. Even gcc
386 * can recognize when a test of a constant expression yields a dead code
387 * path.
388 */
389
390#ifdef CONFIG_USB_FILE_STORAGE_TEST
391
392#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
393#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
394#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
395
396#else
397
398#define transport_is_bbb() 1
399#define transport_is_cbi() 0
400#define protocol_is_scsi() 1
401
402#endif /* CONFIG_USB_FILE_STORAGE_TEST */
403
404
Michal Nazarewiczb6058d02009-10-28 16:57:14 +0100405/*-------------------------------------------------------------------------*/
Linus Torvalds1da177e2005-04-16 15:20:36 -0700406
Linus Torvalds1da177e2005-04-16 15:20:36 -0700407
408struct fsg_dev {
409 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
410 spinlock_t lock;
411 struct usb_gadget *gadget;
412
413 /* filesem protects: backing files in use */
414 struct rw_semaphore filesem;
415
Alan Stern87c42522005-11-09 16:59:56 -0500416 /* reference counting: wait until all LUNs are released */
417 struct kref ref;
418
Linus Torvalds1da177e2005-04-16 15:20:36 -0700419 struct usb_ep *ep0; // Handy copy of gadget->ep0
420 struct usb_request *ep0req; // For control responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500421 unsigned int ep0_req_tag;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700422 const char *ep0req_name;
423
424 struct usb_request *intreq; // For interrupt responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500425 int intreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700426 struct fsg_buffhd *intr_buffhd;
427
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100428 unsigned int bulk_out_maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700429 enum fsg_state state; // For exception handling
430 unsigned int exception_req_tag;
431
432 u8 config, new_config;
433
434 unsigned int running : 1;
435 unsigned int bulk_in_enabled : 1;
436 unsigned int bulk_out_enabled : 1;
437 unsigned int intr_in_enabled : 1;
438 unsigned int phase_error : 1;
439 unsigned int short_packet_received : 1;
440 unsigned int bad_lun_okay : 1;
441
442 unsigned long atomic_bitflags;
443#define REGISTERED 0
Alan Sternb950bdb2008-04-14 11:45:29 -0400444#define IGNORE_BULK_OUT 1
Linus Torvalds1da177e2005-04-16 15:20:36 -0700445#define SUSPENDED 2
446
447 struct usb_ep *bulk_in;
448 struct usb_ep *bulk_out;
449 struct usb_ep *intr_in;
450
451 struct fsg_buffhd *next_buffhd_to_fill;
452 struct fsg_buffhd *next_buffhd_to_drain;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100453 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700454
Linus Torvalds1da177e2005-04-16 15:20:36 -0700455 int thread_wakeup_needed;
456 struct completion thread_notifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700457 struct task_struct *thread_task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700458
459 int cmnd_size;
460 u8 cmnd[MAX_COMMAND_SIZE];
461 enum data_direction data_dir;
462 u32 data_size;
463 u32 data_size_from_cmnd;
464 u32 tag;
465 unsigned int lun;
466 u32 residue;
467 u32 usb_amount_left;
468
469 /* The CB protocol offers no way for a host to know when a command
470 * has completed. As a result the next command may arrive early,
471 * and we will still have to handle it. For that reason we need
472 * a buffer to store new commands when using CB (or CBI, which
473 * does not oblige a host to wait for command completion either). */
474 int cbbuf_cmnd_size;
475 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
476
477 unsigned int nluns;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100478 struct fsg_lun *luns;
479 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700480};
481
482typedef void (*fsg_routine_t)(struct fsg_dev *);
483
Alan Stern79a7d9e2007-08-08 17:10:11 -0400484static int exception_in_progress(struct fsg_dev *fsg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700485{
486 return (fsg->state > FSG_STATE_IDLE);
487}
488
489/* Make bulk-out requests be divisible by the maxpacket size */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400490static void set_bulk_out_req_length(struct fsg_dev *fsg,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700491 struct fsg_buffhd *bh, unsigned int length)
492{
493 unsigned int rem;
494
495 bh->bulk_out_intended_length = length;
496 rem = length % fsg->bulk_out_maxpacket;
497 if (rem > 0)
498 length += fsg->bulk_out_maxpacket - rem;
499 bh->outreq->length = length;
500}
501
502static struct fsg_dev *the_fsg;
503static struct usb_gadget_driver fsg_driver;
504
Linus Torvalds1da177e2005-04-16 15:20:36 -0700505
506/*-------------------------------------------------------------------------*/
507
Linus Torvalds1da177e2005-04-16 15:20:36 -0700508static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
509{
510 const char *name;
511
512 if (ep == fsg->bulk_in)
513 name = "bulk-in";
514 else if (ep == fsg->bulk_out)
515 name = "bulk-out";
516 else
517 name = ep->name;
518 DBG(fsg, "%s set halt\n", name);
519 return usb_ep_set_halt(ep);
520}
521
522
523/*-------------------------------------------------------------------------*/
524
Linus Torvalds1da177e2005-04-16 15:20:36 -0700525/*
526 * DESCRIPTORS ... most are static, but strings and (full) configuration
527 * descriptors are built on demand. Also the (static) config and interface
528 * descriptors are adjusted during fsg_bind().
529 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700530
531/* There is only one configuration. */
532#define CONFIG_VALUE 1
533
534static struct usb_device_descriptor
535device_desc = {
536 .bLength = sizeof device_desc,
537 .bDescriptorType = USB_DT_DEVICE,
538
Harvey Harrison551509d2009-02-11 14:11:36 -0800539 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700540 .bDeviceClass = USB_CLASS_PER_INTERFACE,
541
542 /* The next three values can be overridden by module parameters */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100543 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
544 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
Harvey Harrison551509d2009-02-11 14:11:36 -0800545 .bcdDevice = cpu_to_le16(0xffff),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700546
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100547 .iManufacturer = FSG_STRING_MANUFACTURER,
548 .iProduct = FSG_STRING_PRODUCT,
549 .iSerialNumber = FSG_STRING_SERIAL,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700550 .bNumConfigurations = 1,
551};
552
553static struct usb_config_descriptor
554config_desc = {
555 .bLength = sizeof config_desc,
556 .bDescriptorType = USB_DT_CONFIG,
557
558 /* wTotalLength computed by usb_gadget_config_buf() */
559 .bNumInterfaces = 1,
560 .bConfigurationValue = CONFIG_VALUE,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100561 .iConfiguration = FSG_STRING_CONFIG,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700562 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
David Brownell36e893d2008-09-12 09:39:06 -0700563 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700564};
565
Linus Torvalds1da177e2005-04-16 15:20:36 -0700566
Linus Torvalds1da177e2005-04-16 15:20:36 -0700567static struct usb_qualifier_descriptor
568dev_qualifier = {
569 .bLength = sizeof dev_qualifier,
570 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
571
Harvey Harrison551509d2009-02-11 14:11:36 -0800572 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700573 .bDeviceClass = USB_CLASS_PER_INTERFACE,
574
575 .bNumConfigurations = 1,
576};
577
Linus Torvalds1da177e2005-04-16 15:20:36 -0700578
579
580/*
581 * Config descriptors must agree with the code that sets configurations
582 * and with code managing interfaces and their altsettings. They must
583 * also handle different speeds and other-speed requests.
584 */
585static int populate_config_buf(struct usb_gadget *gadget,
586 u8 *buf, u8 type, unsigned index)
587{
Linus Torvalds1da177e2005-04-16 15:20:36 -0700588 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700589 int len;
590 const struct usb_descriptor_header **function;
591
592 if (index > 0)
593 return -EINVAL;
594
David Brownell2e806f62007-08-02 00:03:39 -0700595 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700596 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
Michal Nazarewiczd23b0f02009-11-09 14:15:20 +0100597 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
598 ? (const struct usb_descriptor_header **)fsg_hs_function
599 : (const struct usb_descriptor_header **)fsg_fs_function;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700600
601 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -0700602 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700603 function++;
604
605 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
606 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
607 return len;
608}
609
610
611/*-------------------------------------------------------------------------*/
612
613/* These routines may be called in process context or in_irq */
614
Alan Sterna21d4fe2005-11-29 12:04:24 -0500615/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700616static void wakeup_thread(struct fsg_dev *fsg)
617{
618 /* Tell the main thread that something has happened */
619 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500620 if (fsg->thread_task)
621 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700622}
623
624
625static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
626{
627 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700628
629 /* Do nothing if a higher-priority exception is already in progress.
630 * If a lower-or-equal priority exception is in progress, preempt it
631 * and notify the main thread by sending it a signal. */
632 spin_lock_irqsave(&fsg->lock, flags);
633 if (fsg->state <= new_state) {
634 fsg->exception_req_tag = fsg->ep0_req_tag;
635 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -0400636 if (fsg->thread_task)
637 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
638 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700639 }
640 spin_unlock_irqrestore(&fsg->lock, flags);
641}
642
643
644/*-------------------------------------------------------------------------*/
645
646/* The disconnect callback and ep0 routines. These always run in_irq,
647 * except that ep0_queue() is called in the main thread to acknowledge
648 * completion of various requests: set config, set interface, and
649 * Bulk-only device reset. */
650
651static void fsg_disconnect(struct usb_gadget *gadget)
652{
653 struct fsg_dev *fsg = get_gadget_data(gadget);
654
655 DBG(fsg, "disconnect or port reset\n");
656 raise_exception(fsg, FSG_STATE_DISCONNECT);
657}
658
659
660static int ep0_queue(struct fsg_dev *fsg)
661{
662 int rc;
663
664 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
665 if (rc != 0 && rc != -ESHUTDOWN) {
666
667 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -0700668 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -0700669 fsg->ep0->name, rc);
670 }
671 return rc;
672}
673
674static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
675{
John Daiker7ca46b82006-12-29 19:02:06 -0800676 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700677
678 if (req->actual > 0)
679 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
680 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800681 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700682 req->status, req->actual, req->length);
683 if (req->status == -ECONNRESET) // Request was cancelled
684 usb_ep_fifo_flush(ep);
685
686 if (req->status == 0 && req->context)
687 ((fsg_routine_t) (req->context))(fsg);
688}
689
690
691/*-------------------------------------------------------------------------*/
692
693/* Bulk and interrupt endpoint completion handlers.
694 * These always run in_irq. */
695
696static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
697{
John Daiker7ca46b82006-12-29 19:02:06 -0800698 struct fsg_dev *fsg = ep->driver_data;
699 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700700
701 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800702 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700703 req->status, req->actual, req->length);
704 if (req->status == -ECONNRESET) // Request was cancelled
705 usb_ep_fifo_flush(ep);
706
707 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500708 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700709 spin_lock(&fsg->lock);
710 bh->inreq_busy = 0;
711 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700712 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500713 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700714}
715
716static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
717{
John Daiker7ca46b82006-12-29 19:02:06 -0800718 struct fsg_dev *fsg = ep->driver_data;
719 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700720
721 dump_msg(fsg, "bulk-out", req->buf, req->actual);
722 if (req->status || req->actual != bh->bulk_out_intended_length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800723 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700724 req->status, req->actual,
725 bh->bulk_out_intended_length);
726 if (req->status == -ECONNRESET) // Request was cancelled
727 usb_ep_fifo_flush(ep);
728
729 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500730 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700731 spin_lock(&fsg->lock);
732 bh->outreq_busy = 0;
733 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700734 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500735 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700736}
737
738
739#ifdef CONFIG_USB_FILE_STORAGE_TEST
740static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
741{
John Daiker7ca46b82006-12-29 19:02:06 -0800742 struct fsg_dev *fsg = ep->driver_data;
743 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700744
745 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800746 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700747 req->status, req->actual, req->length);
748 if (req->status == -ECONNRESET) // Request was cancelled
749 usb_ep_fifo_flush(ep);
750
751 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500752 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700753 spin_lock(&fsg->lock);
754 fsg->intreq_busy = 0;
755 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700756 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500757 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700758}
759
760#else
761static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
762{}
763#endif /* CONFIG_USB_FILE_STORAGE_TEST */
764
765
766/*-------------------------------------------------------------------------*/
767
768/* Ep0 class-specific handlers. These always run in_irq. */
769
770#ifdef CONFIG_USB_FILE_STORAGE_TEST
771static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
772{
773 struct usb_request *req = fsg->ep0req;
774 static u8 cbi_reset_cmnd[6] = {
775 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
776
777 /* Error in command transfer? */
778 if (req->status || req->length != req->actual ||
779 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
780
781 /* Not all controllers allow a protocol stall after
782 * receiving control-out data, but we'll try anyway. */
783 fsg_set_halt(fsg, fsg->ep0);
784 return; // Wait for reset
785 }
786
787 /* Is it the special reset command? */
788 if (req->actual >= sizeof cbi_reset_cmnd &&
789 memcmp(req->buf, cbi_reset_cmnd,
790 sizeof cbi_reset_cmnd) == 0) {
791
792 /* Raise an exception to stop the current operation
793 * and reinitialize our state. */
794 DBG(fsg, "cbi reset request\n");
795 raise_exception(fsg, FSG_STATE_RESET);
796 return;
797 }
798
799 VDBG(fsg, "CB[I] accept device-specific command\n");
800 spin_lock(&fsg->lock);
801
802 /* Save the command for later */
803 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700804 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700805 fsg->cbbuf_cmnd_size = req->actual;
806 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
807
Linus Torvalds1da177e2005-04-16 15:20:36 -0700808 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500809 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700810}
811
812#else
813static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
814{}
815#endif /* CONFIG_USB_FILE_STORAGE_TEST */
816
817
818static int class_setup_req(struct fsg_dev *fsg,
819 const struct usb_ctrlrequest *ctrl)
820{
821 struct usb_request *req = fsg->ep0req;
822 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700823 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -0400824 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -0700825 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700826
827 if (!fsg->config)
828 return value;
829
830 /* Handle Bulk-only class-specific requests */
831 if (transport_is_bbb()) {
832 switch (ctrl->bRequest) {
833
834 case USB_BULK_RESET_REQUEST:
835 if (ctrl->bRequestType != (USB_DIR_OUT |
836 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
837 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400838 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700839 value = -EDOM;
840 break;
841 }
842
843 /* Raise an exception to stop the current operation
844 * and reinitialize our state. */
845 DBG(fsg, "bulk reset request\n");
846 raise_exception(fsg, FSG_STATE_RESET);
847 value = DELAYED_STATUS;
848 break;
849
850 case USB_BULK_GET_MAX_LUN_REQUEST:
851 if (ctrl->bRequestType != (USB_DIR_IN |
852 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
853 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400854 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700855 value = -EDOM;
856 break;
857 }
858 VDBG(fsg, "get max LUN\n");
859 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -0400860 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700861 break;
862 }
863 }
864
865 /* Handle CBI class-specific requests */
866 else {
867 switch (ctrl->bRequest) {
868
869 case USB_CBI_ADSC_REQUEST:
870 if (ctrl->bRequestType != (USB_DIR_OUT |
871 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
872 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400873 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700874 value = -EDOM;
875 break;
876 }
877 if (w_length > MAX_COMMAND_SIZE) {
878 value = -EOVERFLOW;
879 break;
880 }
881 value = w_length;
882 fsg->ep0req->context = received_cbi_adsc;
883 break;
884 }
885 }
886
887 if (value == -EOPNOTSUPP)
888 VDBG(fsg,
889 "unknown class-specific control req "
890 "%02x.%02x v%04x i%04x l%u\n",
891 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -0700892 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 return value;
894}
895
896
897/*-------------------------------------------------------------------------*/
898
899/* Ep0 standard request handlers. These always run in_irq. */
900
901static int standard_setup_req(struct fsg_dev *fsg,
902 const struct usb_ctrlrequest *ctrl)
903{
904 struct usb_request *req = fsg->ep0req;
905 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700906 u16 w_index = le16_to_cpu(ctrl->wIndex);
907 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700908
909 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
910 * but config change events will also reconfigure hardware. */
911 switch (ctrl->bRequest) {
912
913 case USB_REQ_GET_DESCRIPTOR:
914 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
915 USB_RECIP_DEVICE))
916 break;
917 switch (w_value >> 8) {
918
919 case USB_DT_DEVICE:
920 VDBG(fsg, "get device descriptor\n");
Alan Stern76f4af82005-04-05 11:56:54 -0400921 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700922 memcpy(req->buf, &device_desc, value);
923 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700924 case USB_DT_DEVICE_QUALIFIER:
925 VDBG(fsg, "get device qualifier\n");
David Brownell2e806f62007-08-02 00:03:39 -0700926 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700927 break;
Alan Stern76f4af82005-04-05 11:56:54 -0400928 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700929 memcpy(req->buf, &dev_qualifier, value);
930 break;
931
932 case USB_DT_OTHER_SPEED_CONFIG:
933 VDBG(fsg, "get other-speed config descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700934 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700935 break;
936 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700937 case USB_DT_CONFIG:
938 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700939get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700940 value = populate_config_buf(fsg->gadget,
941 req->buf,
942 w_value >> 8,
943 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700944 break;
945
946 case USB_DT_STRING:
947 VDBG(fsg, "get string descriptor\n");
948
949 /* wIndex == language code */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100950 value = usb_gadget_get_string(&fsg_stringtab,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700952 break;
953 }
954 break;
955
956 /* One config, two speeds */
957 case USB_REQ_SET_CONFIGURATION:
958 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
959 USB_RECIP_DEVICE))
960 break;
961 VDBG(fsg, "set configuration\n");
962 if (w_value == CONFIG_VALUE || w_value == 0) {
963 fsg->new_config = w_value;
964
965 /* Raise an exception to wipe out previous transaction
966 * state (queued bufs, etc) and set the new config. */
967 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
968 value = DELAYED_STATUS;
969 }
970 break;
971 case USB_REQ_GET_CONFIGURATION:
972 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
973 USB_RECIP_DEVICE))
974 break;
975 VDBG(fsg, "get configuration\n");
976 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -0400977 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700978 break;
979
980 case USB_REQ_SET_INTERFACE:
981 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
982 USB_RECIP_INTERFACE))
983 break;
984 if (fsg->config && w_index == 0) {
985
986 /* Raise an exception to wipe out previous transaction
987 * state (queued bufs, etc) and install the new
988 * interface altsetting. */
989 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
990 value = DELAYED_STATUS;
991 }
992 break;
993 case USB_REQ_GET_INTERFACE:
994 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
995 USB_RECIP_INTERFACE))
996 break;
997 if (!fsg->config)
998 break;
999 if (w_index != 0) {
1000 value = -EDOM;
1001 break;
1002 }
1003 VDBG(fsg, "get interface\n");
1004 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001005 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001006 break;
1007
1008 default:
1009 VDBG(fsg,
1010 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1011 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001012 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001013 }
1014
1015 return value;
1016}
1017
1018
1019static int fsg_setup(struct usb_gadget *gadget,
1020 const struct usb_ctrlrequest *ctrl)
1021{
1022 struct fsg_dev *fsg = get_gadget_data(gadget);
1023 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001024 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001025
1026 ++fsg->ep0_req_tag; // Record arrival of a new request
1027 fsg->ep0req->context = NULL;
1028 fsg->ep0req->length = 0;
1029 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1030
1031 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1032 rc = class_setup_req(fsg, ctrl);
1033 else
1034 rc = standard_setup_req(fsg, ctrl);
1035
1036 /* Respond with data/status or defer until later? */
1037 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001038 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001039 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001040 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001041 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1042 "ep0-in" : "ep0-out");
1043 rc = ep0_queue(fsg);
1044 }
1045
1046 /* Device either stalls (rc < 0) or reports success */
1047 return rc;
1048}
1049
1050
1051/*-------------------------------------------------------------------------*/
1052
1053/* All the following routines run in process context */
1054
1055
1056/* Use this for bulk or interrupt transfers, not ep0 */
1057static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001058 struct usb_request *req, int *pbusy,
1059 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001060{
1061 int rc;
1062
1063 if (ep == fsg->bulk_in)
1064 dump_msg(fsg, "bulk-in", req->buf, req->length);
1065 else if (ep == fsg->intr_in)
1066 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001067
1068 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001069 *pbusy = 1;
1070 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001071 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001072 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1073 if (rc != 0) {
1074 *pbusy = 0;
1075 *state = BUF_STATE_EMPTY;
1076
1077 /* We can't do much more than wait for a reset */
1078
1079 /* Note: currently the net2280 driver fails zero-length
1080 * submissions if DMA is enabled. */
1081 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1082 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001083 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001084 ep->name, rc);
1085 }
1086}
1087
1088
1089static int sleep_thread(struct fsg_dev *fsg)
1090{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001091 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092
1093 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001094 for (;;) {
1095 try_to_freeze();
1096 set_current_state(TASK_INTERRUPTIBLE);
1097 if (signal_pending(current)) {
1098 rc = -EINTR;
1099 break;
1100 }
1101 if (fsg->thread_wakeup_needed)
1102 break;
1103 schedule();
1104 }
1105 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001106 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001107 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001108}
1109
1110
1111/*-------------------------------------------------------------------------*/
1112
1113static int do_read(struct fsg_dev *fsg)
1114{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001115 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001116 u32 lba;
1117 struct fsg_buffhd *bh;
1118 int rc;
1119 u32 amount_left;
1120 loff_t file_offset, file_offset_tmp;
1121 unsigned int amount;
1122 unsigned int partial_page;
1123 ssize_t nread;
1124
1125 /* Get the starting Logical Block Address and check that it's
1126 * not too big */
1127 if (fsg->cmnd[0] == SC_READ_6)
Alan Stern604eb892009-04-27 13:19:41 -04001128 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001129 else {
Alan Stern604eb892009-04-27 13:19:41 -04001130 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001131
1132 /* We allow DPO (Disable Page Out = don't save data in the
1133 * cache) and FUA (Force Unit Access = don't read from the
1134 * cache), but we don't implement them. */
1135 if ((fsg->cmnd[1] & ~0x18) != 0) {
1136 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1137 return -EINVAL;
1138 }
1139 }
1140 if (lba >= curlun->num_sectors) {
1141 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1142 return -EINVAL;
1143 }
1144 file_offset = ((loff_t) lba) << 9;
1145
1146 /* Carry out the file reads */
1147 amount_left = fsg->data_size_from_cmnd;
1148 if (unlikely(amount_left == 0))
1149 return -EIO; // No default reply
1150
1151 for (;;) {
1152
1153 /* Figure out how much we need to read:
1154 * Try to read the remaining amount.
1155 * But don't read more than the buffer size.
1156 * And don't try to read past the end of the file.
1157 * Finally, if we're not at a page boundary, don't read past
1158 * the next page.
1159 * If this means reading 0 then we were asked to read past
1160 * the end of file. */
1161 amount = min((unsigned int) amount_left, mod_data.buflen);
1162 amount = min((loff_t) amount,
1163 curlun->file_length - file_offset);
1164 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1165 if (partial_page > 0)
1166 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1167 partial_page);
1168
1169 /* Wait for the next buffer to become available */
1170 bh = fsg->next_buffhd_to_fill;
1171 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001172 rc = sleep_thread(fsg);
1173 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001174 return rc;
1175 }
1176
1177 /* If we were asked to read past the end of file,
1178 * end with an empty buffer. */
1179 if (amount == 0) {
1180 curlun->sense_data =
1181 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1182 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001183 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001184 bh->inreq->length = 0;
1185 bh->state = BUF_STATE_FULL;
1186 break;
1187 }
1188
1189 /* Perform the read */
1190 file_offset_tmp = file_offset;
1191 nread = vfs_read(curlun->filp,
1192 (char __user *) bh->buf,
1193 amount, &file_offset_tmp);
1194 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1195 (unsigned long long) file_offset,
1196 (int) nread);
1197 if (signal_pending(current))
1198 return -EINTR;
1199
1200 if (nread < 0) {
1201 LDBG(curlun, "error in file read: %d\n",
1202 (int) nread);
1203 nread = 0;
1204 } else if (nread < amount) {
1205 LDBG(curlun, "partial file read: %d/%u\n",
1206 (int) nread, amount);
1207 nread -= (nread & 511); // Round down to a block
1208 }
1209 file_offset += nread;
1210 amount_left -= nread;
1211 fsg->residue -= nread;
1212 bh->inreq->length = nread;
1213 bh->state = BUF_STATE_FULL;
1214
1215 /* If an error occurred, report it and its position */
1216 if (nread < amount) {
1217 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1218 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001219 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001220 break;
1221 }
1222
1223 if (amount_left == 0)
1224 break; // No more left to read
1225
1226 /* Send this buffer and go read some more */
1227 bh->inreq->zero = 0;
1228 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1229 &bh->inreq_busy, &bh->state);
1230 fsg->next_buffhd_to_fill = bh->next;
1231 }
1232
1233 return -EIO; // No default reply
1234}
1235
1236
1237/*-------------------------------------------------------------------------*/
1238
1239static int do_write(struct fsg_dev *fsg)
1240{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001241 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001242 u32 lba;
1243 struct fsg_buffhd *bh;
1244 int get_some_more;
1245 u32 amount_left_to_req, amount_left_to_write;
1246 loff_t usb_offset, file_offset, file_offset_tmp;
1247 unsigned int amount;
1248 unsigned int partial_page;
1249 ssize_t nwritten;
1250 int rc;
1251
1252 if (curlun->ro) {
1253 curlun->sense_data = SS_WRITE_PROTECTED;
1254 return -EINVAL;
1255 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001256 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001257 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001258 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001259
1260 /* Get the starting Logical Block Address and check that it's
1261 * not too big */
1262 if (fsg->cmnd[0] == SC_WRITE_6)
Alan Stern604eb892009-04-27 13:19:41 -04001263 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001264 else {
Alan Stern604eb892009-04-27 13:19:41 -04001265 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001266
1267 /* We allow DPO (Disable Page Out = don't save data in the
1268 * cache) and FUA (Force Unit Access = write directly to the
1269 * medium). We don't implement DPO; we implement FUA by
1270 * performing synchronous output. */
1271 if ((fsg->cmnd[1] & ~0x18) != 0) {
1272 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1273 return -EINVAL;
1274 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001275 if (fsg->cmnd[1] & 0x08) { // FUA
1276 spin_lock(&curlun->filp->f_lock);
Christoph Hellwig6b2f3d12009-10-27 11:05:28 +01001277 curlun->filp->f_flags |= O_DSYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001278 spin_unlock(&curlun->filp->f_lock);
1279 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001280 }
1281 if (lba >= curlun->num_sectors) {
1282 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1283 return -EINVAL;
1284 }
1285
1286 /* Carry out the file writes */
1287 get_some_more = 1;
1288 file_offset = usb_offset = ((loff_t) lba) << 9;
1289 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1290
1291 while (amount_left_to_write > 0) {
1292
1293 /* Queue a request for more data from the host */
1294 bh = fsg->next_buffhd_to_fill;
1295 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1296
1297 /* Figure out how much we want to get:
1298 * Try to get the remaining amount.
1299 * But don't get more than the buffer size.
1300 * And don't try to go past the end of the file.
1301 * If we're not at a page boundary,
1302 * don't go past the next page.
1303 * If this means getting 0, then we were asked
1304 * to write past the end of file.
1305 * Finally, round down to a block boundary. */
1306 amount = min(amount_left_to_req, mod_data.buflen);
1307 amount = min((loff_t) amount, curlun->file_length -
1308 usb_offset);
1309 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1310 if (partial_page > 0)
1311 amount = min(amount,
1312 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1313
1314 if (amount == 0) {
1315 get_some_more = 0;
1316 curlun->sense_data =
1317 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1318 curlun->sense_data_info = usb_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001319 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001320 continue;
1321 }
1322 amount -= (amount & 511);
1323 if (amount == 0) {
1324
1325 /* Why were we were asked to transfer a
1326 * partial block? */
1327 get_some_more = 0;
1328 continue;
1329 }
1330
1331 /* Get the next buffer */
1332 usb_offset += amount;
1333 fsg->usb_amount_left -= amount;
1334 amount_left_to_req -= amount;
1335 if (amount_left_to_req == 0)
1336 get_some_more = 0;
1337
1338 /* amount is always divisible by 512, hence by
1339 * the bulk-out maxpacket size */
1340 bh->outreq->length = bh->bulk_out_intended_length =
1341 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001342 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001343 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1344 &bh->outreq_busy, &bh->state);
1345 fsg->next_buffhd_to_fill = bh->next;
1346 continue;
1347 }
1348
1349 /* Write the received data to the backing file */
1350 bh = fsg->next_buffhd_to_drain;
1351 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1352 break; // We stopped early
1353 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001354 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001355 fsg->next_buffhd_to_drain = bh->next;
1356 bh->state = BUF_STATE_EMPTY;
1357
1358 /* Did something go wrong with the transfer? */
1359 if (bh->outreq->status != 0) {
1360 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1361 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001362 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001363 break;
1364 }
1365
1366 amount = bh->outreq->actual;
1367 if (curlun->file_length - file_offset < amount) {
1368 LERROR(curlun,
1369 "write %u @ %llu beyond end %llu\n",
1370 amount, (unsigned long long) file_offset,
1371 (unsigned long long) curlun->file_length);
1372 amount = curlun->file_length - file_offset;
1373 }
1374
1375 /* Perform the write */
1376 file_offset_tmp = file_offset;
1377 nwritten = vfs_write(curlun->filp,
1378 (char __user *) bh->buf,
1379 amount, &file_offset_tmp);
1380 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1381 (unsigned long long) file_offset,
1382 (int) nwritten);
1383 if (signal_pending(current))
1384 return -EINTR; // Interrupted!
1385
1386 if (nwritten < 0) {
1387 LDBG(curlun, "error in file write: %d\n",
1388 (int) nwritten);
1389 nwritten = 0;
1390 } else if (nwritten < amount) {
1391 LDBG(curlun, "partial file write: %d/%u\n",
1392 (int) nwritten, amount);
1393 nwritten -= (nwritten & 511);
1394 // Round down to a block
1395 }
1396 file_offset += nwritten;
1397 amount_left_to_write -= nwritten;
1398 fsg->residue -= nwritten;
1399
1400 /* If an error occurred, report it and its position */
1401 if (nwritten < amount) {
1402 curlun->sense_data = SS_WRITE_ERROR;
1403 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001404 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405 break;
1406 }
1407
1408 /* Did the host decide to stop early? */
1409 if (bh->outreq->actual != bh->outreq->length) {
1410 fsg->short_packet_received = 1;
1411 break;
1412 }
1413 continue;
1414 }
1415
1416 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001417 rc = sleep_thread(fsg);
1418 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001419 return rc;
1420 }
1421
1422 return -EIO; // No default reply
1423}
1424
1425
1426/*-------------------------------------------------------------------------*/
1427
Linus Torvalds1da177e2005-04-16 15:20:36 -07001428static int do_synchronize_cache(struct fsg_dev *fsg)
1429{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001430 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001431 int rc;
1432
1433 /* We ignore the requested LBA and write out all file's
1434 * dirty data buffers. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001435 rc = fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001436 if (rc)
1437 curlun->sense_data = SS_WRITE_ERROR;
1438 return 0;
1439}
1440
1441
1442/*-------------------------------------------------------------------------*/
1443
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001444static void invalidate_sub(struct fsg_lun *curlun)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001445{
1446 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001447 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001448 unsigned long rc;
1449
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001450 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01001451 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001452}
1453
1454static int do_verify(struct fsg_dev *fsg)
1455{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001456 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001457 u32 lba;
1458 u32 verification_length;
1459 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1460 loff_t file_offset, file_offset_tmp;
1461 u32 amount_left;
1462 unsigned int amount;
1463 ssize_t nread;
1464
1465 /* Get the starting Logical Block Address and check that it's
1466 * not too big */
Alan Stern604eb892009-04-27 13:19:41 -04001467 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001468 if (lba >= curlun->num_sectors) {
1469 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1470 return -EINVAL;
1471 }
1472
1473 /* We allow DPO (Disable Page Out = don't save data in the
1474 * cache) but we don't implement it. */
1475 if ((fsg->cmnd[1] & ~0x10) != 0) {
1476 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1477 return -EINVAL;
1478 }
1479
Alan Stern604eb892009-04-27 13:19:41 -04001480 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001481 if (unlikely(verification_length == 0))
1482 return -EIO; // No default reply
1483
1484 /* Prepare to carry out the file verify */
1485 amount_left = verification_length << 9;
1486 file_offset = ((loff_t) lba) << 9;
1487
1488 /* Write out all the dirty buffers before invalidating them */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001489 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001490 if (signal_pending(current))
1491 return -EINTR;
1492
1493 invalidate_sub(curlun);
1494 if (signal_pending(current))
1495 return -EINTR;
1496
1497 /* Just try to read the requested blocks */
1498 while (amount_left > 0) {
1499
1500 /* Figure out how much we need to read:
1501 * Try to read the remaining amount, but not more than
1502 * the buffer size.
1503 * And don't try to read past the end of the file.
1504 * If this means reading 0 then we were asked to read
1505 * past the end of file. */
1506 amount = min((unsigned int) amount_left, mod_data.buflen);
1507 amount = min((loff_t) amount,
1508 curlun->file_length - file_offset);
1509 if (amount == 0) {
1510 curlun->sense_data =
1511 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1512 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001513 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001514 break;
1515 }
1516
1517 /* Perform the read */
1518 file_offset_tmp = file_offset;
1519 nread = vfs_read(curlun->filp,
1520 (char __user *) bh->buf,
1521 amount, &file_offset_tmp);
1522 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1523 (unsigned long long) file_offset,
1524 (int) nread);
1525 if (signal_pending(current))
1526 return -EINTR;
1527
1528 if (nread < 0) {
1529 LDBG(curlun, "error in file verify: %d\n",
1530 (int) nread);
1531 nread = 0;
1532 } else if (nread < amount) {
1533 LDBG(curlun, "partial file verify: %d/%u\n",
1534 (int) nread, amount);
1535 nread -= (nread & 511); // Round down to a sector
1536 }
1537 if (nread == 0) {
1538 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1539 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001540 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001541 break;
1542 }
1543 file_offset += nread;
1544 amount_left -= nread;
1545 }
1546 return 0;
1547}
1548
1549
1550/*-------------------------------------------------------------------------*/
1551
1552static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1553{
1554 u8 *buf = (u8 *) bh->buf;
1555
1556 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05001557 static char product_disk_id[] = "File-Stor Gadget";
1558 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07001559
1560 if (!fsg->curlun) { // Unsupported LUNs are okay
1561 fsg->bad_lun_okay = 1;
1562 memset(buf, 0, 36);
1563 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05001564 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07001565 return 36;
1566 }
1567
Alan Stern12aae682008-11-20 14:13:12 -05001568 memset(buf, 0, 8);
1569 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001570 if (mod_data.removable)
1571 buf[1] = 0x80;
1572 buf[2] = 2; // ANSI SCSI level 2
1573 buf[3] = 2; // SCSI-2 INQUIRY data format
1574 buf[4] = 31; // Additional length
1575 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05001576 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1577 (mod_data.cdrom ? product_cdrom_id :
1578 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001579 mod_data.release);
1580 return 36;
1581}
1582
1583
1584static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1585{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001586 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001587 u8 *buf = (u8 *) bh->buf;
1588 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04001589 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001590
1591 /*
1592 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1593 *
1594 * If a REQUEST SENSE command is received from an initiator
1595 * with a pending unit attention condition (before the target
1596 * generates the contingent allegiance condition), then the
1597 * target shall either:
1598 * a) report any pending sense data and preserve the unit
1599 * attention condition on the logical unit, or,
1600 * b) report the unit attention condition, may discard any
1601 * pending sense data, and clear the unit attention
1602 * condition on the logical unit for that initiator.
1603 *
1604 * FSG normally uses option a); enable this code to use option b).
1605 */
1606#if 0
1607 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1608 curlun->sense_data = curlun->unit_attention_data;
1609 curlun->unit_attention_data = SS_NO_SENSE;
1610 }
1611#endif
1612
1613 if (!curlun) { // Unsupported LUNs are okay
1614 fsg->bad_lun_okay = 1;
1615 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1616 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001617 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001618 } else {
1619 sd = curlun->sense_data;
1620 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04001621 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001622 curlun->sense_data = SS_NO_SENSE;
1623 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001624 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001625 }
1626
1627 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04001628 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07001629 buf[2] = SK(sd);
Alan Stern604eb892009-04-27 13:19:41 -04001630 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001631 buf[7] = 18 - 8; // Additional sense length
1632 buf[12] = ASC(sd);
1633 buf[13] = ASCQ(sd);
1634 return 18;
1635}
1636
1637
1638static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1639{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001640 struct fsg_lun *curlun = fsg->curlun;
Alan Stern604eb892009-04-27 13:19:41 -04001641 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001642 int pmi = fsg->cmnd[8];
1643 u8 *buf = (u8 *) bh->buf;
1644
1645 /* Check the PMI and LBA fields */
1646 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1647 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1648 return -EINVAL;
1649 }
1650
Alan Stern604eb892009-04-27 13:19:41 -04001651 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1652 /* Max logical block */
1653 put_unaligned_be32(512, &buf[4]); /* Block length */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001654 return 8;
1655}
1656
1657
Alan Stern12aae682008-11-20 14:13:12 -05001658static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1659{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001660 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001661 int msf = fsg->cmnd[1] & 0x02;
Alan Stern604eb892009-04-27 13:19:41 -04001662 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Alan Stern12aae682008-11-20 14:13:12 -05001663 u8 *buf = (u8 *) bh->buf;
1664
1665 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1666 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1667 return -EINVAL;
1668 }
1669 if (lba >= curlun->num_sectors) {
1670 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1671 return -EINVAL;
1672 }
1673
1674 memset(buf, 0, 8);
1675 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1676 store_cdrom_address(&buf[4], msf, lba);
1677 return 8;
1678}
1679
1680
1681static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1682{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001683 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001684 int msf = fsg->cmnd[1] & 0x02;
1685 int start_track = fsg->cmnd[6];
1686 u8 *buf = (u8 *) bh->buf;
1687
1688 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1689 start_track > 1) {
1690 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1691 return -EINVAL;
1692 }
1693
1694 memset(buf, 0, 20);
1695 buf[1] = (20-2); /* TOC data length */
1696 buf[2] = 1; /* First track number */
1697 buf[3] = 1; /* Last track number */
1698 buf[5] = 0x16; /* Data track, copying allowed */
1699 buf[6] = 0x01; /* Only track is number 1 */
1700 store_cdrom_address(&buf[8], msf, 0);
1701
1702 buf[13] = 0x16; /* Lead-out track is data */
1703 buf[14] = 0xAA; /* Lead-out track number */
1704 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1705 return 20;
1706}
1707
1708
Linus Torvalds1da177e2005-04-16 15:20:36 -07001709static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1710{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001711 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001712 int mscmnd = fsg->cmnd[0];
1713 u8 *buf = (u8 *) bh->buf;
1714 u8 *buf0 = buf;
1715 int pc, page_code;
1716 int changeable_values, all_pages;
1717 int valid_page = 0;
1718 int len, limit;
1719
1720 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1721 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1722 return -EINVAL;
1723 }
1724 pc = fsg->cmnd[2] >> 6;
1725 page_code = fsg->cmnd[2] & 0x3f;
1726 if (pc == 3) {
1727 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1728 return -EINVAL;
1729 }
1730 changeable_values = (pc == 1);
1731 all_pages = (page_code == 0x3f);
1732
1733 /* Write the mode parameter header. Fixed values are: default
1734 * medium type, no cache control (DPOFUA), and no block descriptors.
1735 * The only variable value is the WriteProtect bit. We will fill in
1736 * the mode data length later. */
1737 memset(buf, 0, 8);
1738 if (mscmnd == SC_MODE_SENSE_6) {
1739 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1740 buf += 4;
1741 limit = 255;
1742 } else { // SC_MODE_SENSE_10
1743 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1744 buf += 8;
1745 limit = 65535; // Should really be mod_data.buflen
1746 }
1747
1748 /* No block descriptors */
1749
1750 /* The mode pages, in numerical order. The only page we support
1751 * is the Caching page. */
1752 if (page_code == 0x08 || all_pages) {
1753 valid_page = 1;
1754 buf[0] = 0x08; // Page code
1755 buf[1] = 10; // Page length
1756 memset(buf+2, 0, 10); // None of the fields are changeable
1757
1758 if (!changeable_values) {
1759 buf[2] = 0x04; // Write cache enable,
1760 // Read cache not disabled
1761 // No cache retention priorities
Alan Stern604eb892009-04-27 13:19:41 -04001762 put_unaligned_be16(0xffff, &buf[4]);
1763 /* Don't disable prefetch */
1764 /* Minimum prefetch = 0 */
1765 put_unaligned_be16(0xffff, &buf[8]);
1766 /* Maximum prefetch */
1767 put_unaligned_be16(0xffff, &buf[10]);
1768 /* Maximum prefetch ceiling */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001769 }
1770 buf += 12;
1771 }
1772
1773 /* Check that a valid page was requested and the mode data length
1774 * isn't too long. */
1775 len = buf - buf0;
1776 if (!valid_page || len > limit) {
1777 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1778 return -EINVAL;
1779 }
1780
1781 /* Store the mode data length */
1782 if (mscmnd == SC_MODE_SENSE_6)
1783 buf0[0] = len - 1;
1784 else
Alan Stern604eb892009-04-27 13:19:41 -04001785 put_unaligned_be16(len - 2, buf0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001786 return len;
1787}
1788
1789
1790static int do_start_stop(struct fsg_dev *fsg)
1791{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001792 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001793 int loej, start;
1794
1795 if (!mod_data.removable) {
1796 curlun->sense_data = SS_INVALID_COMMAND;
1797 return -EINVAL;
1798 }
1799
1800 // int immed = fsg->cmnd[1] & 0x01;
1801 loej = fsg->cmnd[4] & 0x02;
1802 start = fsg->cmnd[4] & 0x01;
1803
1804#ifdef CONFIG_USB_FILE_STORAGE_TEST
1805 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1806 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1807 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1808 return -EINVAL;
1809 }
1810
1811 if (!start) {
1812
1813 /* Are we allowed to unload the media? */
1814 if (curlun->prevent_medium_removal) {
1815 LDBG(curlun, "unload attempt prevented\n");
1816 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1817 return -EINVAL;
1818 }
1819 if (loej) { // Simulate an unload/eject
1820 up_read(&fsg->filesem);
1821 down_write(&fsg->filesem);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001822 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001823 up_write(&fsg->filesem);
1824 down_read(&fsg->filesem);
1825 }
1826 } else {
1827
1828 /* Our emulation doesn't support mounting; the medium is
1829 * available for use as soon as it is loaded. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001830 if (!fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001831 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1832 return -EINVAL;
1833 }
1834 }
1835#endif
1836 return 0;
1837}
1838
1839
1840static int do_prevent_allow(struct fsg_dev *fsg)
1841{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001842 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001843 int prevent;
1844
1845 if (!mod_data.removable) {
1846 curlun->sense_data = SS_INVALID_COMMAND;
1847 return -EINVAL;
1848 }
1849
1850 prevent = fsg->cmnd[4] & 0x01;
1851 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1852 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1853 return -EINVAL;
1854 }
1855
1856 if (curlun->prevent_medium_removal && !prevent)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001857 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001858 curlun->prevent_medium_removal = prevent;
1859 return 0;
1860}
1861
1862
1863static int do_read_format_capacities(struct fsg_dev *fsg,
1864 struct fsg_buffhd *bh)
1865{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001866 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001867 u8 *buf = (u8 *) bh->buf;
1868
1869 buf[0] = buf[1] = buf[2] = 0;
1870 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1871 buf += 4;
1872
Alan Stern604eb892009-04-27 13:19:41 -04001873 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1874 /* Number of blocks */
1875 put_unaligned_be32(512, &buf[4]); /* Block length */
1876 buf[4] = 0x02; /* Current capacity */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001877 return 12;
1878}
1879
1880
1881static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1882{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001883 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001884
1885 /* We don't support MODE SELECT */
1886 curlun->sense_data = SS_INVALID_COMMAND;
1887 return -EINVAL;
1888}
1889
1890
1891/*-------------------------------------------------------------------------*/
1892
1893static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1894{
1895 int rc;
1896
1897 rc = fsg_set_halt(fsg, fsg->bulk_in);
1898 if (rc == -EAGAIN)
1899 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1900 while (rc != 0) {
1901 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001902 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001903 rc = 0;
1904 break;
1905 }
1906
1907 /* Wait for a short time and then try again */
1908 if (msleep_interruptible(100) != 0)
1909 return -EINTR;
1910 rc = usb_ep_set_halt(fsg->bulk_in);
1911 }
1912 return rc;
1913}
1914
David Lopo62fd2ca2008-04-29 10:14:38 +01001915static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1916{
1917 int rc;
1918
1919 DBG(fsg, "bulk-in set wedge\n");
1920 rc = usb_ep_set_wedge(fsg->bulk_in);
1921 if (rc == -EAGAIN)
1922 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1923 while (rc != 0) {
1924 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001925 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01001926 rc = 0;
1927 break;
1928 }
1929
1930 /* Wait for a short time and then try again */
1931 if (msleep_interruptible(100) != 0)
1932 return -EINTR;
1933 rc = usb_ep_set_wedge(fsg->bulk_in);
1934 }
1935 return rc;
1936}
1937
Linus Torvalds1da177e2005-04-16 15:20:36 -07001938static int pad_with_zeros(struct fsg_dev *fsg)
1939{
1940 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1941 u32 nkeep = bh->inreq->length;
1942 u32 nsend;
1943 int rc;
1944
1945 bh->state = BUF_STATE_EMPTY; // For the first iteration
1946 fsg->usb_amount_left = nkeep + fsg->residue;
1947 while (fsg->usb_amount_left > 0) {
1948
1949 /* Wait for the next buffer to be free */
1950 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001951 rc = sleep_thread(fsg);
1952 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001953 return rc;
1954 }
1955
1956 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
1957 memset(bh->buf + nkeep, 0, nsend - nkeep);
1958 bh->inreq->length = nsend;
1959 bh->inreq->zero = 0;
1960 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1961 &bh->inreq_busy, &bh->state);
1962 bh = fsg->next_buffhd_to_fill = bh->next;
1963 fsg->usb_amount_left -= nsend;
1964 nkeep = 0;
1965 }
1966 return 0;
1967}
1968
1969static int throw_away_data(struct fsg_dev *fsg)
1970{
1971 struct fsg_buffhd *bh;
1972 u32 amount;
1973 int rc;
1974
1975 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1976 fsg->usb_amount_left > 0) {
1977
1978 /* Throw away the data in a filled buffer */
1979 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001980 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001981 bh->state = BUF_STATE_EMPTY;
1982 fsg->next_buffhd_to_drain = bh->next;
1983
1984 /* A short packet or an error ends everything */
1985 if (bh->outreq->actual != bh->outreq->length ||
1986 bh->outreq->status != 0) {
1987 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1988 return -EINTR;
1989 }
1990 continue;
1991 }
1992
1993 /* Try to submit another request if we need one */
1994 bh = fsg->next_buffhd_to_fill;
1995 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1996 amount = min(fsg->usb_amount_left,
1997 (u32) mod_data.buflen);
1998
1999 /* amount is always divisible by 512, hence by
2000 * the bulk-out maxpacket size */
2001 bh->outreq->length = bh->bulk_out_intended_length =
2002 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05002003 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002004 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2005 &bh->outreq_busy, &bh->state);
2006 fsg->next_buffhd_to_fill = bh->next;
2007 fsg->usb_amount_left -= amount;
2008 continue;
2009 }
2010
2011 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04002012 rc = sleep_thread(fsg);
2013 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002014 return rc;
2015 }
2016 return 0;
2017}
2018
2019
2020static int finish_reply(struct fsg_dev *fsg)
2021{
2022 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2023 int rc = 0;
2024
2025 switch (fsg->data_dir) {
2026 case DATA_DIR_NONE:
2027 break; // Nothing to send
2028
2029 /* If we don't know whether the host wants to read or write,
2030 * this must be CB or CBI with an unknown command. We mustn't
2031 * try to send or receive any data. So stall both bulk pipes
2032 * if we can and wait for a reset. */
2033 case DATA_DIR_UNKNOWN:
2034 if (mod_data.can_stall) {
2035 fsg_set_halt(fsg, fsg->bulk_out);
2036 rc = halt_bulk_in_endpoint(fsg);
2037 }
2038 break;
2039
2040 /* All but the last buffer of data must have already been sent */
2041 case DATA_DIR_TO_HOST:
2042 if (fsg->data_size == 0)
2043 ; // Nothing to send
2044
2045 /* If there's no residue, simply send the last buffer */
2046 else if (fsg->residue == 0) {
2047 bh->inreq->zero = 0;
2048 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2049 &bh->inreq_busy, &bh->state);
2050 fsg->next_buffhd_to_fill = bh->next;
2051 }
2052
2053 /* There is a residue. For CB and CBI, simply mark the end
2054 * of the data with a short packet. However, if we are
2055 * allowed to stall, there was no data at all (residue ==
2056 * data_size), and the command failed (invalid LUN or
2057 * sense data is set), then halt the bulk-in endpoint
2058 * instead. */
2059 else if (!transport_is_bbb()) {
2060 if (mod_data.can_stall &&
2061 fsg->residue == fsg->data_size &&
2062 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2063 bh->state = BUF_STATE_EMPTY;
2064 rc = halt_bulk_in_endpoint(fsg);
2065 } else {
2066 bh->inreq->zero = 1;
2067 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2068 &bh->inreq_busy, &bh->state);
2069 fsg->next_buffhd_to_fill = bh->next;
2070 }
2071 }
2072
2073 /* For Bulk-only, if we're allowed to stall then send the
2074 * short packet and halt the bulk-in endpoint. If we can't
2075 * stall, pad out the remaining data with 0's. */
2076 else {
2077 if (mod_data.can_stall) {
2078 bh->inreq->zero = 1;
2079 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2080 &bh->inreq_busy, &bh->state);
2081 fsg->next_buffhd_to_fill = bh->next;
2082 rc = halt_bulk_in_endpoint(fsg);
2083 } else
2084 rc = pad_with_zeros(fsg);
2085 }
2086 break;
2087
2088 /* We have processed all we want from the data the host has sent.
2089 * There may still be outstanding bulk-out requests. */
2090 case DATA_DIR_FROM_HOST:
2091 if (fsg->residue == 0)
2092 ; // Nothing to receive
2093
2094 /* Did the host stop sending unexpectedly early? */
2095 else if (fsg->short_packet_received) {
2096 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2097 rc = -EINTR;
2098 }
2099
2100 /* We haven't processed all the incoming data. Even though
2101 * we may be allowed to stall, doing so would cause a race.
2102 * The controller may already have ACK'ed all the remaining
2103 * bulk-out packets, in which case the host wouldn't see a
2104 * STALL. Not realizing the endpoint was halted, it wouldn't
2105 * clear the halt -- leading to problems later on. */
2106#if 0
2107 else if (mod_data.can_stall) {
2108 fsg_set_halt(fsg, fsg->bulk_out);
2109 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2110 rc = -EINTR;
2111 }
2112#endif
2113
2114 /* We can't stall. Read in the excess data and throw it
2115 * all away. */
2116 else
2117 rc = throw_away_data(fsg);
2118 break;
2119 }
2120 return rc;
2121}
2122
2123
2124static int send_status(struct fsg_dev *fsg)
2125{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002126 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002127 struct fsg_buffhd *bh;
2128 int rc;
2129 u8 status = USB_STATUS_PASS;
2130 u32 sd, sdinfo = 0;
2131
2132 /* Wait for the next buffer to become available */
2133 bh = fsg->next_buffhd_to_fill;
2134 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002135 rc = sleep_thread(fsg);
2136 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002137 return rc;
2138 }
2139
2140 if (curlun) {
2141 sd = curlun->sense_data;
2142 sdinfo = curlun->sense_data_info;
2143 } else if (fsg->bad_lun_okay)
2144 sd = SS_NO_SENSE;
2145 else
2146 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2147
2148 if (fsg->phase_error) {
2149 DBG(fsg, "sending phase-error status\n");
2150 status = USB_STATUS_PHASE_ERROR;
2151 sd = SS_INVALID_COMMAND;
2152 } else if (sd != SS_NO_SENSE) {
2153 DBG(fsg, "sending command-failure status\n");
2154 status = USB_STATUS_FAIL;
2155 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2156 " info x%x\n",
2157 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2158 }
2159
2160 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002161 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002162
2163 /* Store and send the Bulk-only CSW */
Harvey Harrison551509d2009-02-11 14:11:36 -08002164 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002165 csw->Tag = fsg->tag;
2166 csw->Residue = cpu_to_le32(fsg->residue);
2167 csw->Status = status;
2168
2169 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2170 bh->inreq->zero = 0;
2171 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2172 &bh->inreq_busy, &bh->state);
2173
2174 } else if (mod_data.transport_type == USB_PR_CB) {
2175
2176 /* Control-Bulk transport has no status phase! */
2177 return 0;
2178
2179 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002180 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002181
2182 /* Store and send the Interrupt data. UFI sends the ASC
2183 * and ASCQ bytes. Everything else sends a Type (which
2184 * is always 0) and the status Value. */
2185 if (mod_data.protocol_type == USB_SC_UFI) {
2186 buf->bType = ASC(sd);
2187 buf->bValue = ASCQ(sd);
2188 } else {
2189 buf->bType = 0;
2190 buf->bValue = status;
2191 }
2192 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2193
2194 fsg->intr_buffhd = bh; // Point to the right buffhd
2195 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002196 fsg->intreq->context = bh;
2197 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2198 &fsg->intreq_busy, &bh->state);
2199 }
2200
2201 fsg->next_buffhd_to_fill = bh->next;
2202 return 0;
2203}
2204
2205
2206/*-------------------------------------------------------------------------*/
2207
2208/* Check whether the command is properly formed and whether its data size
2209 * and direction agree with the values we already have. */
2210static int check_command(struct fsg_dev *fsg, int cmnd_size,
2211 enum data_direction data_dir, unsigned int mask,
2212 int needs_medium, const char *name)
2213{
2214 int i;
2215 int lun = fsg->cmnd[1] >> 5;
2216 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2217 char hdlen[20];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002218 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002219
2220 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2221 * Transparent SCSI doesn't pad. */
2222 if (protocol_is_scsi())
2223 ;
2224
2225 /* There's some disagreement as to whether RBC pads commands or not.
2226 * We'll play it safe and accept either form. */
2227 else if (mod_data.protocol_type == USB_SC_RBC) {
2228 if (fsg->cmnd_size == 12)
2229 cmnd_size = 12;
2230
2231 /* All the other protocols pad to 12 bytes */
2232 } else
2233 cmnd_size = 12;
2234
2235 hdlen[0] = 0;
2236 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2237 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2238 fsg->data_size);
2239 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2240 name, cmnd_size, dirletter[(int) data_dir],
2241 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2242
2243 /* We can't reply at all until we know the correct data direction
2244 * and size. */
2245 if (fsg->data_size_from_cmnd == 0)
2246 data_dir = DATA_DIR_NONE;
2247 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2248 fsg->data_dir = data_dir;
2249 fsg->data_size = fsg->data_size_from_cmnd;
2250
2251 } else { // Bulk-only
2252 if (fsg->data_size < fsg->data_size_from_cmnd) {
2253
2254 /* Host data size < Device data size is a phase error.
2255 * Carry out the command, but only transfer as much
2256 * as we are allowed. */
2257 fsg->data_size_from_cmnd = fsg->data_size;
2258 fsg->phase_error = 1;
2259 }
2260 }
2261 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2262
2263 /* Conflicting data directions is a phase error */
2264 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2265 fsg->phase_error = 1;
2266 return -EINVAL;
2267 }
2268
2269 /* Verify the length of the command itself */
2270 if (cmnd_size != fsg->cmnd_size) {
2271
Felipe Balbi549c41e2008-09-19 02:00:02 +03002272 /* Special case workaround: There are plenty of buggy SCSI
2273 * implementations. Many have issues with cbw->Length
2274 * field passing a wrong command size. For those cases we
2275 * always try to work around the problem by using the length
2276 * sent by the host side provided it is at least as large
2277 * as the correct command length.
2278 * Examples of such cases would be MS-Windows, which issues
2279 * REQUEST SENSE with cbw->Length == 12 where it should
2280 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2281 * REQUEST SENSE with cbw->Length == 10 where it should
2282 * be 6 as well.
2283 */
2284 if (cmnd_size <= fsg->cmnd_size) {
2285 DBG(fsg, "%s is buggy! Expected length %d "
2286 "but we got %d\n", name,
2287 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002288 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002289 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002290 fsg->phase_error = 1;
2291 return -EINVAL;
2292 }
2293 }
2294
Alan Sternd794ac72005-04-18 12:43:25 -04002295 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002296 if (transport_is_bbb()) {
2297 if (fsg->lun != lun)
2298 DBG(fsg, "using LUN %d from CBW, "
2299 "not LUN %d from CDB\n",
2300 fsg->lun, lun);
2301 } else
2302 fsg->lun = lun; // Use LUN from the command
2303
2304 /* Check the LUN */
2305 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2306 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2307 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2308 curlun->sense_data = SS_NO_SENSE;
2309 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002310 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002311 }
2312 } else {
2313 fsg->curlun = curlun = NULL;
2314 fsg->bad_lun_okay = 0;
2315
2316 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2317 * to use unsupported LUNs; all others may not. */
2318 if (fsg->cmnd[0] != SC_INQUIRY &&
2319 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2320 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2321 return -EINVAL;
2322 }
2323 }
2324
2325 /* If a unit attention condition exists, only INQUIRY and
2326 * REQUEST SENSE commands are allowed; anything else must fail. */
2327 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2328 fsg->cmnd[0] != SC_INQUIRY &&
2329 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2330 curlun->sense_data = curlun->unit_attention_data;
2331 curlun->unit_attention_data = SS_NO_SENSE;
2332 return -EINVAL;
2333 }
2334
2335 /* Check that only command bytes listed in the mask are non-zero */
2336 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2337 for (i = 1; i < cmnd_size; ++i) {
2338 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2339 if (curlun)
2340 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2341 return -EINVAL;
2342 }
2343 }
2344
2345 /* If the medium isn't mounted and the command needs to access
2346 * it, return an error. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002347 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002348 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2349 return -EINVAL;
2350 }
2351
2352 return 0;
2353}
2354
2355
2356static int do_scsi_command(struct fsg_dev *fsg)
2357{
2358 struct fsg_buffhd *bh;
2359 int rc;
2360 int reply = -EINVAL;
2361 int i;
2362 static char unknown[16];
2363
2364 dump_cdb(fsg);
2365
2366 /* Wait for the next buffer to become available for data or status */
2367 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2368 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002369 rc = sleep_thread(fsg);
2370 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002371 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002372 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002373 fsg->phase_error = 0;
2374 fsg->short_packet_received = 0;
2375
2376 down_read(&fsg->filesem); // We're using the backing file
2377 switch (fsg->cmnd[0]) {
2378
2379 case SC_INQUIRY:
2380 fsg->data_size_from_cmnd = fsg->cmnd[4];
2381 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2382 (1<<4), 0,
2383 "INQUIRY")) == 0)
2384 reply = do_inquiry(fsg, bh);
2385 break;
2386
2387 case SC_MODE_SELECT_6:
2388 fsg->data_size_from_cmnd = fsg->cmnd[4];
2389 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2390 (1<<1) | (1<<4), 0,
2391 "MODE SELECT(6)")) == 0)
2392 reply = do_mode_select(fsg, bh);
2393 break;
2394
2395 case SC_MODE_SELECT_10:
Alan Stern604eb892009-04-27 13:19:41 -04002396 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002397 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2398 (1<<1) | (3<<7), 0,
2399 "MODE SELECT(10)")) == 0)
2400 reply = do_mode_select(fsg, bh);
2401 break;
2402
2403 case SC_MODE_SENSE_6:
2404 fsg->data_size_from_cmnd = fsg->cmnd[4];
2405 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2406 (1<<1) | (1<<2) | (1<<4), 0,
2407 "MODE SENSE(6)")) == 0)
2408 reply = do_mode_sense(fsg, bh);
2409 break;
2410
2411 case SC_MODE_SENSE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002412 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002413 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2414 (1<<1) | (1<<2) | (3<<7), 0,
2415 "MODE SENSE(10)")) == 0)
2416 reply = do_mode_sense(fsg, bh);
2417 break;
2418
2419 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2420 fsg->data_size_from_cmnd = 0;
2421 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2422 (1<<4), 0,
2423 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2424 reply = do_prevent_allow(fsg);
2425 break;
2426
2427 case SC_READ_6:
2428 i = fsg->cmnd[4];
2429 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2430 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2431 (7<<1) | (1<<4), 1,
2432 "READ(6)")) == 0)
2433 reply = do_read(fsg);
2434 break;
2435
2436 case SC_READ_10:
Alan Stern604eb892009-04-27 13:19:41 -04002437 fsg->data_size_from_cmnd =
2438 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002439 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2440 (1<<1) | (0xf<<2) | (3<<7), 1,
2441 "READ(10)")) == 0)
2442 reply = do_read(fsg);
2443 break;
2444
2445 case SC_READ_12:
Alan Stern604eb892009-04-27 13:19:41 -04002446 fsg->data_size_from_cmnd =
2447 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002448 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2449 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2450 "READ(12)")) == 0)
2451 reply = do_read(fsg);
2452 break;
2453
2454 case SC_READ_CAPACITY:
2455 fsg->data_size_from_cmnd = 8;
2456 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2457 (0xf<<2) | (1<<8), 1,
2458 "READ CAPACITY")) == 0)
2459 reply = do_read_capacity(fsg, bh);
2460 break;
2461
Alan Stern12aae682008-11-20 14:13:12 -05002462 case SC_READ_HEADER:
2463 if (!mod_data.cdrom)
2464 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002465 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002466 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2467 (3<<7) | (0x1f<<1), 1,
2468 "READ HEADER")) == 0)
2469 reply = do_read_header(fsg, bh);
2470 break;
2471
2472 case SC_READ_TOC:
2473 if (!mod_data.cdrom)
2474 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002475 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002476 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2477 (7<<6) | (1<<1), 1,
2478 "READ TOC")) == 0)
2479 reply = do_read_toc(fsg, bh);
2480 break;
2481
Linus Torvalds1da177e2005-04-16 15:20:36 -07002482 case SC_READ_FORMAT_CAPACITIES:
Alan Stern604eb892009-04-27 13:19:41 -04002483 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002484 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2485 (3<<7), 1,
2486 "READ FORMAT CAPACITIES")) == 0)
2487 reply = do_read_format_capacities(fsg, bh);
2488 break;
2489
2490 case SC_REQUEST_SENSE:
2491 fsg->data_size_from_cmnd = fsg->cmnd[4];
2492 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2493 (1<<4), 0,
2494 "REQUEST SENSE")) == 0)
2495 reply = do_request_sense(fsg, bh);
2496 break;
2497
2498 case SC_START_STOP_UNIT:
2499 fsg->data_size_from_cmnd = 0;
2500 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2501 (1<<1) | (1<<4), 0,
2502 "START-STOP UNIT")) == 0)
2503 reply = do_start_stop(fsg);
2504 break;
2505
2506 case SC_SYNCHRONIZE_CACHE:
2507 fsg->data_size_from_cmnd = 0;
2508 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2509 (0xf<<2) | (3<<7), 1,
2510 "SYNCHRONIZE CACHE")) == 0)
2511 reply = do_synchronize_cache(fsg);
2512 break;
2513
2514 case SC_TEST_UNIT_READY:
2515 fsg->data_size_from_cmnd = 0;
2516 reply = check_command(fsg, 6, DATA_DIR_NONE,
2517 0, 1,
2518 "TEST UNIT READY");
2519 break;
2520
2521 /* Although optional, this command is used by MS-Windows. We
2522 * support a minimal version: BytChk must be 0. */
2523 case SC_VERIFY:
2524 fsg->data_size_from_cmnd = 0;
2525 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2526 (1<<1) | (0xf<<2) | (3<<7), 1,
2527 "VERIFY")) == 0)
2528 reply = do_verify(fsg);
2529 break;
2530
2531 case SC_WRITE_6:
2532 i = fsg->cmnd[4];
2533 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2534 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2535 (7<<1) | (1<<4), 1,
2536 "WRITE(6)")) == 0)
2537 reply = do_write(fsg);
2538 break;
2539
2540 case SC_WRITE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002541 fsg->data_size_from_cmnd =
2542 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002543 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2544 (1<<1) | (0xf<<2) | (3<<7), 1,
2545 "WRITE(10)")) == 0)
2546 reply = do_write(fsg);
2547 break;
2548
2549 case SC_WRITE_12:
Alan Stern604eb892009-04-27 13:19:41 -04002550 fsg->data_size_from_cmnd =
2551 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002552 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2553 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2554 "WRITE(12)")) == 0)
2555 reply = do_write(fsg);
2556 break;
2557
2558 /* Some mandatory commands that we recognize but don't implement.
2559 * They don't mean much in this setting. It's left as an exercise
2560 * for anyone interested to implement RESERVE and RELEASE in terms
2561 * of Posix locks. */
2562 case SC_FORMAT_UNIT:
2563 case SC_RELEASE:
2564 case SC_RESERVE:
2565 case SC_SEND_DIAGNOSTIC:
2566 // Fall through
2567
2568 default:
Alan Stern12aae682008-11-20 14:13:12 -05002569 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002570 fsg->data_size_from_cmnd = 0;
2571 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2572 if ((reply = check_command(fsg, fsg->cmnd_size,
2573 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2574 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2575 reply = -EINVAL;
2576 }
2577 break;
2578 }
2579 up_read(&fsg->filesem);
2580
2581 if (reply == -EINTR || signal_pending(current))
2582 return -EINTR;
2583
2584 /* Set up the single reply buffer for finish_reply() */
2585 if (reply == -EINVAL)
2586 reply = 0; // Error reply length
2587 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2588 reply = min((u32) reply, fsg->data_size_from_cmnd);
2589 bh->inreq->length = reply;
2590 bh->state = BUF_STATE_FULL;
2591 fsg->residue -= reply;
2592 } // Otherwise it's already set
2593
2594 return 0;
2595}
2596
2597
2598/*-------------------------------------------------------------------------*/
2599
2600static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2601{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002602 struct usb_request *req = bh->outreq;
2603 struct fsg_bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002604
Alan Sternb950bdb2008-04-14 11:45:29 -04002605 /* Was this a real packet? Should it be ignored? */
2606 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002607 return -EINVAL;
2608
2609 /* Is the CBW valid? */
2610 if (req->actual != USB_BULK_CB_WRAP_LEN ||
Harvey Harrison551509d2009-02-11 14:11:36 -08002611 cbw->Signature != cpu_to_le32(
Linus Torvalds1da177e2005-04-16 15:20:36 -07002612 USB_BULK_CB_SIG)) {
2613 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2614 req->actual,
2615 le32_to_cpu(cbw->Signature));
2616
Alan Sternb950bdb2008-04-14 11:45:29 -04002617 /* The Bulk-only spec says we MUST stall the IN endpoint
2618 * (6.6.1), so it's unavoidable. It also says we must
2619 * retain this state until the next reset, but there's
2620 * no way to tell the controller driver it should ignore
2621 * Clear-Feature(HALT) requests.
2622 *
2623 * We aren't required to halt the OUT endpoint; instead
2624 * we can simply accept and discard any data received
2625 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01002626 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04002627 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002628 return -EINVAL;
2629 }
2630
2631 /* Is the CBW meaningful? */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002632 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04002633 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002634 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2635 "cmdlen %u\n",
2636 cbw->Lun, cbw->Flags, cbw->Length);
2637
2638 /* We can do anything we want here, so let's stall the
2639 * bulk pipes if we are allowed to. */
2640 if (mod_data.can_stall) {
2641 fsg_set_halt(fsg, fsg->bulk_out);
2642 halt_bulk_in_endpoint(fsg);
2643 }
2644 return -EINVAL;
2645 }
2646
2647 /* Save the command for later */
2648 fsg->cmnd_size = cbw->Length;
2649 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2650 if (cbw->Flags & USB_BULK_IN_FLAG)
2651 fsg->data_dir = DATA_DIR_TO_HOST;
2652 else
2653 fsg->data_dir = DATA_DIR_FROM_HOST;
2654 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2655 if (fsg->data_size == 0)
2656 fsg->data_dir = DATA_DIR_NONE;
2657 fsg->lun = cbw->Lun;
2658 fsg->tag = cbw->Tag;
2659 return 0;
2660}
2661
2662
2663static int get_next_command(struct fsg_dev *fsg)
2664{
2665 struct fsg_buffhd *bh;
2666 int rc = 0;
2667
2668 if (transport_is_bbb()) {
2669
2670 /* Wait for the next buffer to become available */
2671 bh = fsg->next_buffhd_to_fill;
2672 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002673 rc = sleep_thread(fsg);
2674 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002675 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002676 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002677
2678 /* Queue a request to read a Bulk-only CBW */
2679 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
Alan Stern70ffe6e2006-03-23 15:05:16 -05002680 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002681 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2682 &bh->outreq_busy, &bh->state);
2683
2684 /* We will drain the buffer in software, which means we
2685 * can reuse it for the next filling. No need to advance
2686 * next_buffhd_to_fill. */
2687
2688 /* Wait for the CBW to arrive */
2689 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002690 rc = sleep_thread(fsg);
2691 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002692 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002693 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05002694 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002695 rc = received_cbw(fsg, bh);
2696 bh->state = BUF_STATE_EMPTY;
2697
2698 } else { // USB_PR_CB or USB_PR_CBI
2699
2700 /* Wait for the next command to arrive */
2701 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002702 rc = sleep_thread(fsg);
2703 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002704 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002705 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002706
2707 /* Is the previous status interrupt request still busy?
2708 * The host is allowed to skip reading the status,
2709 * so we must cancel it. */
2710 if (fsg->intreq_busy)
2711 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2712
2713 /* Copy the command and mark the buffer empty */
2714 fsg->data_dir = DATA_DIR_UNKNOWN;
2715 spin_lock_irq(&fsg->lock);
2716 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2717 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2718 fsg->cbbuf_cmnd_size = 0;
2719 spin_unlock_irq(&fsg->lock);
2720 }
2721 return rc;
2722}
2723
2724
2725/*-------------------------------------------------------------------------*/
2726
2727static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2728 const struct usb_endpoint_descriptor *d)
2729{
2730 int rc;
2731
2732 ep->driver_data = fsg;
2733 rc = usb_ep_enable(ep, d);
2734 if (rc)
2735 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2736 return rc;
2737}
2738
2739static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2740 struct usb_request **preq)
2741{
2742 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2743 if (*preq)
2744 return 0;
2745 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2746 return -ENOMEM;
2747}
2748
2749/*
2750 * Reset interface setting and re-init endpoint state (toggle etc).
2751 * Call with altsetting < 0 to disable the interface. The only other
2752 * available altsetting is 0, which enables the interface.
2753 */
2754static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2755{
2756 int rc = 0;
2757 int i;
2758 const struct usb_endpoint_descriptor *d;
2759
2760 if (fsg->running)
2761 DBG(fsg, "reset interface\n");
2762
2763reset:
2764 /* Deallocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002765 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002766 struct fsg_buffhd *bh = &fsg->buffhds[i];
2767
2768 if (bh->inreq) {
2769 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2770 bh->inreq = NULL;
2771 }
2772 if (bh->outreq) {
2773 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2774 bh->outreq = NULL;
2775 }
2776 }
2777 if (fsg->intreq) {
2778 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2779 fsg->intreq = NULL;
2780 }
2781
2782 /* Disable the endpoints */
2783 if (fsg->bulk_in_enabled) {
2784 usb_ep_disable(fsg->bulk_in);
2785 fsg->bulk_in_enabled = 0;
2786 }
2787 if (fsg->bulk_out_enabled) {
2788 usb_ep_disable(fsg->bulk_out);
2789 fsg->bulk_out_enabled = 0;
2790 }
2791 if (fsg->intr_in_enabled) {
2792 usb_ep_disable(fsg->intr_in);
2793 fsg->intr_in_enabled = 0;
2794 }
2795
2796 fsg->running = 0;
2797 if (altsetting < 0 || rc != 0)
2798 return rc;
2799
2800 DBG(fsg, "set interface %d\n", altsetting);
2801
2802 /* Enable the endpoints */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002803 d = fsg_ep_desc(fsg->gadget,
2804 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002805 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2806 goto reset;
2807 fsg->bulk_in_enabled = 1;
2808
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002809 d = fsg_ep_desc(fsg->gadget,
2810 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002811 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2812 goto reset;
2813 fsg->bulk_out_enabled = 1;
2814 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
Alan Sternb950bdb2008-04-14 11:45:29 -04002815 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002816
2817 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002818 d = fsg_ep_desc(fsg->gadget,
2819 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002820 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2821 goto reset;
2822 fsg->intr_in_enabled = 1;
2823 }
2824
2825 /* Allocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002826 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002827 struct fsg_buffhd *bh = &fsg->buffhds[i];
2828
2829 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2830 goto reset;
2831 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2832 goto reset;
2833 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002834 bh->inreq->context = bh->outreq->context = bh;
2835 bh->inreq->complete = bulk_in_complete;
2836 bh->outreq->complete = bulk_out_complete;
2837 }
2838 if (transport_is_cbi()) {
2839 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2840 goto reset;
2841 fsg->intreq->complete = intr_in_complete;
2842 }
2843
2844 fsg->running = 1;
2845 for (i = 0; i < fsg->nluns; ++i)
2846 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2847 return rc;
2848}
2849
2850
2851/*
2852 * Change our operational configuration. This code must agree with the code
2853 * that returns config descriptors, and with interface altsetting code.
2854 *
2855 * It's also responsible for power management interactions. Some
2856 * configurations might not work with our current power sources.
2857 * For now we just assume the gadget is always self-powered.
2858 */
2859static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2860{
2861 int rc = 0;
2862
2863 /* Disable the single interface */
2864 if (fsg->config != 0) {
2865 DBG(fsg, "reset config\n");
2866 fsg->config = 0;
2867 rc = do_set_interface(fsg, -1);
2868 }
2869
2870 /* Enable the interface */
2871 if (new_config != 0) {
2872 fsg->config = new_config;
2873 if ((rc = do_set_interface(fsg, 0)) != 0)
2874 fsg->config = 0; // Reset on errors
2875 else {
2876 char *speed;
2877
2878 switch (fsg->gadget->speed) {
2879 case USB_SPEED_LOW: speed = "low"; break;
2880 case USB_SPEED_FULL: speed = "full"; break;
2881 case USB_SPEED_HIGH: speed = "high"; break;
2882 default: speed = "?"; break;
2883 }
2884 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2885 }
2886 }
2887 return rc;
2888}
2889
2890
2891/*-------------------------------------------------------------------------*/
2892
2893static void handle_exception(struct fsg_dev *fsg)
2894{
2895 siginfo_t info;
2896 int sig;
2897 int i;
2898 int num_active;
2899 struct fsg_buffhd *bh;
2900 enum fsg_state old_state;
2901 u8 new_config;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002902 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002903 unsigned int exception_req_tag;
2904 int rc;
2905
2906 /* Clear the existing signals. Anything but SIGUSR1 is converted
2907 * into a high-priority EXIT exception. */
2908 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04002909 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002910 if (!sig)
2911 break;
2912 if (sig != SIGUSR1) {
2913 if (fsg->state < FSG_STATE_EXIT)
2914 DBG(fsg, "Main thread exiting on signal\n");
2915 raise_exception(fsg, FSG_STATE_EXIT);
2916 }
2917 }
2918
2919 /* Cancel all the pending transfers */
2920 if (fsg->intreq_busy)
2921 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002922 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002923 bh = &fsg->buffhds[i];
2924 if (bh->inreq_busy)
2925 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2926 if (bh->outreq_busy)
2927 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2928 }
2929
2930 /* Wait until everything is idle */
2931 for (;;) {
2932 num_active = fsg->intreq_busy;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002933 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002934 bh = &fsg->buffhds[i];
2935 num_active += bh->inreq_busy + bh->outreq_busy;
2936 }
2937 if (num_active == 0)
2938 break;
2939 if (sleep_thread(fsg))
2940 return;
2941 }
2942
2943 /* Clear out the controller's fifos */
2944 if (fsg->bulk_in_enabled)
2945 usb_ep_fifo_flush(fsg->bulk_in);
2946 if (fsg->bulk_out_enabled)
2947 usb_ep_fifo_flush(fsg->bulk_out);
2948 if (fsg->intr_in_enabled)
2949 usb_ep_fifo_flush(fsg->intr_in);
2950
2951 /* Reset the I/O buffer states and pointers, the SCSI
2952 * state, and the exception. Then invoke the handler. */
2953 spin_lock_irq(&fsg->lock);
2954
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002955 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002956 bh = &fsg->buffhds[i];
2957 bh->state = BUF_STATE_EMPTY;
2958 }
2959 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2960 &fsg->buffhds[0];
2961
2962 exception_req_tag = fsg->exception_req_tag;
2963 new_config = fsg->new_config;
2964 old_state = fsg->state;
2965
2966 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2967 fsg->state = FSG_STATE_STATUS_PHASE;
2968 else {
2969 for (i = 0; i < fsg->nluns; ++i) {
2970 curlun = &fsg->luns[i];
2971 curlun->prevent_medium_removal = 0;
2972 curlun->sense_data = curlun->unit_attention_data =
2973 SS_NO_SENSE;
2974 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002975 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002976 }
2977 fsg->state = FSG_STATE_IDLE;
2978 }
2979 spin_unlock_irq(&fsg->lock);
2980
2981 /* Carry out any extra actions required for the exception */
2982 switch (old_state) {
2983 default:
2984 break;
2985
2986 case FSG_STATE_ABORT_BULK_OUT:
2987 send_status(fsg);
2988 spin_lock_irq(&fsg->lock);
2989 if (fsg->state == FSG_STATE_STATUS_PHASE)
2990 fsg->state = FSG_STATE_IDLE;
2991 spin_unlock_irq(&fsg->lock);
2992 break;
2993
2994 case FSG_STATE_RESET:
2995 /* In case we were forced against our will to halt a
2996 * bulk endpoint, clear the halt now. (The SuperH UDC
2997 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04002998 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002999 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003000
3001 if (transport_is_bbb()) {
3002 if (fsg->ep0_req_tag == exception_req_tag)
3003 ep0_queue(fsg); // Complete the status stage
3004
3005 } else if (transport_is_cbi())
3006 send_status(fsg); // Status by interrupt pipe
3007
3008 /* Technically this should go here, but it would only be
3009 * a waste of time. Ditto for the INTERFACE_CHANGE and
3010 * CONFIG_CHANGE cases. */
3011 // for (i = 0; i < fsg->nluns; ++i)
3012 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3013 break;
3014
3015 case FSG_STATE_INTERFACE_CHANGE:
3016 rc = do_set_interface(fsg, 0);
3017 if (fsg->ep0_req_tag != exception_req_tag)
3018 break;
3019 if (rc != 0) // STALL on errors
3020 fsg_set_halt(fsg, fsg->ep0);
3021 else // Complete the status stage
3022 ep0_queue(fsg);
3023 break;
3024
3025 case FSG_STATE_CONFIG_CHANGE:
3026 rc = do_set_config(fsg, new_config);
3027 if (fsg->ep0_req_tag != exception_req_tag)
3028 break;
3029 if (rc != 0) // STALL on errors
3030 fsg_set_halt(fsg, fsg->ep0);
3031 else // Complete the status stage
3032 ep0_queue(fsg);
3033 break;
3034
3035 case FSG_STATE_DISCONNECT:
Michal Nazarewiczb6058d02009-10-28 16:57:14 +01003036 for (i = 0; i < fsg->nluns; ++i)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003037 fsg_lun_fsync_sub(fsg->luns + i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003038 do_set_config(fsg, 0); // Unconfigured state
3039 break;
3040
3041 case FSG_STATE_EXIT:
3042 case FSG_STATE_TERMINATED:
3043 do_set_config(fsg, 0); // Free resources
3044 spin_lock_irq(&fsg->lock);
3045 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3046 spin_unlock_irq(&fsg->lock);
3047 break;
3048 }
3049}
3050
3051
3052/*-------------------------------------------------------------------------*/
3053
3054static int fsg_main_thread(void *fsg_)
3055{
John Daiker7ca46b82006-12-29 19:02:06 -08003056 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003057
Linus Torvalds1da177e2005-04-16 15:20:36 -07003058 /* Allow the thread to be killed by a signal, but set the signal mask
3059 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003060 allow_signal(SIGINT);
3061 allow_signal(SIGTERM);
3062 allow_signal(SIGKILL);
3063 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003064
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003065 /* Allow the thread to be frozen */
3066 set_freezable();
3067
Linus Torvalds1da177e2005-04-16 15:20:36 -07003068 /* Arrange for userspace references to be interpreted as kernel
3069 * pointers. That way we can pass a kernel pointer to a routine
3070 * that expects a __user pointer and it will work okay. */
3071 set_fs(get_ds());
3072
Linus Torvalds1da177e2005-04-16 15:20:36 -07003073 /* The main loop */
3074 while (fsg->state != FSG_STATE_TERMINATED) {
3075 if (exception_in_progress(fsg) || signal_pending(current)) {
3076 handle_exception(fsg);
3077 continue;
3078 }
3079
3080 if (!fsg->running) {
3081 sleep_thread(fsg);
3082 continue;
3083 }
3084
3085 if (get_next_command(fsg))
3086 continue;
3087
3088 spin_lock_irq(&fsg->lock);
3089 if (!exception_in_progress(fsg))
3090 fsg->state = FSG_STATE_DATA_PHASE;
3091 spin_unlock_irq(&fsg->lock);
3092
3093 if (do_scsi_command(fsg) || finish_reply(fsg))
3094 continue;
3095
3096 spin_lock_irq(&fsg->lock);
3097 if (!exception_in_progress(fsg))
3098 fsg->state = FSG_STATE_STATUS_PHASE;
3099 spin_unlock_irq(&fsg->lock);
3100
3101 if (send_status(fsg))
3102 continue;
3103
3104 spin_lock_irq(&fsg->lock);
3105 if (!exception_in_progress(fsg))
3106 fsg->state = FSG_STATE_IDLE;
3107 spin_unlock_irq(&fsg->lock);
3108 }
3109
Alan Stern22efcf42005-09-26 16:12:02 -04003110 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003111 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003112 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003113
Alan Stern82a10a82009-04-16 15:37:28 -04003114 /* If we are exiting because of a signal, unregister the
3115 * gadget driver. */
3116 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003117 usb_gadget_unregister_driver(&fsg_driver);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003118
3119 /* Let the unbind and cleanup routines know the thread has exited */
3120 complete_and_exit(&fsg->thread_notifier, 0);
3121}
3122
3123
3124/*-------------------------------------------------------------------------*/
3125
Linus Torvalds1da177e2005-04-16 15:20:36 -07003126
3127/* The write permissions and store_xxx pointers are set in fsg_bind() */
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003128static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
3129static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003130
3131
3132/*-------------------------------------------------------------------------*/
3133
Alan Stern87c42522005-11-09 16:59:56 -05003134static void fsg_release(struct kref *ref)
3135{
3136 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3137
3138 kfree(fsg->luns);
3139 kfree(fsg);
3140}
3141
Linus Torvalds1da177e2005-04-16 15:20:36 -07003142static void lun_release(struct device *dev)
3143{
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003144 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3145 struct fsg_dev *fsg =
3146 container_of(filesem, struct fsg_dev, filesem);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003147
Alan Stern87c42522005-11-09 16:59:56 -05003148 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003149}
3150
David Brownella3536782006-07-06 15:48:53 -07003151static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003152{
3153 struct fsg_dev *fsg = get_gadget_data(gadget);
3154 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003155 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003156 struct usb_request *req = fsg->ep0req;
3157
3158 DBG(fsg, "unbind\n");
3159 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3160
3161 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003162 for (i = 0; i < fsg->nluns; ++i) {
3163 curlun = &fsg->luns[i];
3164 if (curlun->registered) {
3165 device_remove_file(&curlun->dev, &dev_attr_ro);
3166 device_remove_file(&curlun->dev, &dev_attr_file);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003167 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003168 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003169 curlun->registered = 0;
3170 }
3171 }
3172
3173 /* If the thread isn't already dead, tell it to exit now */
3174 if (fsg->state != FSG_STATE_TERMINATED) {
3175 raise_exception(fsg, FSG_STATE_EXIT);
3176 wait_for_completion(&fsg->thread_notifier);
3177
3178 /* The cleanup routine waits for this completion also */
3179 complete(&fsg->thread_notifier);
3180 }
3181
3182 /* Free the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003183 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
David Brownell9d8bab52007-07-01 11:04:54 -07003184 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003185
3186 /* Free the request and buffer for endpoint 0 */
3187 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003188 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003189 usb_ep_free_request(fsg->ep0, req);
3190 }
3191
3192 set_gadget_data(gadget, NULL);
3193}
3194
3195
3196static int __init check_parameters(struct fsg_dev *fsg)
3197{
3198 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003199 int gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003200
3201 /* Store the default values */
3202 mod_data.transport_type = USB_PR_BULK;
3203 mod_data.transport_name = "Bulk-only";
3204 mod_data.protocol_type = USB_SC_SCSI;
3205 mod_data.protocol_name = "Transparent SCSI";
3206
Alan Sternce459ec2009-02-24 16:19:47 -05003207 /* Some peripheral controllers are known not to be able to
3208 * halt bulk endpoints correctly. If one of them is present,
3209 * disable stalls.
3210 */
Christoph Egger90f79762010-02-05 13:24:12 +01003211 if (gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003212 mod_data.can_stall = 0;
3213
3214 if (mod_data.release == 0xffff) { // Parameter wasn't set
Christoph Egger90f79762010-02-05 13:24:12 +01003215 gcnum = usb_gadget_controller_number(fsg->gadget);
David Brownell91e79c92005-07-13 15:18:30 -07003216 if (gcnum >= 0)
3217 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003218 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003219 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003220 fsg->gadget->name);
3221 mod_data.release = 0x0399;
3222 }
3223 }
3224
3225 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3226
3227#ifdef CONFIG_USB_FILE_STORAGE_TEST
3228 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3229 ; // Use default setting
3230 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3231 mod_data.transport_type = USB_PR_CB;
3232 mod_data.transport_name = "Control-Bulk";
3233 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3234 mod_data.transport_type = USB_PR_CBI;
3235 mod_data.transport_name = "Control-Bulk-Interrupt";
3236 } else {
3237 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3238 return -EINVAL;
3239 }
3240
3241 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3242 prot == USB_SC_SCSI) {
3243 ; // Use default setting
3244 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3245 prot == USB_SC_RBC) {
3246 mod_data.protocol_type = USB_SC_RBC;
3247 mod_data.protocol_name = "RBC";
3248 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3249 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3250 prot == USB_SC_8020) {
3251 mod_data.protocol_type = USB_SC_8020;
3252 mod_data.protocol_name = "8020i (ATAPI)";
3253 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3254 prot == USB_SC_QIC) {
3255 mod_data.protocol_type = USB_SC_QIC;
3256 mod_data.protocol_name = "QIC-157";
3257 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3258 prot == USB_SC_UFI) {
3259 mod_data.protocol_type = USB_SC_UFI;
3260 mod_data.protocol_name = "UFI";
3261 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3262 prot == USB_SC_8070) {
3263 mod_data.protocol_type = USB_SC_8070;
3264 mod_data.protocol_name = "8070i";
3265 } else {
3266 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3267 return -EINVAL;
3268 }
3269
3270 mod_data.buflen &= PAGE_CACHE_MASK;
3271 if (mod_data.buflen <= 0) {
3272 ERROR(fsg, "invalid buflen\n");
3273 return -ETOOSMALL;
3274 }
3275#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3276
3277 return 0;
3278}
3279
3280
3281static int __init fsg_bind(struct usb_gadget *gadget)
3282{
3283 struct fsg_dev *fsg = the_fsg;
3284 int rc;
3285 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003286 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003287 struct usb_ep *ep;
3288 struct usb_request *req;
3289 char *pathbuf, *p;
3290
3291 fsg->gadget = gadget;
3292 set_gadget_data(gadget, fsg);
3293 fsg->ep0 = gadget->ep0;
3294 fsg->ep0->driver_data = fsg;
3295
3296 if ((rc = check_parameters(fsg)) != 0)
3297 goto out;
3298
3299 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003300 dev_attr_file.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003301 dev_attr_file.store = fsg_store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003302 if (!mod_data.cdrom) {
3303 dev_attr_ro.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003304 dev_attr_ro.store = fsg_store_ro;
Alan Stern12aae682008-11-20 14:13:12 -05003305 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003306 }
3307
3308 /* Find out how many LUNs there should be */
3309 i = mod_data.nluns;
3310 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003311 i = max(mod_data.num_filenames, 1u);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003312 if (i > FSG_MAX_LUNS) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003313 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3314 rc = -EINVAL;
3315 goto out;
3316 }
3317
3318 /* Create the LUNs, open their backing files, and register the
3319 * LUN devices in sysfs. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003320 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003321 if (!fsg->luns) {
3322 rc = -ENOMEM;
3323 goto out;
3324 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003325 fsg->nluns = i;
3326
3327 for (i = 0; i < fsg->nluns; ++i) {
3328 curlun = &fsg->luns[i];
Michal Nazarewicze909ef52009-10-28 16:57:16 +01003329 curlun->cdrom = !!mod_data.cdrom;
3330 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3331 curlun->initially_ro = curlun->ro;
3332 curlun->removable = mod_data.removable;
Alan Stern2de9eae2006-09-25 14:31:15 -04003333 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003334 curlun->dev.parent = &gadget->dev;
3335 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003336 dev_set_drvdata(&curlun->dev, &fsg->filesem);
Kay Sievers0031a062008-05-02 06:02:41 +02003337 dev_set_name(&curlun->dev,"%s-lun%d",
3338 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003339
Alan Stern2de9eae2006-09-25 14:31:15 -04003340 if ((rc = device_register(&curlun->dev)) != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003341 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Alan Stern2de9eae2006-09-25 14:31:15 -04003342 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003343 }
Alan Stern2de9eae2006-09-25 14:31:15 -04003344 if ((rc = device_create_file(&curlun->dev,
3345 &dev_attr_ro)) != 0 ||
3346 (rc = device_create_file(&curlun->dev,
3347 &dev_attr_file)) != 0) {
3348 device_unregister(&curlun->dev);
3349 goto out;
3350 }
3351 curlun->registered = 1;
3352 kref_get(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003353
Alan Sternaafe5bd2006-03-31 11:46:43 -05003354 if (mod_data.file[i] && *mod_data.file[i]) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003355 if ((rc = fsg_lun_open(curlun,
Alan Sternaafe5bd2006-03-31 11:46:43 -05003356 mod_data.file[i])) != 0)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003357 goto out;
3358 } else if (!mod_data.removable) {
3359 ERROR(fsg, "no file given for LUN%d\n", i);
3360 rc = -EINVAL;
3361 goto out;
3362 }
3363 }
3364
3365 /* Find all the endpoints we will use */
3366 usb_ep_autoconfig_reset(gadget);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003367 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003368 if (!ep)
3369 goto autoconf_fail;
3370 ep->driver_data = fsg; // claim the endpoint
3371 fsg->bulk_in = ep;
3372
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003373 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003374 if (!ep)
3375 goto autoconf_fail;
3376 ep->driver_data = fsg; // claim the endpoint
3377 fsg->bulk_out = ep;
3378
3379 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003380 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003381 if (!ep)
3382 goto autoconf_fail;
3383 ep->driver_data = fsg; // claim the endpoint
3384 fsg->intr_in = ep;
3385 }
3386
3387 /* Fix up the descriptors */
3388 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3389 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3390 device_desc.idProduct = cpu_to_le16(mod_data.product);
3391 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3392
3393 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003394 fsg_intf_desc.bNumEndpoints = i;
3395 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3396 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3397 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003398
David Brownell2e806f62007-08-02 00:03:39 -07003399 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003400 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003401
David Brownell2e806f62007-08-02 00:03:39 -07003402 /* Assume ep0 uses the same maxpacket value for both speeds */
3403 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003404
David Brownell2e806f62007-08-02 00:03:39 -07003405 /* Assume endpoint addresses are the same for both speeds */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003406 fsg_hs_bulk_in_desc.bEndpointAddress =
3407 fsg_fs_bulk_in_desc.bEndpointAddress;
3408 fsg_hs_bulk_out_desc.bEndpointAddress =
3409 fsg_fs_bulk_out_desc.bEndpointAddress;
3410 fsg_hs_intr_in_desc.bEndpointAddress =
3411 fsg_fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003412 }
3413
David Brownell2e806f62007-08-02 00:03:39 -07003414 if (gadget_is_otg(gadget))
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003415 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
David Brownell2e806f62007-08-02 00:03:39 -07003416
Linus Torvalds1da177e2005-04-16 15:20:36 -07003417 rc = -ENOMEM;
3418
3419 /* Allocate the request and buffer for endpoint 0 */
3420 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3421 if (!req)
3422 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003423 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003424 if (!req->buf)
3425 goto out;
3426 req->complete = ep0_complete;
3427
3428 /* Allocate the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003429 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003430 struct fsg_buffhd *bh = &fsg->buffhds[i];
3431
Alan Stern14cd5f82006-03-23 15:07:25 -05003432 /* Allocate for the bulk-in endpoint. We assume that
3433 * the buffer will also work with the bulk-out (and
3434 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003435 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003436 if (!bh->buf)
3437 goto out;
3438 bh->next = bh + 1;
3439 }
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003440 fsg->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->buffhds[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07003441
3442 /* This should reflect the actual gadget power source */
3443 usb_gadget_set_selfpowered(gadget);
3444
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003445 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3446 "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003447 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003448 gadget->name);
3449
3450 /* On a real device, serial[] would be loaded from permanent
3451 * storage. We just encode it from the driver version string. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003452 for (i = 0; i < sizeof fsg_string_serial - 2; i += 2) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003453 unsigned char c = DRIVER_VERSION[i / 2];
3454
3455 if (!c)
3456 break;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003457 sprintf(&fsg_string_serial[i], "%02X", c);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003458 }
3459
Alan Stern22efcf42005-09-26 16:12:02 -04003460 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3461 "file-storage-gadget");
3462 if (IS_ERR(fsg->thread_task)) {
3463 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003464 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04003465 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003466
3467 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3468 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3469
3470 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3471 for (i = 0; i < fsg->nluns; ++i) {
3472 curlun = &fsg->luns[i];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003473 if (fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003474 p = NULL;
3475 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08003476 p = d_path(&curlun->filp->f_path,
3477 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003478 if (IS_ERR(p))
3479 p = NULL;
3480 }
3481 LINFO(curlun, "ro=%d, file: %s\n",
3482 curlun->ro, (p ? p : "(error)"));
3483 }
3484 }
3485 kfree(pathbuf);
3486
3487 DBG(fsg, "transport=%s (x%02x)\n",
3488 mod_data.transport_name, mod_data.transport_type);
3489 DBG(fsg, "protocol=%s (x%02x)\n",
3490 mod_data.protocol_name, mod_data.protocol_type);
3491 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3492 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05003493 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003494 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05003495 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07003496 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04003497
3498 set_bit(REGISTERED, &fsg->atomic_bitflags);
3499
3500 /* Tell the thread to start working */
3501 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003502 return 0;
3503
3504autoconf_fail:
3505 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3506 rc = -ENOTSUPP;
3507
3508out:
3509 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3510 fsg_unbind(gadget);
Felipe Balbi889394b2008-12-08 13:50:27 +02003511 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003512 return rc;
3513}
3514
3515
3516/*-------------------------------------------------------------------------*/
3517
3518static void fsg_suspend(struct usb_gadget *gadget)
3519{
3520 struct fsg_dev *fsg = get_gadget_data(gadget);
3521
3522 DBG(fsg, "suspend\n");
3523 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3524}
3525
3526static void fsg_resume(struct usb_gadget *gadget)
3527{
3528 struct fsg_dev *fsg = get_gadget_data(gadget);
3529
3530 DBG(fsg, "resume\n");
3531 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3532}
3533
3534
3535/*-------------------------------------------------------------------------*/
3536
3537static struct usb_gadget_driver fsg_driver = {
3538#ifdef CONFIG_USB_GADGET_DUALSPEED
3539 .speed = USB_SPEED_HIGH,
3540#else
3541 .speed = USB_SPEED_FULL,
3542#endif
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003543 .function = (char *) fsg_string_product,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003544 .bind = fsg_bind,
David Brownell6bea4762006-12-05 03:15:33 -08003545 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003546 .disconnect = fsg_disconnect,
3547 .setup = fsg_setup,
3548 .suspend = fsg_suspend,
3549 .resume = fsg_resume,
3550
3551 .driver = {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003552 .name = DRIVER_NAME,
Ben Dooksd0d50492005-10-10 10:52:33 +01003553 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003554 // .release = ...
3555 // .suspend = ...
3556 // .resume = ...
3557 },
3558};
3559
3560
3561static int __init fsg_alloc(void)
3562{
3563 struct fsg_dev *fsg;
3564
Alan Sterna922c682005-10-06 16:38:45 -04003565 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003566 if (!fsg)
3567 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003568 spin_lock_init(&fsg->lock);
3569 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05003570 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003571 init_completion(&fsg->thread_notifier);
3572
3573 the_fsg = fsg;
3574 return 0;
3575}
3576
3577
Linus Torvalds1da177e2005-04-16 15:20:36 -07003578static int __init fsg_init(void)
3579{
3580 int rc;
3581 struct fsg_dev *fsg;
3582
3583 if ((rc = fsg_alloc()) != 0)
3584 return rc;
3585 fsg = the_fsg;
Alan Sterna922c682005-10-06 16:38:45 -04003586 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05003587 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04003588 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003589}
3590module_init(fsg_init);
3591
3592
3593static void __exit fsg_cleanup(void)
3594{
3595 struct fsg_dev *fsg = the_fsg;
3596
3597 /* Unregister the driver iff the thread hasn't already done so */
3598 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3599 usb_gadget_unregister_driver(&fsg_driver);
3600
3601 /* Wait for the thread to finish up */
3602 wait_for_completion(&fsg->thread_notifier);
3603
Alan Stern87c42522005-11-09 16:59:56 -05003604 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003605}
3606module_exit(fsg_cleanup);