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