blob: 01ddb6d3e51b85ec24863d32662cffde083c3ce8 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
3 *
4 * Copyright (C) 2003-2005 Alan Stern
5 * 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,
41 * appearing to the host as a disk drive. In addition to providing an
42 * example of a genuinely useful gadget driver for a USB device, it also
43 * illustrates a technique of double-buffering for increased throughput.
44 * Last but not least, it gives an easy way to probe the behavior of the
45 * Mass Storage drivers in a USB host.
46 *
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
49 * setting the optional "ro" module parameter. The gadget will indicate that
50 * it has removable media if the optional "removable" module parameter is set.
51 *
52 * The gadget supports the Control-Bulk (CB), Control-Bulk-Interrupt (CBI),
53 * and Bulk-Only (also known as Bulk-Bulk-Bulk or BBB) transports, selected
54 * by the optional "transport" module parameter. It also supports the
55 * following protocols: RBC (0x01), ATAPI or SFF-8020i (0x02), QIC-157 (0c03),
56 * UFI (0x04), SFF-8070i (0x05), and transparent SCSI (0x06), selected by
57 * the optional "protocol" module parameter. In addition, the default
58 * Vendor ID, Product ID, and release number can be overridden.
59 *
60 * There is support for multiple logical units (LUNs), each of which has
61 * its own backing file. The number of LUNs can be set using the optional
62 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
63 * files are specified using comma-separated lists for "file" and "ro".
64 * The default number of LUNs is taken from the number of "file" elements;
65 * it is 1 if "file" is not given. If "removable" is not set then a backing
66 * file must be specified for each LUN. If it is set, then an unspecified
67 * or empty backing filename means the LUN's medium is not loaded.
68 *
69 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
70 * needed (an interrupt-out endpoint is also needed for CBI). The memory
71 * requirement amounts to two 16K buffers, size configurable by a parameter.
72 * Support is included for both full-speed and high-speed operation.
73 *
Alan Stern14cd5f82006-03-23 15:07:25 -050074 * Note that the driver is slightly non-portable in that it assumes a
75 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
76 * interrupt-in endpoints. With most device controllers this isn't an
77 * issue, but there may be some with hardware restrictions that prevent
78 * a buffer from being used by more than one endpoint.
79 *
Linus Torvalds1da177e2005-04-16 15:20:36 -070080 * Module options:
81 *
82 * file=filename[,filename...]
83 * Required if "removable" is not set, names of
84 * the files or block devices used for
85 * backing storage
86 * ro=b[,b...] Default false, booleans for read-only access
87 * removable Default false, boolean for removable media
88 * luns=N Default N = number of filenames, number of
89 * LUNs to support
Alan Sternd794ac72005-04-18 12:43:25 -040090 * stall Default determined according to the type of
91 * USB device controller (usually true),
92 * boolean to permit the driver to halt
93 * bulk endpoints
Linus Torvalds1da177e2005-04-16 15:20:36 -070094 * transport=XXX Default BBB, transport name (CB, CBI, or BBB)
95 * protocol=YYY Default SCSI, protocol name (RBC, 8020 or
96 * ATAPI, QIC, UFI, 8070, or SCSI;
97 * also 1 - 6)
98 * vendor=0xVVVV Default 0x0525 (NetChip), USB Vendor ID
99 * product=0xPPPP Default 0xa4a5 (FSG), USB Product ID
100 * release=0xRRRR Override the USB release number (bcdDevice)
101 * buflen=N Default N=16384, buffer size used (will be
102 * rounded down to a multiple of
103 * PAGE_CACHE_SIZE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700104 *
105 * If CONFIG_USB_FILE_STORAGE_TEST is not set, only the "file", "ro",
Alan Sternd794ac72005-04-18 12:43:25 -0400106 * "removable", "luns", and "stall" options are available; default values
107 * are used for everything else.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700108 *
109 * The pathnames of the backing files and the ro settings are available in
110 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
111 * gadget's sysfs directory. If the "removable" option is set, writing to
112 * these files will simulate ejecting/loading the medium (writing an empty
113 * line means eject) and adjusting a write-enable tab. Changes to the ro
114 * setting are not allowed when the medium is loaded.
115 *
116 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
Alan Sternaafe5bd2006-03-31 11:46:43 -0500117 * The driver's SCSI command interface was based on the "Information
118 * technology - Small Computer System Interface - 2" document from
119 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
120 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
121 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
122 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
123 * document, Revision 1.0, December 14, 1998, available at
124 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700125 */
126
127
128/*
129 * Driver Design
130 *
131 * The FSG driver is fairly straightforward. There is a main kernel
132 * thread that handles most of the work. Interrupt routines field
133 * callbacks from the controller driver: bulk- and interrupt-request
134 * completion notifications, endpoint-0 events, and disconnect events.
135 * Completion events are passed to the main thread by wakeup calls. Many
136 * ep0 requests are handled at interrupt time, but SetInterface,
137 * SetConfiguration, and device reset requests are forwarded to the
138 * thread in the form of "exceptions" using SIGUSR1 signals (since they
139 * should interrupt any ongoing file I/O operations).
140 *
141 * The thread's main routine implements the standard command/data/status
142 * parts of a SCSI interaction. It and its subroutines are full of tests
143 * for pending signals/exceptions -- all this polling is necessary since
144 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
145 * indication that the driver really wants to be running in userspace.)
146 * An important point is that so long as the thread is alive it keeps an
147 * open reference to the backing file. This will prevent unmounting
148 * the backing file's underlying filesystem and could cause problems
149 * during system shutdown, for example. To prevent such problems, the
150 * thread catches INT, TERM, and KILL signals and converts them into
151 * an EXIT exception.
152 *
153 * In normal operation the main thread is started during the gadget's
154 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
155 * exit when it receives a signal, and there's no point leaving the
156 * gadget running when the thread is dead. So just before the thread
157 * exits, it deregisters the gadget driver. This makes things a little
158 * tricky: The driver is deregistered at two places, and the exiting
159 * thread can indirectly call fsg_unbind() which in turn can tell the
160 * thread to exit. The first problem is resolved through the use of the
161 * REGISTERED atomic bitflag; the driver will only be deregistered once.
162 * The second problem is resolved by having fsg_unbind() check
163 * fsg->state; it won't try to stop the thread if the state is already
164 * FSG_STATE_TERMINATED.
165 *
166 * To provide maximum throughput, the driver uses a circular pipeline of
167 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
168 * arbitrarily long; in practice the benefits don't justify having more
169 * than 2 stages (i.e., double buffering). But it helps to think of the
170 * pipeline as being a long one. Each buffer head contains a bulk-in and
171 * a bulk-out request pointer (since the buffer can be used for both
172 * output and input -- directions always are given from the host's
173 * point of view) as well as a pointer to the buffer and various state
174 * variables.
175 *
176 * Use of the pipeline follows a simple protocol. There is a variable
177 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
178 * At any time that buffer head may still be in use from an earlier
179 * request, so each buffer head has a state variable indicating whether
180 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
181 * buffer head to be EMPTY, filling the buffer either by file I/O or by
182 * USB I/O (during which the buffer head is BUSY), and marking the buffer
183 * head FULL when the I/O is complete. Then the buffer will be emptied
184 * (again possibly by USB I/O, during which it is marked BUSY) and
185 * finally marked EMPTY again (possibly by a completion routine).
186 *
187 * A module parameter tells the driver to avoid stalling the bulk
188 * endpoints wherever the transport specification allows. This is
189 * necessary for some UDCs like the SuperH, which cannot reliably clear a
190 * halt on a bulk endpoint. However, under certain circumstances the
191 * Bulk-only specification requires a stall. In such cases the driver
192 * will halt the endpoint and set a flag indicating that it should clear
193 * the halt in software during the next device reset. Hopefully this
194 * will permit everything to work correctly. Furthermore, although the
195 * specification allows the bulk-out endpoint to halt when the host sends
196 * too much data, implementing this would cause an unavoidable race.
197 * The driver will always use the "no-stall" approach for OUT transfers.
198 *
199 * One subtle point concerns sending status-stage responses for ep0
200 * requests. Some of these requests, such as device reset, can involve
201 * interrupting an ongoing file I/O operation, which might take an
202 * arbitrarily long time. During that delay the host might give up on
203 * the original ep0 request and issue a new one. When that happens the
204 * driver should not notify the host about completion of the original
205 * request, as the host will no longer be waiting for it. So the driver
206 * assigns to each ep0 request a unique tag, and it keeps track of the
207 * tag value of the request associated with a long-running exception
208 * (device-reset, interface-change, or configuration-change). When the
209 * exception handler is finished, the status-stage response is submitted
210 * only if the current ep0 request tag is equal to the exception request
211 * tag. Thus only the most recently received ep0 request will get a
212 * status-stage response.
213 *
214 * Warning: This driver source file is too long. It ought to be split up
215 * into a header file plus about 3 separate .c files, to handle the details
216 * of the Gadget, USB Mass Storage, and SCSI protocols.
217 */
218
219
220#undef DEBUG
221#undef VERBOSE
222#undef DUMP_MSGS
223
Linus Torvalds1da177e2005-04-16 15:20:36 -0700224
225#include <asm/system.h>
226#include <asm/uaccess.h>
227
228#include <linux/bitops.h>
229#include <linux/blkdev.h>
230#include <linux/compiler.h>
231#include <linux/completion.h>
232#include <linux/dcache.h>
233#include <linux/delay.h>
234#include <linux/device.h>
235#include <linux/fcntl.h>
236#include <linux/file.h>
237#include <linux/fs.h>
238#include <linux/init.h>
239#include <linux/kernel.h>
Alan Stern87c42522005-11-09 16:59:56 -0500240#include <linux/kref.h>
Alan Stern22efcf42005-09-26 16:12:02 -0400241#include <linux/kthread.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700242#include <linux/limits.h>
243#include <linux/list.h>
244#include <linux/module.h>
245#include <linux/moduleparam.h>
246#include <linux/pagemap.h>
247#include <linux/rwsem.h>
248#include <linux/sched.h>
249#include <linux/signal.h>
250#include <linux/slab.h>
251#include <linux/spinlock.h>
252#include <linux/string.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -0800253#include <linux/freezer.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700254#include <linux/utsname.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700255
David Brownell5f848132006-12-16 15:34:53 -0800256#include <linux/usb/ch9.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -0700257#include <linux/usb_gadget.h>
258
259#include "gadget_chips.h"
260
261
262/*-------------------------------------------------------------------------*/
263
264#define DRIVER_DESC "File-backed Storage Gadget"
265#define DRIVER_NAME "g_file_storage"
Alan Sterna21d4fe2005-11-29 12:04:24 -0500266#define DRIVER_VERSION "28 November 2005"
Linus Torvalds1da177e2005-04-16 15:20:36 -0700267
268static const char longname[] = DRIVER_DESC;
269static const char shortname[] = DRIVER_NAME;
270
271MODULE_DESCRIPTION(DRIVER_DESC);
272MODULE_AUTHOR("Alan Stern");
273MODULE_LICENSE("Dual BSD/GPL");
274
275/* Thanks to NetChip Technologies for donating this product ID.
276 *
277 * DO NOT REUSE THESE IDs with any other driver!! Ever!!
278 * Instead: allocate your own, using normal USB-IF procedures. */
279#define DRIVER_VENDOR_ID 0x0525 // NetChip
280#define DRIVER_PRODUCT_ID 0xa4a5 // Linux-USB File-backed Storage Gadget
281
282
283/*
284 * This driver assumes self-powered hardware and has no way for users to
285 * trigger remote wakeup. It uses autoconfiguration to select endpoints
286 * and endpoint addresses.
287 */
288
289
290/*-------------------------------------------------------------------------*/
291
292#define xprintk(f,level,fmt,args...) \
293 dev_printk(level , &(f)->gadget->dev , fmt , ## args)
294#define yprintk(l,level,fmt,args...) \
295 dev_printk(level , &(l)->dev , fmt , ## args)
296
297#ifdef DEBUG
298#define DBG(fsg,fmt,args...) \
299 xprintk(fsg , KERN_DEBUG , fmt , ## args)
300#define LDBG(lun,fmt,args...) \
301 yprintk(lun , KERN_DEBUG , fmt , ## args)
302#define MDBG(fmt,args...) \
303 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
304#else
305#define DBG(fsg,fmt,args...) \
306 do { } while (0)
307#define LDBG(lun,fmt,args...) \
308 do { } while (0)
309#define MDBG(fmt,args...) \
310 do { } while (0)
311#undef VERBOSE
312#undef DUMP_MSGS
313#endif /* DEBUG */
314
315#ifdef VERBOSE
316#define VDBG DBG
317#define VLDBG LDBG
318#else
319#define VDBG(fsg,fmt,args...) \
320 do { } while (0)
321#define VLDBG(lun,fmt,args...) \
322 do { } while (0)
323#endif /* VERBOSE */
324
325#define ERROR(fsg,fmt,args...) \
326 xprintk(fsg , KERN_ERR , fmt , ## args)
327#define LERROR(lun,fmt,args...) \
328 yprintk(lun , KERN_ERR , fmt , ## args)
329
330#define WARN(fsg,fmt,args...) \
331 xprintk(fsg , KERN_WARNING , fmt , ## args)
332#define LWARN(lun,fmt,args...) \
333 yprintk(lun , KERN_WARNING , fmt , ## args)
334
335#define INFO(fsg,fmt,args...) \
336 xprintk(fsg , KERN_INFO , fmt , ## args)
337#define LINFO(lun,fmt,args...) \
338 yprintk(lun , KERN_INFO , fmt , ## args)
339
340#define MINFO(fmt,args...) \
341 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
342
343
344/*-------------------------------------------------------------------------*/
345
346/* Encapsulate the module parameter settings */
347
348#define MAX_LUNS 8
349
Linus Torvalds1da177e2005-04-16 15:20:36 -0700350static struct {
Alan Sternaafe5bd2006-03-31 11:46:43 -0500351 char *file[MAX_LUNS];
352 int ro[MAX_LUNS];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700353 int num_filenames;
354 int num_ros;
355 unsigned int nluns;
356
Alan Sternd794ac72005-04-18 12:43:25 -0400357 int removable;
358 int can_stall;
359
Linus Torvalds1da177e2005-04-16 15:20:36 -0700360 char *transport_parm;
361 char *protocol_parm;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700362 unsigned short vendor;
363 unsigned short product;
364 unsigned short release;
365 unsigned int buflen;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700366
367 int transport_type;
368 char *transport_name;
369 int protocol_type;
370 char *protocol_name;
371
372} mod_data = { // Default values
373 .transport_parm = "BBB",
374 .protocol_parm = "SCSI",
375 .removable = 0,
Alan Sternd794ac72005-04-18 12:43:25 -0400376 .can_stall = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700377 .vendor = DRIVER_VENDOR_ID,
378 .product = DRIVER_PRODUCT_ID,
379 .release = 0xffff, // Use controller chip type
380 .buflen = 16384,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700381 };
382
383
Alan Sternaafe5bd2006-03-31 11:46:43 -0500384module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
385 S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700386MODULE_PARM_DESC(file, "names of backing files or devices");
387
Alan Sternaafe5bd2006-03-31 11:46:43 -0500388module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700389MODULE_PARM_DESC(ro, "true to force read-only");
390
391module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
392MODULE_PARM_DESC(luns, "number of LUNs");
393
394module_param_named(removable, mod_data.removable, bool, S_IRUGO);
395MODULE_PARM_DESC(removable, "true to simulate removable media");
396
Alan Sternd794ac72005-04-18 12:43:25 -0400397module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
398MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
399
Linus Torvalds1da177e2005-04-16 15:20:36 -0700400
401/* In the non-TEST version, only the module parameters listed above
402 * are available. */
403#ifdef CONFIG_USB_FILE_STORAGE_TEST
404
405module_param_named(transport, mod_data.transport_parm, charp, S_IRUGO);
406MODULE_PARM_DESC(transport, "type of transport (BBB, CBI, or CB)");
407
408module_param_named(protocol, mod_data.protocol_parm, charp, S_IRUGO);
409MODULE_PARM_DESC(protocol, "type of protocol (RBC, 8020, QIC, UFI, "
410 "8070, or SCSI)");
411
412module_param_named(vendor, mod_data.vendor, ushort, S_IRUGO);
413MODULE_PARM_DESC(vendor, "USB Vendor ID");
414
415module_param_named(product, mod_data.product, ushort, S_IRUGO);
416MODULE_PARM_DESC(product, "USB Product ID");
417
418module_param_named(release, mod_data.release, ushort, S_IRUGO);
419MODULE_PARM_DESC(release, "USB release number");
420
421module_param_named(buflen, mod_data.buflen, uint, S_IRUGO);
422MODULE_PARM_DESC(buflen, "I/O buffer size");
423
Linus Torvalds1da177e2005-04-16 15:20:36 -0700424#endif /* CONFIG_USB_FILE_STORAGE_TEST */
425
426
427/*-------------------------------------------------------------------------*/
428
429/* USB protocol value = the transport method */
430#define USB_PR_CBI 0x00 // Control/Bulk/Interrupt
431#define USB_PR_CB 0x01 // Control/Bulk w/o interrupt
432#define USB_PR_BULK 0x50 // Bulk-only
433
434/* USB subclass value = the protocol encapsulation */
435#define USB_SC_RBC 0x01 // Reduced Block Commands (flash)
436#define USB_SC_8020 0x02 // SFF-8020i, MMC-2, ATAPI (CD-ROM)
437#define USB_SC_QIC 0x03 // QIC-157 (tape)
438#define USB_SC_UFI 0x04 // UFI (floppy)
439#define USB_SC_8070 0x05 // SFF-8070i (removable)
440#define USB_SC_SCSI 0x06 // Transparent SCSI
441
442/* Bulk-only data structures */
443
444/* Command Block Wrapper */
445struct bulk_cb_wrap {
446 __le32 Signature; // Contains 'USBC'
447 u32 Tag; // Unique per command id
448 __le32 DataTransferLength; // Size of the data
449 u8 Flags; // Direction in bit 7
450 u8 Lun; // LUN (normally 0)
451 u8 Length; // Of the CDB, <= MAX_COMMAND_SIZE
452 u8 CDB[16]; // Command Data Block
453};
454
455#define USB_BULK_CB_WRAP_LEN 31
456#define USB_BULK_CB_SIG 0x43425355 // Spells out USBC
457#define USB_BULK_IN_FLAG 0x80
458
459/* Command Status Wrapper */
460struct bulk_cs_wrap {
461 __le32 Signature; // Should = 'USBS'
462 u32 Tag; // Same as original command
463 __le32 Residue; // Amount not transferred
464 u8 Status; // See below
465};
466
467#define USB_BULK_CS_WRAP_LEN 13
468#define USB_BULK_CS_SIG 0x53425355 // Spells out 'USBS'
469#define USB_STATUS_PASS 0
470#define USB_STATUS_FAIL 1
471#define USB_STATUS_PHASE_ERROR 2
472
473/* Bulk-only class specific requests */
474#define USB_BULK_RESET_REQUEST 0xff
475#define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
476
477
478/* CBI Interrupt data structure */
479struct interrupt_data {
480 u8 bType;
481 u8 bValue;
482};
483
484#define CBI_INTERRUPT_DATA_LEN 2
485
486/* CBI Accept Device-Specific Command request */
487#define USB_CBI_ADSC_REQUEST 0x00
488
489
490#define MAX_COMMAND_SIZE 16 // Length of a SCSI Command Data Block
491
492/* SCSI commands that we recognize */
493#define SC_FORMAT_UNIT 0x04
494#define SC_INQUIRY 0x12
495#define SC_MODE_SELECT_6 0x15
496#define SC_MODE_SELECT_10 0x55
497#define SC_MODE_SENSE_6 0x1a
498#define SC_MODE_SENSE_10 0x5a
499#define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
500#define SC_READ_6 0x08
501#define SC_READ_10 0x28
502#define SC_READ_12 0xa8
503#define SC_READ_CAPACITY 0x25
504#define SC_READ_FORMAT_CAPACITIES 0x23
505#define SC_RELEASE 0x17
506#define SC_REQUEST_SENSE 0x03
507#define SC_RESERVE 0x16
508#define SC_SEND_DIAGNOSTIC 0x1d
509#define SC_START_STOP_UNIT 0x1b
510#define SC_SYNCHRONIZE_CACHE 0x35
511#define SC_TEST_UNIT_READY 0x00
512#define SC_VERIFY 0x2f
513#define SC_WRITE_6 0x0a
514#define SC_WRITE_10 0x2a
515#define SC_WRITE_12 0xaa
516
517/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
518#define SS_NO_SENSE 0
519#define SS_COMMUNICATION_FAILURE 0x040800
520#define SS_INVALID_COMMAND 0x052000
521#define SS_INVALID_FIELD_IN_CDB 0x052400
522#define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
523#define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
524#define SS_MEDIUM_NOT_PRESENT 0x023a00
525#define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
526#define SS_NOT_READY_TO_READY_TRANSITION 0x062800
527#define SS_RESET_OCCURRED 0x062900
528#define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
529#define SS_UNRECOVERED_READ_ERROR 0x031100
530#define SS_WRITE_ERROR 0x030c02
531#define SS_WRITE_PROTECTED 0x072700
532
533#define SK(x) ((u8) ((x) >> 16)) // Sense Key byte, etc.
534#define ASC(x) ((u8) ((x) >> 8))
535#define ASCQ(x) ((u8) (x))
536
537
538/*-------------------------------------------------------------------------*/
539
540/*
541 * These definitions will permit the compiler to avoid generating code for
542 * parts of the driver that aren't used in the non-TEST version. Even gcc
543 * can recognize when a test of a constant expression yields a dead code
544 * path.
545 */
546
547#ifdef CONFIG_USB_FILE_STORAGE_TEST
548
549#define transport_is_bbb() (mod_data.transport_type == USB_PR_BULK)
550#define transport_is_cbi() (mod_data.transport_type == USB_PR_CBI)
551#define protocol_is_scsi() (mod_data.protocol_type == USB_SC_SCSI)
552
553#else
554
555#define transport_is_bbb() 1
556#define transport_is_cbi() 0
557#define protocol_is_scsi() 1
558
559#endif /* CONFIG_USB_FILE_STORAGE_TEST */
560
561
562struct lun {
563 struct file *filp;
564 loff_t file_length;
565 loff_t num_sectors;
566
567 unsigned int ro : 1;
568 unsigned int prevent_medium_removal : 1;
569 unsigned int registered : 1;
Alan Stern6174d0f2006-09-26 14:51:48 -0400570 unsigned int info_valid : 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700571
572 u32 sense_data;
573 u32 sense_data_info;
574 u32 unit_attention_data;
575
576 struct device dev;
577};
578
579#define backing_file_is_open(curlun) ((curlun)->filp != NULL)
580
581static inline struct lun *dev_to_lun(struct device *dev)
582{
583 return container_of(dev, struct lun, dev);
584}
585
586
587/* Big enough to hold our biggest descriptor */
588#define EP0_BUFSIZE 256
589#define DELAYED_STATUS (EP0_BUFSIZE + 999) // An impossibly large value
590
591/* Number of buffers we will use. 2 is enough for double-buffering */
592#define NUM_BUFFERS 2
593
594enum fsg_buffer_state {
595 BUF_STATE_EMPTY = 0,
596 BUF_STATE_FULL,
597 BUF_STATE_BUSY
598};
599
600struct fsg_buffhd {
601 void *buf;
602 dma_addr_t dma;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500603 enum fsg_buffer_state state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700604 struct fsg_buffhd *next;
605
606 /* The NetChip 2280 is faster, and handles some protocol faults
607 * better, if we don't submit any short bulk-out read requests.
608 * So we will record the intended request length here. */
609 unsigned int bulk_out_intended_length;
610
611 struct usb_request *inreq;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500612 int inreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700613 struct usb_request *outreq;
Alan Sterna21d4fe2005-11-29 12:04:24 -0500614 int outreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700615};
616
617enum fsg_state {
618 FSG_STATE_COMMAND_PHASE = -10, // This one isn't used anywhere
619 FSG_STATE_DATA_PHASE,
620 FSG_STATE_STATUS_PHASE,
621
622 FSG_STATE_IDLE = 0,
623 FSG_STATE_ABORT_BULK_OUT,
624 FSG_STATE_RESET,
625 FSG_STATE_INTERFACE_CHANGE,
626 FSG_STATE_CONFIG_CHANGE,
627 FSG_STATE_DISCONNECT,
628 FSG_STATE_EXIT,
629 FSG_STATE_TERMINATED
630};
631
632enum data_direction {
633 DATA_DIR_UNKNOWN = 0,
634 DATA_DIR_FROM_HOST,
635 DATA_DIR_TO_HOST,
636 DATA_DIR_NONE
637};
638
639struct fsg_dev {
640 /* lock protects: state, all the req_busy's, and cbbuf_cmnd */
641 spinlock_t lock;
642 struct usb_gadget *gadget;
643
644 /* filesem protects: backing files in use */
645 struct rw_semaphore filesem;
646
Alan Stern87c42522005-11-09 16:59:56 -0500647 /* reference counting: wait until all LUNs are released */
648 struct kref ref;
649
Linus Torvalds1da177e2005-04-16 15:20:36 -0700650 struct usb_ep *ep0; // Handy copy of gadget->ep0
651 struct usb_request *ep0req; // For control responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500652 unsigned int ep0_req_tag;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700653 const char *ep0req_name;
654
655 struct usb_request *intreq; // For interrupt responses
Alan Sterna21d4fe2005-11-29 12:04:24 -0500656 int intreq_busy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700657 struct fsg_buffhd *intr_buffhd;
658
659 unsigned int bulk_out_maxpacket;
660 enum fsg_state state; // For exception handling
661 unsigned int exception_req_tag;
662
663 u8 config, new_config;
664
665 unsigned int running : 1;
666 unsigned int bulk_in_enabled : 1;
667 unsigned int bulk_out_enabled : 1;
668 unsigned int intr_in_enabled : 1;
669 unsigned int phase_error : 1;
670 unsigned int short_packet_received : 1;
671 unsigned int bad_lun_okay : 1;
672
673 unsigned long atomic_bitflags;
674#define REGISTERED 0
675#define CLEAR_BULK_HALTS 1
676#define SUSPENDED 2
677
678 struct usb_ep *bulk_in;
679 struct usb_ep *bulk_out;
680 struct usb_ep *intr_in;
681
682 struct fsg_buffhd *next_buffhd_to_fill;
683 struct fsg_buffhd *next_buffhd_to_drain;
684 struct fsg_buffhd buffhds[NUM_BUFFERS];
685
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686 int thread_wakeup_needed;
687 struct completion thread_notifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688 struct task_struct *thread_task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700689
690 int cmnd_size;
691 u8 cmnd[MAX_COMMAND_SIZE];
692 enum data_direction data_dir;
693 u32 data_size;
694 u32 data_size_from_cmnd;
695 u32 tag;
696 unsigned int lun;
697 u32 residue;
698 u32 usb_amount_left;
699
700 /* The CB protocol offers no way for a host to know when a command
701 * has completed. As a result the next command may arrive early,
702 * and we will still have to handle it. For that reason we need
703 * a buffer to store new commands when using CB (or CBI, which
704 * does not oblige a host to wait for command completion either). */
705 int cbbuf_cmnd_size;
706 u8 cbbuf_cmnd[MAX_COMMAND_SIZE];
707
708 unsigned int nluns;
709 struct lun *luns;
710 struct lun *curlun;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700711};
712
713typedef void (*fsg_routine_t)(struct fsg_dev *);
714
715static int inline exception_in_progress(struct fsg_dev *fsg)
716{
717 return (fsg->state > FSG_STATE_IDLE);
718}
719
720/* Make bulk-out requests be divisible by the maxpacket size */
721static void inline set_bulk_out_req_length(struct fsg_dev *fsg,
722 struct fsg_buffhd *bh, unsigned int length)
723{
724 unsigned int rem;
725
726 bh->bulk_out_intended_length = length;
727 rem = length % fsg->bulk_out_maxpacket;
728 if (rem > 0)
729 length += fsg->bulk_out_maxpacket - rem;
730 bh->outreq->length = length;
731}
732
733static struct fsg_dev *the_fsg;
734static struct usb_gadget_driver fsg_driver;
735
736static void close_backing_file(struct lun *curlun);
737static void close_all_backing_files(struct fsg_dev *fsg);
738
739
740/*-------------------------------------------------------------------------*/
741
742#ifdef DUMP_MSGS
743
744static void dump_msg(struct fsg_dev *fsg, const char *label,
745 const u8 *buf, unsigned int length)
746{
747 unsigned int start, num, i;
748 char line[52], *p;
749
750 if (length >= 512)
751 return;
752 DBG(fsg, "%s, length %u:\n", label, length);
753
754 start = 0;
755 while (length > 0) {
756 num = min(length, 16u);
757 p = line;
758 for (i = 0; i < num; ++i) {
759 if (i == 8)
760 *p++ = ' ';
761 sprintf(p, " %02x", buf[i]);
762 p += 3;
763 }
764 *p = 0;
765 printk(KERN_DEBUG "%6x: %s\n", start, line);
766 buf += num;
767 start += num;
768 length -= num;
769 }
770}
771
772static void inline dump_cdb(struct fsg_dev *fsg)
773{}
774
775#else
776
777static void inline dump_msg(struct fsg_dev *fsg, const char *label,
778 const u8 *buf, unsigned int length)
779{}
780
781static void inline dump_cdb(struct fsg_dev *fsg)
782{
783 int i;
784 char cmdbuf[3*MAX_COMMAND_SIZE + 1];
785
786 for (i = 0; i < fsg->cmnd_size; ++i)
787 sprintf(cmdbuf + i*3, " %02x", fsg->cmnd[i]);
788 VDBG(fsg, "SCSI CDB: %s\n", cmdbuf);
789}
790
791#endif /* DUMP_MSGS */
792
793
794static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
795{
796 const char *name;
797
798 if (ep == fsg->bulk_in)
799 name = "bulk-in";
800 else if (ep == fsg->bulk_out)
801 name = "bulk-out";
802 else
803 name = ep->name;
804 DBG(fsg, "%s set halt\n", name);
805 return usb_ep_set_halt(ep);
806}
807
808
809/*-------------------------------------------------------------------------*/
810
811/* Routines for unaligned data access */
812
813static u16 inline get_be16(u8 *buf)
814{
815 return ((u16) buf[0] << 8) | ((u16) buf[1]);
816}
817
818static u32 inline get_be32(u8 *buf)
819{
820 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
821 ((u32) buf[2] << 8) | ((u32) buf[3]);
822}
823
824static void inline put_be16(u8 *buf, u16 val)
825{
826 buf[0] = val >> 8;
827 buf[1] = val;
828}
829
830static void inline put_be32(u8 *buf, u32 val)
831{
832 buf[0] = val >> 24;
833 buf[1] = val >> 16;
834 buf[2] = val >> 8;
David Brownell1bbc1692005-05-07 13:05:13 -0700835 buf[3] = val & 0xff;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700836}
837
838
839/*-------------------------------------------------------------------------*/
840
841/*
842 * DESCRIPTORS ... most are static, but strings and (full) configuration
843 * descriptors are built on demand. Also the (static) config and interface
844 * descriptors are adjusted during fsg_bind().
845 */
846#define STRING_MANUFACTURER 1
847#define STRING_PRODUCT 2
848#define STRING_SERIAL 3
849#define STRING_CONFIG 4
850#define STRING_INTERFACE 5
851
852/* There is only one configuration. */
853#define CONFIG_VALUE 1
854
855static struct usb_device_descriptor
856device_desc = {
857 .bLength = sizeof device_desc,
858 .bDescriptorType = USB_DT_DEVICE,
859
860 .bcdUSB = __constant_cpu_to_le16(0x0200),
861 .bDeviceClass = USB_CLASS_PER_INTERFACE,
862
863 /* The next three values can be overridden by module parameters */
864 .idVendor = __constant_cpu_to_le16(DRIVER_VENDOR_ID),
865 .idProduct = __constant_cpu_to_le16(DRIVER_PRODUCT_ID),
866 .bcdDevice = __constant_cpu_to_le16(0xffff),
867
868 .iManufacturer = STRING_MANUFACTURER,
869 .iProduct = STRING_PRODUCT,
870 .iSerialNumber = STRING_SERIAL,
871 .bNumConfigurations = 1,
872};
873
874static struct usb_config_descriptor
875config_desc = {
876 .bLength = sizeof config_desc,
877 .bDescriptorType = USB_DT_CONFIG,
878
879 /* wTotalLength computed by usb_gadget_config_buf() */
880 .bNumInterfaces = 1,
881 .bConfigurationValue = CONFIG_VALUE,
882 .iConfiguration = STRING_CONFIG,
883 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
884 .bMaxPower = 1, // self-powered
885};
886
887static struct usb_otg_descriptor
888otg_desc = {
889 .bLength = sizeof(otg_desc),
890 .bDescriptorType = USB_DT_OTG,
891
892 .bmAttributes = USB_OTG_SRP,
893};
894
895/* There is only one interface. */
896
897static struct usb_interface_descriptor
898intf_desc = {
899 .bLength = sizeof intf_desc,
900 .bDescriptorType = USB_DT_INTERFACE,
901
902 .bNumEndpoints = 2, // Adjusted during fsg_bind()
903 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
904 .bInterfaceSubClass = USB_SC_SCSI, // Adjusted during fsg_bind()
905 .bInterfaceProtocol = USB_PR_BULK, // Adjusted during fsg_bind()
906 .iInterface = STRING_INTERFACE,
907};
908
909/* Three full-speed endpoint descriptors: bulk-in, bulk-out,
910 * and interrupt-in. */
911
912static struct usb_endpoint_descriptor
913fs_bulk_in_desc = {
914 .bLength = USB_DT_ENDPOINT_SIZE,
915 .bDescriptorType = USB_DT_ENDPOINT,
916
917 .bEndpointAddress = USB_DIR_IN,
918 .bmAttributes = USB_ENDPOINT_XFER_BULK,
919 /* wMaxPacketSize set by autoconfiguration */
920};
921
922static struct usb_endpoint_descriptor
923fs_bulk_out_desc = {
924 .bLength = USB_DT_ENDPOINT_SIZE,
925 .bDescriptorType = USB_DT_ENDPOINT,
926
927 .bEndpointAddress = USB_DIR_OUT,
928 .bmAttributes = USB_ENDPOINT_XFER_BULK,
929 /* wMaxPacketSize set by autoconfiguration */
930};
931
932static struct usb_endpoint_descriptor
933fs_intr_in_desc = {
934 .bLength = USB_DT_ENDPOINT_SIZE,
935 .bDescriptorType = USB_DT_ENDPOINT,
936
937 .bEndpointAddress = USB_DIR_IN,
938 .bmAttributes = USB_ENDPOINT_XFER_INT,
939 .wMaxPacketSize = __constant_cpu_to_le16(2),
940 .bInterval = 32, // frames -> 32 ms
941};
942
943static const struct usb_descriptor_header *fs_function[] = {
944 (struct usb_descriptor_header *) &otg_desc,
945 (struct usb_descriptor_header *) &intf_desc,
946 (struct usb_descriptor_header *) &fs_bulk_in_desc,
947 (struct usb_descriptor_header *) &fs_bulk_out_desc,
948 (struct usb_descriptor_header *) &fs_intr_in_desc,
949 NULL,
950};
951#define FS_FUNCTION_PRE_EP_ENTRIES 2
952
953
954#ifdef CONFIG_USB_GADGET_DUALSPEED
955
956/*
957 * USB 2.0 devices need to expose both high speed and full speed
958 * descriptors, unless they only run at full speed.
959 *
960 * That means alternate endpoint descriptors (bigger packets)
961 * and a "device qualifier" ... plus more construction options
962 * for the config descriptor.
963 */
964static struct usb_qualifier_descriptor
965dev_qualifier = {
966 .bLength = sizeof dev_qualifier,
967 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
968
969 .bcdUSB = __constant_cpu_to_le16(0x0200),
970 .bDeviceClass = USB_CLASS_PER_INTERFACE,
971
972 .bNumConfigurations = 1,
973};
974
975static struct usb_endpoint_descriptor
976hs_bulk_in_desc = {
977 .bLength = USB_DT_ENDPOINT_SIZE,
978 .bDescriptorType = USB_DT_ENDPOINT,
979
980 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
981 .bmAttributes = USB_ENDPOINT_XFER_BULK,
982 .wMaxPacketSize = __constant_cpu_to_le16(512),
983};
984
985static struct usb_endpoint_descriptor
986hs_bulk_out_desc = {
987 .bLength = USB_DT_ENDPOINT_SIZE,
988 .bDescriptorType = USB_DT_ENDPOINT,
989
990 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
991 .bmAttributes = USB_ENDPOINT_XFER_BULK,
992 .wMaxPacketSize = __constant_cpu_to_le16(512),
993 .bInterval = 1, // NAK every 1 uframe
994};
995
996static struct usb_endpoint_descriptor
997hs_intr_in_desc = {
998 .bLength = USB_DT_ENDPOINT_SIZE,
999 .bDescriptorType = USB_DT_ENDPOINT,
1000
1001 /* bEndpointAddress copied from fs_intr_in_desc during fsg_bind() */
1002 .bmAttributes = USB_ENDPOINT_XFER_INT,
1003 .wMaxPacketSize = __constant_cpu_to_le16(2),
1004 .bInterval = 9, // 2**(9-1) = 256 uframes -> 32 ms
1005};
1006
1007static const struct usb_descriptor_header *hs_function[] = {
1008 (struct usb_descriptor_header *) &otg_desc,
1009 (struct usb_descriptor_header *) &intf_desc,
1010 (struct usb_descriptor_header *) &hs_bulk_in_desc,
1011 (struct usb_descriptor_header *) &hs_bulk_out_desc,
1012 (struct usb_descriptor_header *) &hs_intr_in_desc,
1013 NULL,
1014};
1015#define HS_FUNCTION_PRE_EP_ENTRIES 2
1016
1017/* Maxpacket and other transfer characteristics vary by speed. */
1018#define ep_desc(g,fs,hs) (((g)->speed==USB_SPEED_HIGH) ? (hs) : (fs))
1019
1020#else
1021
1022/* If there's no high speed support, always use the full-speed descriptor. */
1023#define ep_desc(g,fs,hs) fs
1024
1025#endif /* !CONFIG_USB_GADGET_DUALSPEED */
1026
1027
1028/* The CBI specification limits the serial string to 12 uppercase hexadecimal
1029 * characters. */
1030static char manufacturer[64];
1031static char serial[13];
1032
1033/* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
1034static struct usb_string strings[] = {
1035 {STRING_MANUFACTURER, manufacturer},
1036 {STRING_PRODUCT, longname},
1037 {STRING_SERIAL, serial},
1038 {STRING_CONFIG, "Self-powered"},
1039 {STRING_INTERFACE, "Mass Storage"},
1040 {}
1041};
1042
1043static struct usb_gadget_strings stringtab = {
1044 .language = 0x0409, // en-us
1045 .strings = strings,
1046};
1047
1048
1049/*
1050 * Config descriptors must agree with the code that sets configurations
1051 * and with code managing interfaces and their altsettings. They must
1052 * also handle different speeds and other-speed requests.
1053 */
1054static int populate_config_buf(struct usb_gadget *gadget,
1055 u8 *buf, u8 type, unsigned index)
1056{
1057#ifdef CONFIG_USB_GADGET_DUALSPEED
1058 enum usb_device_speed speed = gadget->speed;
1059#endif
1060 int len;
1061 const struct usb_descriptor_header **function;
1062
1063 if (index > 0)
1064 return -EINVAL;
1065
1066#ifdef CONFIG_USB_GADGET_DUALSPEED
1067 if (type == USB_DT_OTHER_SPEED_CONFIG)
1068 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
1069 if (speed == USB_SPEED_HIGH)
1070 function = hs_function;
1071 else
1072#endif
1073 function = fs_function;
1074
1075 /* for now, don't advertise srp-only devices */
1076 if (!gadget->is_otg)
1077 function++;
1078
1079 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
1080 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1081 return len;
1082}
1083
1084
1085/*-------------------------------------------------------------------------*/
1086
1087/* These routines may be called in process context or in_irq */
1088
Alan Sterna21d4fe2005-11-29 12:04:24 -05001089/* Caller must hold fsg->lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001090static void wakeup_thread(struct fsg_dev *fsg)
1091{
1092 /* Tell the main thread that something has happened */
1093 fsg->thread_wakeup_needed = 1;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001094 if (fsg->thread_task)
1095 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001096}
1097
1098
1099static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
1100{
1101 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001102
1103 /* Do nothing if a higher-priority exception is already in progress.
1104 * If a lower-or-equal priority exception is in progress, preempt it
1105 * and notify the main thread by sending it a signal. */
1106 spin_lock_irqsave(&fsg->lock, flags);
1107 if (fsg->state <= new_state) {
1108 fsg->exception_req_tag = fsg->ep0_req_tag;
1109 fsg->state = new_state;
Alan Stern22efcf42005-09-26 16:12:02 -04001110 if (fsg->thread_task)
1111 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
1112 fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001113 }
1114 spin_unlock_irqrestore(&fsg->lock, flags);
1115}
1116
1117
1118/*-------------------------------------------------------------------------*/
1119
1120/* The disconnect callback and ep0 routines. These always run in_irq,
1121 * except that ep0_queue() is called in the main thread to acknowledge
1122 * completion of various requests: set config, set interface, and
1123 * Bulk-only device reset. */
1124
1125static void fsg_disconnect(struct usb_gadget *gadget)
1126{
1127 struct fsg_dev *fsg = get_gadget_data(gadget);
1128
1129 DBG(fsg, "disconnect or port reset\n");
1130 raise_exception(fsg, FSG_STATE_DISCONNECT);
1131}
1132
1133
1134static int ep0_queue(struct fsg_dev *fsg)
1135{
1136 int rc;
1137
1138 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
1139 if (rc != 0 && rc != -ESHUTDOWN) {
1140
1141 /* We can't do much more than wait for a reset */
1142 WARN(fsg, "error in submission: %s --> %d\n",
1143 fsg->ep0->name, rc);
1144 }
1145 return rc;
1146}
1147
1148static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
1149{
John Daiker7ca46b82006-12-29 19:02:06 -08001150 struct fsg_dev *fsg = ep->driver_data;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001151
1152 if (req->actual > 0)
1153 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
1154 if (req->status || req->actual != req->length)
1155 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1156 req->status, req->actual, req->length);
1157 if (req->status == -ECONNRESET) // Request was cancelled
1158 usb_ep_fifo_flush(ep);
1159
1160 if (req->status == 0 && req->context)
1161 ((fsg_routine_t) (req->context))(fsg);
1162}
1163
1164
1165/*-------------------------------------------------------------------------*/
1166
1167/* Bulk and interrupt endpoint completion handlers.
1168 * These always run in_irq. */
1169
1170static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
1171{
John Daiker7ca46b82006-12-29 19:02:06 -08001172 struct fsg_dev *fsg = ep->driver_data;
1173 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001174
1175 if (req->status || req->actual != req->length)
1176 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1177 req->status, req->actual, req->length);
1178 if (req->status == -ECONNRESET) // Request was cancelled
1179 usb_ep_fifo_flush(ep);
1180
1181 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001182 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001183 spin_lock(&fsg->lock);
1184 bh->inreq_busy = 0;
1185 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001186 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001187 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001188}
1189
1190static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
1191{
John Daiker7ca46b82006-12-29 19:02:06 -08001192 struct fsg_dev *fsg = ep->driver_data;
1193 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001194
1195 dump_msg(fsg, "bulk-out", req->buf, req->actual);
1196 if (req->status || req->actual != bh->bulk_out_intended_length)
1197 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1198 req->status, req->actual,
1199 bh->bulk_out_intended_length);
1200 if (req->status == -ECONNRESET) // Request was cancelled
1201 usb_ep_fifo_flush(ep);
1202
1203 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001204 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001205 spin_lock(&fsg->lock);
1206 bh->outreq_busy = 0;
1207 bh->state = BUF_STATE_FULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001208 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001209 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001210}
1211
1212
1213#ifdef CONFIG_USB_FILE_STORAGE_TEST
1214static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1215{
John Daiker7ca46b82006-12-29 19:02:06 -08001216 struct fsg_dev *fsg = ep->driver_data;
1217 struct fsg_buffhd *bh = req->context;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001218
1219 if (req->status || req->actual != req->length)
1220 DBG(fsg, "%s --> %d, %u/%u\n", __FUNCTION__,
1221 req->status, req->actual, req->length);
1222 if (req->status == -ECONNRESET) // Request was cancelled
1223 usb_ep_fifo_flush(ep);
1224
1225 /* Hold the lock while we update the request and buffer states */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001226 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001227 spin_lock(&fsg->lock);
1228 fsg->intreq_busy = 0;
1229 bh->state = BUF_STATE_EMPTY;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001230 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001231 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001232}
1233
1234#else
1235static void intr_in_complete(struct usb_ep *ep, struct usb_request *req)
1236{}
1237#endif /* CONFIG_USB_FILE_STORAGE_TEST */
1238
1239
1240/*-------------------------------------------------------------------------*/
1241
1242/* Ep0 class-specific handlers. These always run in_irq. */
1243
1244#ifdef CONFIG_USB_FILE_STORAGE_TEST
1245static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1246{
1247 struct usb_request *req = fsg->ep0req;
1248 static u8 cbi_reset_cmnd[6] = {
1249 SC_SEND_DIAGNOSTIC, 4, 0xff, 0xff, 0xff, 0xff};
1250
1251 /* Error in command transfer? */
1252 if (req->status || req->length != req->actual ||
1253 req->actual < 6 || req->actual > MAX_COMMAND_SIZE) {
1254
1255 /* Not all controllers allow a protocol stall after
1256 * receiving control-out data, but we'll try anyway. */
1257 fsg_set_halt(fsg, fsg->ep0);
1258 return; // Wait for reset
1259 }
1260
1261 /* Is it the special reset command? */
1262 if (req->actual >= sizeof cbi_reset_cmnd &&
1263 memcmp(req->buf, cbi_reset_cmnd,
1264 sizeof cbi_reset_cmnd) == 0) {
1265
1266 /* Raise an exception to stop the current operation
1267 * and reinitialize our state. */
1268 DBG(fsg, "cbi reset request\n");
1269 raise_exception(fsg, FSG_STATE_RESET);
1270 return;
1271 }
1272
1273 VDBG(fsg, "CB[I] accept device-specific command\n");
1274 spin_lock(&fsg->lock);
1275
1276 /* Save the command for later */
1277 if (fsg->cbbuf_cmnd_size)
1278 WARN(fsg, "CB[I] overwriting previous command\n");
1279 fsg->cbbuf_cmnd_size = req->actual;
1280 memcpy(fsg->cbbuf_cmnd, req->buf, fsg->cbbuf_cmnd_size);
1281
Linus Torvalds1da177e2005-04-16 15:20:36 -07001282 wakeup_thread(fsg);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001283 spin_unlock(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001284}
1285
1286#else
1287static void received_cbi_adsc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1288{}
1289#endif /* CONFIG_USB_FILE_STORAGE_TEST */
1290
1291
1292static int class_setup_req(struct fsg_dev *fsg,
1293 const struct usb_ctrlrequest *ctrl)
1294{
1295 struct usb_request *req = fsg->ep0req;
1296 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -07001297 u16 w_index = le16_to_cpu(ctrl->wIndex);
Luis Lloret88e45db2007-07-26 10:08:47 -04001298 u16 w_value = le16_to_cpu(ctrl->wValue);
David Brownell1bbc1692005-05-07 13:05:13 -07001299 u16 w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001300
1301 if (!fsg->config)
1302 return value;
1303
1304 /* Handle Bulk-only class-specific requests */
1305 if (transport_is_bbb()) {
1306 switch (ctrl->bRequest) {
1307
1308 case USB_BULK_RESET_REQUEST:
1309 if (ctrl->bRequestType != (USB_DIR_OUT |
1310 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1311 break;
Luis Lloret88e45db2007-07-26 10:08:47 -04001312 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001313 value = -EDOM;
1314 break;
1315 }
1316
1317 /* Raise an exception to stop the current operation
1318 * and reinitialize our state. */
1319 DBG(fsg, "bulk reset request\n");
1320 raise_exception(fsg, FSG_STATE_RESET);
1321 value = DELAYED_STATUS;
1322 break;
1323
1324 case USB_BULK_GET_MAX_LUN_REQUEST:
1325 if (ctrl->bRequestType != (USB_DIR_IN |
1326 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1327 break;
Luis Lloret88e45db2007-07-26 10:08:47 -04001328 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001329 value = -EDOM;
1330 break;
1331 }
1332 VDBG(fsg, "get max LUN\n");
1333 *(u8 *) req->buf = fsg->nluns - 1;
Alan Stern76f4af82005-04-05 11:56:54 -04001334 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001335 break;
1336 }
1337 }
1338
1339 /* Handle CBI class-specific requests */
1340 else {
1341 switch (ctrl->bRequest) {
1342
1343 case USB_CBI_ADSC_REQUEST:
1344 if (ctrl->bRequestType != (USB_DIR_OUT |
1345 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
1346 break;
Luis Lloret88e45db2007-07-26 10:08:47 -04001347 if (w_index != 0 || w_value != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001348 value = -EDOM;
1349 break;
1350 }
1351 if (w_length > MAX_COMMAND_SIZE) {
1352 value = -EOVERFLOW;
1353 break;
1354 }
1355 value = w_length;
1356 fsg->ep0req->context = received_cbi_adsc;
1357 break;
1358 }
1359 }
1360
1361 if (value == -EOPNOTSUPP)
1362 VDBG(fsg,
1363 "unknown class-specific control req "
1364 "%02x.%02x v%04x i%04x l%u\n",
1365 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001366 le16_to_cpu(ctrl->wValue), w_index, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001367 return value;
1368}
1369
1370
1371/*-------------------------------------------------------------------------*/
1372
1373/* Ep0 standard request handlers. These always run in_irq. */
1374
1375static int standard_setup_req(struct fsg_dev *fsg,
1376 const struct usb_ctrlrequest *ctrl)
1377{
1378 struct usb_request *req = fsg->ep0req;
1379 int value = -EOPNOTSUPP;
David Brownell1bbc1692005-05-07 13:05:13 -07001380 u16 w_index = le16_to_cpu(ctrl->wIndex);
1381 u16 w_value = le16_to_cpu(ctrl->wValue);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001382
1383 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
1384 * but config change events will also reconfigure hardware. */
1385 switch (ctrl->bRequest) {
1386
1387 case USB_REQ_GET_DESCRIPTOR:
1388 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1389 USB_RECIP_DEVICE))
1390 break;
1391 switch (w_value >> 8) {
1392
1393 case USB_DT_DEVICE:
1394 VDBG(fsg, "get device descriptor\n");
Alan Stern76f4af82005-04-05 11:56:54 -04001395 value = sizeof device_desc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001396 memcpy(req->buf, &device_desc, value);
1397 break;
1398#ifdef CONFIG_USB_GADGET_DUALSPEED
1399 case USB_DT_DEVICE_QUALIFIER:
1400 VDBG(fsg, "get device qualifier\n");
1401 if (!fsg->gadget->is_dualspeed)
1402 break;
Alan Stern76f4af82005-04-05 11:56:54 -04001403 value = sizeof dev_qualifier;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001404 memcpy(req->buf, &dev_qualifier, value);
1405 break;
1406
1407 case USB_DT_OTHER_SPEED_CONFIG:
1408 VDBG(fsg, "get other-speed config descriptor\n");
1409 if (!fsg->gadget->is_dualspeed)
1410 break;
1411 goto get_config;
1412#endif
1413 case USB_DT_CONFIG:
1414 VDBG(fsg, "get configuration descriptor\n");
1415#ifdef CONFIG_USB_GADGET_DUALSPEED
1416 get_config:
1417#endif
1418 value = populate_config_buf(fsg->gadget,
1419 req->buf,
1420 w_value >> 8,
1421 w_value & 0xff);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001422 break;
1423
1424 case USB_DT_STRING:
1425 VDBG(fsg, "get string descriptor\n");
1426
1427 /* wIndex == language code */
1428 value = usb_gadget_get_string(&stringtab,
1429 w_value & 0xff, req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001430 break;
1431 }
1432 break;
1433
1434 /* One config, two speeds */
1435 case USB_REQ_SET_CONFIGURATION:
1436 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
1437 USB_RECIP_DEVICE))
1438 break;
1439 VDBG(fsg, "set configuration\n");
1440 if (w_value == CONFIG_VALUE || w_value == 0) {
1441 fsg->new_config = w_value;
1442
1443 /* Raise an exception to wipe out previous transaction
1444 * state (queued bufs, etc) and set the new config. */
1445 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
1446 value = DELAYED_STATUS;
1447 }
1448 break;
1449 case USB_REQ_GET_CONFIGURATION:
1450 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1451 USB_RECIP_DEVICE))
1452 break;
1453 VDBG(fsg, "get configuration\n");
1454 *(u8 *) req->buf = fsg->config;
Alan Stern76f4af82005-04-05 11:56:54 -04001455 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001456 break;
1457
1458 case USB_REQ_SET_INTERFACE:
1459 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
1460 USB_RECIP_INTERFACE))
1461 break;
1462 if (fsg->config && w_index == 0) {
1463
1464 /* Raise an exception to wipe out previous transaction
1465 * state (queued bufs, etc) and install the new
1466 * interface altsetting. */
1467 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
1468 value = DELAYED_STATUS;
1469 }
1470 break;
1471 case USB_REQ_GET_INTERFACE:
1472 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
1473 USB_RECIP_INTERFACE))
1474 break;
1475 if (!fsg->config)
1476 break;
1477 if (w_index != 0) {
1478 value = -EDOM;
1479 break;
1480 }
1481 VDBG(fsg, "get interface\n");
1482 *(u8 *) req->buf = 0;
Alan Stern76f4af82005-04-05 11:56:54 -04001483 value = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001484 break;
1485
1486 default:
1487 VDBG(fsg,
1488 "unknown control req %02x.%02x v%04x i%04x l%u\n",
1489 ctrl->bRequestType, ctrl->bRequest,
David Brownell1bbc1692005-05-07 13:05:13 -07001490 w_value, w_index, le16_to_cpu(ctrl->wLength));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001491 }
1492
1493 return value;
1494}
1495
1496
1497static int fsg_setup(struct usb_gadget *gadget,
1498 const struct usb_ctrlrequest *ctrl)
1499{
1500 struct fsg_dev *fsg = get_gadget_data(gadget);
1501 int rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001502 int w_length = le16_to_cpu(ctrl->wLength);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001503
1504 ++fsg->ep0_req_tag; // Record arrival of a new request
1505 fsg->ep0req->context = NULL;
1506 fsg->ep0req->length = 0;
1507 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
1508
1509 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
1510 rc = class_setup_req(fsg, ctrl);
1511 else
1512 rc = standard_setup_req(fsg, ctrl);
1513
1514 /* Respond with data/status or defer until later? */
1515 if (rc >= 0 && rc != DELAYED_STATUS) {
Alan Stern76f4af82005-04-05 11:56:54 -04001516 rc = min(rc, w_length);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001517 fsg->ep0req->length = rc;
David Brownell1bbc1692005-05-07 13:05:13 -07001518 fsg->ep0req->zero = rc < w_length;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001519 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
1520 "ep0-in" : "ep0-out");
1521 rc = ep0_queue(fsg);
1522 }
1523
1524 /* Device either stalls (rc < 0) or reports success */
1525 return rc;
1526}
1527
1528
1529/*-------------------------------------------------------------------------*/
1530
1531/* All the following routines run in process context */
1532
1533
1534/* Use this for bulk or interrupt transfers, not ep0 */
1535static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
Alan Sterna21d4fe2005-11-29 12:04:24 -05001536 struct usb_request *req, int *pbusy,
1537 enum fsg_buffer_state *state)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001538{
1539 int rc;
1540
1541 if (ep == fsg->bulk_in)
1542 dump_msg(fsg, "bulk-in", req->buf, req->length);
1543 else if (ep == fsg->intr_in)
1544 dump_msg(fsg, "intr-in", req->buf, req->length);
Alan Sterna21d4fe2005-11-29 12:04:24 -05001545
1546 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001547 *pbusy = 1;
1548 *state = BUF_STATE_BUSY;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001549 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550 rc = usb_ep_queue(ep, req, GFP_KERNEL);
1551 if (rc != 0) {
1552 *pbusy = 0;
1553 *state = BUF_STATE_EMPTY;
1554
1555 /* We can't do much more than wait for a reset */
1556
1557 /* Note: currently the net2280 driver fails zero-length
1558 * submissions if DMA is enabled. */
1559 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
1560 req->length == 0))
1561 WARN(fsg, "error in submission: %s --> %d\n",
1562 ep->name, rc);
1563 }
1564}
1565
1566
1567static int sleep_thread(struct fsg_dev *fsg)
1568{
Alan Sterna21d4fe2005-11-29 12:04:24 -05001569 int rc = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001570
1571 /* Wait until a signal arrives or we are woken up */
Alan Sterna21d4fe2005-11-29 12:04:24 -05001572 for (;;) {
1573 try_to_freeze();
1574 set_current_state(TASK_INTERRUPTIBLE);
1575 if (signal_pending(current)) {
1576 rc = -EINTR;
1577 break;
1578 }
1579 if (fsg->thread_wakeup_needed)
1580 break;
1581 schedule();
1582 }
1583 __set_current_state(TASK_RUNNING);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001584 fsg->thread_wakeup_needed = 0;
Alan Sterna21d4fe2005-11-29 12:04:24 -05001585 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001586}
1587
1588
1589/*-------------------------------------------------------------------------*/
1590
1591static int do_read(struct fsg_dev *fsg)
1592{
1593 struct lun *curlun = fsg->curlun;
1594 u32 lba;
1595 struct fsg_buffhd *bh;
1596 int rc;
1597 u32 amount_left;
1598 loff_t file_offset, file_offset_tmp;
1599 unsigned int amount;
1600 unsigned int partial_page;
1601 ssize_t nread;
1602
1603 /* Get the starting Logical Block Address and check that it's
1604 * not too big */
1605 if (fsg->cmnd[0] == SC_READ_6)
1606 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1607 else {
1608 lba = get_be32(&fsg->cmnd[2]);
1609
1610 /* We allow DPO (Disable Page Out = don't save data in the
1611 * cache) and FUA (Force Unit Access = don't read from the
1612 * cache), but we don't implement them. */
1613 if ((fsg->cmnd[1] & ~0x18) != 0) {
1614 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1615 return -EINVAL;
1616 }
1617 }
1618 if (lba >= curlun->num_sectors) {
1619 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1620 return -EINVAL;
1621 }
1622 file_offset = ((loff_t) lba) << 9;
1623
1624 /* Carry out the file reads */
1625 amount_left = fsg->data_size_from_cmnd;
1626 if (unlikely(amount_left == 0))
1627 return -EIO; // No default reply
1628
1629 for (;;) {
1630
1631 /* Figure out how much we need to read:
1632 * Try to read the remaining amount.
1633 * But don't read more than the buffer size.
1634 * And don't try to read past the end of the file.
1635 * Finally, if we're not at a page boundary, don't read past
1636 * the next page.
1637 * If this means reading 0 then we were asked to read past
1638 * the end of file. */
1639 amount = min((unsigned int) amount_left, mod_data.buflen);
1640 amount = min((loff_t) amount,
1641 curlun->file_length - file_offset);
1642 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
1643 if (partial_page > 0)
1644 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
1645 partial_page);
1646
1647 /* Wait for the next buffer to become available */
1648 bh = fsg->next_buffhd_to_fill;
1649 while (bh->state != BUF_STATE_EMPTY) {
1650 if ((rc = sleep_thread(fsg)) != 0)
1651 return rc;
1652 }
1653
1654 /* If we were asked to read past the end of file,
1655 * end with an empty buffer. */
1656 if (amount == 0) {
1657 curlun->sense_data =
1658 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1659 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001660 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001661 bh->inreq->length = 0;
1662 bh->state = BUF_STATE_FULL;
1663 break;
1664 }
1665
1666 /* Perform the read */
1667 file_offset_tmp = file_offset;
1668 nread = vfs_read(curlun->filp,
1669 (char __user *) bh->buf,
1670 amount, &file_offset_tmp);
1671 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1672 (unsigned long long) file_offset,
1673 (int) nread);
1674 if (signal_pending(current))
1675 return -EINTR;
1676
1677 if (nread < 0) {
1678 LDBG(curlun, "error in file read: %d\n",
1679 (int) nread);
1680 nread = 0;
1681 } else if (nread < amount) {
1682 LDBG(curlun, "partial file read: %d/%u\n",
1683 (int) nread, amount);
1684 nread -= (nread & 511); // Round down to a block
1685 }
1686 file_offset += nread;
1687 amount_left -= nread;
1688 fsg->residue -= nread;
1689 bh->inreq->length = nread;
1690 bh->state = BUF_STATE_FULL;
1691
1692 /* If an error occurred, report it and its position */
1693 if (nread < amount) {
1694 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1695 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001696 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001697 break;
1698 }
1699
1700 if (amount_left == 0)
1701 break; // No more left to read
1702
1703 /* Send this buffer and go read some more */
1704 bh->inreq->zero = 0;
1705 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1706 &bh->inreq_busy, &bh->state);
1707 fsg->next_buffhd_to_fill = bh->next;
1708 }
1709
1710 return -EIO; // No default reply
1711}
1712
1713
1714/*-------------------------------------------------------------------------*/
1715
1716static int do_write(struct fsg_dev *fsg)
1717{
1718 struct lun *curlun = fsg->curlun;
1719 u32 lba;
1720 struct fsg_buffhd *bh;
1721 int get_some_more;
1722 u32 amount_left_to_req, amount_left_to_write;
1723 loff_t usb_offset, file_offset, file_offset_tmp;
1724 unsigned int amount;
1725 unsigned int partial_page;
1726 ssize_t nwritten;
1727 int rc;
1728
1729 if (curlun->ro) {
1730 curlun->sense_data = SS_WRITE_PROTECTED;
1731 return -EINVAL;
1732 }
1733 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1734
1735 /* Get the starting Logical Block Address and check that it's
1736 * not too big */
1737 if (fsg->cmnd[0] == SC_WRITE_6)
1738 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
1739 else {
1740 lba = get_be32(&fsg->cmnd[2]);
1741
1742 /* We allow DPO (Disable Page Out = don't save data in the
1743 * cache) and FUA (Force Unit Access = write directly to the
1744 * medium). We don't implement DPO; we implement FUA by
1745 * performing synchronous output. */
1746 if ((fsg->cmnd[1] & ~0x18) != 0) {
1747 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1748 return -EINVAL;
1749 }
1750 if (fsg->cmnd[1] & 0x08) // FUA
1751 curlun->filp->f_flags |= O_SYNC;
1752 }
1753 if (lba >= curlun->num_sectors) {
1754 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1755 return -EINVAL;
1756 }
1757
1758 /* Carry out the file writes */
1759 get_some_more = 1;
1760 file_offset = usb_offset = ((loff_t) lba) << 9;
1761 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1762
1763 while (amount_left_to_write > 0) {
1764
1765 /* Queue a request for more data from the host */
1766 bh = fsg->next_buffhd_to_fill;
1767 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1768
1769 /* Figure out how much we want to get:
1770 * Try to get the remaining amount.
1771 * But don't get more than the buffer size.
1772 * And don't try to go past the end of the file.
1773 * If we're not at a page boundary,
1774 * don't go past the next page.
1775 * If this means getting 0, then we were asked
1776 * to write past the end of file.
1777 * Finally, round down to a block boundary. */
1778 amount = min(amount_left_to_req, mod_data.buflen);
1779 amount = min((loff_t) amount, curlun->file_length -
1780 usb_offset);
1781 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1782 if (partial_page > 0)
1783 amount = min(amount,
1784 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1785
1786 if (amount == 0) {
1787 get_some_more = 0;
1788 curlun->sense_data =
1789 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1790 curlun->sense_data_info = usb_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001791 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001792 continue;
1793 }
1794 amount -= (amount & 511);
1795 if (amount == 0) {
1796
1797 /* Why were we were asked to transfer a
1798 * partial block? */
1799 get_some_more = 0;
1800 continue;
1801 }
1802
1803 /* Get the next buffer */
1804 usb_offset += amount;
1805 fsg->usb_amount_left -= amount;
1806 amount_left_to_req -= amount;
1807 if (amount_left_to_req == 0)
1808 get_some_more = 0;
1809
1810 /* amount is always divisible by 512, hence by
1811 * the bulk-out maxpacket size */
1812 bh->outreq->length = bh->bulk_out_intended_length =
1813 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05001814 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001815 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1816 &bh->outreq_busy, &bh->state);
1817 fsg->next_buffhd_to_fill = bh->next;
1818 continue;
1819 }
1820
1821 /* Write the received data to the backing file */
1822 bh = fsg->next_buffhd_to_drain;
1823 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1824 break; // We stopped early
1825 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05001826 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001827 fsg->next_buffhd_to_drain = bh->next;
1828 bh->state = BUF_STATE_EMPTY;
1829
1830 /* Did something go wrong with the transfer? */
1831 if (bh->outreq->status != 0) {
1832 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1833 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001834 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001835 break;
1836 }
1837
1838 amount = bh->outreq->actual;
1839 if (curlun->file_length - file_offset < amount) {
1840 LERROR(curlun,
1841 "write %u @ %llu beyond end %llu\n",
1842 amount, (unsigned long long) file_offset,
1843 (unsigned long long) curlun->file_length);
1844 amount = curlun->file_length - file_offset;
1845 }
1846
1847 /* Perform the write */
1848 file_offset_tmp = file_offset;
1849 nwritten = vfs_write(curlun->filp,
1850 (char __user *) bh->buf,
1851 amount, &file_offset_tmp);
1852 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1853 (unsigned long long) file_offset,
1854 (int) nwritten);
1855 if (signal_pending(current))
1856 return -EINTR; // Interrupted!
1857
1858 if (nwritten < 0) {
1859 LDBG(curlun, "error in file write: %d\n",
1860 (int) nwritten);
1861 nwritten = 0;
1862 } else if (nwritten < amount) {
1863 LDBG(curlun, "partial file write: %d/%u\n",
1864 (int) nwritten, amount);
1865 nwritten -= (nwritten & 511);
1866 // Round down to a block
1867 }
1868 file_offset += nwritten;
1869 amount_left_to_write -= nwritten;
1870 fsg->residue -= nwritten;
1871
1872 /* If an error occurred, report it and its position */
1873 if (nwritten < amount) {
1874 curlun->sense_data = SS_WRITE_ERROR;
1875 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04001876 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001877 break;
1878 }
1879
1880 /* Did the host decide to stop early? */
1881 if (bh->outreq->actual != bh->outreq->length) {
1882 fsg->short_packet_received = 1;
1883 break;
1884 }
1885 continue;
1886 }
1887
1888 /* Wait for something to happen */
1889 if ((rc = sleep_thread(fsg)) != 0)
1890 return rc;
1891 }
1892
1893 return -EIO; // No default reply
1894}
1895
1896
1897/*-------------------------------------------------------------------------*/
1898
1899/* Sync the file data, don't bother with the metadata.
1900 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1901static int fsync_sub(struct lun *curlun)
1902{
1903 struct file *filp = curlun->filp;
1904 struct inode *inode;
1905 int rc, err;
1906
1907 if (curlun->ro || !filp)
1908 return 0;
1909 if (!filp->f_op->fsync)
1910 return -EINVAL;
1911
Josef Sipek33cb8992006-12-08 02:37:46 -08001912 inode = filp->f_path.dentry->d_inode;
Jes Sorensen1b1dcc12006-01-09 15:59:24 -08001913 mutex_lock(&inode->i_mutex);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001914 rc = filemap_fdatawrite(inode->i_mapping);
Josef Sipek33cb8992006-12-08 02:37:46 -08001915 err = filp->f_op->fsync(filp, filp->f_path.dentry, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001916 if (!rc)
1917 rc = err;
1918 err = filemap_fdatawait(inode->i_mapping);
1919 if (!rc)
1920 rc = err;
Jes Sorensen1b1dcc12006-01-09 15:59:24 -08001921 mutex_unlock(&inode->i_mutex);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001922 VLDBG(curlun, "fdatasync -> %d\n", rc);
1923 return rc;
1924}
1925
1926static void fsync_all(struct fsg_dev *fsg)
1927{
1928 int i;
1929
1930 for (i = 0; i < fsg->nluns; ++i)
1931 fsync_sub(&fsg->luns[i]);
1932}
1933
1934static int do_synchronize_cache(struct fsg_dev *fsg)
1935{
1936 struct lun *curlun = fsg->curlun;
1937 int rc;
1938
1939 /* We ignore the requested LBA and write out all file's
1940 * dirty data buffers. */
1941 rc = fsync_sub(curlun);
1942 if (rc)
1943 curlun->sense_data = SS_WRITE_ERROR;
1944 return 0;
1945}
1946
1947
1948/*-------------------------------------------------------------------------*/
1949
1950static void invalidate_sub(struct lun *curlun)
1951{
1952 struct file *filp = curlun->filp;
Josef Sipek33cb8992006-12-08 02:37:46 -08001953 struct inode *inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001954 unsigned long rc;
1955
Andrew Mortonfc0ecff2007-02-10 01:45:39 -08001956 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001957 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1958}
1959
1960static int do_verify(struct fsg_dev *fsg)
1961{
1962 struct lun *curlun = fsg->curlun;
1963 u32 lba;
1964 u32 verification_length;
1965 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1966 loff_t file_offset, file_offset_tmp;
1967 u32 amount_left;
1968 unsigned int amount;
1969 ssize_t nread;
1970
1971 /* Get the starting Logical Block Address and check that it's
1972 * not too big */
1973 lba = get_be32(&fsg->cmnd[2]);
1974 if (lba >= curlun->num_sectors) {
1975 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1976 return -EINVAL;
1977 }
1978
1979 /* We allow DPO (Disable Page Out = don't save data in the
1980 * cache) but we don't implement it. */
1981 if ((fsg->cmnd[1] & ~0x10) != 0) {
1982 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1983 return -EINVAL;
1984 }
1985
1986 verification_length = get_be16(&fsg->cmnd[7]);
1987 if (unlikely(verification_length == 0))
1988 return -EIO; // No default reply
1989
1990 /* Prepare to carry out the file verify */
1991 amount_left = verification_length << 9;
1992 file_offset = ((loff_t) lba) << 9;
1993
1994 /* Write out all the dirty buffers before invalidating them */
1995 fsync_sub(curlun);
1996 if (signal_pending(current))
1997 return -EINTR;
1998
1999 invalidate_sub(curlun);
2000 if (signal_pending(current))
2001 return -EINTR;
2002
2003 /* Just try to read the requested blocks */
2004 while (amount_left > 0) {
2005
2006 /* Figure out how much we need to read:
2007 * Try to read the remaining amount, but not more than
2008 * the buffer size.
2009 * And don't try to read past the end of the file.
2010 * If this means reading 0 then we were asked to read
2011 * past the end of file. */
2012 amount = min((unsigned int) amount_left, mod_data.buflen);
2013 amount = min((loff_t) amount,
2014 curlun->file_length - file_offset);
2015 if (amount == 0) {
2016 curlun->sense_data =
2017 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
2018 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04002019 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002020 break;
2021 }
2022
2023 /* Perform the read */
2024 file_offset_tmp = file_offset;
2025 nread = vfs_read(curlun->filp,
2026 (char __user *) bh->buf,
2027 amount, &file_offset_tmp);
2028 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
2029 (unsigned long long) file_offset,
2030 (int) nread);
2031 if (signal_pending(current))
2032 return -EINTR;
2033
2034 if (nread < 0) {
2035 LDBG(curlun, "error in file verify: %d\n",
2036 (int) nread);
2037 nread = 0;
2038 } else if (nread < amount) {
2039 LDBG(curlun, "partial file verify: %d/%u\n",
2040 (int) nread, amount);
2041 nread -= (nread & 511); // Round down to a sector
2042 }
2043 if (nread == 0) {
2044 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
2045 curlun->sense_data_info = file_offset >> 9;
Alan Stern6174d0f2006-09-26 14:51:48 -04002046 curlun->info_valid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002047 break;
2048 }
2049 file_offset += nread;
2050 amount_left -= nread;
2051 }
2052 return 0;
2053}
2054
2055
2056/*-------------------------------------------------------------------------*/
2057
2058static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2059{
2060 u8 *buf = (u8 *) bh->buf;
2061
2062 static char vendor_id[] = "Linux ";
2063 static char product_id[] = "File-Stor Gadget";
2064
2065 if (!fsg->curlun) { // Unsupported LUNs are okay
2066 fsg->bad_lun_okay = 1;
2067 memset(buf, 0, 36);
2068 buf[0] = 0x7f; // Unsupported, no device-type
2069 return 36;
2070 }
2071
2072 memset(buf, 0, 8); // Non-removable, direct-access device
2073 if (mod_data.removable)
2074 buf[1] = 0x80;
2075 buf[2] = 2; // ANSI SCSI level 2
2076 buf[3] = 2; // SCSI-2 INQUIRY data format
2077 buf[4] = 31; // Additional length
2078 // No special options
2079 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id, product_id,
2080 mod_data.release);
2081 return 36;
2082}
2083
2084
2085static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2086{
2087 struct lun *curlun = fsg->curlun;
2088 u8 *buf = (u8 *) bh->buf;
2089 u32 sd, sdinfo;
Alan Stern6174d0f2006-09-26 14:51:48 -04002090 int valid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002091
2092 /*
2093 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
2094 *
2095 * If a REQUEST SENSE command is received from an initiator
2096 * with a pending unit attention condition (before the target
2097 * generates the contingent allegiance condition), then the
2098 * target shall either:
2099 * a) report any pending sense data and preserve the unit
2100 * attention condition on the logical unit, or,
2101 * b) report the unit attention condition, may discard any
2102 * pending sense data, and clear the unit attention
2103 * condition on the logical unit for that initiator.
2104 *
2105 * FSG normally uses option a); enable this code to use option b).
2106 */
2107#if 0
2108 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
2109 curlun->sense_data = curlun->unit_attention_data;
2110 curlun->unit_attention_data = SS_NO_SENSE;
2111 }
2112#endif
2113
2114 if (!curlun) { // Unsupported LUNs are okay
2115 fsg->bad_lun_okay = 1;
2116 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2117 sdinfo = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002118 valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002119 } else {
2120 sd = curlun->sense_data;
2121 sdinfo = curlun->sense_data_info;
Alan Stern6174d0f2006-09-26 14:51:48 -04002122 valid = curlun->info_valid << 7;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002123 curlun->sense_data = SS_NO_SENSE;
2124 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002125 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002126 }
2127
2128 memset(buf, 0, 18);
Alan Stern6174d0f2006-09-26 14:51:48 -04002129 buf[0] = valid | 0x70; // Valid, current error
Linus Torvalds1da177e2005-04-16 15:20:36 -07002130 buf[2] = SK(sd);
2131 put_be32(&buf[3], sdinfo); // Sense information
2132 buf[7] = 18 - 8; // Additional sense length
2133 buf[12] = ASC(sd);
2134 buf[13] = ASCQ(sd);
2135 return 18;
2136}
2137
2138
2139static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2140{
2141 struct lun *curlun = fsg->curlun;
2142 u32 lba = get_be32(&fsg->cmnd[2]);
2143 int pmi = fsg->cmnd[8];
2144 u8 *buf = (u8 *) bh->buf;
2145
2146 /* Check the PMI and LBA fields */
2147 if (pmi > 1 || (pmi == 0 && lba != 0)) {
2148 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2149 return -EINVAL;
2150 }
2151
2152 put_be32(&buf[0], curlun->num_sectors - 1); // Max logical block
2153 put_be32(&buf[4], 512); // Block length
2154 return 8;
2155}
2156
2157
2158static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2159{
2160 struct lun *curlun = fsg->curlun;
2161 int mscmnd = fsg->cmnd[0];
2162 u8 *buf = (u8 *) bh->buf;
2163 u8 *buf0 = buf;
2164 int pc, page_code;
2165 int changeable_values, all_pages;
2166 int valid_page = 0;
2167 int len, limit;
2168
2169 if ((fsg->cmnd[1] & ~0x08) != 0) { // Mask away DBD
2170 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2171 return -EINVAL;
2172 }
2173 pc = fsg->cmnd[2] >> 6;
2174 page_code = fsg->cmnd[2] & 0x3f;
2175 if (pc == 3) {
2176 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
2177 return -EINVAL;
2178 }
2179 changeable_values = (pc == 1);
2180 all_pages = (page_code == 0x3f);
2181
2182 /* Write the mode parameter header. Fixed values are: default
2183 * medium type, no cache control (DPOFUA), and no block descriptors.
2184 * The only variable value is the WriteProtect bit. We will fill in
2185 * the mode data length later. */
2186 memset(buf, 0, 8);
2187 if (mscmnd == SC_MODE_SENSE_6) {
2188 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2189 buf += 4;
2190 limit = 255;
2191 } else { // SC_MODE_SENSE_10
2192 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
2193 buf += 8;
2194 limit = 65535; // Should really be mod_data.buflen
2195 }
2196
2197 /* No block descriptors */
2198
2199 /* The mode pages, in numerical order. The only page we support
2200 * is the Caching page. */
2201 if (page_code == 0x08 || all_pages) {
2202 valid_page = 1;
2203 buf[0] = 0x08; // Page code
2204 buf[1] = 10; // Page length
2205 memset(buf+2, 0, 10); // None of the fields are changeable
2206
2207 if (!changeable_values) {
2208 buf[2] = 0x04; // Write cache enable,
2209 // Read cache not disabled
2210 // No cache retention priorities
2211 put_be16(&buf[4], 0xffff); // Don't disable prefetch
2212 // Minimum prefetch = 0
2213 put_be16(&buf[8], 0xffff); // Maximum prefetch
2214 put_be16(&buf[10], 0xffff); // Maximum prefetch ceiling
2215 }
2216 buf += 12;
2217 }
2218
2219 /* Check that a valid page was requested and the mode data length
2220 * isn't too long. */
2221 len = buf - buf0;
2222 if (!valid_page || len > limit) {
2223 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2224 return -EINVAL;
2225 }
2226
2227 /* Store the mode data length */
2228 if (mscmnd == SC_MODE_SENSE_6)
2229 buf0[0] = len - 1;
2230 else
2231 put_be16(buf0, len - 2);
2232 return len;
2233}
2234
2235
2236static int do_start_stop(struct fsg_dev *fsg)
2237{
2238 struct lun *curlun = fsg->curlun;
2239 int loej, start;
2240
2241 if (!mod_data.removable) {
2242 curlun->sense_data = SS_INVALID_COMMAND;
2243 return -EINVAL;
2244 }
2245
2246 // int immed = fsg->cmnd[1] & 0x01;
2247 loej = fsg->cmnd[4] & 0x02;
2248 start = fsg->cmnd[4] & 0x01;
2249
2250#ifdef CONFIG_USB_FILE_STORAGE_TEST
2251 if ((fsg->cmnd[1] & ~0x01) != 0 || // Mask away Immed
2252 (fsg->cmnd[4] & ~0x03) != 0) { // Mask LoEj, Start
2253 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2254 return -EINVAL;
2255 }
2256
2257 if (!start) {
2258
2259 /* Are we allowed to unload the media? */
2260 if (curlun->prevent_medium_removal) {
2261 LDBG(curlun, "unload attempt prevented\n");
2262 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
2263 return -EINVAL;
2264 }
2265 if (loej) { // Simulate an unload/eject
2266 up_read(&fsg->filesem);
2267 down_write(&fsg->filesem);
2268 close_backing_file(curlun);
2269 up_write(&fsg->filesem);
2270 down_read(&fsg->filesem);
2271 }
2272 } else {
2273
2274 /* Our emulation doesn't support mounting; the medium is
2275 * available for use as soon as it is loaded. */
2276 if (!backing_file_is_open(curlun)) {
2277 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2278 return -EINVAL;
2279 }
2280 }
2281#endif
2282 return 0;
2283}
2284
2285
2286static int do_prevent_allow(struct fsg_dev *fsg)
2287{
2288 struct lun *curlun = fsg->curlun;
2289 int prevent;
2290
2291 if (!mod_data.removable) {
2292 curlun->sense_data = SS_INVALID_COMMAND;
2293 return -EINVAL;
2294 }
2295
2296 prevent = fsg->cmnd[4] & 0x01;
2297 if ((fsg->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
2298 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2299 return -EINVAL;
2300 }
2301
2302 if (curlun->prevent_medium_removal && !prevent)
2303 fsync_sub(curlun);
2304 curlun->prevent_medium_removal = prevent;
2305 return 0;
2306}
2307
2308
2309static int do_read_format_capacities(struct fsg_dev *fsg,
2310 struct fsg_buffhd *bh)
2311{
2312 struct lun *curlun = fsg->curlun;
2313 u8 *buf = (u8 *) bh->buf;
2314
2315 buf[0] = buf[1] = buf[2] = 0;
2316 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
2317 buf += 4;
2318
2319 put_be32(&buf[0], curlun->num_sectors); // Number of blocks
2320 put_be32(&buf[4], 512); // Block length
2321 buf[4] = 0x02; // Current capacity
2322 return 12;
2323}
2324
2325
2326static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2327{
2328 struct lun *curlun = fsg->curlun;
2329
2330 /* We don't support MODE SELECT */
2331 curlun->sense_data = SS_INVALID_COMMAND;
2332 return -EINVAL;
2333}
2334
2335
2336/*-------------------------------------------------------------------------*/
2337
2338static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
2339{
2340 int rc;
2341
2342 rc = fsg_set_halt(fsg, fsg->bulk_in);
2343 if (rc == -EAGAIN)
2344 VDBG(fsg, "delayed bulk-in endpoint halt\n");
2345 while (rc != 0) {
2346 if (rc != -EAGAIN) {
2347 WARN(fsg, "usb_ep_set_halt -> %d\n", rc);
2348 rc = 0;
2349 break;
2350 }
2351
2352 /* Wait for a short time and then try again */
2353 if (msleep_interruptible(100) != 0)
2354 return -EINTR;
2355 rc = usb_ep_set_halt(fsg->bulk_in);
2356 }
2357 return rc;
2358}
2359
2360static int pad_with_zeros(struct fsg_dev *fsg)
2361{
2362 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2363 u32 nkeep = bh->inreq->length;
2364 u32 nsend;
2365 int rc;
2366
2367 bh->state = BUF_STATE_EMPTY; // For the first iteration
2368 fsg->usb_amount_left = nkeep + fsg->residue;
2369 while (fsg->usb_amount_left > 0) {
2370
2371 /* Wait for the next buffer to be free */
2372 while (bh->state != BUF_STATE_EMPTY) {
2373 if ((rc = sleep_thread(fsg)) != 0)
2374 return rc;
2375 }
2376
2377 nsend = min(fsg->usb_amount_left, (u32) mod_data.buflen);
2378 memset(bh->buf + nkeep, 0, nsend - nkeep);
2379 bh->inreq->length = nsend;
2380 bh->inreq->zero = 0;
2381 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2382 &bh->inreq_busy, &bh->state);
2383 bh = fsg->next_buffhd_to_fill = bh->next;
2384 fsg->usb_amount_left -= nsend;
2385 nkeep = 0;
2386 }
2387 return 0;
2388}
2389
2390static int throw_away_data(struct fsg_dev *fsg)
2391{
2392 struct fsg_buffhd *bh;
2393 u32 amount;
2394 int rc;
2395
2396 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
2397 fsg->usb_amount_left > 0) {
2398
2399 /* Throw away the data in a filled buffer */
2400 if (bh->state == BUF_STATE_FULL) {
Alan Sterna21d4fe2005-11-29 12:04:24 -05002401 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002402 bh->state = BUF_STATE_EMPTY;
2403 fsg->next_buffhd_to_drain = bh->next;
2404
2405 /* A short packet or an error ends everything */
2406 if (bh->outreq->actual != bh->outreq->length ||
2407 bh->outreq->status != 0) {
2408 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2409 return -EINTR;
2410 }
2411 continue;
2412 }
2413
2414 /* Try to submit another request if we need one */
2415 bh = fsg->next_buffhd_to_fill;
2416 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
2417 amount = min(fsg->usb_amount_left,
2418 (u32) mod_data.buflen);
2419
2420 /* amount is always divisible by 512, hence by
2421 * the bulk-out maxpacket size */
2422 bh->outreq->length = bh->bulk_out_intended_length =
2423 amount;
Alan Stern70ffe6e2006-03-23 15:05:16 -05002424 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002425 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2426 &bh->outreq_busy, &bh->state);
2427 fsg->next_buffhd_to_fill = bh->next;
2428 fsg->usb_amount_left -= amount;
2429 continue;
2430 }
2431
2432 /* Otherwise wait for something to happen */
2433 if ((rc = sleep_thread(fsg)) != 0)
2434 return rc;
2435 }
2436 return 0;
2437}
2438
2439
2440static int finish_reply(struct fsg_dev *fsg)
2441{
2442 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
2443 int rc = 0;
2444
2445 switch (fsg->data_dir) {
2446 case DATA_DIR_NONE:
2447 break; // Nothing to send
2448
2449 /* If we don't know whether the host wants to read or write,
2450 * this must be CB or CBI with an unknown command. We mustn't
2451 * try to send or receive any data. So stall both bulk pipes
2452 * if we can and wait for a reset. */
2453 case DATA_DIR_UNKNOWN:
2454 if (mod_data.can_stall) {
2455 fsg_set_halt(fsg, fsg->bulk_out);
2456 rc = halt_bulk_in_endpoint(fsg);
2457 }
2458 break;
2459
2460 /* All but the last buffer of data must have already been sent */
2461 case DATA_DIR_TO_HOST:
2462 if (fsg->data_size == 0)
2463 ; // Nothing to send
2464
2465 /* If there's no residue, simply send the last buffer */
2466 else if (fsg->residue == 0) {
2467 bh->inreq->zero = 0;
2468 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2469 &bh->inreq_busy, &bh->state);
2470 fsg->next_buffhd_to_fill = bh->next;
2471 }
2472
2473 /* There is a residue. For CB and CBI, simply mark the end
2474 * of the data with a short packet. However, if we are
2475 * allowed to stall, there was no data at all (residue ==
2476 * data_size), and the command failed (invalid LUN or
2477 * sense data is set), then halt the bulk-in endpoint
2478 * instead. */
2479 else if (!transport_is_bbb()) {
2480 if (mod_data.can_stall &&
2481 fsg->residue == fsg->data_size &&
2482 (!fsg->curlun || fsg->curlun->sense_data != SS_NO_SENSE)) {
2483 bh->state = BUF_STATE_EMPTY;
2484 rc = halt_bulk_in_endpoint(fsg);
2485 } else {
2486 bh->inreq->zero = 1;
2487 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2488 &bh->inreq_busy, &bh->state);
2489 fsg->next_buffhd_to_fill = bh->next;
2490 }
2491 }
2492
2493 /* For Bulk-only, if we're allowed to stall then send the
2494 * short packet and halt the bulk-in endpoint. If we can't
2495 * stall, pad out the remaining data with 0's. */
2496 else {
2497 if (mod_data.can_stall) {
2498 bh->inreq->zero = 1;
2499 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2500 &bh->inreq_busy, &bh->state);
2501 fsg->next_buffhd_to_fill = bh->next;
2502 rc = halt_bulk_in_endpoint(fsg);
2503 } else
2504 rc = pad_with_zeros(fsg);
2505 }
2506 break;
2507
2508 /* We have processed all we want from the data the host has sent.
2509 * There may still be outstanding bulk-out requests. */
2510 case DATA_DIR_FROM_HOST:
2511 if (fsg->residue == 0)
2512 ; // Nothing to receive
2513
2514 /* Did the host stop sending unexpectedly early? */
2515 else if (fsg->short_packet_received) {
2516 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2517 rc = -EINTR;
2518 }
2519
2520 /* We haven't processed all the incoming data. Even though
2521 * we may be allowed to stall, doing so would cause a race.
2522 * The controller may already have ACK'ed all the remaining
2523 * bulk-out packets, in which case the host wouldn't see a
2524 * STALL. Not realizing the endpoint was halted, it wouldn't
2525 * clear the halt -- leading to problems later on. */
2526#if 0
2527 else if (mod_data.can_stall) {
2528 fsg_set_halt(fsg, fsg->bulk_out);
2529 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
2530 rc = -EINTR;
2531 }
2532#endif
2533
2534 /* We can't stall. Read in the excess data and throw it
2535 * all away. */
2536 else
2537 rc = throw_away_data(fsg);
2538 break;
2539 }
2540 return rc;
2541}
2542
2543
2544static int send_status(struct fsg_dev *fsg)
2545{
2546 struct lun *curlun = fsg->curlun;
2547 struct fsg_buffhd *bh;
2548 int rc;
2549 u8 status = USB_STATUS_PASS;
2550 u32 sd, sdinfo = 0;
2551
2552 /* Wait for the next buffer to become available */
2553 bh = fsg->next_buffhd_to_fill;
2554 while (bh->state != BUF_STATE_EMPTY) {
2555 if ((rc = sleep_thread(fsg)) != 0)
2556 return rc;
2557 }
2558
2559 if (curlun) {
2560 sd = curlun->sense_data;
2561 sdinfo = curlun->sense_data_info;
2562 } else if (fsg->bad_lun_okay)
2563 sd = SS_NO_SENSE;
2564 else
2565 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
2566
2567 if (fsg->phase_error) {
2568 DBG(fsg, "sending phase-error status\n");
2569 status = USB_STATUS_PHASE_ERROR;
2570 sd = SS_INVALID_COMMAND;
2571 } else if (sd != SS_NO_SENSE) {
2572 DBG(fsg, "sending command-failure status\n");
2573 status = USB_STATUS_FAIL;
2574 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
2575 " info x%x\n",
2576 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
2577 }
2578
2579 if (transport_is_bbb()) {
John Daiker7ca46b82006-12-29 19:02:06 -08002580 struct bulk_cs_wrap *csw = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002581
2582 /* Store and send the Bulk-only CSW */
2583 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
2584 csw->Tag = fsg->tag;
2585 csw->Residue = cpu_to_le32(fsg->residue);
2586 csw->Status = status;
2587
2588 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
2589 bh->inreq->zero = 0;
2590 start_transfer(fsg, fsg->bulk_in, bh->inreq,
2591 &bh->inreq_busy, &bh->state);
2592
2593 } else if (mod_data.transport_type == USB_PR_CB) {
2594
2595 /* Control-Bulk transport has no status phase! */
2596 return 0;
2597
2598 } else { // USB_PR_CBI
John Daiker7ca46b82006-12-29 19:02:06 -08002599 struct interrupt_data *buf = bh->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002600
2601 /* Store and send the Interrupt data. UFI sends the ASC
2602 * and ASCQ bytes. Everything else sends a Type (which
2603 * is always 0) and the status Value. */
2604 if (mod_data.protocol_type == USB_SC_UFI) {
2605 buf->bType = ASC(sd);
2606 buf->bValue = ASCQ(sd);
2607 } else {
2608 buf->bType = 0;
2609 buf->bValue = status;
2610 }
2611 fsg->intreq->length = CBI_INTERRUPT_DATA_LEN;
2612
2613 fsg->intr_buffhd = bh; // Point to the right buffhd
2614 fsg->intreq->buf = bh->inreq->buf;
2615 fsg->intreq->dma = bh->inreq->dma;
2616 fsg->intreq->context = bh;
2617 start_transfer(fsg, fsg->intr_in, fsg->intreq,
2618 &fsg->intreq_busy, &bh->state);
2619 }
2620
2621 fsg->next_buffhd_to_fill = bh->next;
2622 return 0;
2623}
2624
2625
2626/*-------------------------------------------------------------------------*/
2627
2628/* Check whether the command is properly formed and whether its data size
2629 * and direction agree with the values we already have. */
2630static int check_command(struct fsg_dev *fsg, int cmnd_size,
2631 enum data_direction data_dir, unsigned int mask,
2632 int needs_medium, const char *name)
2633{
2634 int i;
2635 int lun = fsg->cmnd[1] >> 5;
2636 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
2637 char hdlen[20];
2638 struct lun *curlun;
2639
2640 /* Adjust the expected cmnd_size for protocol encapsulation padding.
2641 * Transparent SCSI doesn't pad. */
2642 if (protocol_is_scsi())
2643 ;
2644
2645 /* There's some disagreement as to whether RBC pads commands or not.
2646 * We'll play it safe and accept either form. */
2647 else if (mod_data.protocol_type == USB_SC_RBC) {
2648 if (fsg->cmnd_size == 12)
2649 cmnd_size = 12;
2650
2651 /* All the other protocols pad to 12 bytes */
2652 } else
2653 cmnd_size = 12;
2654
2655 hdlen[0] = 0;
2656 if (fsg->data_dir != DATA_DIR_UNKNOWN)
2657 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
2658 fsg->data_size);
2659 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
2660 name, cmnd_size, dirletter[(int) data_dir],
2661 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
2662
2663 /* We can't reply at all until we know the correct data direction
2664 * and size. */
2665 if (fsg->data_size_from_cmnd == 0)
2666 data_dir = DATA_DIR_NONE;
2667 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
2668 fsg->data_dir = data_dir;
2669 fsg->data_size = fsg->data_size_from_cmnd;
2670
2671 } else { // Bulk-only
2672 if (fsg->data_size < fsg->data_size_from_cmnd) {
2673
2674 /* Host data size < Device data size is a phase error.
2675 * Carry out the command, but only transfer as much
2676 * as we are allowed. */
2677 fsg->data_size_from_cmnd = fsg->data_size;
2678 fsg->phase_error = 1;
2679 }
2680 }
2681 fsg->residue = fsg->usb_amount_left = fsg->data_size;
2682
2683 /* Conflicting data directions is a phase error */
2684 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
2685 fsg->phase_error = 1;
2686 return -EINVAL;
2687 }
2688
2689 /* Verify the length of the command itself */
2690 if (cmnd_size != fsg->cmnd_size) {
2691
2692 /* Special case workaround: MS-Windows issues REQUEST SENSE
2693 * with cbw->Length == 12 (it should be 6). */
2694 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
2695 cmnd_size = fsg->cmnd_size;
2696 else {
2697 fsg->phase_error = 1;
2698 return -EINVAL;
2699 }
2700 }
2701
Alan Sternd794ac72005-04-18 12:43:25 -04002702 /* Check that the LUN values are consistent */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002703 if (transport_is_bbb()) {
2704 if (fsg->lun != lun)
2705 DBG(fsg, "using LUN %d from CBW, "
2706 "not LUN %d from CDB\n",
2707 fsg->lun, lun);
2708 } else
2709 fsg->lun = lun; // Use LUN from the command
2710
2711 /* Check the LUN */
2712 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
2713 fsg->curlun = curlun = &fsg->luns[fsg->lun];
2714 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
2715 curlun->sense_data = SS_NO_SENSE;
2716 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04002717 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002718 }
2719 } else {
2720 fsg->curlun = curlun = NULL;
2721 fsg->bad_lun_okay = 0;
2722
2723 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2724 * to use unsupported LUNs; all others may not. */
2725 if (fsg->cmnd[0] != SC_INQUIRY &&
2726 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2727 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
2728 return -EINVAL;
2729 }
2730 }
2731
2732 /* If a unit attention condition exists, only INQUIRY and
2733 * REQUEST SENSE commands are allowed; anything else must fail. */
2734 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2735 fsg->cmnd[0] != SC_INQUIRY &&
2736 fsg->cmnd[0] != SC_REQUEST_SENSE) {
2737 curlun->sense_data = curlun->unit_attention_data;
2738 curlun->unit_attention_data = SS_NO_SENSE;
2739 return -EINVAL;
2740 }
2741
2742 /* Check that only command bytes listed in the mask are non-zero */
2743 fsg->cmnd[1] &= 0x1f; // Mask away the LUN
2744 for (i = 1; i < cmnd_size; ++i) {
2745 if (fsg->cmnd[i] && !(mask & (1 << i))) {
2746 if (curlun)
2747 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2748 return -EINVAL;
2749 }
2750 }
2751
2752 /* If the medium isn't mounted and the command needs to access
2753 * it, return an error. */
2754 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
2755 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2756 return -EINVAL;
2757 }
2758
2759 return 0;
2760}
2761
2762
2763static int do_scsi_command(struct fsg_dev *fsg)
2764{
2765 struct fsg_buffhd *bh;
2766 int rc;
2767 int reply = -EINVAL;
2768 int i;
2769 static char unknown[16];
2770
2771 dump_cdb(fsg);
2772
2773 /* Wait for the next buffer to become available for data or status */
2774 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
2775 while (bh->state != BUF_STATE_EMPTY) {
2776 if ((rc = sleep_thread(fsg)) != 0)
2777 return rc;
2778 }
2779 fsg->phase_error = 0;
2780 fsg->short_packet_received = 0;
2781
2782 down_read(&fsg->filesem); // We're using the backing file
2783 switch (fsg->cmnd[0]) {
2784
2785 case SC_INQUIRY:
2786 fsg->data_size_from_cmnd = fsg->cmnd[4];
2787 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2788 (1<<4), 0,
2789 "INQUIRY")) == 0)
2790 reply = do_inquiry(fsg, bh);
2791 break;
2792
2793 case SC_MODE_SELECT_6:
2794 fsg->data_size_from_cmnd = fsg->cmnd[4];
2795 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2796 (1<<1) | (1<<4), 0,
2797 "MODE SELECT(6)")) == 0)
2798 reply = do_mode_select(fsg, bh);
2799 break;
2800
2801 case SC_MODE_SELECT_10:
2802 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2803 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2804 (1<<1) | (3<<7), 0,
2805 "MODE SELECT(10)")) == 0)
2806 reply = do_mode_select(fsg, bh);
2807 break;
2808
2809 case SC_MODE_SENSE_6:
2810 fsg->data_size_from_cmnd = fsg->cmnd[4];
2811 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2812 (1<<1) | (1<<2) | (1<<4), 0,
2813 "MODE SENSE(6)")) == 0)
2814 reply = do_mode_sense(fsg, bh);
2815 break;
2816
2817 case SC_MODE_SENSE_10:
2818 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2819 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2820 (1<<1) | (1<<2) | (3<<7), 0,
2821 "MODE SENSE(10)")) == 0)
2822 reply = do_mode_sense(fsg, bh);
2823 break;
2824
2825 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2826 fsg->data_size_from_cmnd = 0;
2827 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2828 (1<<4), 0,
2829 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2830 reply = do_prevent_allow(fsg);
2831 break;
2832
2833 case SC_READ_6:
2834 i = fsg->cmnd[4];
2835 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2836 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2837 (7<<1) | (1<<4), 1,
2838 "READ(6)")) == 0)
2839 reply = do_read(fsg);
2840 break;
2841
2842 case SC_READ_10:
2843 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2844 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2845 (1<<1) | (0xf<<2) | (3<<7), 1,
2846 "READ(10)")) == 0)
2847 reply = do_read(fsg);
2848 break;
2849
2850 case SC_READ_12:
2851 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2852 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2853 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2854 "READ(12)")) == 0)
2855 reply = do_read(fsg);
2856 break;
2857
2858 case SC_READ_CAPACITY:
2859 fsg->data_size_from_cmnd = 8;
2860 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2861 (0xf<<2) | (1<<8), 1,
2862 "READ CAPACITY")) == 0)
2863 reply = do_read_capacity(fsg, bh);
2864 break;
2865
2866 case SC_READ_FORMAT_CAPACITIES:
2867 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
2868 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2869 (3<<7), 1,
2870 "READ FORMAT CAPACITIES")) == 0)
2871 reply = do_read_format_capacities(fsg, bh);
2872 break;
2873
2874 case SC_REQUEST_SENSE:
2875 fsg->data_size_from_cmnd = fsg->cmnd[4];
2876 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2877 (1<<4), 0,
2878 "REQUEST SENSE")) == 0)
2879 reply = do_request_sense(fsg, bh);
2880 break;
2881
2882 case SC_START_STOP_UNIT:
2883 fsg->data_size_from_cmnd = 0;
2884 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2885 (1<<1) | (1<<4), 0,
2886 "START-STOP UNIT")) == 0)
2887 reply = do_start_stop(fsg);
2888 break;
2889
2890 case SC_SYNCHRONIZE_CACHE:
2891 fsg->data_size_from_cmnd = 0;
2892 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2893 (0xf<<2) | (3<<7), 1,
2894 "SYNCHRONIZE CACHE")) == 0)
2895 reply = do_synchronize_cache(fsg);
2896 break;
2897
2898 case SC_TEST_UNIT_READY:
2899 fsg->data_size_from_cmnd = 0;
2900 reply = check_command(fsg, 6, DATA_DIR_NONE,
2901 0, 1,
2902 "TEST UNIT READY");
2903 break;
2904
2905 /* Although optional, this command is used by MS-Windows. We
2906 * support a minimal version: BytChk must be 0. */
2907 case SC_VERIFY:
2908 fsg->data_size_from_cmnd = 0;
2909 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2910 (1<<1) | (0xf<<2) | (3<<7), 1,
2911 "VERIFY")) == 0)
2912 reply = do_verify(fsg);
2913 break;
2914
2915 case SC_WRITE_6:
2916 i = fsg->cmnd[4];
2917 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2918 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2919 (7<<1) | (1<<4), 1,
2920 "WRITE(6)")) == 0)
2921 reply = do_write(fsg);
2922 break;
2923
2924 case SC_WRITE_10:
2925 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2926 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2927 (1<<1) | (0xf<<2) | (3<<7), 1,
2928 "WRITE(10)")) == 0)
2929 reply = do_write(fsg);
2930 break;
2931
2932 case SC_WRITE_12:
2933 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2934 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2935 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2936 "WRITE(12)")) == 0)
2937 reply = do_write(fsg);
2938 break;
2939
2940 /* Some mandatory commands that we recognize but don't implement.
2941 * They don't mean much in this setting. It's left as an exercise
2942 * for anyone interested to implement RESERVE and RELEASE in terms
2943 * of Posix locks. */
2944 case SC_FORMAT_UNIT:
2945 case SC_RELEASE:
2946 case SC_RESERVE:
2947 case SC_SEND_DIAGNOSTIC:
2948 // Fall through
2949
2950 default:
2951 fsg->data_size_from_cmnd = 0;
2952 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2953 if ((reply = check_command(fsg, fsg->cmnd_size,
2954 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2955 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2956 reply = -EINVAL;
2957 }
2958 break;
2959 }
2960 up_read(&fsg->filesem);
2961
2962 if (reply == -EINTR || signal_pending(current))
2963 return -EINTR;
2964
2965 /* Set up the single reply buffer for finish_reply() */
2966 if (reply == -EINVAL)
2967 reply = 0; // Error reply length
2968 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2969 reply = min((u32) reply, fsg->data_size_from_cmnd);
2970 bh->inreq->length = reply;
2971 bh->state = BUF_STATE_FULL;
2972 fsg->residue -= reply;
2973 } // Otherwise it's already set
2974
2975 return 0;
2976}
2977
2978
2979/*-------------------------------------------------------------------------*/
2980
2981static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2982{
2983 struct usb_request *req = bh->outreq;
John Daiker7ca46b82006-12-29 19:02:06 -08002984 struct bulk_cb_wrap *cbw = req->buf;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002985
2986 /* Was this a real packet? */
2987 if (req->status)
2988 return -EINVAL;
2989
2990 /* Is the CBW valid? */
2991 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2992 cbw->Signature != __constant_cpu_to_le32(
2993 USB_BULK_CB_SIG)) {
2994 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2995 req->actual,
2996 le32_to_cpu(cbw->Signature));
2997
2998 /* The Bulk-only spec says we MUST stall the bulk pipes!
2999 * If we want to avoid stalls, set a flag so that we will
3000 * clear the endpoint halts at the next reset. */
3001 if (!mod_data.can_stall)
3002 set_bit(CLEAR_BULK_HALTS, &fsg->atomic_bitflags);
3003 fsg_set_halt(fsg, fsg->bulk_out);
3004 halt_bulk_in_endpoint(fsg);
3005 return -EINVAL;
3006 }
3007
3008 /* Is the CBW meaningful? */
3009 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
3010 cbw->Length < 6 || cbw->Length > MAX_COMMAND_SIZE) {
3011 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
3012 "cmdlen %u\n",
3013 cbw->Lun, cbw->Flags, cbw->Length);
3014
3015 /* We can do anything we want here, so let's stall the
3016 * bulk pipes if we are allowed to. */
3017 if (mod_data.can_stall) {
3018 fsg_set_halt(fsg, fsg->bulk_out);
3019 halt_bulk_in_endpoint(fsg);
3020 }
3021 return -EINVAL;
3022 }
3023
3024 /* Save the command for later */
3025 fsg->cmnd_size = cbw->Length;
3026 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
3027 if (cbw->Flags & USB_BULK_IN_FLAG)
3028 fsg->data_dir = DATA_DIR_TO_HOST;
3029 else
3030 fsg->data_dir = DATA_DIR_FROM_HOST;
3031 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
3032 if (fsg->data_size == 0)
3033 fsg->data_dir = DATA_DIR_NONE;
3034 fsg->lun = cbw->Lun;
3035 fsg->tag = cbw->Tag;
3036 return 0;
3037}
3038
3039
3040static int get_next_command(struct fsg_dev *fsg)
3041{
3042 struct fsg_buffhd *bh;
3043 int rc = 0;
3044
3045 if (transport_is_bbb()) {
3046
3047 /* Wait for the next buffer to become available */
3048 bh = fsg->next_buffhd_to_fill;
3049 while (bh->state != BUF_STATE_EMPTY) {
3050 if ((rc = sleep_thread(fsg)) != 0)
3051 return rc;
3052 }
3053
3054 /* Queue a request to read a Bulk-only CBW */
3055 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
Alan Stern70ffe6e2006-03-23 15:05:16 -05003056 bh->outreq->short_not_ok = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003057 start_transfer(fsg, fsg->bulk_out, bh->outreq,
3058 &bh->outreq_busy, &bh->state);
3059
3060 /* We will drain the buffer in software, which means we
3061 * can reuse it for the next filling. No need to advance
3062 * next_buffhd_to_fill. */
3063
3064 /* Wait for the CBW to arrive */
3065 while (bh->state != BUF_STATE_FULL) {
3066 if ((rc = sleep_thread(fsg)) != 0)
3067 return rc;
3068 }
Alan Sterna21d4fe2005-11-29 12:04:24 -05003069 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07003070 rc = received_cbw(fsg, bh);
3071 bh->state = BUF_STATE_EMPTY;
3072
3073 } else { // USB_PR_CB or USB_PR_CBI
3074
3075 /* Wait for the next command to arrive */
3076 while (fsg->cbbuf_cmnd_size == 0) {
3077 if ((rc = sleep_thread(fsg)) != 0)
3078 return rc;
3079 }
3080
3081 /* Is the previous status interrupt request still busy?
3082 * The host is allowed to skip reading the status,
3083 * so we must cancel it. */
3084 if (fsg->intreq_busy)
3085 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3086
3087 /* Copy the command and mark the buffer empty */
3088 fsg->data_dir = DATA_DIR_UNKNOWN;
3089 spin_lock_irq(&fsg->lock);
3090 fsg->cmnd_size = fsg->cbbuf_cmnd_size;
3091 memcpy(fsg->cmnd, fsg->cbbuf_cmnd, fsg->cmnd_size);
3092 fsg->cbbuf_cmnd_size = 0;
3093 spin_unlock_irq(&fsg->lock);
3094 }
3095 return rc;
3096}
3097
3098
3099/*-------------------------------------------------------------------------*/
3100
3101static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
3102 const struct usb_endpoint_descriptor *d)
3103{
3104 int rc;
3105
3106 ep->driver_data = fsg;
3107 rc = usb_ep_enable(ep, d);
3108 if (rc)
3109 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
3110 return rc;
3111}
3112
3113static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
3114 struct usb_request **preq)
3115{
3116 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
3117 if (*preq)
3118 return 0;
3119 ERROR(fsg, "can't allocate request for %s\n", ep->name);
3120 return -ENOMEM;
3121}
3122
3123/*
3124 * Reset interface setting and re-init endpoint state (toggle etc).
3125 * Call with altsetting < 0 to disable the interface. The only other
3126 * available altsetting is 0, which enables the interface.
3127 */
3128static int do_set_interface(struct fsg_dev *fsg, int altsetting)
3129{
3130 int rc = 0;
3131 int i;
3132 const struct usb_endpoint_descriptor *d;
3133
3134 if (fsg->running)
3135 DBG(fsg, "reset interface\n");
3136
3137reset:
3138 /* Deallocate the requests */
3139 for (i = 0; i < NUM_BUFFERS; ++i) {
3140 struct fsg_buffhd *bh = &fsg->buffhds[i];
3141
3142 if (bh->inreq) {
3143 usb_ep_free_request(fsg->bulk_in, bh->inreq);
3144 bh->inreq = NULL;
3145 }
3146 if (bh->outreq) {
3147 usb_ep_free_request(fsg->bulk_out, bh->outreq);
3148 bh->outreq = NULL;
3149 }
3150 }
3151 if (fsg->intreq) {
3152 usb_ep_free_request(fsg->intr_in, fsg->intreq);
3153 fsg->intreq = NULL;
3154 }
3155
3156 /* Disable the endpoints */
3157 if (fsg->bulk_in_enabled) {
3158 usb_ep_disable(fsg->bulk_in);
3159 fsg->bulk_in_enabled = 0;
3160 }
3161 if (fsg->bulk_out_enabled) {
3162 usb_ep_disable(fsg->bulk_out);
3163 fsg->bulk_out_enabled = 0;
3164 }
3165 if (fsg->intr_in_enabled) {
3166 usb_ep_disable(fsg->intr_in);
3167 fsg->intr_in_enabled = 0;
3168 }
3169
3170 fsg->running = 0;
3171 if (altsetting < 0 || rc != 0)
3172 return rc;
3173
3174 DBG(fsg, "set interface %d\n", altsetting);
3175
3176 /* Enable the endpoints */
3177 d = ep_desc(fsg->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
3178 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
3179 goto reset;
3180 fsg->bulk_in_enabled = 1;
3181
3182 d = ep_desc(fsg->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
3183 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
3184 goto reset;
3185 fsg->bulk_out_enabled = 1;
3186 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
3187
3188 if (transport_is_cbi()) {
3189 d = ep_desc(fsg->gadget, &fs_intr_in_desc, &hs_intr_in_desc);
3190 if ((rc = enable_endpoint(fsg, fsg->intr_in, d)) != 0)
3191 goto reset;
3192 fsg->intr_in_enabled = 1;
3193 }
3194
3195 /* Allocate the requests */
3196 for (i = 0; i < NUM_BUFFERS; ++i) {
3197 struct fsg_buffhd *bh = &fsg->buffhds[i];
3198
3199 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
3200 goto reset;
3201 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
3202 goto reset;
3203 bh->inreq->buf = bh->outreq->buf = bh->buf;
3204 bh->inreq->dma = bh->outreq->dma = bh->dma;
3205 bh->inreq->context = bh->outreq->context = bh;
3206 bh->inreq->complete = bulk_in_complete;
3207 bh->outreq->complete = bulk_out_complete;
3208 }
3209 if (transport_is_cbi()) {
3210 if ((rc = alloc_request(fsg, fsg->intr_in, &fsg->intreq)) != 0)
3211 goto reset;
3212 fsg->intreq->complete = intr_in_complete;
3213 }
3214
3215 fsg->running = 1;
3216 for (i = 0; i < fsg->nluns; ++i)
3217 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3218 return rc;
3219}
3220
3221
3222/*
3223 * Change our operational configuration. This code must agree with the code
3224 * that returns config descriptors, and with interface altsetting code.
3225 *
3226 * It's also responsible for power management interactions. Some
3227 * configurations might not work with our current power sources.
3228 * For now we just assume the gadget is always self-powered.
3229 */
3230static int do_set_config(struct fsg_dev *fsg, u8 new_config)
3231{
3232 int rc = 0;
3233
3234 /* Disable the single interface */
3235 if (fsg->config != 0) {
3236 DBG(fsg, "reset config\n");
3237 fsg->config = 0;
3238 rc = do_set_interface(fsg, -1);
3239 }
3240
3241 /* Enable the interface */
3242 if (new_config != 0) {
3243 fsg->config = new_config;
3244 if ((rc = do_set_interface(fsg, 0)) != 0)
3245 fsg->config = 0; // Reset on errors
3246 else {
3247 char *speed;
3248
3249 switch (fsg->gadget->speed) {
3250 case USB_SPEED_LOW: speed = "low"; break;
3251 case USB_SPEED_FULL: speed = "full"; break;
3252 case USB_SPEED_HIGH: speed = "high"; break;
3253 default: speed = "?"; break;
3254 }
3255 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
3256 }
3257 }
3258 return rc;
3259}
3260
3261
3262/*-------------------------------------------------------------------------*/
3263
3264static void handle_exception(struct fsg_dev *fsg)
3265{
3266 siginfo_t info;
3267 int sig;
3268 int i;
3269 int num_active;
3270 struct fsg_buffhd *bh;
3271 enum fsg_state old_state;
3272 u8 new_config;
3273 struct lun *curlun;
3274 unsigned int exception_req_tag;
3275 int rc;
3276
3277 /* Clear the existing signals. Anything but SIGUSR1 is converted
3278 * into a high-priority EXIT exception. */
3279 for (;;) {
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003280 sig = dequeue_signal_lock(current, &current->blocked, &info);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003281 if (!sig)
3282 break;
3283 if (sig != SIGUSR1) {
3284 if (fsg->state < FSG_STATE_EXIT)
3285 DBG(fsg, "Main thread exiting on signal\n");
3286 raise_exception(fsg, FSG_STATE_EXIT);
3287 }
3288 }
3289
3290 /* Cancel all the pending transfers */
3291 if (fsg->intreq_busy)
3292 usb_ep_dequeue(fsg->intr_in, fsg->intreq);
3293 for (i = 0; i < NUM_BUFFERS; ++i) {
3294 bh = &fsg->buffhds[i];
3295 if (bh->inreq_busy)
3296 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
3297 if (bh->outreq_busy)
3298 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
3299 }
3300
3301 /* Wait until everything is idle */
3302 for (;;) {
3303 num_active = fsg->intreq_busy;
3304 for (i = 0; i < NUM_BUFFERS; ++i) {
3305 bh = &fsg->buffhds[i];
3306 num_active += bh->inreq_busy + bh->outreq_busy;
3307 }
3308 if (num_active == 0)
3309 break;
3310 if (sleep_thread(fsg))
3311 return;
3312 }
3313
3314 /* Clear out the controller's fifos */
3315 if (fsg->bulk_in_enabled)
3316 usb_ep_fifo_flush(fsg->bulk_in);
3317 if (fsg->bulk_out_enabled)
3318 usb_ep_fifo_flush(fsg->bulk_out);
3319 if (fsg->intr_in_enabled)
3320 usb_ep_fifo_flush(fsg->intr_in);
3321
3322 /* Reset the I/O buffer states and pointers, the SCSI
3323 * state, and the exception. Then invoke the handler. */
3324 spin_lock_irq(&fsg->lock);
3325
3326 for (i = 0; i < NUM_BUFFERS; ++i) {
3327 bh = &fsg->buffhds[i];
3328 bh->state = BUF_STATE_EMPTY;
3329 }
3330 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
3331 &fsg->buffhds[0];
3332
3333 exception_req_tag = fsg->exception_req_tag;
3334 new_config = fsg->new_config;
3335 old_state = fsg->state;
3336
3337 if (old_state == FSG_STATE_ABORT_BULK_OUT)
3338 fsg->state = FSG_STATE_STATUS_PHASE;
3339 else {
3340 for (i = 0; i < fsg->nluns; ++i) {
3341 curlun = &fsg->luns[i];
3342 curlun->prevent_medium_removal = 0;
3343 curlun->sense_data = curlun->unit_attention_data =
3344 SS_NO_SENSE;
3345 curlun->sense_data_info = 0;
Alan Stern6174d0f2006-09-26 14:51:48 -04003346 curlun->info_valid = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003347 }
3348 fsg->state = FSG_STATE_IDLE;
3349 }
3350 spin_unlock_irq(&fsg->lock);
3351
3352 /* Carry out any extra actions required for the exception */
3353 switch (old_state) {
3354 default:
3355 break;
3356
3357 case FSG_STATE_ABORT_BULK_OUT:
3358 send_status(fsg);
3359 spin_lock_irq(&fsg->lock);
3360 if (fsg->state == FSG_STATE_STATUS_PHASE)
3361 fsg->state = FSG_STATE_IDLE;
3362 spin_unlock_irq(&fsg->lock);
3363 break;
3364
3365 case FSG_STATE_RESET:
3366 /* In case we were forced against our will to halt a
3367 * bulk endpoint, clear the halt now. (The SuperH UDC
3368 * requires this.) */
3369 if (test_and_clear_bit(CLEAR_BULK_HALTS,
3370 &fsg->atomic_bitflags)) {
3371 usb_ep_clear_halt(fsg->bulk_in);
3372 usb_ep_clear_halt(fsg->bulk_out);
3373 }
3374
3375 if (transport_is_bbb()) {
3376 if (fsg->ep0_req_tag == exception_req_tag)
3377 ep0_queue(fsg); // Complete the status stage
3378
3379 } else if (transport_is_cbi())
3380 send_status(fsg); // Status by interrupt pipe
3381
3382 /* Technically this should go here, but it would only be
3383 * a waste of time. Ditto for the INTERFACE_CHANGE and
3384 * CONFIG_CHANGE cases. */
3385 // for (i = 0; i < fsg->nluns; ++i)
3386 // fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
3387 break;
3388
3389 case FSG_STATE_INTERFACE_CHANGE:
3390 rc = do_set_interface(fsg, 0);
3391 if (fsg->ep0_req_tag != exception_req_tag)
3392 break;
3393 if (rc != 0) // STALL on errors
3394 fsg_set_halt(fsg, fsg->ep0);
3395 else // Complete the status stage
3396 ep0_queue(fsg);
3397 break;
3398
3399 case FSG_STATE_CONFIG_CHANGE:
3400 rc = do_set_config(fsg, new_config);
3401 if (fsg->ep0_req_tag != exception_req_tag)
3402 break;
3403 if (rc != 0) // STALL on errors
3404 fsg_set_halt(fsg, fsg->ep0);
3405 else // Complete the status stage
3406 ep0_queue(fsg);
3407 break;
3408
3409 case FSG_STATE_DISCONNECT:
3410 fsync_all(fsg);
3411 do_set_config(fsg, 0); // Unconfigured state
3412 break;
3413
3414 case FSG_STATE_EXIT:
3415 case FSG_STATE_TERMINATED:
3416 do_set_config(fsg, 0); // Free resources
3417 spin_lock_irq(&fsg->lock);
3418 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
3419 spin_unlock_irq(&fsg->lock);
3420 break;
3421 }
3422}
3423
3424
3425/*-------------------------------------------------------------------------*/
3426
3427static int fsg_main_thread(void *fsg_)
3428{
John Daiker7ca46b82006-12-29 19:02:06 -08003429 struct fsg_dev *fsg = fsg_;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003430
Linus Torvalds1da177e2005-04-16 15:20:36 -07003431 /* Allow the thread to be killed by a signal, but set the signal mask
3432 * to block everything but INT, TERM, KILL, and USR1. */
Oleg Nesterov8cfbe7e2007-05-30 11:06:33 -04003433 allow_signal(SIGINT);
3434 allow_signal(SIGTERM);
3435 allow_signal(SIGKILL);
3436 allow_signal(SIGUSR1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003437
Rafael J. Wysocki83144182007-07-17 04:03:35 -07003438 /* Allow the thread to be frozen */
3439 set_freezable();
3440
Linus Torvalds1da177e2005-04-16 15:20:36 -07003441 /* Arrange for userspace references to be interpreted as kernel
3442 * pointers. That way we can pass a kernel pointer to a routine
3443 * that expects a __user pointer and it will work okay. */
3444 set_fs(get_ds());
3445
Linus Torvalds1da177e2005-04-16 15:20:36 -07003446 /* The main loop */
3447 while (fsg->state != FSG_STATE_TERMINATED) {
3448 if (exception_in_progress(fsg) || signal_pending(current)) {
3449 handle_exception(fsg);
3450 continue;
3451 }
3452
3453 if (!fsg->running) {
3454 sleep_thread(fsg);
3455 continue;
3456 }
3457
3458 if (get_next_command(fsg))
3459 continue;
3460
3461 spin_lock_irq(&fsg->lock);
3462 if (!exception_in_progress(fsg))
3463 fsg->state = FSG_STATE_DATA_PHASE;
3464 spin_unlock_irq(&fsg->lock);
3465
3466 if (do_scsi_command(fsg) || finish_reply(fsg))
3467 continue;
3468
3469 spin_lock_irq(&fsg->lock);
3470 if (!exception_in_progress(fsg))
3471 fsg->state = FSG_STATE_STATUS_PHASE;
3472 spin_unlock_irq(&fsg->lock);
3473
3474 if (send_status(fsg))
3475 continue;
3476
3477 spin_lock_irq(&fsg->lock);
3478 if (!exception_in_progress(fsg))
3479 fsg->state = FSG_STATE_IDLE;
3480 spin_unlock_irq(&fsg->lock);
3481 }
3482
Alan Stern22efcf42005-09-26 16:12:02 -04003483 spin_lock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003484 fsg->thread_task = NULL;
Alan Stern22efcf42005-09-26 16:12:02 -04003485 spin_unlock_irq(&fsg->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003486
3487 /* In case we are exiting because of a signal, unregister the
3488 * gadget driver and close the backing file. */
3489 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags)) {
3490 usb_gadget_unregister_driver(&fsg_driver);
3491 close_all_backing_files(fsg);
3492 }
3493
3494 /* Let the unbind and cleanup routines know the thread has exited */
3495 complete_and_exit(&fsg->thread_notifier, 0);
3496}
3497
3498
3499/*-------------------------------------------------------------------------*/
3500
3501/* If the next two routines are called while the gadget is registered,
3502 * the caller must own fsg->filesem for writing. */
3503
3504static int open_backing_file(struct lun *curlun, const char *filename)
3505{
3506 int ro;
3507 struct file *filp = NULL;
3508 int rc = -EINVAL;
3509 struct inode *inode = NULL;
3510 loff_t size;
3511 loff_t num_sectors;
3512
3513 /* R/W if we can, R/O if we must */
3514 ro = curlun->ro;
3515 if (!ro) {
3516 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
3517 if (-EROFS == PTR_ERR(filp))
3518 ro = 1;
3519 }
3520 if (ro)
3521 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
3522 if (IS_ERR(filp)) {
3523 LINFO(curlun, "unable to open backing file: %s\n", filename);
3524 return PTR_ERR(filp);
3525 }
3526
3527 if (!(filp->f_mode & FMODE_WRITE))
3528 ro = 1;
3529
Josef Sipek33cb8992006-12-08 02:37:46 -08003530 if (filp->f_path.dentry)
3531 inode = filp->f_path.dentry->d_inode;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003532 if (inode && S_ISBLK(inode->i_mode)) {
3533 if (bdev_read_only(inode->i_bdev))
3534 ro = 1;
3535 } else if (!inode || !S_ISREG(inode->i_mode)) {
3536 LINFO(curlun, "invalid file type: %s\n", filename);
3537 goto out;
3538 }
3539
3540 /* If we can't read the file, it's no good.
3541 * If we can't write the file, use it read-only. */
3542 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
3543 LINFO(curlun, "file not readable: %s\n", filename);
3544 goto out;
3545 }
3546 if (!(filp->f_op->write || filp->f_op->aio_write))
3547 ro = 1;
3548
3549 size = i_size_read(inode->i_mapping->host);
3550 if (size < 0) {
3551 LINFO(curlun, "unable to find file size: %s\n", filename);
3552 rc = (int) size;
3553 goto out;
3554 }
3555 num_sectors = size >> 9; // File size in 512-byte sectors
3556 if (num_sectors == 0) {
3557 LINFO(curlun, "file too small: %s\n", filename);
3558 rc = -ETOOSMALL;
3559 goto out;
3560 }
3561
3562 get_file(filp);
3563 curlun->ro = ro;
3564 curlun->filp = filp;
3565 curlun->file_length = size;
3566 curlun->num_sectors = num_sectors;
3567 LDBG(curlun, "open backing file: %s\n", filename);
3568 rc = 0;
3569
3570out:
3571 filp_close(filp, current->files);
3572 return rc;
3573}
3574
3575
3576static void close_backing_file(struct lun *curlun)
3577{
3578 if (curlun->filp) {
3579 LDBG(curlun, "close backing file\n");
3580 fput(curlun->filp);
3581 curlun->filp = NULL;
3582 }
3583}
3584
3585static void close_all_backing_files(struct fsg_dev *fsg)
3586{
3587 int i;
3588
3589 for (i = 0; i < fsg->nluns; ++i)
3590 close_backing_file(&fsg->luns[i]);
3591}
3592
3593
Yani Ioannou10523b32005-05-17 06:43:37 -04003594static ssize_t show_ro(struct device *dev, struct device_attribute *attr, char *buf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003595{
3596 struct lun *curlun = dev_to_lun(dev);
3597
3598 return sprintf(buf, "%d\n", curlun->ro);
3599}
3600
Yani Ioannou10523b32005-05-17 06:43:37 -04003601static ssize_t show_file(struct device *dev, struct device_attribute *attr, char *buf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003602{
3603 struct lun *curlun = dev_to_lun(dev);
John Daiker7ca46b82006-12-29 19:02:06 -08003604 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003605 char *p;
3606 ssize_t rc;
3607
3608 down_read(&fsg->filesem);
3609 if (backing_file_is_open(curlun)) { // Get the complete pathname
Josef Sipek33cb8992006-12-08 02:37:46 -08003610 p = d_path(curlun->filp->f_path.dentry, curlun->filp->f_path.mnt,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003611 buf, PAGE_SIZE - 1);
3612 if (IS_ERR(p))
3613 rc = PTR_ERR(p);
3614 else {
3615 rc = strlen(p);
3616 memmove(buf, p, rc);
3617 buf[rc] = '\n'; // Add a newline
3618 buf[++rc] = 0;
3619 }
3620 } else { // No file, return 0 bytes
3621 *buf = 0;
3622 rc = 0;
3623 }
3624 up_read(&fsg->filesem);
3625 return rc;
3626}
3627
3628
Yani Ioannou10523b32005-05-17 06:43:37 -04003629static ssize_t store_ro(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003630{
3631 ssize_t rc = count;
3632 struct lun *curlun = dev_to_lun(dev);
John Daiker7ca46b82006-12-29 19:02:06 -08003633 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003634 int i;
3635
3636 if (sscanf(buf, "%d", &i) != 1)
3637 return -EINVAL;
3638
3639 /* Allow the write-enable status to change only while the backing file
3640 * is closed. */
3641 down_read(&fsg->filesem);
3642 if (backing_file_is_open(curlun)) {
3643 LDBG(curlun, "read-only status change prevented\n");
3644 rc = -EBUSY;
3645 } else {
3646 curlun->ro = !!i;
3647 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
3648 }
3649 up_read(&fsg->filesem);
3650 return rc;
3651}
3652
Yani Ioannou10523b32005-05-17 06:43:37 -04003653static ssize_t store_file(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003654{
3655 struct lun *curlun = dev_to_lun(dev);
John Daiker7ca46b82006-12-29 19:02:06 -08003656 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003657 int rc = 0;
3658
3659 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
3660 LDBG(curlun, "eject attempt prevented\n");
3661 return -EBUSY; // "Door is locked"
3662 }
3663
3664 /* Remove a trailing newline */
3665 if (count > 0 && buf[count-1] == '\n')
3666 ((char *) buf)[count-1] = 0; // Ugh!
3667
3668 /* Eject current medium */
3669 down_write(&fsg->filesem);
3670 if (backing_file_is_open(curlun)) {
3671 close_backing_file(curlun);
3672 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
3673 }
3674
3675 /* Load new medium */
3676 if (count > 0 && buf[0]) {
3677 rc = open_backing_file(curlun, buf);
3678 if (rc == 0)
3679 curlun->unit_attention_data =
3680 SS_NOT_READY_TO_READY_TRANSITION;
3681 }
3682 up_write(&fsg->filesem);
3683 return (rc < 0 ? rc : count);
3684}
3685
3686
3687/* The write permissions and store_xxx pointers are set in fsg_bind() */
3688static DEVICE_ATTR(ro, 0444, show_ro, NULL);
3689static DEVICE_ATTR(file, 0444, show_file, NULL);
3690
3691
3692/*-------------------------------------------------------------------------*/
3693
Alan Stern87c42522005-11-09 16:59:56 -05003694static void fsg_release(struct kref *ref)
3695{
3696 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
3697
3698 kfree(fsg->luns);
3699 kfree(fsg);
3700}
3701
Linus Torvalds1da177e2005-04-16 15:20:36 -07003702static void lun_release(struct device *dev)
3703{
John Daiker7ca46b82006-12-29 19:02:06 -08003704 struct fsg_dev *fsg = dev_get_drvdata(dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003705
Alan Stern87c42522005-11-09 16:59:56 -05003706 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003707}
3708
David Brownella3536782006-07-06 15:48:53 -07003709static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003710{
3711 struct fsg_dev *fsg = get_gadget_data(gadget);
3712 int i;
3713 struct lun *curlun;
3714 struct usb_request *req = fsg->ep0req;
3715
3716 DBG(fsg, "unbind\n");
3717 clear_bit(REGISTERED, &fsg->atomic_bitflags);
3718
3719 /* Unregister the sysfs attribute files and the LUNs */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003720 for (i = 0; i < fsg->nluns; ++i) {
3721 curlun = &fsg->luns[i];
3722 if (curlun->registered) {
3723 device_remove_file(&curlun->dev, &dev_attr_ro);
3724 device_remove_file(&curlun->dev, &dev_attr_file);
3725 device_unregister(&curlun->dev);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003726 curlun->registered = 0;
3727 }
3728 }
3729
3730 /* If the thread isn't already dead, tell it to exit now */
3731 if (fsg->state != FSG_STATE_TERMINATED) {
3732 raise_exception(fsg, FSG_STATE_EXIT);
3733 wait_for_completion(&fsg->thread_notifier);
3734
3735 /* The cleanup routine waits for this completion also */
3736 complete(&fsg->thread_notifier);
3737 }
3738
3739 /* Free the data buffers */
David Brownell9d8bab52007-07-01 11:04:54 -07003740 for (i = 0; i < NUM_BUFFERS; ++i)
3741 kfree(fsg->buffhds[i].buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003742
3743 /* Free the request and buffer for endpoint 0 */
3744 if (req) {
David Brownell9d8bab52007-07-01 11:04:54 -07003745 kfree(req->buf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003746 usb_ep_free_request(fsg->ep0, req);
3747 }
3748
3749 set_gadget_data(gadget, NULL);
3750}
3751
3752
3753static int __init check_parameters(struct fsg_dev *fsg)
3754{
3755 int prot;
David Brownell91e79c92005-07-13 15:18:30 -07003756 int gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003757
3758 /* Store the default values */
3759 mod_data.transport_type = USB_PR_BULK;
3760 mod_data.transport_name = "Bulk-only";
3761 mod_data.protocol_type = USB_SC_SCSI;
3762 mod_data.protocol_name = "Transparent SCSI";
3763
3764 if (gadget_is_sh(fsg->gadget))
3765 mod_data.can_stall = 0;
3766
3767 if (mod_data.release == 0xffff) { // Parameter wasn't set
Linus Torvalds1da177e2005-04-16 15:20:36 -07003768 /* The sa1100 controller is not supported */
David Brownell91e79c92005-07-13 15:18:30 -07003769 if (gadget_is_sa1100(fsg->gadget))
3770 gcnum = -1;
3771 else
3772 gcnum = usb_gadget_controller_number(fsg->gadget);
3773 if (gcnum >= 0)
3774 mod_data.release = 0x0300 + gcnum;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003775 else {
3776 WARN(fsg, "controller '%s' not recognized\n",
3777 fsg->gadget->name);
3778 mod_data.release = 0x0399;
3779 }
3780 }
3781
3782 prot = simple_strtol(mod_data.protocol_parm, NULL, 0);
3783
3784#ifdef CONFIG_USB_FILE_STORAGE_TEST
3785 if (strnicmp(mod_data.transport_parm, "BBB", 10) == 0) {
3786 ; // Use default setting
3787 } else if (strnicmp(mod_data.transport_parm, "CB", 10) == 0) {
3788 mod_data.transport_type = USB_PR_CB;
3789 mod_data.transport_name = "Control-Bulk";
3790 } else if (strnicmp(mod_data.transport_parm, "CBI", 10) == 0) {
3791 mod_data.transport_type = USB_PR_CBI;
3792 mod_data.transport_name = "Control-Bulk-Interrupt";
3793 } else {
3794 ERROR(fsg, "invalid transport: %s\n", mod_data.transport_parm);
3795 return -EINVAL;
3796 }
3797
3798 if (strnicmp(mod_data.protocol_parm, "SCSI", 10) == 0 ||
3799 prot == USB_SC_SCSI) {
3800 ; // Use default setting
3801 } else if (strnicmp(mod_data.protocol_parm, "RBC", 10) == 0 ||
3802 prot == USB_SC_RBC) {
3803 mod_data.protocol_type = USB_SC_RBC;
3804 mod_data.protocol_name = "RBC";
3805 } else if (strnicmp(mod_data.protocol_parm, "8020", 4) == 0 ||
3806 strnicmp(mod_data.protocol_parm, "ATAPI", 10) == 0 ||
3807 prot == USB_SC_8020) {
3808 mod_data.protocol_type = USB_SC_8020;
3809 mod_data.protocol_name = "8020i (ATAPI)";
3810 } else if (strnicmp(mod_data.protocol_parm, "QIC", 3) == 0 ||
3811 prot == USB_SC_QIC) {
3812 mod_data.protocol_type = USB_SC_QIC;
3813 mod_data.protocol_name = "QIC-157";
3814 } else if (strnicmp(mod_data.protocol_parm, "UFI", 10) == 0 ||
3815 prot == USB_SC_UFI) {
3816 mod_data.protocol_type = USB_SC_UFI;
3817 mod_data.protocol_name = "UFI";
3818 } else if (strnicmp(mod_data.protocol_parm, "8070", 4) == 0 ||
3819 prot == USB_SC_8070) {
3820 mod_data.protocol_type = USB_SC_8070;
3821 mod_data.protocol_name = "8070i";
3822 } else {
3823 ERROR(fsg, "invalid protocol: %s\n", mod_data.protocol_parm);
3824 return -EINVAL;
3825 }
3826
3827 mod_data.buflen &= PAGE_CACHE_MASK;
3828 if (mod_data.buflen <= 0) {
3829 ERROR(fsg, "invalid buflen\n");
3830 return -ETOOSMALL;
3831 }
3832#endif /* CONFIG_USB_FILE_STORAGE_TEST */
3833
3834 return 0;
3835}
3836
3837
3838static int __init fsg_bind(struct usb_gadget *gadget)
3839{
3840 struct fsg_dev *fsg = the_fsg;
3841 int rc;
3842 int i;
3843 struct lun *curlun;
3844 struct usb_ep *ep;
3845 struct usb_request *req;
3846 char *pathbuf, *p;
3847
3848 fsg->gadget = gadget;
3849 set_gadget_data(gadget, fsg);
3850 fsg->ep0 = gadget->ep0;
3851 fsg->ep0->driver_data = fsg;
3852
3853 if ((rc = check_parameters(fsg)) != 0)
3854 goto out;
3855
3856 if (mod_data.removable) { // Enable the store_xxx attributes
3857 dev_attr_ro.attr.mode = dev_attr_file.attr.mode = 0644;
3858 dev_attr_ro.store = store_ro;
3859 dev_attr_file.store = store_file;
3860 }
3861
3862 /* Find out how many LUNs there should be */
3863 i = mod_data.nluns;
3864 if (i == 0)
3865 i = max(mod_data.num_filenames, 1);
3866 if (i > MAX_LUNS) {
3867 ERROR(fsg, "invalid number of LUNs: %d\n", i);
3868 rc = -EINVAL;
3869 goto out;
3870 }
3871
3872 /* Create the LUNs, open their backing files, and register the
3873 * LUN devices in sysfs. */
Alan Sterna922c682005-10-06 16:38:45 -04003874 fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003875 if (!fsg->luns) {
3876 rc = -ENOMEM;
3877 goto out;
3878 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003879 fsg->nluns = i;
3880
3881 for (i = 0; i < fsg->nluns; ++i) {
3882 curlun = &fsg->luns[i];
Alan Sternaafe5bd2006-03-31 11:46:43 -05003883 curlun->ro = mod_data.ro[i];
Alan Stern2de9eae2006-09-25 14:31:15 -04003884 curlun->dev.release = lun_release;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003885 curlun->dev.parent = &gadget->dev;
3886 curlun->dev.driver = &fsg_driver.driver;
3887 dev_set_drvdata(&curlun->dev, fsg);
3888 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
3889 "%s-lun%d", gadget->dev.bus_id, i);
3890
Alan Stern2de9eae2006-09-25 14:31:15 -04003891 if ((rc = device_register(&curlun->dev)) != 0) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003892 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
Alan Stern2de9eae2006-09-25 14:31:15 -04003893 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003894 }
Alan Stern2de9eae2006-09-25 14:31:15 -04003895 if ((rc = device_create_file(&curlun->dev,
3896 &dev_attr_ro)) != 0 ||
3897 (rc = device_create_file(&curlun->dev,
3898 &dev_attr_file)) != 0) {
3899 device_unregister(&curlun->dev);
3900 goto out;
3901 }
3902 curlun->registered = 1;
3903 kref_get(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003904
Alan Sternaafe5bd2006-03-31 11:46:43 -05003905 if (mod_data.file[i] && *mod_data.file[i]) {
3906 if ((rc = open_backing_file(curlun,
3907 mod_data.file[i])) != 0)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003908 goto out;
3909 } else if (!mod_data.removable) {
3910 ERROR(fsg, "no file given for LUN%d\n", i);
3911 rc = -EINVAL;
3912 goto out;
3913 }
3914 }
3915
3916 /* Find all the endpoints we will use */
3917 usb_ep_autoconfig_reset(gadget);
3918 ep = usb_ep_autoconfig(gadget, &fs_bulk_in_desc);
3919 if (!ep)
3920 goto autoconf_fail;
3921 ep->driver_data = fsg; // claim the endpoint
3922 fsg->bulk_in = ep;
3923
3924 ep = usb_ep_autoconfig(gadget, &fs_bulk_out_desc);
3925 if (!ep)
3926 goto autoconf_fail;
3927 ep->driver_data = fsg; // claim the endpoint
3928 fsg->bulk_out = ep;
3929
3930 if (transport_is_cbi()) {
3931 ep = usb_ep_autoconfig(gadget, &fs_intr_in_desc);
3932 if (!ep)
3933 goto autoconf_fail;
3934 ep->driver_data = fsg; // claim the endpoint
3935 fsg->intr_in = ep;
3936 }
3937
3938 /* Fix up the descriptors */
3939 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3940 device_desc.idVendor = cpu_to_le16(mod_data.vendor);
3941 device_desc.idProduct = cpu_to_le16(mod_data.product);
3942 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3943
3944 i = (transport_is_cbi() ? 3 : 2); // Number of endpoints
3945 intf_desc.bNumEndpoints = i;
3946 intf_desc.bInterfaceSubClass = mod_data.protocol_type;
3947 intf_desc.bInterfaceProtocol = mod_data.transport_type;
3948 fs_function[i + FS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3949
3950#ifdef CONFIG_USB_GADGET_DUALSPEED
3951 hs_function[i + HS_FUNCTION_PRE_EP_ENTRIES] = NULL;
3952
3953 /* Assume ep0 uses the same maxpacket value for both speeds */
3954 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3955
3956 /* Assume that all endpoint addresses are the same for both speeds */
3957 hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress;
3958 hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress;
3959 hs_intr_in_desc.bEndpointAddress = fs_intr_in_desc.bEndpointAddress;
3960#endif
3961
3962 if (gadget->is_otg) {
Tony Lindgren02036332007-05-29 09:57:41 -07003963 otg_desc.bmAttributes |= USB_OTG_HNP;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003964 }
3965
3966 rc = -ENOMEM;
3967
3968 /* Allocate the request and buffer for endpoint 0 */
3969 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3970 if (!req)
3971 goto out;
David Brownell9d8bab52007-07-01 11:04:54 -07003972 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003973 if (!req->buf)
3974 goto out;
3975 req->complete = ep0_complete;
3976
3977 /* Allocate the data buffers */
3978 for (i = 0; i < NUM_BUFFERS; ++i) {
3979 struct fsg_buffhd *bh = &fsg->buffhds[i];
3980
Alan Stern14cd5f82006-03-23 15:07:25 -05003981 /* Allocate for the bulk-in endpoint. We assume that
3982 * the buffer will also work with the bulk-out (and
3983 * interrupt-in) endpoint. */
David Brownell9d8bab52007-07-01 11:04:54 -07003984 bh->buf = kmalloc(mod_data.buflen, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003985 if (!bh->buf)
3986 goto out;
3987 bh->next = bh + 1;
3988 }
3989 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
3990
3991 /* This should reflect the actual gadget power source */
3992 usb_gadget_set_selfpowered(gadget);
3993
3994 snprintf(manufacturer, sizeof manufacturer, "%s %s with %s",
Serge E. Hallyn96b644b2006-10-02 02:18:13 -07003995 init_utsname()->sysname, init_utsname()->release,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003996 gadget->name);
3997
3998 /* On a real device, serial[] would be loaded from permanent
3999 * storage. We just encode it from the driver version string. */
4000 for (i = 0; i < sizeof(serial) - 2; i += 2) {
4001 unsigned char c = DRIVER_VERSION[i / 2];
4002
4003 if (!c)
4004 break;
4005 sprintf(&serial[i], "%02X", c);
4006 }
4007
Alan Stern22efcf42005-09-26 16:12:02 -04004008 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
4009 "file-storage-gadget");
4010 if (IS_ERR(fsg->thread_task)) {
4011 rc = PTR_ERR(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004012 goto out;
Alan Stern22efcf42005-09-26 16:12:02 -04004013 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07004014
4015 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
4016 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
4017
4018 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4019 for (i = 0; i < fsg->nluns; ++i) {
4020 curlun = &fsg->luns[i];
4021 if (backing_file_is_open(curlun)) {
4022 p = NULL;
4023 if (pathbuf) {
Josef Sipek33cb8992006-12-08 02:37:46 -08004024 p = d_path(curlun->filp->f_path.dentry,
4025 curlun->filp->f_path.mnt,
Linus Torvalds1da177e2005-04-16 15:20:36 -07004026 pathbuf, PATH_MAX);
4027 if (IS_ERR(p))
4028 p = NULL;
4029 }
4030 LINFO(curlun, "ro=%d, file: %s\n",
4031 curlun->ro, (p ? p : "(error)"));
4032 }
4033 }
4034 kfree(pathbuf);
4035
4036 DBG(fsg, "transport=%s (x%02x)\n",
4037 mod_data.transport_name, mod_data.transport_type);
4038 DBG(fsg, "protocol=%s (x%02x)\n",
4039 mod_data.protocol_name, mod_data.protocol_type);
4040 DBG(fsg, "VendorID=x%04x, ProductID=x%04x, Release=x%04x\n",
4041 mod_data.vendor, mod_data.product, mod_data.release);
4042 DBG(fsg, "removable=%d, stall=%d, buflen=%u\n",
4043 mod_data.removable, mod_data.can_stall,
4044 mod_data.buflen);
Alan Stern22efcf42005-09-26 16:12:02 -04004045 DBG(fsg, "I/O thread pid: %d\n", fsg->thread_task->pid);
Alan Sterna922c682005-10-06 16:38:45 -04004046
4047 set_bit(REGISTERED, &fsg->atomic_bitflags);
4048
4049 /* Tell the thread to start working */
4050 wake_up_process(fsg->thread_task);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004051 return 0;
4052
4053autoconf_fail:
4054 ERROR(fsg, "unable to autoconfigure all endpoints\n");
4055 rc = -ENOTSUPP;
4056
4057out:
4058 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
4059 fsg_unbind(gadget);
4060 close_all_backing_files(fsg);
4061 return rc;
4062}
4063
4064
4065/*-------------------------------------------------------------------------*/
4066
4067static void fsg_suspend(struct usb_gadget *gadget)
4068{
4069 struct fsg_dev *fsg = get_gadget_data(gadget);
4070
4071 DBG(fsg, "suspend\n");
4072 set_bit(SUSPENDED, &fsg->atomic_bitflags);
4073}
4074
4075static void fsg_resume(struct usb_gadget *gadget)
4076{
4077 struct fsg_dev *fsg = get_gadget_data(gadget);
4078
4079 DBG(fsg, "resume\n");
4080 clear_bit(SUSPENDED, &fsg->atomic_bitflags);
4081}
4082
4083
4084/*-------------------------------------------------------------------------*/
4085
4086static struct usb_gadget_driver fsg_driver = {
4087#ifdef CONFIG_USB_GADGET_DUALSPEED
4088 .speed = USB_SPEED_HIGH,
4089#else
4090 .speed = USB_SPEED_FULL,
4091#endif
4092 .function = (char *) longname,
4093 .bind = fsg_bind,
David Brownell6bea4762006-12-05 03:15:33 -08004094 .unbind = fsg_unbind,
Linus Torvalds1da177e2005-04-16 15:20:36 -07004095 .disconnect = fsg_disconnect,
4096 .setup = fsg_setup,
4097 .suspend = fsg_suspend,
4098 .resume = fsg_resume,
4099
4100 .driver = {
4101 .name = (char *) shortname,
Ben Dooksd0d50492005-10-10 10:52:33 +01004102 .owner = THIS_MODULE,
Linus Torvalds1da177e2005-04-16 15:20:36 -07004103 // .release = ...
4104 // .suspend = ...
4105 // .resume = ...
4106 },
4107};
4108
4109
4110static int __init fsg_alloc(void)
4111{
4112 struct fsg_dev *fsg;
4113
Alan Sterna922c682005-10-06 16:38:45 -04004114 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004115 if (!fsg)
4116 return -ENOMEM;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004117 spin_lock_init(&fsg->lock);
4118 init_rwsem(&fsg->filesem);
Alan Stern87c42522005-11-09 16:59:56 -05004119 kref_init(&fsg->ref);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004120 init_completion(&fsg->thread_notifier);
4121
4122 the_fsg = fsg;
4123 return 0;
4124}
4125
4126
Linus Torvalds1da177e2005-04-16 15:20:36 -07004127static int __init fsg_init(void)
4128{
4129 int rc;
4130 struct fsg_dev *fsg;
4131
4132 if ((rc = fsg_alloc()) != 0)
4133 return rc;
4134 fsg = the_fsg;
Alan Sterna922c682005-10-06 16:38:45 -04004135 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
Alan Stern87c42522005-11-09 16:59:56 -05004136 kref_put(&fsg->ref, fsg_release);
Alan Sterna922c682005-10-06 16:38:45 -04004137 return rc;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004138}
4139module_init(fsg_init);
4140
4141
4142static void __exit fsg_cleanup(void)
4143{
4144 struct fsg_dev *fsg = the_fsg;
4145
4146 /* Unregister the driver iff the thread hasn't already done so */
4147 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
4148 usb_gadget_unregister_driver(&fsg_driver);
4149
4150 /* Wait for the thread to finish up */
4151 wait_for_completion(&fsg->thread_notifier);
4152
4153 close_all_backing_files(fsg);
Alan Stern87c42522005-11-09 16:59:56 -05004154 kref_put(&fsg->ref, fsg_release);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004155}
4156module_exit(fsg_cleanup);