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