blob: 2b6d3649d02cc3e316b02b8718dcefe1b9aaabe5 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
3 *
Alan Stern12aae682008-11-20 14:13:12 -05004 * Copyright (C) 2003-2008 Alan Stern
Linus Torvalds1da177e2005-04-16 15:20:36 -07005 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions, and the following disclaimer,
12 * without modification.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The names of the above-listed copyright holders may not be used
17 * to endorse or promote products derived from this software without
18 * specific prior written permission.
19 *
20 * ALTERNATIVELY, this software may be distributed under the terms of the
21 * GNU General Public License ("GPL") as published by the Free Software
22 * Foundation, either version 2 of that License or (at your option) any
23 * later version.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 */
37
38
39/*
40 * The File-backed Storage Gadget acts as a USB Mass Storage device,
Alan Stern12aae682008-11-20 14:13:12 -050041 * appearing to the host as a disk drive or as a CD-ROM drive. In addition
42 * to providing an example of a genuinely useful gadget driver for a USB
43 * device, it also illustrates a technique of double-buffering for increased
44 * throughput. Last but not least, it gives an easy way to probe the
45 * behavior of the Mass Storage drivers in a USB host.
Linus Torvalds1da177e2005-04-16 15:20:36 -070046 *
47 * Backing storage is provided by a regular file or a block device, specified
48 * by the "file" module parameter. Access can be limited to read-only by
Alan Stern12aae682008-11-20 14:13:12 -050049 * setting the optional "ro" module parameter. (For CD-ROM emulation,
50 * access is always read-only.) The gadget will indicate that it has
51 * removable media if the optional "removable" module parameter is set.
Linus Torvalds1da177e2005-04-16 15:20:36 -070052 *
53 * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
54 * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
55 * by the optional "transport" module parameter. It also supports the
56 * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
57 * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
58 * the optional "protocol" module parameter. In addition, the default
Yann Cantin87eb1be2010-06-05 23:06:31 +020059 * Vendor ID, Product ID, release number and serial number can be overridden.
Linus Torvalds1da177e2005-04-16 15:20:36 -070060 *
61 * There is support for multiple logical units (LUNs), each of which has
62 * its own backing file. The number of LUNs can be set using the optional
63 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
64 * files are specified using comma-separated lists for "file" and "ro".
65 * The default number of LUNs is taken from the number of "file" elements;
66 * it is 1 if "file" is not given. If "removable" is not set then a backing
67 * file must be specified for each LUN. If it is set, then an unspecified
Alan Stern12aae682008-11-20 14:13:12 -050068 * or empty backing filename means the LUN's medium is not loaded. Ideally
69 * each LUN would be settable independently as a disk drive or a CD-ROM
70 * drive, but currently all LUNs have to be the same type. The CD-ROM
71 * emulation includes a single data track and no audio tracks; hence there
72 * need be only one backing file per LUN. Note also that the CD-ROM block
73 * length is set to 512 rather than the more common value 2048.
Linus Torvalds1da177e2005-04-16 15:20:36 -070074 *
75 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
76 * needed (an interrupt-out endpoint is also needed for CBI). The memory
77 * requirement amounts to two 16K buffers, size configurable by a parameter.
78 * Support is included for both full-speed and high-speed operation.
79 *
Alan Stern14cd5f82006-03-23 15:07:25 -050080 * Note that the driver is slightly non-portable in that it assumes a
81 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
82 * interrupt-in endpoints. With most device controllers this isn't an
83 * issue, but there may be some with hardware restrictions that prevent
84 * a buffer from being used by more than one endpoint.
85 *
Linus Torvalds1da177e2005-04-16 15:20:36 -070086 * Module options:
87 *
88 * file=filename[,filename...]
89 * Required if "removable" is not set, names of
90 * the files or block devices used for
91 * backing storage
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)
Yann Cantin87eb1be2010-06-05 23:06:31 +0200109 * serial=HHHH... Override serial number (string of hex chars)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700110 * buflen=N Default N=16384, buffer size used (will be
111 * rounded down to a multiple of
112 * PAGE_CACHE_SIZE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700113 *
114 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
Alan Stern12aae682008-11-20 14:13:12 -0500115 * "removable", "luns", "stall", and "cdrom" options are available; default
116 * values are used for everything else.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700117 *
118 * The pathnames of the backing files and the ro settings are available in
119 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
120 * gadget's sysfs directory. If the "removable" option is set, writing to
121 * these files will simulate ejecting/loading the medium (writing an empty
122 * line means eject) and adjusting a write-enable tab. Changes to the ro
Alan Stern12aae682008-11-20 14:13:12 -0500123 * setting are not allowed when the medium is loaded or if CD-ROM emulation
124 * is being used.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700125 *
126 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
Alan Sternaafe5bd2006-03-31 11:46:43 -0500127 * The driver's SCSI command interface was based on the "Information
128 * technology - Small Computer System Interface - 2" document from
129 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
130 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
131 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
132 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
133 * document, Revision 1.0, December 14, 1998, available at
134 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700135 */
136
137
138/*
139 * Driver Design
140 *
141 * The FSG driver is fairly straightforward. There is a main kernel
142 * thread that handles most of the work. Interrupt routines field
143 * callbacks from the controller driver: bulk- and interrupt-request
144 * completion notifications, endpoint-0 events, and disconnect events.
145 * Completion events are passed to the main thread by wakeup calls. Many
146 * ep0 requests are handled at interrupt time, but SetInterface,
147 * SetConfiguration, and device reset requests are forwarded to the
148 * thread in the form of "exceptions" using SIGUSR1 signals (since they
149 * should interrupt any ongoing file I/O operations).
150 *
151 * The thread's main routine implements the standard command/data/status
152 * parts of a SCSI interaction. It and its subroutines are full of tests
153 * for pending signals/exceptions -- all this polling is necessary since
154 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
155 * indication that the driver really wants to be running in userspace.)
156 * An important point is that so long as the thread is alive it keeps an
157 * open reference to the backing file. This will prevent unmounting
158 * the backing file's underlying filesystem and could cause problems
159 * during system shutdown, for example. To prevent such problems, the
160 * thread catches INT, TERM, and KILL signals and converts them into
161 * an EXIT exception.
162 *
163 * In normal operation the main thread is started during the gadget's
164 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
165 * exit when it receives a signal, and there's no point leaving the
166 * gadget running when the thread is dead. So just before the thread
167 * exits, it deregisters the gadget driver. This makes things a little
168 * tricky: The driver is deregistered at two places, and the exiting
169 * thread can indirectly call fsg_unbind() which in turn can tell the
170 * thread to exit. The first problem is resolved through the use of the
171 * REGISTERED atomic bitflag; the driver will only be deregistered once.
172 * The second problem is resolved by having fsg_unbind() check
173 * fsg->state; it won't try to stop the thread if the state is already
174 * FSG_STATE_TERMINATED.
175 *
176 * To provide maximum throughput, the driver uses a circular pipeline of
177 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
178 * arbitrarily long; in practice the benefits don't justify having more
179 * than 2 stages (i.e., double buffering). But it helps to think of the
180 * pipeline as being a long one. Each buffer head contains a bulk-in and
181 * a bulk-out request pointer (since the buffer can be used for both
182 * output and input -- directions always are given from the host's
183 * point of view) as well as a pointer to the buffer and various state
184 * variables.
185 *
186 * Use of the pipeline follows a simple protocol. There is a variable
187 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
188 * At any time that buffer head may still be in use from an earlier
189 * request, so each buffer head has a state variable indicating whether
190 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
191 * buffer head to be EMPTY, filling the buffer either by file I/O or by
192 * USB I/O (during which the buffer head is BUSY), and marking the buffer
193 * head FULL when the I/O is complete. Then the buffer will be emptied
194 * (again possibly by USB I/O, during which it is marked BUSY) and
195 * finally marked EMPTY again (possibly by a completion routine).
196 *
197 * A module parameter tells the driver to avoid stalling the bulk
198 * endpoints wherever the transport specification allows. This is
199 * necessary for some UDCs like the SuperH, which cannot reliably clear a
200 * halt on a bulk endpoint. However, under certain circumstances the
201 * Bulk-only specification requires a stall. In such cases the driver
202 * will halt the endpoint and set a flag indicating that it should clear
203 * the halt in software during the next device reset. Hopefully this
204 * will permit everything to work correctly. Furthermore, although the
205 * specification allows the bulk-out endpoint to halt when the host sends
206 * too much data, implementing this would cause an unavoidable race.
207 * The driver will always use the "no-stall" approach for OUT transfers.
208 *
209 * One subtle point concerns sending status-stage responses for ep0
210 * requests. Some of these requests, such as device reset, can involve
211 * interrupting an ongoing file I/O operation, which might take an
212 * arbitrarily long time. During that delay the host might give up on
213 * the original ep0 request and issue a new one. When that happens the
214 * driver should not notify the host about completion of the original
215 * request, as the host will no longer be waiting for it. So the driver
216 * assigns to each ep0 request a unique tag, and it keeps track of the
217 * tag value of the request associated with a long-running exception
218 * (device-reset, interface-change, or configuration-change). When the
219 * exception handler is finished, the status-stage response is submitted
220 * only if the current ep0 request tag is equal to the exception request
221 * tag. Thus only the most recently received ep0 request will get a
222 * status-stage response.
223 *
224 * Warning: This driver source file is too long. It ought to be split up
225 * into a header file plus about 3 separate .c files, to handle the details
226 * of the Gadget, USB Mass Storage, and SCSI protocols.
227 */
228
229
David Brownell2e806f62007-08-02 00:03:39 -0700230/* #define VERBOSE_DEBUG */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400231/* #define DUMP_MSGS */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700232
Linus Torvalds1da177e2005-04-16 15:20:36 -0700233
Linus Torvalds1da177e2005-04-16 15:20:36 -0700234#include <linux/blkdev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700235#include <linux/completion.h>
236#include <linux/dcache.h>
237#include <linux/delay.h>
238#include <linux/device.h>
239#include <linux/fcntl.h>
240#include <linux/file.h>
241#include <linux/fs.h>
Alan Stern87c42522005-11-09 16:59:56 -0500242#include <linux/kref.h>
Alan Stern22efcf42005-09-26 16:12:02 -0400243#include <linux/kthread.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700244#include <linux/limits.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700245#include <linux/rwsem.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700246#include <linux/slab.h>
247#include <linux/spinlock.h>
248#include <linux/string.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -0800249#include <linux/freezer.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700250#include <linux/utsname.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700251
David Brownell5f848132006-12-16 15:34:53 -0800252#include <linux/usb/ch9.h>
David Brownell9454a572007-10-04 18:05:17 -0700253#include <linux/usb/gadget.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700254
255#include "gadget_chips.h"
256
257
David Brownell352e2b92008-08-18 17:43:25 -0700258
259/*
260 * Kbuild is not very cooperative with respect to linking separately
261 * compiled library objects into one module. So for now we won't use
262 * separate compilation ... ensuring init/exit sections work to shrink
263 * the runtime footprint, and giving us at least some parts of what
264 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
265 */
266#include "usbstring.c"
267#include "config.c"
268#include "epautoconf.c"
269
Linus Torvalds1da177e2005-04-16 15:20:36 -0700270/*-------------------------------------------------------------------------*/
271
272#define DRIVER_DESC "File-backed Storage Gadget"
273#define DRIVER_NAME "g_file_storage"
Yann Cantin87eb1be2010-06-05 23:06:31 +0200274/* DRIVER_VERSION must be at least 6 characters long, as it is used
275 * to generate a fallback serial number. */
Alan Stern12aae682008-11-20 14:13:12 -0500276#define DRIVER_VERSION "20 November 2008"
Linus Torvalds1da177e2005-04-16 15:20:36 -0700277
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100278static char fsg_string_manufacturer[64];
279static const char fsg_string_product[] = DRIVER_DESC;
280static char fsg_string_serial[13];
281static const char fsg_string_config[] = "Self-powered";
282static const char fsg_string_interface[] = "Mass Storage";
Linus Torvalds1da177e2005-04-16 15:20:36 -0700283
Michal Nazarewicz93f93742009-10-28 16:57:17 +0100284
285#include "storage_common.c"
286
287
Linus Torvalds1da177e2005-04-16 15:20:36 -0700288MODULE_DESCRIPTION(DRIVER_DESC);
289MODULE_AUTHOR("Alan Stern");
290MODULE_LICENSE("Dual BSD/GPL");
291
Linus Torvalds1da177e2005-04-16 15:20:36 -0700292/*
293 * This driver assumes self-powered hardware and has no way for users to
294 * trigger remote wakeup. It uses autoconfiguration to select endpoints
295 * and endpoint addresses.
296 */
297
298
299/*-------------------------------------------------------------------------*/
300
Linus Torvalds1da177e2005-04-16 15:20:36 -0700301
302/* Encapsulate the module parameter settings */
303
Linus Torvalds1da177e2005-04-16 15:20:36 -0700304static struct {
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100305 char *file[FSG_MAX_LUNS];
306 int ro[FSG_MAX_LUNS];
David Brownell2e806f62007-08-02 00:03:39 -0700307 unsigned int num_filenames;
308 unsigned int num_ros;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700309 unsigned int nluns;
310
Alan Sternd794ac72005-04-18 12:43:25 -0400311 int removable;
312 int can_stall;
Alan Stern12aae682008-11-20 14:13:12 -0500313 int cdrom;
Alan Sternd794ac72005-04-18 12:43:25 -0400314
Linus Torvalds1da177e2005-04-16 15:20:36 -0700315 char *transport_parm;
316 char *protocol_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700317 unsigned short vendor;
318 unsigned short product;
319 unsigned short release;
Yann Cantin87eb1be2010-06-05 23:06:31 +0200320 char *serial_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700321 unsigned int buflen;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700322
323 int transport_type;
324 char *transport_name;
325 int protocol_type;
326 char *protocol_name;
327
328} mod_data = { // Default values
329 .transport_parm = "BBB",
330 .protocol_parm = "SCSI",
331 .removable = 0,
Alan Sternd794ac72005-04-18 12:43:25 -0400332 .can_stall = 1,
Alan Stern12aae682008-11-20 14:13:12 -0500333 .cdrom = 0,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100334 .vendor = FSG_VENDOR_ID,
335 .product = FSG_PRODUCT_ID,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700336 .release = 0xffff, // Use controller chip type
337 .buflen = 16384,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700338 };
339
340
Alan Sternaafe5bd2006-03-31 11:46:43 -0500341module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
342 S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700343MODULE_PARM_DESC(file, "names of backing files or devices");
344
Alan Sternaafe5bd2006-03-31 11:46:43 -0500345module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700346MODULE_PARM_DESC(ro, "true to force read-only");
347
348module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
349MODULE_PARM_DESC(luns, "number of LUNs");
350
351module_param_named(removable, mod_data.removable, bool, S_IRUGO);
352MODULE_PARM_DESC(removable, "true to simulate removable media");
353
Alan Sternd794ac72005-04-18 12:43:25 -0400354module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
355MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
356
Alan Stern12aae682008-11-20 14:13:12 -0500357module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
358MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
359
Linus Torvalds1da177e2005-04-16 15:20:36 -0700360
361/* In the non-TEST version, only the module parameters listed above
362 * are available. */
363#ifdef CONFIG_USB_FILE_STORAGE_TEST
364
365module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
366MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
367
368module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
369MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
370 "8070, or SCSI)");
371
372module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
373MODULE_PARM_DESC(vendor, "USB Vendor ID");
374
375module_param_named(product, mod_data.product, ushort, S_IRUGO);
376MODULE_PARM_DESC(product, "USB Product ID");
377
378module_param_named(release, mod_data.release, ushort, S_IRUGO);
379MODULE_PARM_DESC(release, "USB release number");
380
Yann Cantin87eb1be2010-06-05 23:06:31 +0200381module_param_named(serial, mod_data.serial_parm, charp, S_IRUGO);
382MODULE_PARM_DESC(serial, "USB serial number");
383
Linus Torvalds1da177e2005-04-16 15:20:36 -0700384module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
385MODULE_PARM_DESC(buflen, "I/O buffer size");
386
Linus Torvalds1da177e2005-04-16 15:20:36 -0700387#endif /* CONFIG_USB_FILE_STORAGE_TEST */
388
389
Linus Torvalds1da177e2005-04-16 15:20:36 -0700390/*
391 * These definitions will permit the compiler to avoid generating code for
392 * parts of the driver that aren't used in the non-TEST version. Even gcc
393 * can recognize when a test of a constant expression yields a dead code
394 * path.
395 */
396
397#ifdef CONFIG_USB_FILE_STORAGE_TEST
398
399#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
400#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
401#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
402
403#else
404
405#define transport_is_bbb() 1
406#define transport_is_cbi() 0
407#define protocol_is_scsi() 1
408
409#endif /* CONFIG_USB_FILE_STORAGE_TEST */
410
411
Michal Nazarewiczb6058d02009-10-28 16:57:14 +0100412/*-------------------------------------------------------------------------*/
Linus Torvalds1da177e2005-04-16 15:20:36 -0700413
Linus Torvalds1da177e2005-04-16 15:20:36 -0700414
415struct fsg_dev {
416 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
417 spinlock_t lock;
418 struct usb_gadget *gadget;
419
420 /* filesem protects: backing files in use */
421 struct rw_semaphore filesem;
422
Alan Stern87c42522005-11-09 16:59:56 -0500423 /* reference counting: wait until all LUNs are released */
424 struct kref ref;
425
Linus Torvalds1da177e2005-04-16 15:20:36 -0700426 struct usb_ep *ep0; // Handy copy of gadget->ep0
427 struct usb_request *ep0req; // For control responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500428 unsigned int ep0_req_tag;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700429 const char *ep0req_name;
430
431 struct usb_request *intreq; // For interrupt responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500432 int intreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700433 struct fsg_buffhd *intr_buffhd;
434
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100435 unsigned int bulk_out_maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700436 enum fsg_state state; // For exception handling
437 unsigned int exception_req_tag;
438
439 u8 config, new_config;
440
441 unsigned int running : 1;
442 unsigned int bulk_in_enabled : 1;
443 unsigned int bulk_out_enabled : 1;
444 unsigned int intr_in_enabled : 1;
445 unsigned int phase_error : 1;
446 unsigned int short_packet_received : 1;
447 unsigned int bad_lun_okay : 1;
448
449 unsigned long atomic_bitflags;
450#define REGISTERED 0
Alan Sternb950bdb2008-04-14 11:45:29 -0400451#define IGNORE_BULK_OUT 1
Linus Torvalds1da177e2005-04-16 15:20:36 -0700452#define SUSPENDED 2
453
454 struct usb_ep *bulk_in;
455 struct usb_ep *bulk_out;
456 struct usb_ep *intr_in;
457
458 struct fsg_buffhd *next_buffhd_to_fill;
459 struct fsg_buffhd *next_buffhd_to_drain;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100460 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700461
Linus Torvalds1da177e2005-04-16 15:20:36 -0700462 int thread_wakeup_needed;
463 struct completion thread_notifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700464 struct task_struct *thread_task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700465
466 int cmnd_size;
467 u8 cmnd[MAX_COMMAND_SIZE];
468 enum data_direction data_dir;
469 u32 data_size;
470 u32 data_size_from_cmnd;
471 u32 tag;
472 unsigned int lun;
473 u32 residue;
474 u32 usb_amount_left;
475
476 /* The CB protocol offers no way for a host to know when a command
477 * has completed. As a result the next command may arrive early,
478 * and we will still have to handle it. For that reason we need
479 * a buffer to store new commands when using CB (or CBI, which
480 * does not oblige a host to wait for command completion either). */
481 int cbbuf_cmnd_size;
482 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
483
484 unsigned int nluns;
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100485 struct fsg_lun *luns;
486 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700487};
488
489typedef void (*fsg_routine_t)(struct fsg_dev *);
490
Alan Stern79a7d9e2007-08-08 17:10:11 -0400491static int exception_in_progress(struct fsg_dev *fsg)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700492{
493 return (fsg->state > FSG_STATE_IDLE);
494}
495
496/* Make bulk-out requests be divisible by the maxpacket size */
Alan Stern79a7d9e2007-08-08 17:10:11 -0400497static void set_bulk_out_req_length(struct fsg_dev *fsg,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700498 struct fsg_buffhd *bh, unsigned int length)
499{
500 unsigned int rem;
501
502 bh->bulk_out_intended_length = length;
503 rem = length % fsg->bulk_out_maxpacket;
504 if (rem > 0)
505 length += fsg->bulk_out_maxpacket - rem;
506 bh->outreq->length = length;
507}
508
509static struct fsg_dev *the_fsg;
510static struct usb_gadget_driver fsg_driver;
511
Linus Torvalds1da177e2005-04-16 15:20:36 -0700512
513/*-------------------------------------------------------------------------*/
514
Linus Torvalds1da177e2005-04-16 15:20:36 -0700515static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
516{
517 const char *name;
518
519 if (ep == fsg->bulk_in)
520 name = "bulk-in";
521 else if (ep == fsg->bulk_out)
522 name = "bulk-out";
523 else
524 name = ep->name;
525 DBG(fsg, "%s set halt\n", name);
526 return usb_ep_set_halt(ep);
527}
528
529
530/*-------------------------------------------------------------------------*/
531
Linus Torvalds1da177e2005-04-16 15:20:36 -0700532/*
533 * DESCRIPTORS ... most are static, but strings and (full) configuration
534 * descriptors are built on demand. Also the (static) config and interface
535 * descriptors are adjusted during fsg_bind().
536 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700537
538/* There is only one configuration. */
539#define CONFIG_VALUE 1
540
541static struct usb_device_descriptor
542device_desc = {
543 .bLength = sizeof device_desc,
544 .bDescriptorType = USB_DT_DEVICE,
545
Harvey Harrison551509d2009-02-11 14:11:36 -0800546 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700547 .bDeviceClass = USB_CLASS_PER_INTERFACE,
548
549 /* The next three values can be overridden by module parameters */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100550 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
551 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
Harvey Harrison551509d2009-02-11 14:11:36 -0800552 .bcdDevice = cpu_to_le16(0xffff),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700553
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100554 .iManufacturer = FSG_STRING_MANUFACTURER,
555 .iProduct = FSG_STRING_PRODUCT,
556 .iSerialNumber = FSG_STRING_SERIAL,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700557 .bNumConfigurations = 1,
558};
559
560static struct usb_config_descriptor
561config_desc = {
562 .bLength = sizeof config_desc,
563 .bDescriptorType = USB_DT_CONFIG,
564
565 /* wTotalLength computed by usb_gadget_config_buf() */
566 .bNumInterfaces = 1,
567 .bConfigurationValue = CONFIG_VALUE,
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100568 .iConfiguration = FSG_STRING_CONFIG,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700569 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
David Brownell36e893d2008-09-12 09:39:06 -0700570 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700571};
572
Linus Torvalds1da177e2005-04-16 15:20:36 -0700573
Linus Torvalds1da177e2005-04-16 15:20:36 -0700574static struct usb_qualifier_descriptor
575dev_qualifier = {
576 .bLength = sizeof dev_qualifier,
577 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
578
Harvey Harrison551509d2009-02-11 14:11:36 -0800579 .bcdUSB = cpu_to_le16(0x0200),
Linus Torvalds1da177e2005-04-16 15:20:36 -0700580 .bDeviceClass = USB_CLASS_PER_INTERFACE,
581
582 .bNumConfigurations = 1,
583};
584
Linus Torvalds1da177e2005-04-16 15:20:36 -0700585
586
587/*
588 * Config descriptors must agree with the code that sets configurations
589 * and with code managing interfaces and their altsettings. They must
590 * also handle different speeds and other-speed requests.
591 */
592static int populate_config_buf(struct usb_gadget *gadget,
593 u8 *buf, u8 type, unsigned index)
594{
Linus Torvalds1da177e2005-04-16 15:20:36 -0700595 enum usb_device_speed speed = gadget->speed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700596 int len;
597 const struct usb_descriptor_header **function;
598
599 if (index > 0)
600 return -EINVAL;
601
David Brownell2e806f62007-08-02 00:03:39 -0700602 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700603 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
Michal Nazarewiczd23b0f02009-11-09 14:15:20 +0100604 function = gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH
605 ? (const struct usb_descriptor_header **)fsg_hs_function
606 : (const struct usb_descriptor_header **)fsg_fs_function;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700607
608 /* for now, don't advertise srp-only devices */
David Brownell2e806f62007-08-02 00:03:39 -0700609 if (!gadget_is_otg(gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700610 function++;
611
612 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
613 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
614 return len;
615}
616
617
618/*-------------------------------------------------------------------------*/
619
620/* These routines may be called in process context or in_irq */
621
Alan Sterna21d4fe2005-11-29 12:04:24 -0500622/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700623static void wakeup_thread(struct fsg_dev *fsg)
624{
625 /* Tell the main thread that something has happened */
626 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500627 if (fsg->thread_task)
628 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700629}
630
631
632static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
633{
634 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700635
636 /* Do nothing if a higher-priority exception is already in progress.
637 * If a lower-or-equal priority exception is in progress, preempt it
638 * and notify the main thread by sending it a signal. */
639 spin_lock_irqsave(&fsg->lock, flags);
640 if (fsg->state <= new_state) {
641 fsg->exception_req_tag = fsg->ep0_req_tag;
642 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -0400643 if (fsg->thread_task)
644 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
645 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700646 }
647 spin_unlock_irqrestore(&fsg->lock, flags);
648}
649
650
651/*-------------------------------------------------------------------------*/
652
653/* The disconnect callback and ep0 routines. These always run in_irq,
654 * except that ep0_queue() is called in the main thread to acknowledge
655 * completion of various requests: set config, set interface, and
656 * Bulk-only device reset. */
657
658static void fsg_disconnect(struct usb_gadget *gadget)
659{
660 struct fsg_dev *fsg = get_gadget_data(gadget);
661
662 DBG(fsg, "disconnect or port reset\n");
663 raise_exception(fsg, FSG_STATE_DISCONNECT);
664}
665
666
667static int ep0_queue(struct fsg_dev *fsg)
668{
669 int rc;
670
671 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
672 if (rc != 0 && rc != -ESHUTDOWN) {
673
674 /* We can't do much more than wait for a reset */
Arjan van de Venb6c63932008-07-25 01:45:52 -0700675 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -0700676 fsg->ep0->name, rc);
677 }
678 return rc;
679}
680
681static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
682{
John Daiker7ca46b82006-12-29 19:02:06 -0800683 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700684
685 if (req->actual > 0)
686 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
687 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800688 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700689 req->status, req->actual, req->length);
690 if (req->status == -ECONNRESET) // Request was cancelled
691 usb_ep_fifo_flush(ep);
692
693 if (req->status == 0 && req->context)
694 ((fsg_routine_t) (req->context))(fsg);
695}
696
697
698/*-------------------------------------------------------------------------*/
699
700/* Bulk and interrupt endpoint completion handlers.
701 * These always run in_irq. */
702
703static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
704{
John Daiker7ca46b82006-12-29 19:02:06 -0800705 struct fsg_dev *fsg = ep->driver_data;
706 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700707
708 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800709 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700710 req->status, req->actual, req->length);
711 if (req->status == -ECONNRESET) // Request was cancelled
712 usb_ep_fifo_flush(ep);
713
714 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500715 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700716 spin_lock(&fsg->lock);
717 bh->inreq_busy = 0;
718 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700719 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500720 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700721}
722
723static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
724{
John Daiker7ca46b82006-12-29 19:02:06 -0800725 struct fsg_dev *fsg = ep->driver_data;
726 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700727
728 dump_msg(fsg, "bulk-out", req->buf, req->actual);
729 if (req->status || req->actual != bh->bulk_out_intended_length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800730 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700731 req->status, req->actual,
732 bh->bulk_out_intended_length);
733 if (req->status == -ECONNRESET) // Request was cancelled
734 usb_ep_fifo_flush(ep);
735
736 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500737 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700738 spin_lock(&fsg->lock);
739 bh->outreq_busy = 0;
740 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700741 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500742 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700743}
744
745
746#ifdef CONFIG_USB_FILE_STORAGE_TEST
747static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
748{
John Daiker7ca46b82006-12-29 19:02:06 -0800749 struct fsg_dev *fsg = ep->driver_data;
750 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700751
752 if (req->status || req->actual != req->length)
Harvey Harrison441b62c2008-03-03 16:08:34 -0800753 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700754 req->status, req->actual, req->length);
755 if (req->status == -ECONNRESET) // Request was cancelled
756 usb_ep_fifo_flush(ep);
757
758 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -0500759 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700760 spin_lock(&fsg->lock);
761 fsg->intreq_busy = 0;
762 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700763 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500764 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700765}
766
767#else
768static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
769{}
770#endif /* CONFIG_USB_FILE_STORAGE_TEST */
771
772
773/*-------------------------------------------------------------------------*/
774
775/* Ep0 class-specific handlers. These always run in_irq. */
776
777#ifdef CONFIG_USB_FILE_STORAGE_TEST
778static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
779{
780 struct usb_request *req = fsg->ep0req;
781 static u8 cbi_reset_cmnd[6] = {
782 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
783
784 /* Error in command transfer? */
785 if (req->status || req->length != req->actual ||
786 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
787
788 /* Not all controllers allow a protocol stall after
789 * receiving control-out data, but we'll try anyway. */
790 fsg_set_halt(fsg, fsg->ep0);
791 return; // Wait for reset
792 }
793
794 /* Is it the special reset command? */
795 if (req->actual >= sizeof cbi_reset_cmnd &&
796 memcmp(req->buf, cbi_reset_cmnd,
797 sizeof cbi_reset_cmnd) == 0) {
798
799 /* Raise an exception to stop the current operation
800 * and reinitialize our state. */
801 DBG(fsg, "cbi reset request\n");
802 raise_exception(fsg, FSG_STATE_RESET);
803 return;
804 }
805
806 VDBG(fsg, "CB[I] accept device-specific command\n");
807 spin_lock(&fsg->lock);
808
809 /* Save the command for later */
810 if (fsg->cbbuf_cmnd_size)
Arjan van de Venb6c63932008-07-25 01:45:52 -0700811 WARNING(fsg, "CB[I] overwriting previous command\n");
Linus Torvalds1da177e2005-04-16 15:20:36 -0700812 fsg->cbbuf_cmnd_size = req->actual;
813 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
814
Linus Torvalds1da177e2005-04-16 15:20:36 -0700815 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -0500816 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700817}
818
819#else
820static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
821{}
822#endif /* CONFIG_USB_FILE_STORAGE_TEST */
823
824
825static int class_setup_req(struct fsg_dev *fsg,
826 const struct usb_ctrlrequest *ctrl)
827{
828 struct usb_request *req = fsg->ep0req;
829 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700830 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -0400831 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -0700832 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700833
834 if (!fsg->config)
835 return value;
836
837 /* Handle Bulk-only class-specific requests */
838 if (transport_is_bbb()) {
839 switch (ctrl->bRequest) {
840
841 case USB_BULK_RESET_REQUEST:
842 if (ctrl->bRequestType != (USB_DIR_OUT |
843 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
844 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400845 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700846 value = -EDOM;
847 break;
848 }
849
850 /* Raise an exception to stop the current operation
851 * and reinitialize our state. */
852 DBG(fsg, "bulk reset request\n");
853 raise_exception(fsg, FSG_STATE_RESET);
854 value = DELAYED_STATUS;
855 break;
856
857 case USB_BULK_GET_MAX_LUN_REQUEST:
858 if (ctrl->bRequestType != (USB_DIR_IN |
859 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
860 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400861 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700862 value = -EDOM;
863 break;
864 }
865 VDBG(fsg, "get max LUN\n");
866 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -0400867 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700868 break;
869 }
870 }
871
872 /* Handle CBI class-specific requests */
873 else {
874 switch (ctrl->bRequest) {
875
876 case USB_CBI_ADSC_REQUEST:
877 if (ctrl->bRequestType != (USB_DIR_OUT |
878 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
879 break;
Luis Lloret88e45db2007-07-26 10:08:47 -0400880 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700881 value = -EDOM;
882 break;
883 }
884 if (w_length > MAX_COMMAND_SIZE) {
885 value = -EOVERFLOW;
886 break;
887 }
888 value = w_length;
889 fsg->ep0req->context = received_cbi_adsc;
890 break;
891 }
892 }
893
894 if (value == -EOPNOTSUPP)
895 VDBG(fsg,
896 "unknown class-specific control req "
897 "%02x.%02x v%04x i%04x l%u\n",
898 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -0700899 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700900 return value;
901}
902
903
904/*-------------------------------------------------------------------------*/
905
906/* Ep0 standard request handlers. These always run in_irq. */
907
908static int standard_setup_req(struct fsg_dev *fsg,
909 const struct usb_ctrlrequest *ctrl)
910{
911 struct usb_request *req = fsg->ep0req;
912 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -0700913 u16 w_index = le16_to_cpu(ctrl->wIndex);
914 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700915
916 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
917 * but config change events will also reconfigure hardware. */
918 switch (ctrl->bRequest) {
919
920 case USB_REQ_GET_DESCRIPTOR:
921 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
922 USB_RECIP_DEVICE))
923 break;
924 switch (w_value >> 8) {
925
926 case USB_DT_DEVICE:
927 VDBG(fsg, "get device descriptor\n");
Alan Stern76f4af82005-04-05 11:56:54 -0400928 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700929 memcpy(req->buf, &device_desc, value);
930 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700931 case USB_DT_DEVICE_QUALIFIER:
932 VDBG(fsg, "get device qualifier\n");
David Brownell2e806f62007-08-02 00:03:39 -0700933 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700934 break;
Alan Stern76f4af82005-04-05 11:56:54 -0400935 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936 memcpy(req->buf, &dev_qualifier, value);
937 break;
938
939 case USB_DT_OTHER_SPEED_CONFIG:
940 VDBG(fsg, "get other-speed config descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700941 if (!gadget_is_dualspeed(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700942 break;
943 goto get_config;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700944 case USB_DT_CONFIG:
945 VDBG(fsg, "get configuration descriptor\n");
David Brownell2e806f62007-08-02 00:03:39 -0700946get_config:
Linus Torvalds1da177e2005-04-16 15:20:36 -0700947 value = populate_config_buf(fsg->gadget,
948 req->buf,
949 w_value >> 8,
950 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951 break;
952
953 case USB_DT_STRING:
954 VDBG(fsg, "get string descriptor\n");
955
956 /* wIndex == language code */
Michal Nazarewiczd6181702009-10-28 16:57:15 +0100957 value = usb_gadget_get_string(&fsg_stringtab,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700958 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959 break;
960 }
961 break;
962
963 /* One config, two speeds */
964 case USB_REQ_SET_CONFIGURATION:
965 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
966 USB_RECIP_DEVICE))
967 break;
968 VDBG(fsg, "set configuration\n");
969 if (w_value == CONFIG_VALUE || w_value == 0) {
970 fsg->new_config = w_value;
971
972 /* Raise an exception to wipe out previous transaction
973 * state (queued bufs, etc) and set the new config. */
974 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
975 value = DELAYED_STATUS;
976 }
977 break;
978 case USB_REQ_GET_CONFIGURATION:
979 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
980 USB_RECIP_DEVICE))
981 break;
982 VDBG(fsg, "get configuration\n");
983 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -0400984 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700985 break;
986
987 case USB_REQ_SET_INTERFACE:
988 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
989 USB_RECIP_INTERFACE))
990 break;
991 if (fsg->config && w_index == 0) {
992
993 /* Raise an exception to wipe out previous transaction
994 * state (queued bufs, etc) and install the new
995 * interface altsetting. */
996 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
997 value = DELAYED_STATUS;
998 }
999 break;
1000 case USB_REQ_GET_INTERFACE:
1001 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1002 USB_RECIP_INTERFACE))
1003 break;
1004 if (!fsg->config)
1005 break;
1006 if (w_index != 0) {
1007 value = -EDOM;
1008 break;
1009 }
1010 VDBG(fsg, "get interface\n");
1011 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001012 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001013 break;
1014
1015 default:
1016 VDBG(fsg,
1017 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1018 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001019 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001020 }
1021
1022 return value;
1023}
1024
1025
1026static int fsg_setup(struct usb_gadget *gadget,
1027 const struct usb_ctrlrequest *ctrl)
1028{
1029 struct fsg_dev *fsg = get_gadget_data(gadget);
1030 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001031 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001032
1033 ++fsg->ep0_req_tag; // Record arrival of a new request
1034 fsg->ep0req->context = NULL;
1035 fsg->ep0req->length = 0;
1036 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1037
1038 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1039 rc = class_setup_req(fsg, ctrl);
1040 else
1041 rc = standard_setup_req(fsg, ctrl);
1042
1043 /* Respond with data/status or defer until later? */
1044 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001045 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001046 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001047 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1049 "ep0-in" : "ep0-out");
1050 rc = ep0_queue(fsg);
1051 }
1052
1053 /* Device either stalls (rc < 0) or reports success */
1054 return rc;
1055}
1056
1057
1058/*-------------------------------------------------------------------------*/
1059
1060/* All the following routines run in process context */
1061
1062
1063/* Use this for bulk or interrupt transfers, not ep0 */
1064static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001065 struct usb_request *req, int *pbusy,
1066 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001067{
1068 int rc;
1069
1070 if (ep == fsg->bulk_in)
1071 dump_msg(fsg, "bulk-in", req->buf, req->length);
1072 else if (ep == fsg->intr_in)
1073 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001074
1075 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001076 *pbusy = 1;
1077 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001078 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001079 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1080 if (rc != 0) {
1081 *pbusy = 0;
1082 *state = BUF_STATE_EMPTY;
1083
1084 /* We can't do much more than wait for a reset */
1085
1086 /* Note: currently the net2280 driver fails zero-length
1087 * submissions if DMA is enabled. */
1088 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1089 req->length == 0))
Arjan van de Venb6c63932008-07-25 01:45:52 -07001090 WARNING(fsg, "error in submission: %s --> %d\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07001091 ep->name, rc);
1092 }
1093}
1094
1095
1096static int sleep_thread(struct fsg_dev *fsg)
1097{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001098 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001099
1100 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001101 for (;;) {
1102 try_to_freeze();
1103 set_current_state(TASK_INTERRUPTIBLE);
1104 if (signal_pending(current)) {
1105 rc = -EINTR;
1106 break;
1107 }
1108 if (fsg->thread_wakeup_needed)
1109 break;
1110 schedule();
1111 }
1112 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001113 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001114 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001115}
1116
1117
1118/*-------------------------------------------------------------------------*/
1119
1120static int do_read(struct fsg_dev *fsg)
1121{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001122 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001123 u32 lba;
1124 struct fsg_buffhd *bh;
1125 int rc;
1126 u32 amount_left;
1127 loff_t file_offset, file_offset_tmp;
1128 unsigned int amount;
1129 unsigned int partial_page;
1130 ssize_t nread;
1131
1132 /* Get the starting Logical Block Address and check that it's
1133 * not too big */
1134 if (fsg->cmnd[0] == SC_READ_6)
Alan Stern604eb892009-04-27 13:19:41 -04001135 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001136 else {
Alan Stern604eb892009-04-27 13:19:41 -04001137 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001138
1139 /* We allow DPO (Disable Page Out = don't save data in the
1140 * cache) and FUA (Force Unit Access = don't read from the
1141 * cache), but we don't implement them. */
1142 if ((fsg->cmnd[1] & ~0x18) != 0) {
1143 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1144 return -EINVAL;
1145 }
1146 }
1147 if (lba >= curlun->num_sectors) {
1148 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1149 return -EINVAL;
1150 }
1151 file_offset = ((loff_t) lba) << 9;
1152
1153 /* Carry out the file reads */
1154 amount_left = fsg->data_size_from_cmnd;
1155 if (unlikely(amount_left == 0))
1156 return -EIO; // No default reply
1157
1158 for (;;) {
1159
1160 /* Figure out how much we need to read:
1161 * Try to read the remaining amount.
1162 * But don't read more than the buffer size.
1163 * And don't try to read past the end of the file.
1164 * Finally, if we're not at a page boundary, don't read past
1165 * the next page.
1166 * If this means reading 0 then we were asked to read past
1167 * the end of file. */
1168 amount = min((unsigned int) amount_left, mod_data.buflen);
1169 amount = min((loff_t) amount,
1170 curlun->file_length - file_offset);
1171 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1172 if (partial_page > 0)
1173 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1174 partial_page);
1175
1176 /* Wait for the next buffer to become available */
1177 bh = fsg->next_buffhd_to_fill;
1178 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001179 rc = sleep_thread(fsg);
1180 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001181 return rc;
1182 }
1183
1184 /* If we were asked to read past the end of file,
1185 * end with an empty buffer. */
1186 if (amount == 0) {
1187 curlun->sense_data =
1188 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1189 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001190 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001191 bh->inreq->length = 0;
1192 bh->state = BUF_STATE_FULL;
1193 break;
1194 }
1195
1196 /* Perform the read */
1197 file_offset_tmp = file_offset;
1198 nread = vfs_read(curlun->filp,
1199 (char __user *) bh->buf,
1200 amount, &file_offset_tmp);
1201 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1202 (unsigned long long) file_offset,
1203 (int) nread);
1204 if (signal_pending(current))
1205 return -EINTR;
1206
1207 if (nread < 0) {
1208 LDBG(curlun, "error in file read: %d\n",
1209 (int) nread);
1210 nread = 0;
1211 } else if (nread < amount) {
1212 LDBG(curlun, "partial file read: %d/%u\n",
1213 (int) nread, amount);
1214 nread -= (nread & 511); // Round down to a block
1215 }
1216 file_offset += nread;
1217 amount_left -= nread;
1218 fsg->residue -= nread;
1219 bh->inreq->length = nread;
1220 bh->state = BUF_STATE_FULL;
1221
1222 /* If an error occurred, report it and its position */
1223 if (nread < amount) {
1224 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1225 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001226 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001227 break;
1228 }
1229
1230 if (amount_left == 0)
1231 break; // No more left to read
1232
1233 /* Send this buffer and go read some more */
1234 bh->inreq->zero = 0;
1235 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1236 &bh->inreq_busy, &bh->state);
1237 fsg->next_buffhd_to_fill = bh->next;
1238 }
1239
1240 return -EIO; // No default reply
1241}
1242
1243
1244/*-------------------------------------------------------------------------*/
1245
1246static int do_write(struct fsg_dev *fsg)
1247{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001248 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001249 u32 lba;
1250 struct fsg_buffhd *bh;
1251 int get_some_more;
1252 u32 amount_left_to_req, amount_left_to_write;
1253 loff_t usb_offset, file_offset, file_offset_tmp;
1254 unsigned int amount;
1255 unsigned int partial_page;
1256 ssize_t nwritten;
1257 int rc;
1258
1259 if (curlun->ro) {
1260 curlun->sense_data = SS_WRITE_PROTECTED;
1261 return -EINVAL;
1262 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001263 spin_lock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001264 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001265 spin_unlock(&curlun->filp->f_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001266
1267 /* Get the starting Logical Block Address and check that it's
1268 * not too big */
1269 if (fsg->cmnd[0] == SC_WRITE_6)
Alan Stern604eb892009-04-27 13:19:41 -04001270 lba = get_unaligned_be24(&fsg->cmnd[1]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001271 else {
Alan Stern604eb892009-04-27 13:19:41 -04001272 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001273
1274 /* We allow DPO (Disable Page Out = don't save data in the
1275 * cache) and FUA (Force Unit Access = write directly to the
1276 * medium). We don't implement DPO; we implement FUA by
1277 * performing synchronous output. */
1278 if ((fsg->cmnd[1] & ~0x18) != 0) {
1279 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1280 return -EINVAL;
1281 }
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001282 if (fsg->cmnd[1] & 0x08) { // FUA
1283 spin_lock(&curlun->filp->f_lock);
Christoph Hellwig6b2f3d12009-10-27 11:05:28 +01001284 curlun->filp->f_flags |= O_DSYNC;
Jonathan Corbetdb1dd4d2009-02-06 15:25:24 -07001285 spin_unlock(&curlun->filp->f_lock);
1286 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001287 }
1288 if (lba >= curlun->num_sectors) {
1289 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1290 return -EINVAL;
1291 }
1292
1293 /* Carry out the file writes */
1294 get_some_more = 1;
1295 file_offset = usb_offset = ((loff_t) lba) << 9;
1296 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1297
1298 while (amount_left_to_write > 0) {
1299
1300 /* Queue a request for more data from the host */
1301 bh = fsg->next_buffhd_to_fill;
1302 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1303
1304 /* Figure out how much we want to get:
1305 * Try to get the remaining amount.
1306 * But don't get more than the buffer size.
1307 * And don't try to go past the end of the file.
1308 * If we're not at a page boundary,
1309 * don't go past the next page.
1310 * If this means getting 0, then we were asked
1311 * to write past the end of file.
1312 * Finally, round down to a block boundary. */
1313 amount = min(amount_left_to_req, mod_data.buflen);
1314 amount = min((loff_t) amount, curlun->file_length -
1315 usb_offset);
1316 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1317 if (partial_page > 0)
1318 amount = min(amount,
1319 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1320
1321 if (amount == 0) {
1322 get_some_more = 0;
1323 curlun->sense_data =
1324 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1325 curlun->sense_data_info = usb_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001326 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001327 continue;
1328 }
1329 amount -= (amount & 511);
1330 if (amount == 0) {
1331
1332 /* Why were we were asked to transfer a
1333 * partial block? */
1334 get_some_more = 0;
1335 continue;
1336 }
1337
1338 /* Get the next buffer */
1339 usb_offset += amount;
1340 fsg->usb_amount_left -= amount;
1341 amount_left_to_req -= amount;
1342 if (amount_left_to_req == 0)
1343 get_some_more = 0;
1344
1345 /* amount is always divisible by 512, hence by
1346 * the bulk-out maxpacket size */
1347 bh->outreq->length = bh->bulk_out_intended_length =
1348 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001349 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001350 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1351 &bh->outreq_busy, &bh->state);
1352 fsg->next_buffhd_to_fill = bh->next;
1353 continue;
1354 }
1355
1356 /* Write the received data to the backing file */
1357 bh = fsg->next_buffhd_to_drain;
1358 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1359 break; // We stopped early
1360 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001361 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001362 fsg->next_buffhd_to_drain = bh->next;
1363 bh->state = BUF_STATE_EMPTY;
1364
1365 /* Did something go wrong with the transfer? */
1366 if (bh->outreq->status != 0) {
1367 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1368 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001369 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001370 break;
1371 }
1372
1373 amount = bh->outreq->actual;
1374 if (curlun->file_length - file_offset < amount) {
1375 LERROR(curlun,
1376 "write %u @ %llu beyond end %llu\n",
1377 amount, (unsigned long long) file_offset,
1378 (unsigned long long) curlun->file_length);
1379 amount = curlun->file_length - file_offset;
1380 }
1381
1382 /* Perform the write */
1383 file_offset_tmp = file_offset;
1384 nwritten = vfs_write(curlun->filp,
1385 (char __user *) bh->buf,
1386 amount, &file_offset_tmp);
1387 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1388 (unsigned long long) file_offset,
1389 (int) nwritten);
1390 if (signal_pending(current))
1391 return -EINTR; // Interrupted!
1392
1393 if (nwritten < 0) {
1394 LDBG(curlun, "error in file write: %d\n",
1395 (int) nwritten);
1396 nwritten = 0;
1397 } else if (nwritten < amount) {
1398 LDBG(curlun, "partial file write: %d/%u\n",
1399 (int) nwritten, amount);
1400 nwritten -= (nwritten & 511);
1401 // Round down to a block
1402 }
1403 file_offset += nwritten;
1404 amount_left_to_write -= nwritten;
1405 fsg->residue -= nwritten;
1406
1407 /* If an error occurred, report it and its position */
1408 if (nwritten < amount) {
1409 curlun->sense_data = SS_WRITE_ERROR;
1410 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001411 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001412 break;
1413 }
1414
1415 /* Did the host decide to stop early? */
1416 if (bh->outreq->actual != bh->outreq->length) {
1417 fsg->short_packet_received = 1;
1418 break;
1419 }
1420 continue;
1421 }
1422
1423 /* Wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04001424 rc = sleep_thread(fsg);
1425 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001426 return rc;
1427 }
1428
1429 return -EIO; // No default reply
1430}
1431
1432
1433/*-------------------------------------------------------------------------*/
1434
Linus Torvalds1da177e2005-04-16 15:20:36 -07001435static int do_synchronize_cache(struct fsg_dev *fsg)
1436{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001437 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001438 int rc;
1439
1440 /* We ignore the requested LBA and write out all file's
1441 * dirty data buffers. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001442 rc = fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001443 if (rc)
1444 curlun->sense_data = SS_WRITE_ERROR;
1445 return 0;
1446}
1447
1448
1449/*-------------------------------------------------------------------------*/
1450
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001451static void invalidate_sub(struct fsg_lun *curlun)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001452{
1453 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001454 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001455 unsigned long rc;
1456
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001457 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01001458 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001459}
1460
1461static int do_verify(struct fsg_dev *fsg)
1462{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001463 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001464 u32 lba;
1465 u32 verification_length;
1466 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1467 loff_t file_offset, file_offset_tmp;
1468 u32 amount_left;
1469 unsigned int amount;
1470 ssize_t nread;
1471
1472 /* Get the starting Logical Block Address and check that it's
1473 * not too big */
Alan Stern604eb892009-04-27 13:19:41 -04001474 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001475 if (lba >= curlun->num_sectors) {
1476 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1477 return -EINVAL;
1478 }
1479
1480 /* We allow DPO (Disable Page Out = don't save data in the
1481 * cache) but we don't implement it. */
1482 if ((fsg->cmnd[1] & ~0x10) != 0) {
1483 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1484 return -EINVAL;
1485 }
1486
Alan Stern604eb892009-04-27 13:19:41 -04001487 verification_length = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001488 if (unlikely(verification_length == 0))
1489 return -EIO; // No default reply
1490
1491 /* Prepare to carry out the file verify */
1492 amount_left = verification_length << 9;
1493 file_offset = ((loff_t) lba) << 9;
1494
1495 /* Write out all the dirty buffers before invalidating them */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001496 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001497 if (signal_pending(current))
1498 return -EINTR;
1499
1500 invalidate_sub(curlun);
1501 if (signal_pending(current))
1502 return -EINTR;
1503
1504 /* Just try to read the requested blocks */
1505 while (amount_left > 0) {
1506
1507 /* Figure out how much we need to read:
1508 * Try to read the remaining amount, but not more than
1509 * the buffer size.
1510 * And don't try to read past the end of the file.
1511 * If this means reading 0 then we were asked to read
1512 * past the end of file. */
1513 amount = min((unsigned int) amount_left, mod_data.buflen);
1514 amount = min((loff_t) amount,
1515 curlun->file_length - file_offset);
1516 if (amount == 0) {
1517 curlun->sense_data =
1518 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1519 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001520 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001521 break;
1522 }
1523
1524 /* Perform the read */
1525 file_offset_tmp = file_offset;
1526 nread = vfs_read(curlun->filp,
1527 (char __user *) bh->buf,
1528 amount, &file_offset_tmp);
1529 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1530 (unsigned long long) file_offset,
1531 (int) nread);
1532 if (signal_pending(current))
1533 return -EINTR;
1534
1535 if (nread < 0) {
1536 LDBG(curlun, "error in file verify: %d\n",
1537 (int) nread);
1538 nread = 0;
1539 } else if (nread < amount) {
1540 LDBG(curlun, "partial file verify: %d/%u\n",
1541 (int) nread, amount);
1542 nread -= (nread & 511); // Round down to a sector
1543 }
1544 if (nread == 0) {
1545 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1546 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001547 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001548 break;
1549 }
1550 file_offset += nread;
1551 amount_left -= nread;
1552 }
1553 return 0;
1554}
1555
1556
1557/*-------------------------------------------------------------------------*/
1558
1559static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1560{
1561 u8 *buf = (u8 *) bh->buf;
1562
1563 static char vendor_id[] = "Linux ";
Alan Stern12aae682008-11-20 14:13:12 -05001564 static char product_disk_id[] = "File-Stor Gadget";
1565 static char product_cdrom_id[] = "File-CD Gadget ";
Linus Torvalds1da177e2005-04-16 15:20:36 -07001566
1567 if (!fsg->curlun) { // Unsupported LUNs are okay
1568 fsg->bad_lun_okay = 1;
1569 memset(buf, 0, 36);
1570 buf[0] = 0x7f; // Unsupported, no device-type
Alan Stern12aae682008-11-20 14:13:12 -05001571 buf[4] = 31; // Additional length
Linus Torvalds1da177e2005-04-16 15:20:36 -07001572 return 36;
1573 }
1574
Alan Stern12aae682008-11-20 14:13:12 -05001575 memset(buf, 0, 8);
1576 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577 if (mod_data.removable)
1578 buf[1] = 0x80;
1579 buf[2] = 2; // ANSI SCSI level 2
1580 buf[3] = 2; // SCSI-2 INQUIRY data format
1581 buf[4] = 31; // Additional length
1582 // No special options
Alan Stern12aae682008-11-20 14:13:12 -05001583 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1584 (mod_data.cdrom ? product_cdrom_id :
1585 product_disk_id),
Linus Torvalds1da177e2005-04-16 15:20:36 -07001586 mod_data.release);
1587 return 36;
1588}
1589
1590
1591static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1592{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001593 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001594 u8 *buf = (u8 *) bh->buf;
1595 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04001596 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001597
1598 /*
1599 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1600 *
1601 * If a REQUEST SENSE command is received from an initiator
1602 * with a pending unit attention condition (before the target
1603 * generates the contingent allegiance condition), then the
1604 * target shall either:
1605 * a) report any pending sense data and preserve the unit
1606 * attention condition on the logical unit, or,
1607 * b) report the unit attention condition, may discard any
1608 * pending sense data, and clear the unit attention
1609 * condition on the logical unit for that initiator.
1610 *
1611 * FSG normally uses option a); enable this code to use option b).
1612 */
1613#if 0
1614 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1615 curlun->sense_data = curlun->unit_attention_data;
1616 curlun->unit_attention_data = SS_NO_SENSE;
1617 }
1618#endif
1619
1620 if (!curlun) { // Unsupported LUNs are okay
1621 fsg->bad_lun_okay = 1;
1622 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1623 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001624 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001625 } else {
1626 sd = curlun->sense_data;
1627 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04001628 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001629 curlun->sense_data = SS_NO_SENSE;
1630 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04001631 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001632 }
1633
1634 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04001635 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07001636 buf[2] = SK(sd);
Alan Stern604eb892009-04-27 13:19:41 -04001637 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001638 buf[7] = 18 - 8; // Additional sense length
1639 buf[12] = ASC(sd);
1640 buf[13] = ASCQ(sd);
1641 return 18;
1642}
1643
1644
1645static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1646{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001647 struct fsg_lun *curlun = fsg->curlun;
Alan Stern604eb892009-04-27 13:19:41 -04001648 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001649 int pmi = fsg->cmnd[8];
1650 u8 *buf = (u8 *) bh->buf;
1651
1652 /* Check the PMI and LBA fields */
1653 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1654 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1655 return -EINVAL;
1656 }
1657
Alan Stern604eb892009-04-27 13:19:41 -04001658 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1659 /* Max logical block */
1660 put_unaligned_be32(512, &buf[4]); /* Block length */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001661 return 8;
1662}
1663
1664
Alan Stern12aae682008-11-20 14:13:12 -05001665static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1666{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001667 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001668 int msf = fsg->cmnd[1] & 0x02;
Alan Stern604eb892009-04-27 13:19:41 -04001669 u32 lba = get_unaligned_be32(&fsg->cmnd[2]);
Alan Stern12aae682008-11-20 14:13:12 -05001670 u8 *buf = (u8 *) bh->buf;
1671
1672 if ((fsg->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1673 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1674 return -EINVAL;
1675 }
1676 if (lba >= curlun->num_sectors) {
1677 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1678 return -EINVAL;
1679 }
1680
1681 memset(buf, 0, 8);
1682 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1683 store_cdrom_address(&buf[4], msf, lba);
1684 return 8;
1685}
1686
1687
1688static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1689{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001690 struct fsg_lun *curlun = fsg->curlun;
Alan Stern12aae682008-11-20 14:13:12 -05001691 int msf = fsg->cmnd[1] & 0x02;
1692 int start_track = fsg->cmnd[6];
1693 u8 *buf = (u8 *) bh->buf;
1694
1695 if ((fsg->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1696 start_track > 1) {
1697 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1698 return -EINVAL;
1699 }
1700
1701 memset(buf, 0, 20);
1702 buf[1] = (20-2); /* TOC data length */
1703 buf[2] = 1; /* First track number */
1704 buf[3] = 1; /* Last track number */
1705 buf[5] = 0x16; /* Data track, copying allowed */
1706 buf[6] = 0x01; /* Only track is number 1 */
1707 store_cdrom_address(&buf[8], msf, 0);
1708
1709 buf[13] = 0x16; /* Lead-out track is data */
1710 buf[14] = 0xAA; /* Lead-out track number */
1711 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1712 return 20;
1713}
1714
1715
Linus Torvalds1da177e2005-04-16 15:20:36 -07001716static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1717{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001718 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001719 int mscmnd = fsg->cmnd[0];
1720 u8 *buf = (u8 *) bh->buf;
1721 u8 *buf0 = buf;
1722 int pc, page_code;
1723 int changeable_values, all_pages;
1724 int valid_page = 0;
1725 int len, limit;
1726
1727 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1728 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1729 return -EINVAL;
1730 }
1731 pc = fsg->cmnd[2] >> 6;
1732 page_code = fsg->cmnd[2] & 0x3f;
1733 if (pc == 3) {
1734 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1735 return -EINVAL;
1736 }
1737 changeable_values = (pc == 1);
1738 all_pages = (page_code == 0x3f);
1739
1740 /* Write the mode parameter header. Fixed values are: default
1741 * medium type, no cache control (DPOFUA), and no block descriptors.
1742 * The only variable value is the WriteProtect bit. We will fill in
1743 * the mode data length later. */
1744 memset(buf, 0, 8);
1745 if (mscmnd == SC_MODE_SENSE_6) {
1746 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1747 buf += 4;
1748 limit = 255;
1749 } else { // SC_MODE_SENSE_10
1750 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1751 buf += 8;
1752 limit = 65535; // Should really be mod_data.buflen
1753 }
1754
1755 /* No block descriptors */
1756
1757 /* The mode pages, in numerical order. The only page we support
1758 * is the Caching page. */
1759 if (page_code == 0x08 || all_pages) {
1760 valid_page = 1;
1761 buf[0] = 0x08; // Page code
1762 buf[1] = 10; // Page length
1763 memset(buf+2, 0, 10); // None of the fields are changeable
1764
1765 if (!changeable_values) {
1766 buf[2] = 0x04; // Write cache enable,
1767 // Read cache not disabled
1768 // No cache retention priorities
Alan Stern604eb892009-04-27 13:19:41 -04001769 put_unaligned_be16(0xffff, &buf[4]);
1770 /* Don't disable prefetch */
1771 /* Minimum prefetch = 0 */
1772 put_unaligned_be16(0xffff, &buf[8]);
1773 /* Maximum prefetch */
1774 put_unaligned_be16(0xffff, &buf[10]);
1775 /* Maximum prefetch ceiling */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001776 }
1777 buf += 12;
1778 }
1779
1780 /* Check that a valid page was requested and the mode data length
1781 * isn't too long. */
1782 len = buf - buf0;
1783 if (!valid_page || len > limit) {
1784 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1785 return -EINVAL;
1786 }
1787
1788 /* Store the mode data length */
1789 if (mscmnd == SC_MODE_SENSE_6)
1790 buf0[0] = len - 1;
1791 else
Alan Stern604eb892009-04-27 13:19:41 -04001792 put_unaligned_be16(len - 2, buf0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001793 return len;
1794}
1795
1796
1797static int do_start_stop(struct fsg_dev *fsg)
1798{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001799 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001800 int loej, start;
1801
1802 if (!mod_data.removable) {
1803 curlun->sense_data = SS_INVALID_COMMAND;
1804 return -EINVAL;
1805 }
1806
1807 // int immed = fsg->cmnd[1] & 0x01;
1808 loej = fsg->cmnd[4] & 0x02;
1809 start = fsg->cmnd[4] & 0x01;
1810
1811#ifdef CONFIG_USB_FILE_STORAGE_TEST
1812 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
1813 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
1814 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1815 return -EINVAL;
1816 }
1817
1818 if (!start) {
1819
1820 /* Are we allowed to unload the media? */
1821 if (curlun->prevent_medium_removal) {
1822 LDBG(curlun, "unload attempt prevented\n");
1823 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1824 return -EINVAL;
1825 }
1826 if (loej) { // Simulate an unload/eject
1827 up_read(&fsg->filesem);
1828 down_write(&fsg->filesem);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001829 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001830 up_write(&fsg->filesem);
1831 down_read(&fsg->filesem);
1832 }
1833 } else {
1834
1835 /* Our emulation doesn't support mounting; the medium is
1836 * available for use as soon as it is loaded. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001837 if (!fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001838 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1839 return -EINVAL;
1840 }
1841 }
1842#endif
1843 return 0;
1844}
1845
1846
1847static int do_prevent_allow(struct fsg_dev *fsg)
1848{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001849 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001850 int prevent;
1851
1852 if (!mod_data.removable) {
1853 curlun->sense_data = SS_INVALID_COMMAND;
1854 return -EINVAL;
1855 }
1856
1857 prevent = fsg->cmnd[4] & 0x01;
1858 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1859 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1860 return -EINVAL;
1861 }
1862
1863 if (curlun->prevent_medium_removal && !prevent)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001864 fsg_lun_fsync_sub(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001865 curlun->prevent_medium_removal = prevent;
1866 return 0;
1867}
1868
1869
1870static int do_read_format_capacities(struct fsg_dev *fsg,
1871 struct fsg_buffhd *bh)
1872{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001873 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001874 u8 *buf = (u8 *) bh->buf;
1875
1876 buf[0] = buf[1] = buf[2] = 0;
1877 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1878 buf += 4;
1879
Alan Stern604eb892009-04-27 13:19:41 -04001880 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1881 /* Number of blocks */
1882 put_unaligned_be32(512, &buf[4]); /* Block length */
1883 buf[4] = 0x02; /* Current capacity */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001884 return 12;
1885}
1886
1887
1888static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1889{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01001890 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001891
1892 /* We don't support MODE SELECT */
1893 curlun->sense_data = SS_INVALID_COMMAND;
1894 return -EINVAL;
1895}
1896
1897
1898/*-------------------------------------------------------------------------*/
1899
1900static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1901{
1902 int rc;
1903
1904 rc = fsg_set_halt(fsg, fsg->bulk_in);
1905 if (rc == -EAGAIN)
1906 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1907 while (rc != 0) {
1908 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001909 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001910 rc = 0;
1911 break;
1912 }
1913
1914 /* Wait for a short time and then try again */
1915 if (msleep_interruptible(100) != 0)
1916 return -EINTR;
1917 rc = usb_ep_set_halt(fsg->bulk_in);
1918 }
1919 return rc;
1920}
1921
David Lopo62fd2ca2008-04-29 10:14:38 +01001922static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1923{
1924 int rc;
1925
1926 DBG(fsg, "bulk-in set wedge\n");
1927 rc = usb_ep_set_wedge(fsg->bulk_in);
1928 if (rc == -EAGAIN)
1929 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1930 while (rc != 0) {
1931 if (rc != -EAGAIN) {
Arjan van de Venb6c63932008-07-25 01:45:52 -07001932 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
David Lopo62fd2ca2008-04-29 10:14:38 +01001933 rc = 0;
1934 break;
1935 }
1936
1937 /* Wait for a short time and then try again */
1938 if (msleep_interruptible(100) != 0)
1939 return -EINTR;
1940 rc = usb_ep_set_wedge(fsg->bulk_in);
1941 }
1942 return rc;
1943}
1944
Linus Torvalds1da177e2005-04-16 15:20:36 -07001945static int pad_with_zeros(struct fsg_dev *fsg)
1946{
1947 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1948 u32 nkeep = bh->inreq->length;
1949 u32 nsend;
1950 int rc;
1951
1952 bh->state = BUF_STATE_EMPTY; // For the first iteration
1953 fsg->usb_amount_left = nkeep + fsg->residue;
1954 while (fsg->usb_amount_left > 0) {
1955
1956 /* Wait for the next buffer to be free */
1957 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04001958 rc = sleep_thread(fsg);
1959 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001960 return rc;
1961 }
1962
1963 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
1964 memset(bh->buf + nkeep, 0, nsend - nkeep);
1965 bh->inreq->length = nsend;
1966 bh->inreq->zero = 0;
1967 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1968 &bh->inreq_busy, &bh->state);
1969 bh = fsg->next_buffhd_to_fill = bh->next;
1970 fsg->usb_amount_left -= nsend;
1971 nkeep = 0;
1972 }
1973 return 0;
1974}
1975
1976static int throw_away_data(struct fsg_dev *fsg)
1977{
1978 struct fsg_buffhd *bh;
1979 u32 amount;
1980 int rc;
1981
1982 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1983 fsg->usb_amount_left > 0) {
1984
1985 /* Throw away the data in a filled buffer */
1986 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001987 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001988 bh->state = BUF_STATE_EMPTY;
1989 fsg->next_buffhd_to_drain = bh->next;
1990
1991 /* A short packet or an error ends everything */
1992 if (bh->outreq->actual != bh->outreq->length ||
1993 bh->outreq->status != 0) {
1994 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1995 return -EINTR;
1996 }
1997 continue;
1998 }
1999
2000 /* Try to submit another request if we need one */
2001 bh = fsg->next_buffhd_to_fill;
2002 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2003 amount = min(fsg->usb_amount_left,
2004 (u32) mod_data.buflen);
2005
2006 /* amount is always divisible by 512, hence by
2007 * the bulk-out maxpacket size */
2008 bh->outreq->length = bh->bulk_out_intended_length =
2009 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05002010 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002011 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2012 &bh->outreq_busy, &bh->state);
2013 fsg->next_buffhd_to_fill = bh->next;
2014 fsg->usb_amount_left -= amount;
2015 continue;
2016 }
2017
2018 /* Otherwise wait for something to happen */
Alan Stern79a7d9e2007-08-08 17:10:11 -04002019 rc = sleep_thread(fsg);
2020 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002021 return rc;
2022 }
2023 return 0;
2024}
2025
2026
2027static int finish_reply(struct fsg_dev *fsg)
2028{
2029 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2030 int rc = 0;
2031
2032 switch (fsg->data_dir) {
2033 case DATA_DIR_NONE:
2034 break; // Nothing to send
2035
2036 /* If we don't know whether the host wants to read or write,
2037 * this must be CB or CBI with an unknown command. We mustn't
2038 * try to send or receive any data. So stall both bulk pipes
2039 * if we can and wait for a reset. */
2040 case DATA_DIR_UNKNOWN:
2041 if (mod_data.can_stall) {
2042 fsg_set_halt(fsg, fsg->bulk_out);
2043 rc = halt_bulk_in_endpoint(fsg);
2044 }
2045 break;
2046
2047 /* All but the last buffer of data must have already been sent */
2048 case DATA_DIR_TO_HOST:
2049 if (fsg->data_size == 0)
2050 ; // Nothing to send
2051
2052 /* If there's no residue, simply send the last buffer */
2053 else if (fsg->residue == 0) {
2054 bh->inreq->zero = 0;
2055 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2056 &bh->inreq_busy, &bh->state);
2057 fsg->next_buffhd_to_fill = bh->next;
2058 }
2059
2060 /* There is a residue. For CB and CBI, simply mark the end
2061 * of the data with a short packet. However, if we are
2062 * allowed to stall, there was no data at all (residue ==
2063 * data_size), and the command failed (invalid LUN or
2064 * sense data is set), then halt the bulk-in endpoint
2065 * instead. */
2066 else if (!transport_is_bbb()) {
2067 if (mod_data.can_stall &&
2068 fsg->residue == fsg->data_size &&
2069 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2070 bh->state = BUF_STATE_EMPTY;
2071 rc = halt_bulk_in_endpoint(fsg);
2072 } else {
2073 bh->inreq->zero = 1;
2074 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2075 &bh->inreq_busy, &bh->state);
2076 fsg->next_buffhd_to_fill = bh->next;
2077 }
2078 }
2079
2080 /* For Bulk-only, if we're allowed to stall then send the
2081 * short packet and halt the bulk-in endpoint. If we can't
2082 * stall, pad out the remaining data with 0's. */
2083 else {
2084 if (mod_data.can_stall) {
2085 bh->inreq->zero = 1;
2086 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2087 &bh->inreq_busy, &bh->state);
2088 fsg->next_buffhd_to_fill = bh->next;
2089 rc = halt_bulk_in_endpoint(fsg);
2090 } else
2091 rc = pad_with_zeros(fsg);
2092 }
2093 break;
2094
2095 /* We have processed all we want from the data the host has sent.
2096 * There may still be outstanding bulk-out requests. */
2097 case DATA_DIR_FROM_HOST:
2098 if (fsg->residue == 0)
2099 ; // Nothing to receive
2100
2101 /* Did the host stop sending unexpectedly early? */
2102 else if (fsg->short_packet_received) {
2103 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2104 rc = -EINTR;
2105 }
2106
2107 /* We haven't processed all the incoming data. Even though
2108 * we may be allowed to stall, doing so would cause a race.
2109 * The controller may already have ACK'ed all the remaining
2110 * bulk-out packets, in which case the host wouldn't see a
2111 * STALL. Not realizing the endpoint was halted, it wouldn't
2112 * clear the halt -- leading to problems later on. */
2113#if 0
2114 else if (mod_data.can_stall) {
2115 fsg_set_halt(fsg, fsg->bulk_out);
2116 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2117 rc = -EINTR;
2118 }
2119#endif
2120
2121 /* We can't stall. Read in the excess data and throw it
2122 * all away. */
2123 else
2124 rc = throw_away_data(fsg);
2125 break;
2126 }
2127 return rc;
2128}
2129
2130
2131static int send_status(struct fsg_dev *fsg)
2132{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002133 struct fsg_lun *curlun = fsg->curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002134 struct fsg_buffhd *bh;
2135 int rc;
2136 u8 status = USB_STATUS_PASS;
2137 u32 sd, sdinfo = 0;
2138
2139 /* Wait for the next buffer to become available */
2140 bh = fsg->next_buffhd_to_fill;
2141 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002142 rc = sleep_thread(fsg);
2143 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002144 return rc;
2145 }
2146
2147 if (curlun) {
2148 sd = curlun->sense_data;
2149 sdinfo = curlun->sense_data_info;
2150 } else if (fsg->bad_lun_okay)
2151 sd = SS_NO_SENSE;
2152 else
2153 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2154
2155 if (fsg->phase_error) {
2156 DBG(fsg, "sending phase-error status\n");
2157 status = USB_STATUS_PHASE_ERROR;
2158 sd = SS_INVALID_COMMAND;
2159 } else if (sd != SS_NO_SENSE) {
2160 DBG(fsg, "sending command-failure status\n");
2161 status = USB_STATUS_FAIL;
2162 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2163 " info x%x\n",
2164 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2165 }
2166
2167 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002168 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002169
2170 /* Store and send the Bulk-only CSW */
Harvey Harrison551509d2009-02-11 14:11:36 -08002171 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002172 csw->Tag = fsg->tag;
2173 csw->Residue = cpu_to_le32(fsg->residue);
2174 csw->Status = status;
2175
2176 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2177 bh->inreq->zero = 0;
2178 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2179 &bh->inreq_busy, &bh->state);
2180
2181 } else if (mod_data.transport_type == USB_PR_CB) {
2182
2183 /* Control-Bulk transport has no status phase! */
2184 return 0;
2185
2186 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002187 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002188
2189 /* Store and send the Interrupt data. UFI sends the ASC
2190 * and ASCQ bytes. Everything else sends a Type (which
2191 * is always 0) and the status Value. */
2192 if (mod_data.protocol_type == USB_SC_UFI) {
2193 buf->bType = ASC(sd);
2194 buf->bValue = ASCQ(sd);
2195 } else {
2196 buf->bType = 0;
2197 buf->bValue = status;
2198 }
2199 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2200
2201 fsg->intr_buffhd = bh; // Point to the right buffhd
2202 fsg->intreq->buf = bh->inreq->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002203 fsg->intreq->context = bh;
2204 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2205 &fsg->intreq_busy, &bh->state);
2206 }
2207
2208 fsg->next_buffhd_to_fill = bh->next;
2209 return 0;
2210}
2211
2212
2213/*-------------------------------------------------------------------------*/
2214
2215/* Check whether the command is properly formed and whether its data size
2216 * and direction agree with the values we already have. */
2217static int check_command(struct fsg_dev *fsg, int cmnd_size,
2218 enum data_direction data_dir, unsigned int mask,
2219 int needs_medium, const char *name)
2220{
2221 int i;
2222 int lun = fsg->cmnd[1] >> 5;
2223 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2224 char hdlen[20];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002225 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002226
2227 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2228 * Transparent SCSI doesn't pad. */
2229 if (protocol_is_scsi())
2230 ;
2231
2232 /* There's some disagreement as to whether RBC pads commands or not.
2233 * We'll play it safe and accept either form. */
2234 else if (mod_data.protocol_type == USB_SC_RBC) {
2235 if (fsg->cmnd_size == 12)
2236 cmnd_size = 12;
2237
2238 /* All the other protocols pad to 12 bytes */
2239 } else
2240 cmnd_size = 12;
2241
2242 hdlen[0] = 0;
2243 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2244 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2245 fsg->data_size);
2246 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2247 name, cmnd_size, dirletter[(int) data_dir],
2248 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2249
2250 /* We can't reply at all until we know the correct data direction
2251 * and size. */
2252 if (fsg->data_size_from_cmnd == 0)
2253 data_dir = DATA_DIR_NONE;
2254 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2255 fsg->data_dir = data_dir;
2256 fsg->data_size = fsg->data_size_from_cmnd;
2257
2258 } else { // Bulk-only
2259 if (fsg->data_size < fsg->data_size_from_cmnd) {
2260
2261 /* Host data size < Device data size is a phase error.
2262 * Carry out the command, but only transfer as much
2263 * as we are allowed. */
2264 fsg->data_size_from_cmnd = fsg->data_size;
2265 fsg->phase_error = 1;
2266 }
2267 }
2268 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2269
2270 /* Conflicting data directions is a phase error */
2271 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2272 fsg->phase_error = 1;
2273 return -EINVAL;
2274 }
2275
2276 /* Verify the length of the command itself */
2277 if (cmnd_size != fsg->cmnd_size) {
2278
Felipe Balbi549c41e2008-09-19 02:00:02 +03002279 /* Special case workaround: There are plenty of buggy SCSI
2280 * implementations. Many have issues with cbw->Length
2281 * field passing a wrong command size. For those cases we
2282 * always try to work around the problem by using the length
2283 * sent by the host side provided it is at least as large
2284 * as the correct command length.
2285 * Examples of such cases would be MS-Windows, which issues
2286 * REQUEST SENSE with cbw->Length == 12 where it should
2287 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
2288 * REQUEST SENSE with cbw->Length == 10 where it should
2289 * be 6 as well.
2290 */
2291 if (cmnd_size <= fsg->cmnd_size) {
2292 DBG(fsg, "%s is buggy! Expected length %d "
2293 "but we got %d\n", name,
2294 cmnd_size, fsg->cmnd_size);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002295 cmnd_size = fsg->cmnd_size;
Felipe Balbi549c41e2008-09-19 02:00:02 +03002296 } else {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002297 fsg->phase_error = 1;
2298 return -EINVAL;
2299 }
2300 }
2301
Alan Sternd794ac72005-04-18 12:43:25 -04002302 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002303 if (transport_is_bbb()) {
2304 if (fsg->lun != lun)
2305 DBG(fsg, "using LUN %d from CBW, "
2306 "not LUN %d from CDB\n",
2307 fsg->lun, lun);
2308 } else
2309 fsg->lun = lun; // Use LUN from the command
2310
2311 /* Check the LUN */
2312 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2313 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2314 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2315 curlun->sense_data = SS_NO_SENSE;
2316 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002317 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002318 }
2319 } else {
2320 fsg->curlun = curlun = NULL;
2321 fsg->bad_lun_okay = 0;
2322
2323 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2324 * to use unsupported LUNs; all others may not. */
2325 if (fsg->cmnd[0] != SC_INQUIRY &&
2326 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2327 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2328 return -EINVAL;
2329 }
2330 }
2331
2332 /* If a unit attention condition exists, only INQUIRY and
2333 * REQUEST SENSE commands are allowed; anything else must fail. */
2334 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2335 fsg->cmnd[0] != SC_INQUIRY &&
2336 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2337 curlun->sense_data = curlun->unit_attention_data;
2338 curlun->unit_attention_data = SS_NO_SENSE;
2339 return -EINVAL;
2340 }
2341
2342 /* Check that only command bytes listed in the mask are non-zero */
2343 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2344 for (i = 1; i < cmnd_size; ++i) {
2345 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2346 if (curlun)
2347 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2348 return -EINVAL;
2349 }
2350 }
2351
2352 /* If the medium isn't mounted and the command needs to access
2353 * it, return an error. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002354 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002355 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2356 return -EINVAL;
2357 }
2358
2359 return 0;
2360}
2361
2362
2363static int do_scsi_command(struct fsg_dev *fsg)
2364{
2365 struct fsg_buffhd *bh;
2366 int rc;
2367 int reply = -EINVAL;
2368 int i;
2369 static char unknown[16];
2370
2371 dump_cdb(fsg);
2372
2373 /* Wait for the next buffer to become available for data or status */
2374 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2375 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002376 rc = sleep_thread(fsg);
2377 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002378 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002379 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380 fsg->phase_error = 0;
2381 fsg->short_packet_received = 0;
2382
2383 down_read(&fsg->filesem); // We're using the backing file
2384 switch (fsg->cmnd[0]) {
2385
2386 case SC_INQUIRY:
2387 fsg->data_size_from_cmnd = fsg->cmnd[4];
2388 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2389 (1<<4), 0,
2390 "INQUIRY")) == 0)
2391 reply = do_inquiry(fsg, bh);
2392 break;
2393
2394 case SC_MODE_SELECT_6:
2395 fsg->data_size_from_cmnd = fsg->cmnd[4];
2396 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2397 (1<<1) | (1<<4), 0,
2398 "MODE SELECT(6)")) == 0)
2399 reply = do_mode_select(fsg, bh);
2400 break;
2401
2402 case SC_MODE_SELECT_10:
Alan Stern604eb892009-04-27 13:19:41 -04002403 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002404 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2405 (1<<1) | (3<<7), 0,
2406 "MODE SELECT(10)")) == 0)
2407 reply = do_mode_select(fsg, bh);
2408 break;
2409
2410 case SC_MODE_SENSE_6:
2411 fsg->data_size_from_cmnd = fsg->cmnd[4];
2412 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2413 (1<<1) | (1<<2) | (1<<4), 0,
2414 "MODE SENSE(6)")) == 0)
2415 reply = do_mode_sense(fsg, bh);
2416 break;
2417
2418 case SC_MODE_SENSE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002419 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002420 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2421 (1<<1) | (1<<2) | (3<<7), 0,
2422 "MODE SENSE(10)")) == 0)
2423 reply = do_mode_sense(fsg, bh);
2424 break;
2425
2426 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2427 fsg->data_size_from_cmnd = 0;
2428 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2429 (1<<4), 0,
2430 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2431 reply = do_prevent_allow(fsg);
2432 break;
2433
2434 case SC_READ_6:
2435 i = fsg->cmnd[4];
2436 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2437 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2438 (7<<1) | (1<<4), 1,
2439 "READ(6)")) == 0)
2440 reply = do_read(fsg);
2441 break;
2442
2443 case SC_READ_10:
Alan Stern604eb892009-04-27 13:19:41 -04002444 fsg->data_size_from_cmnd =
2445 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002446 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2447 (1<<1) | (0xf<<2) | (3<<7), 1,
2448 "READ(10)")) == 0)
2449 reply = do_read(fsg);
2450 break;
2451
2452 case SC_READ_12:
Alan Stern604eb892009-04-27 13:19:41 -04002453 fsg->data_size_from_cmnd =
2454 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002455 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2456 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2457 "READ(12)")) == 0)
2458 reply = do_read(fsg);
2459 break;
2460
2461 case SC_READ_CAPACITY:
2462 fsg->data_size_from_cmnd = 8;
2463 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2464 (0xf<<2) | (1<<8), 1,
2465 "READ CAPACITY")) == 0)
2466 reply = do_read_capacity(fsg, bh);
2467 break;
2468
Alan Stern12aae682008-11-20 14:13:12 -05002469 case SC_READ_HEADER:
2470 if (!mod_data.cdrom)
2471 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002472 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002473 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2474 (3<<7) | (0x1f<<1), 1,
2475 "READ HEADER")) == 0)
2476 reply = do_read_header(fsg, bh);
2477 break;
2478
2479 case SC_READ_TOC:
2480 if (!mod_data.cdrom)
2481 goto unknown_cmnd;
Alan Stern604eb892009-04-27 13:19:41 -04002482 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Alan Stern12aae682008-11-20 14:13:12 -05002483 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2484 (7<<6) | (1<<1), 1,
2485 "READ TOC")) == 0)
2486 reply = do_read_toc(fsg, bh);
2487 break;
2488
Linus Torvalds1da177e2005-04-16 15:20:36 -07002489 case SC_READ_FORMAT_CAPACITIES:
Alan Stern604eb892009-04-27 13:19:41 -04002490 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->cmnd[7]);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002491 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2492 (3<<7), 1,
2493 "READ FORMAT CAPACITIES")) == 0)
2494 reply = do_read_format_capacities(fsg, bh);
2495 break;
2496
2497 case SC_REQUEST_SENSE:
2498 fsg->data_size_from_cmnd = fsg->cmnd[4];
2499 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2500 (1<<4), 0,
2501 "REQUEST SENSE")) == 0)
2502 reply = do_request_sense(fsg, bh);
2503 break;
2504
2505 case SC_START_STOP_UNIT:
2506 fsg->data_size_from_cmnd = 0;
2507 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2508 (1<<1) | (1<<4), 0,
2509 "START-STOP UNIT")) == 0)
2510 reply = do_start_stop(fsg);
2511 break;
2512
2513 case SC_SYNCHRONIZE_CACHE:
2514 fsg->data_size_from_cmnd = 0;
2515 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2516 (0xf<<2) | (3<<7), 1,
2517 "SYNCHRONIZE CACHE")) == 0)
2518 reply = do_synchronize_cache(fsg);
2519 break;
2520
2521 case SC_TEST_UNIT_READY:
2522 fsg->data_size_from_cmnd = 0;
2523 reply = check_command(fsg, 6, DATA_DIR_NONE,
2524 0, 1,
2525 "TEST UNIT READY");
2526 break;
2527
2528 /* Although optional, this command is used by MS-Windows. We
2529 * support a minimal version: BytChk must be 0. */
2530 case SC_VERIFY:
2531 fsg->data_size_from_cmnd = 0;
2532 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2533 (1<<1) | (0xf<<2) | (3<<7), 1,
2534 "VERIFY")) == 0)
2535 reply = do_verify(fsg);
2536 break;
2537
2538 case SC_WRITE_6:
2539 i = fsg->cmnd[4];
2540 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2541 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2542 (7<<1) | (1<<4), 1,
2543 "WRITE(6)")) == 0)
2544 reply = do_write(fsg);
2545 break;
2546
2547 case SC_WRITE_10:
Alan Stern604eb892009-04-27 13:19:41 -04002548 fsg->data_size_from_cmnd =
2549 get_unaligned_be16(&fsg->cmnd[7]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002550 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2551 (1<<1) | (0xf<<2) | (3<<7), 1,
2552 "WRITE(10)")) == 0)
2553 reply = do_write(fsg);
2554 break;
2555
2556 case SC_WRITE_12:
Alan Stern604eb892009-04-27 13:19:41 -04002557 fsg->data_size_from_cmnd =
2558 get_unaligned_be32(&fsg->cmnd[6]) << 9;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002559 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2560 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2561 "WRITE(12)")) == 0)
2562 reply = do_write(fsg);
2563 break;
2564
2565 /* Some mandatory commands that we recognize but don't implement.
2566 * They don't mean much in this setting. It's left as an exercise
2567 * for anyone interested to implement RESERVE and RELEASE in terms
2568 * of Posix locks. */
2569 case SC_FORMAT_UNIT:
2570 case SC_RELEASE:
2571 case SC_RESERVE:
2572 case SC_SEND_DIAGNOSTIC:
2573 // Fall through
2574
2575 default:
Alan Stern12aae682008-11-20 14:13:12 -05002576 unknown_cmnd:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002577 fsg->data_size_from_cmnd = 0;
2578 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2579 if ((reply = check_command(fsg, fsg->cmnd_size,
2580 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2581 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2582 reply = -EINVAL;
2583 }
2584 break;
2585 }
2586 up_read(&fsg->filesem);
2587
2588 if (reply == -EINTR || signal_pending(current))
2589 return -EINTR;
2590
2591 /* Set up the single reply buffer for finish_reply() */
2592 if (reply == -EINVAL)
2593 reply = 0; // Error reply length
2594 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2595 reply = min((u32) reply, fsg->data_size_from_cmnd);
2596 bh->inreq->length = reply;
2597 bh->state = BUF_STATE_FULL;
2598 fsg->residue -= reply;
2599 } // Otherwise it's already set
2600
2601 return 0;
2602}
2603
2604
2605/*-------------------------------------------------------------------------*/
2606
2607static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2608{
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002609 struct usb_request *req = bh->outreq;
2610 struct fsg_bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002611
Alan Sternb950bdb2008-04-14 11:45:29 -04002612 /* Was this a real packet? Should it be ignored? */
2613 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002614 return -EINVAL;
2615
2616 /* Is the CBW valid? */
2617 if (req->actual != USB_BULK_CB_WRAP_LEN ||
Harvey Harrison551509d2009-02-11 14:11:36 -08002618 cbw->Signature != cpu_to_le32(
Linus Torvalds1da177e2005-04-16 15:20:36 -07002619 USB_BULK_CB_SIG)) {
2620 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2621 req->actual,
2622 le32_to_cpu(cbw->Signature));
2623
Alan Sternb950bdb2008-04-14 11:45:29 -04002624 /* The Bulk-only spec says we MUST stall the IN endpoint
2625 * (6.6.1), so it's unavoidable. It also says we must
2626 * retain this state until the next reset, but there's
2627 * no way to tell the controller driver it should ignore
2628 * Clear-Feature(HALT) requests.
2629 *
2630 * We aren't required to halt the OUT endpoint; instead
2631 * we can simply accept and discard any data received
2632 * until the next reset. */
David Lopo62fd2ca2008-04-29 10:14:38 +01002633 wedge_bulk_in_endpoint(fsg);
Alan Sternb950bdb2008-04-14 11:45:29 -04002634 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002635 return -EINVAL;
2636 }
2637
2638 /* Is the CBW meaningful? */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002639 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
Alan Stern12943f02007-08-24 16:27:50 -04002640 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002641 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2642 "cmdlen %u\n",
2643 cbw->Lun, cbw->Flags, cbw->Length);
2644
2645 /* We can do anything we want here, so let's stall the
2646 * bulk pipes if we are allowed to. */
2647 if (mod_data.can_stall) {
2648 fsg_set_halt(fsg, fsg->bulk_out);
2649 halt_bulk_in_endpoint(fsg);
2650 }
2651 return -EINVAL;
2652 }
2653
2654 /* Save the command for later */
2655 fsg->cmnd_size = cbw->Length;
2656 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2657 if (cbw->Flags & USB_BULK_IN_FLAG)
2658 fsg->data_dir = DATA_DIR_TO_HOST;
2659 else
2660 fsg->data_dir = DATA_DIR_FROM_HOST;
2661 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2662 if (fsg->data_size == 0)
2663 fsg->data_dir = DATA_DIR_NONE;
2664 fsg->lun = cbw->Lun;
2665 fsg->tag = cbw->Tag;
2666 return 0;
2667}
2668
2669
2670static int get_next_command(struct fsg_dev *fsg)
2671{
2672 struct fsg_buffhd *bh;
2673 int rc = 0;
2674
2675 if (transport_is_bbb()) {
2676
2677 /* Wait for the next buffer to become available */
2678 bh = fsg->next_buffhd_to_fill;
2679 while (bh->state != BUF_STATE_EMPTY) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002680 rc = sleep_thread(fsg);
2681 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002682 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002683 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002684
2685 /* Queue a request to read a Bulk-only CBW */
2686 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
Alan Stern70ffe6e2006-03-23 15:05:16 -05002687 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002688 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2689 &bh->outreq_busy, &bh->state);
2690
2691 /* We will drain the buffer in software, which means we
2692 * can reuse it for the next filling. No need to advance
2693 * next_buffhd_to_fill. */
2694
2695 /* Wait for the CBW to arrive */
2696 while (bh->state != BUF_STATE_FULL) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002697 rc = sleep_thread(fsg);
2698 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002699 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002700 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05002701 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002702 rc = received_cbw(fsg, bh);
2703 bh->state = BUF_STATE_EMPTY;
2704
2705 } else { // USB_PR_CB or USB_PR_CBI
2706
2707 /* Wait for the next command to arrive */
2708 while (fsg->cbbuf_cmnd_size == 0) {
Alan Stern79a7d9e2007-08-08 17:10:11 -04002709 rc = sleep_thread(fsg);
2710 if (rc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002711 return rc;
Alan Stern79a7d9e2007-08-08 17:10:11 -04002712 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002713
2714 /* Is the previous status interrupt request still busy?
2715 * The host is allowed to skip reading the status,
2716 * so we must cancel it. */
2717 if (fsg->intreq_busy)
2718 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
2719
2720 /* Copy the command and mark the buffer empty */
2721 fsg->data_dir = DATA_DIR_UNKNOWN;
2722 spin_lock_irq(&fsg->lock);
2723 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
2724 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
2725 fsg->cbbuf_cmnd_size = 0;
2726 spin_unlock_irq(&fsg->lock);
2727 }
2728 return rc;
2729}
2730
2731
2732/*-------------------------------------------------------------------------*/
2733
2734static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2735 const struct usb_endpoint_descriptor *d)
2736{
2737 int rc;
2738
2739 ep->driver_data = fsg;
2740 rc = usb_ep_enable(ep, d);
2741 if (rc)
2742 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2743 return rc;
2744}
2745
2746static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2747 struct usb_request **preq)
2748{
2749 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2750 if (*preq)
2751 return 0;
2752 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2753 return -ENOMEM;
2754}
2755
2756/*
2757 * Reset interface setting and re-init endpoint state (toggle etc).
2758 * Call with altsetting < 0 to disable the interface. The only other
2759 * available altsetting is 0, which enables the interface.
2760 */
2761static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2762{
2763 int rc = 0;
2764 int i;
2765 const struct usb_endpoint_descriptor *d;
2766
2767 if (fsg->running)
2768 DBG(fsg, "reset interface\n");
2769
2770reset:
2771 /* Deallocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002772 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002773 struct fsg_buffhd *bh = &fsg->buffhds[i];
2774
2775 if (bh->inreq) {
2776 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2777 bh->inreq = NULL;
2778 }
2779 if (bh->outreq) {
2780 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2781 bh->outreq = NULL;
2782 }
2783 }
2784 if (fsg->intreq) {
2785 usb_ep_free_request(fsg->intr_in, fsg->intreq);
2786 fsg->intreq = NULL;
2787 }
2788
2789 /* Disable the endpoints */
2790 if (fsg->bulk_in_enabled) {
2791 usb_ep_disable(fsg->bulk_in);
2792 fsg->bulk_in_enabled = 0;
2793 }
2794 if (fsg->bulk_out_enabled) {
2795 usb_ep_disable(fsg->bulk_out);
2796 fsg->bulk_out_enabled = 0;
2797 }
2798 if (fsg->intr_in_enabled) {
2799 usb_ep_disable(fsg->intr_in);
2800 fsg->intr_in_enabled = 0;
2801 }
2802
2803 fsg->running = 0;
2804 if (altsetting < 0 || rc != 0)
2805 return rc;
2806
2807 DBG(fsg, "set interface %d\n", altsetting);
2808
2809 /* Enable the endpoints */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002810 d = fsg_ep_desc(fsg->gadget,
2811 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002812 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2813 goto reset;
2814 fsg->bulk_in_enabled = 1;
2815
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002816 d = fsg_ep_desc(fsg->gadget,
2817 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002818 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2819 goto reset;
2820 fsg->bulk_out_enabled = 1;
2821 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
Alan Sternb950bdb2008-04-14 11:45:29 -04002822 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002823
2824 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002825 d = fsg_ep_desc(fsg->gadget,
2826 &fsg_fs_intr_in_desc, &fsg_hs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002827 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
2828 goto reset;
2829 fsg->intr_in_enabled = 1;
2830 }
2831
2832 /* Allocate the requests */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002833 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002834 struct fsg_buffhd *bh = &fsg->buffhds[i];
2835
2836 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2837 goto reset;
2838 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2839 goto reset;
2840 bh->inreq->buf = bh->outreq->buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002841 bh->inreq->context = bh->outreq->context = bh;
2842 bh->inreq->complete = bulk_in_complete;
2843 bh->outreq->complete = bulk_out_complete;
2844 }
2845 if (transport_is_cbi()) {
2846 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
2847 goto reset;
2848 fsg->intreq->complete = intr_in_complete;
2849 }
2850
2851 fsg->running = 1;
2852 for (i = 0; i < fsg->nluns; ++i)
2853 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2854 return rc;
2855}
2856
2857
2858/*
2859 * Change our operational configuration. This code must agree with the code
2860 * that returns config descriptors, and with interface altsetting code.
2861 *
2862 * It's also responsible for power management interactions. Some
2863 * configurations might not work with our current power sources.
2864 * For now we just assume the gadget is always self-powered.
2865 */
2866static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2867{
2868 int rc = 0;
2869
2870 /* Disable the single interface */
2871 if (fsg->config != 0) {
2872 DBG(fsg, "reset config\n");
2873 fsg->config = 0;
2874 rc = do_set_interface(fsg, -1);
2875 }
2876
2877 /* Enable the interface */
2878 if (new_config != 0) {
2879 fsg->config = new_config;
2880 if ((rc = do_set_interface(fsg, 0)) != 0)
2881 fsg->config = 0; // Reset on errors
2882 else {
2883 char *speed;
2884
2885 switch (fsg->gadget->speed) {
2886 case USB_SPEED_LOW: speed = "low"; break;
2887 case USB_SPEED_FULL: speed = "full"; break;
2888 case USB_SPEED_HIGH: speed = "high"; break;
2889 default: speed = "?"; break;
2890 }
2891 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2892 }
2893 }
2894 return rc;
2895}
2896
2897
2898/*-------------------------------------------------------------------------*/
2899
2900static void handle_exception(struct fsg_dev *fsg)
2901{
2902 siginfo_t info;
2903 int sig;
2904 int i;
2905 int num_active;
2906 struct fsg_buffhd *bh;
2907 enum fsg_state old_state;
2908 u8 new_config;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002909 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002910 unsigned int exception_req_tag;
2911 int rc;
2912
2913 /* Clear the existing signals. Anything but SIGUSR1 is converted
2914 * into a high-priority EXIT exception. */
2915 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04002916 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002917 if (!sig)
2918 break;
2919 if (sig != SIGUSR1) {
2920 if (fsg->state < FSG_STATE_EXIT)
2921 DBG(fsg, "Main thread exiting on signal\n");
2922 raise_exception(fsg, FSG_STATE_EXIT);
2923 }
2924 }
2925
2926 /* Cancel all the pending transfers */
2927 if (fsg->intreq_busy)
2928 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002929 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002930 bh = &fsg->buffhds[i];
2931 if (bh->inreq_busy)
2932 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2933 if (bh->outreq_busy)
2934 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2935 }
2936
2937 /* Wait until everything is idle */
2938 for (;;) {
2939 num_active = fsg->intreq_busy;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002940 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002941 bh = &fsg->buffhds[i];
2942 num_active += bh->inreq_busy + bh->outreq_busy;
2943 }
2944 if (num_active == 0)
2945 break;
2946 if (sleep_thread(fsg))
2947 return;
2948 }
2949
2950 /* Clear out the controller's fifos */
2951 if (fsg->bulk_in_enabled)
2952 usb_ep_fifo_flush(fsg->bulk_in);
2953 if (fsg->bulk_out_enabled)
2954 usb_ep_fifo_flush(fsg->bulk_out);
2955 if (fsg->intr_in_enabled)
2956 usb_ep_fifo_flush(fsg->intr_in);
2957
2958 /* Reset the I/O buffer states and pointers, the SCSI
2959 * state, and the exception. Then invoke the handler. */
2960 spin_lock_irq(&fsg->lock);
2961
Michal Nazarewiczd6181702009-10-28 16:57:15 +01002962 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002963 bh = &fsg->buffhds[i];
2964 bh->state = BUF_STATE_EMPTY;
2965 }
2966 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2967 &fsg->buffhds[0];
2968
2969 exception_req_tag = fsg->exception_req_tag;
2970 new_config = fsg->new_config;
2971 old_state = fsg->state;
2972
2973 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2974 fsg->state = FSG_STATE_STATUS_PHASE;
2975 else {
2976 for (i = 0; i < fsg->nluns; ++i) {
2977 curlun = &fsg->luns[i];
2978 curlun->prevent_medium_removal = 0;
2979 curlun->sense_data = curlun->unit_attention_data =
2980 SS_NO_SENSE;
2981 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002982 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002983 }
2984 fsg->state = FSG_STATE_IDLE;
2985 }
2986 spin_unlock_irq(&fsg->lock);
2987
2988 /* Carry out any extra actions required for the exception */
2989 switch (old_state) {
2990 default:
2991 break;
2992
2993 case FSG_STATE_ABORT_BULK_OUT:
2994 send_status(fsg);
2995 spin_lock_irq(&fsg->lock);
2996 if (fsg->state == FSG_STATE_STATUS_PHASE)
2997 fsg->state = FSG_STATE_IDLE;
2998 spin_unlock_irq(&fsg->lock);
2999 break;
3000
3001 case FSG_STATE_RESET:
3002 /* In case we were forced against our will to halt a
3003 * bulk endpoint, clear the halt now. (The SuperH UDC
3004 * requires this.) */
Alan Sternb950bdb2008-04-14 11:45:29 -04003005 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003006 usb_ep_clear_halt(fsg->bulk_in);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003007
3008 if (transport_is_bbb()) {
3009 if (fsg->ep0_req_tag == exception_req_tag)
3010 ep0_queue(fsg); // Complete the status stage
3011
3012 } else if (transport_is_cbi())
3013 send_status(fsg); // Status by interrupt pipe
3014
3015 /* Technically this should go here, but it would only be
3016 * a waste of time. Ditto for the INTERFACE_CHANGE and
3017 * CONFIG_CHANGE cases. */
3018 // for (i = 0; i < fsg->nluns; ++i)
3019 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3020 break;
3021
3022 case FSG_STATE_INTERFACE_CHANGE:
3023 rc = do_set_interface(fsg, 0);
3024 if (fsg->ep0_req_tag != exception_req_tag)
3025 break;
3026 if (rc != 0) // STALL on errors
3027 fsg_set_halt(fsg, fsg->ep0);
3028 else // Complete the status stage
3029 ep0_queue(fsg);
3030 break;
3031
3032 case FSG_STATE_CONFIG_CHANGE:
3033 rc = do_set_config(fsg, new_config);
3034 if (fsg->ep0_req_tag != exception_req_tag)
3035 break;
3036 if (rc != 0) // STALL on errors
3037 fsg_set_halt(fsg, fsg->ep0);
3038 else // Complete the status stage
3039 ep0_queue(fsg);
3040 break;
3041
3042 case FSG_STATE_DISCONNECT:
Michal Nazarewiczb6058d02009-10-28 16:57:14 +01003043 for (i = 0; i < fsg->nluns; ++i)
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003044 fsg_lun_fsync_sub(fsg->luns + i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003045 do_set_config(fsg, 0); // Unconfigured state
3046 break;
3047
3048 case FSG_STATE_EXIT:
3049 case FSG_STATE_TERMINATED:
3050 do_set_config(fsg, 0); // Free resources
3051 spin_lock_irq(&fsg->lock);
3052 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3053 spin_unlock_irq(&fsg->lock);
3054 break;
3055 }
3056}
3057
3058
3059/*-------------------------------------------------------------------------*/
3060
3061static int fsg_main_thread(void *fsg_)
3062{
John Daiker7ca46b82006-12-29 19:02:06 -08003063 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003064
Linus Torvalds1da177e2005-04-16 15:20:36 -07003065 /* Allow the thread to be killed by a signal, but set the signal mask
3066 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003067 allow_signal(SIGINT);
3068 allow_signal(SIGTERM);
3069 allow_signal(SIGKILL);
3070 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003071
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003072 /* Allow the thread to be frozen */
3073 set_freezable();
3074
Linus Torvalds1da177e2005-04-16 15:20:36 -07003075 /* Arrange for userspace references to be interpreted as kernel
3076 * pointers. That way we can pass a kernel pointer to a routine
3077 * that expects a __user pointer and it will work okay. */
3078 set_fs(get_ds());
3079
Linus Torvalds1da177e2005-04-16 15:20:36 -07003080 /* The main loop */
3081 while (fsg->state != FSG_STATE_TERMINATED) {
3082 if (exception_in_progress(fsg) || signal_pending(current)) {
3083 handle_exception(fsg);
3084 continue;
3085 }
3086
3087 if (!fsg->running) {
3088 sleep_thread(fsg);
3089 continue;
3090 }
3091
3092 if (get_next_command(fsg))
3093 continue;
3094
3095 spin_lock_irq(&fsg->lock);
3096 if (!exception_in_progress(fsg))
3097 fsg->state = FSG_STATE_DATA_PHASE;
3098 spin_unlock_irq(&fsg->lock);
3099
3100 if (do_scsi_command(fsg) || finish_reply(fsg))
3101 continue;
3102
3103 spin_lock_irq(&fsg->lock);
3104 if (!exception_in_progress(fsg))
3105 fsg->state = FSG_STATE_STATUS_PHASE;
3106 spin_unlock_irq(&fsg->lock);
3107
3108 if (send_status(fsg))
3109 continue;
3110
3111 spin_lock_irq(&fsg->lock);
3112 if (!exception_in_progress(fsg))
3113 fsg->state = FSG_STATE_IDLE;
3114 spin_unlock_irq(&fsg->lock);
3115 }
3116
Alan Stern22efcf42005-09-26 16:12:02 -04003117 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003118 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003119 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003120
Alan Stern82a10a82009-04-16 15:37:28 -04003121 /* If we are exiting because of a signal, unregister the
3122 * gadget driver. */
3123 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003124 usb_gadget_unregister_driver(&fsg_driver);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003125
3126 /* Let the unbind and cleanup routines know the thread has exited */
3127 complete_and_exit(&fsg->thread_notifier, 0);
3128}
3129
3130
3131/*-------------------------------------------------------------------------*/
3132
Linus Torvalds1da177e2005-04-16 15:20:36 -07003133
3134/* The write permissions and store_xxx pointers are set in fsg_bind() */
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003135static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
3136static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003137
3138
3139/*-------------------------------------------------------------------------*/
3140
Alan Stern87c42522005-11-09 16:59:56 -05003141static void fsg_release(struct kref *ref)
3142{
3143 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3144
3145 kfree(fsg->luns);
3146 kfree(fsg);
3147}
3148
Linus Torvalds1da177e2005-04-16 15:20:36 -07003149static void lun_release(struct device *dev)
3150{
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003151 struct rw_semaphore *filesem = dev_get_drvdata(dev);
3152 struct fsg_dev *fsg =
3153 container_of(filesem, struct fsg_dev, filesem);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003154
Alan Stern87c42522005-11-09 16:59:56 -05003155 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003156}
3157
David Brownella3536782006-07-06 15:48:53 -07003158static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003159{
3160 struct fsg_dev *fsg = get_gadget_data(gadget);
3161 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003162 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003163 struct usb_request *req = fsg->ep0req;
3164
3165 DBG(fsg, "unbind\n");
3166 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3167
3168 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003169 for (i = 0; i < fsg->nluns; ++i) {
3170 curlun = &fsg->luns[i];
3171 if (curlun->registered) {
3172 device_remove_file(&curlun->dev, &dev_attr_ro);
3173 device_remove_file(&curlun->dev, &dev_attr_file);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003174 fsg_lun_close(curlun);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003175 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003176 curlun->registered = 0;
3177 }
3178 }
3179
3180 /* If the thread isn't already dead, tell it to exit now */
3181 if (fsg->state != FSG_STATE_TERMINATED) {
3182 raise_exception(fsg, FSG_STATE_EXIT);
3183 wait_for_completion(&fsg->thread_notifier);
3184
3185 /* The cleanup routine waits for this completion also */
3186 complete(&fsg->thread_notifier);
3187 }
3188
3189 /* Free the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003190 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
David Brownell9d8bab52007-07-01 11:04:54 -07003191 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003192
3193 /* Free the request and buffer for endpoint 0 */
3194 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003195 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003196 usb_ep_free_request(fsg->ep0, req);
3197 }
3198
3199 set_gadget_data(gadget, NULL);
3200}
3201
3202
3203static int __init check_parameters(struct fsg_dev *fsg)
3204{
3205 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003206 int gcnum;
Yann Cantin87eb1be2010-06-05 23:06:31 +02003207 int i;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003208
3209 /* Store the default values */
3210 mod_data.transport_type = USB_PR_BULK;
3211 mod_data.transport_name = "Bulk-only";
3212 mod_data.protocol_type = USB_SC_SCSI;
3213 mod_data.protocol_name = "Transparent SCSI";
3214
Alan Sternce459ec2009-02-24 16:19:47 -05003215 /* Some peripheral controllers are known not to be able to
3216 * halt bulk endpoints correctly. If one of them is present,
3217 * disable stalls.
3218 */
Christoph Egger90f79762010-02-05 13:24:12 +01003219 if (gadget_is_at91(fsg->gadget))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003220 mod_data.can_stall = 0;
3221
3222 if (mod_data.release == 0xffff) { // Parameter wasn't set
Christoph Egger90f79762010-02-05 13:24:12 +01003223 gcnum = usb_gadget_controller_number(fsg->gadget);
David Brownell91e79c92005-07-13 15:18:30 -07003224 if (gcnum >= 0)
3225 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003226 else {
Arjan van de Venb6c63932008-07-25 01:45:52 -07003227 WARNING(fsg, "controller '%s' not recognized\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003228 fsg->gadget->name);
3229 mod_data.release = 0x0399;
3230 }
3231 }
3232
3233 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3234
3235#ifdef CONFIG_USB_FILE_STORAGE_TEST
3236 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3237 ; // Use default setting
3238 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3239 mod_data.transport_type = USB_PR_CB;
3240 mod_data.transport_name = "Control-Bulk";
3241 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3242 mod_data.transport_type = USB_PR_CBI;
3243 mod_data.transport_name = "Control-Bulk-Interrupt";
3244 } else {
3245 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3246 return -EINVAL;
3247 }
3248
3249 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3250 prot == USB_SC_SCSI) {
3251 ; // Use default setting
3252 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3253 prot == USB_SC_RBC) {
3254 mod_data.protocol_type = USB_SC_RBC;
3255 mod_data.protocol_name = "RBC";
3256 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3257 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3258 prot == USB_SC_8020) {
3259 mod_data.protocol_type = USB_SC_8020;
3260 mod_data.protocol_name = "8020i (ATAPI)";
3261 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3262 prot == USB_SC_QIC) {
3263 mod_data.protocol_type = USB_SC_QIC;
3264 mod_data.protocol_name = "QIC-157";
3265 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3266 prot == USB_SC_UFI) {
3267 mod_data.protocol_type = USB_SC_UFI;
3268 mod_data.protocol_name = "UFI";
3269 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3270 prot == USB_SC_8070) {
3271 mod_data.protocol_type = USB_SC_8070;
3272 mod_data.protocol_name = "8070i";
3273 } else {
3274 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3275 return -EINVAL;
3276 }
3277
3278 mod_data.buflen &= PAGE_CACHE_MASK;
3279 if (mod_data.buflen <= 0) {
3280 ERROR(fsg, "invalid buflen\n");
3281 return -ETOOSMALL;
3282 }
Yann Cantin87eb1be2010-06-05 23:06:31 +02003283
3284 /* Serial string handling.
3285 * On a real device, the serial string would be loaded
3286 * from permanent storage. */
3287 if (mod_data.serial_parm) {
3288 const char *ch;
3289 unsigned len = 0;
3290
3291 /* Sanity check :
3292 * The CB[I] specification limits the serial string to
3293 * 12 uppercase hexadecimal characters.
3294 * BBB need at least 12 uppercase hexadecimal characters,
3295 * with a maximum of 126. */
3296 for (ch = mod_data.serial_parm; *ch; ++ch) {
3297 ++len;
3298 if ((*ch < '0' || *ch > '9') &&
3299 (*ch < 'A' || *ch > 'F')) { /* not uppercase hex */
3300 WARNING(fsg,
3301 "Invalid serial string character: %c; "
3302 "Failing back to default\n",
3303 *ch);
3304 goto fill_serial;
3305 }
3306 }
3307 if (len > 126 ||
3308 (mod_data.transport_type == USB_PR_BULK && len < 12) ||
3309 (mod_data.transport_type != USB_PR_BULK && len > 12)) {
3310 WARNING(fsg,
3311 "Invalid serial string length; "
3312 "Failing back to default\n");
3313 goto fill_serial;
3314 }
3315 fsg_strings[FSG_STRING_SERIAL - 1].s = mod_data.serial_parm;
3316 } else {
3317fill_serial:
3318 /* Serial number not specified or invalid, make our own.
3319 * We just encode it from the driver version string,
3320 * 12 characters to comply with both CB[I] and BBB spec.
3321 * Warning : Two devices running the same kernel will have
3322 * the same fallback serial number. */
3323 for (i = 0; i < 12; i += 2) {
3324 unsigned char c = DRIVER_VERSION[i / 2];
3325
3326 if (!c)
3327 break;
3328 sprintf(&fsg_string_serial[i], "%02X", c);
3329 }
3330 }
3331
Linus Torvalds1da177e2005-04-16 15:20:36 -07003332#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3333
3334 return 0;
3335}
3336
3337
3338static int __init fsg_bind(struct usb_gadget *gadget)
3339{
3340 struct fsg_dev *fsg = the_fsg;
3341 int rc;
3342 int i;
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003343 struct fsg_lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003344 struct usb_ep *ep;
3345 struct usb_request *req;
3346 char *pathbuf, *p;
3347
3348 fsg->gadget = gadget;
3349 set_gadget_data(gadget, fsg);
3350 fsg->ep0 = gadget->ep0;
3351 fsg->ep0->driver_data = fsg;
3352
3353 if ((rc = check_parameters(fsg)) != 0)
3354 goto out;
3355
3356 if (mod_data.removable) { // Enable the store_xxx attributes
Alan Stern12aae682008-11-20 14:13:12 -05003357 dev_attr_file.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003358 dev_attr_file.store = fsg_store_file;
Alan Stern12aae682008-11-20 14:13:12 -05003359 if (!mod_data.cdrom) {
3360 dev_attr_ro.attr.mode = 0644;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003361 dev_attr_ro.store = fsg_store_ro;
Alan Stern12aae682008-11-20 14:13:12 -05003362 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003363 }
3364
3365 /* Find out how many LUNs there should be */
3366 i = mod_data.nluns;
3367 if (i == 0)
David Brownell2e806f62007-08-02 00:03:39 -07003368 i = max(mod_data.num_filenames, 1u);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003369 if (i > FSG_MAX_LUNS) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003370 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3371 rc = -EINVAL;
3372 goto out;
3373 }
3374
3375 /* Create the LUNs, open their backing files, and register the
3376 * LUN devices in sysfs. */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003377 fsg->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003378 if (!fsg->luns) {
3379 rc = -ENOMEM;
3380 goto out;
3381 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003382 fsg->nluns = i;
3383
3384 for (i = 0; i < fsg->nluns; ++i) {
3385 curlun = &fsg->luns[i];
Michal Nazarewicze909ef52009-10-28 16:57:16 +01003386 curlun->cdrom = !!mod_data.cdrom;
3387 curlun->ro = mod_data.cdrom || mod_data.ro[i];
3388 curlun->initially_ro = curlun->ro;
3389 curlun->removable = mod_data.removable;
Alan Stern2de9eae2006-09-25 14:31:15 -04003390 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003391 curlun->dev.parent = &gadget->dev;
3392 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicz93f93742009-10-28 16:57:17 +01003393 dev_set_drvdata(&curlun->dev, &fsg->filesem);
Kay Sievers0031a062008-05-02 06:02:41 +02003394 dev_set_name(&curlun->dev,"%s-lun%d",
3395 dev_name(&gadget->dev), i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003396
Alan Stern2de9eae2006-09-25 14:31:15 -04003397 if ((rc = device_register(&curlun->dev)) != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003398 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Alan Stern2de9eae2006-09-25 14:31:15 -04003399 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003400 }
Alan Stern2de9eae2006-09-25 14:31:15 -04003401 if ((rc = device_create_file(&curlun->dev,
3402 &dev_attr_ro)) != 0 ||
3403 (rc = device_create_file(&curlun->dev,
3404 &dev_attr_file)) != 0) {
3405 device_unregister(&curlun->dev);
3406 goto out;
3407 }
3408 curlun->registered = 1;
3409 kref_get(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003410
Alan Sternaafe5bd2006-03-31 11:46:43 -05003411 if (mod_data.file[i] && *mod_data.file[i]) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003412 if ((rc = fsg_lun_open(curlun,
Alan Sternaafe5bd2006-03-31 11:46:43 -05003413 mod_data.file[i])) != 0)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003414 goto out;
3415 } else if (!mod_data.removable) {
3416 ERROR(fsg, "no file given for LUN%d\n", i);
3417 rc = -EINVAL;
3418 goto out;
3419 }
3420 }
3421
3422 /* Find all the endpoints we will use */
3423 usb_ep_autoconfig_reset(gadget);
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003424 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003425 if (!ep)
3426 goto autoconf_fail;
3427 ep->driver_data = fsg; // claim the endpoint
3428 fsg->bulk_in = ep;
3429
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003430 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003431 if (!ep)
3432 goto autoconf_fail;
3433 ep->driver_data = fsg; // claim the endpoint
3434 fsg->bulk_out = ep;
3435
3436 if (transport_is_cbi()) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003437 ep = usb_ep_autoconfig(gadget, &fsg_fs_intr_in_desc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003438 if (!ep)
3439 goto autoconf_fail;
3440 ep->driver_data = fsg; // claim the endpoint
3441 fsg->intr_in = ep;
3442 }
3443
3444 /* Fix up the descriptors */
3445 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3446 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3447 device_desc.idProduct = cpu_to_le16(mod_data.product);
3448 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3449
3450 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003451 fsg_intf_desc.bNumEndpoints = i;
3452 fsg_intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3453 fsg_intf_desc.bInterfaceProtocol = mod_data.transport_type;
3454 fsg_fs_function[i + FSG_FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003455
David Brownell2e806f62007-08-02 00:03:39 -07003456 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003457 fsg_hs_function[i + FSG_HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003458
David Brownell2e806f62007-08-02 00:03:39 -07003459 /* Assume ep0 uses the same maxpacket value for both speeds */
3460 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003461
David Brownell2e806f62007-08-02 00:03:39 -07003462 /* Assume endpoint addresses are the same for both speeds */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003463 fsg_hs_bulk_in_desc.bEndpointAddress =
3464 fsg_fs_bulk_in_desc.bEndpointAddress;
3465 fsg_hs_bulk_out_desc.bEndpointAddress =
3466 fsg_fs_bulk_out_desc.bEndpointAddress;
3467 fsg_hs_intr_in_desc.bEndpointAddress =
3468 fsg_fs_intr_in_desc.bEndpointAddress;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003469 }
3470
David Brownell2e806f62007-08-02 00:03:39 -07003471 if (gadget_is_otg(gadget))
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003472 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
David Brownell2e806f62007-08-02 00:03:39 -07003473
Linus Torvalds1da177e2005-04-16 15:20:36 -07003474 rc = -ENOMEM;
3475
3476 /* Allocate the request and buffer for endpoint 0 */
3477 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3478 if (!req)
3479 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003480 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003481 if (!req->buf)
3482 goto out;
3483 req->complete = ep0_complete;
3484
3485 /* Allocate the data buffers */
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003486 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003487 struct fsg_buffhd *bh = &fsg->buffhds[i];
3488
Alan Stern14cd5f82006-03-23 15:07:25 -05003489 /* Allocate for the bulk-in endpoint. We assume that
3490 * the buffer will also work with the bulk-out (and
3491 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003492 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003493 if (!bh->buf)
3494 goto out;
3495 bh->next = bh + 1;
3496 }
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003497 fsg->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->buffhds[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07003498
3499 /* This should reflect the actual gadget power source */
3500 usb_gadget_set_selfpowered(gadget);
3501
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003502 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3503 "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003504 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003505 gadget->name);
3506
Alan Stern22efcf42005-09-26 16:12:02 -04003507 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3508 "file-storage-gadget");
3509 if (IS_ERR(fsg->thread_task)) {
3510 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003511 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04003512 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003513
3514 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3515 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
3516
3517 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3518 for (i = 0; i < fsg->nluns; ++i) {
3519 curlun = &fsg->luns[i];
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003520 if (fsg_lun_is_open(curlun)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003521 p = NULL;
3522 if (pathbuf) {
Jan Blunckcf28b482008-02-14 19:38:44 -08003523 p = d_path(&curlun->filp->f_path,
3524 pathbuf, PATH_MAX);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003525 if (IS_ERR(p))
3526 p = NULL;
3527 }
3528 LINFO(curlun, "ro=%d, file: %s\n",
3529 curlun->ro, (p ? p : "(error)"));
3530 }
3531 }
3532 kfree(pathbuf);
3533
3534 DBG(fsg, "transport=%s (x%02x)\n",
3535 mod_data.transport_name, mod_data.transport_type);
3536 DBG(fsg, "protocol=%s (x%02x)\n",
3537 mod_data.protocol_name, mod_data.protocol_type);
3538 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
3539 mod_data.vendor, mod_data.product, mod_data.release);
Alan Stern12aae682008-11-20 14:13:12 -05003540 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
Linus Torvalds1da177e2005-04-16 15:20:36 -07003541 mod_data.removable, mod_data.can_stall,
Alan Stern12aae682008-11-20 14:13:12 -05003542 mod_data.cdrom, mod_data.buflen);
Pavel Emelyanovba25f9d2007-10-18 23:40:40 -07003543 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
Alan Sterna922c682005-10-06 16:38:45 -04003544
3545 set_bit(REGISTERED, &fsg->atomic_bitflags);
3546
3547 /* Tell the thread to start working */
3548 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003549 return 0;
3550
3551autoconf_fail:
3552 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3553 rc = -ENOTSUPP;
3554
3555out:
3556 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3557 fsg_unbind(gadget);
Felipe Balbi889394b2008-12-08 13:50:27 +02003558 complete(&fsg->thread_notifier);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003559 return rc;
3560}
3561
3562
3563/*-------------------------------------------------------------------------*/
3564
3565static void fsg_suspend(struct usb_gadget *gadget)
3566{
3567 struct fsg_dev *fsg = get_gadget_data(gadget);
3568
3569 DBG(fsg, "suspend\n");
3570 set_bit(SUSPENDED, &fsg->atomic_bitflags);
3571}
3572
3573static void fsg_resume(struct usb_gadget *gadget)
3574{
3575 struct fsg_dev *fsg = get_gadget_data(gadget);
3576
3577 DBG(fsg, "resume\n");
3578 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
3579}
3580
3581
3582/*-------------------------------------------------------------------------*/
3583
3584static struct usb_gadget_driver fsg_driver = {
3585#ifdef CONFIG_USB_GADGET_DUALSPEED
3586 .speed = USB_SPEED_HIGH,
3587#else
3588 .speed = USB_SPEED_FULL,
3589#endif
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003590 .function = (char *) fsg_string_product,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003591 .bind = fsg_bind,
David Brownell6bea4762006-12-05 03:15:33 -08003592 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003593 .disconnect = fsg_disconnect,
3594 .setup = fsg_setup,
3595 .suspend = fsg_suspend,
3596 .resume = fsg_resume,
3597
3598 .driver = {
Michal Nazarewiczd6181702009-10-28 16:57:15 +01003599 .name = DRIVER_NAME,
Ben Dooksd0d50492005-10-10 10:52:33 +01003600 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003601 // .release = ...
3602 // .suspend = ...
3603 // .resume = ...
3604 },
3605};
3606
3607
3608static int __init fsg_alloc(void)
3609{
3610 struct fsg_dev *fsg;
3611
Alan Sterna922c682005-10-06 16:38:45 -04003612 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003613 if (!fsg)
3614 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003615 spin_lock_init(&fsg->lock);
3616 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05003617 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003618 init_completion(&fsg->thread_notifier);
3619
3620 the_fsg = fsg;
3621 return 0;
3622}
3623
3624
Linus Torvalds1da177e2005-04-16 15:20:36 -07003625static int __init fsg_init(void)
3626{
3627 int rc;
3628 struct fsg_dev *fsg;
3629
3630 if ((rc = fsg_alloc()) != 0)
3631 return rc;
3632 fsg = the_fsg;
Alan Sterna922c682005-10-06 16:38:45 -04003633 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05003634 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04003635 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003636}
3637module_init(fsg_init);
3638
3639
3640static void __exit fsg_cleanup(void)
3641{
3642 struct fsg_dev *fsg = the_fsg;
3643
3644 /* Unregister the driver iff the thread hasn't already done so */
3645 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3646 usb_gadget_unregister_driver(&fsg_driver);
3647
3648 /* Wait for the thread to finish up */
3649 wait_for_completion(&fsg->thread_notifier);
3650
Alan Stern87c42522005-11-09 16:59:56 -05003651 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003652}
3653module_exit(fsg_cleanup);