]> bbs.cooldavid.org Git - net-next-2.6.git/blame - drivers/usb/gadget/f_mass_storage.c
USB: g_mass_storage: fsg_common_init() created
[net-next-2.6.git] / drivers / usb / gadget / f_mass_storage.c
CommitLineData
d5e2b67a
MN
1/*
2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
3 *
4 * Copyright (C) 2003-2008 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 or as a CD-ROM drive. In addition
42 * to providing an example of a genuinely useful gadget driver for a USB
43 * device, it also illustrates a technique of double-buffering for increased
44 * throughput. Last but not least, it gives an easy way to probe the
45 * behavior of the Mass Storage drivers in a USB host.
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. (For CD-ROM emulation,
50 * access is always read-only.) The gadget will indicate that it has
51 * removable media if the optional "removable" module parameter is set.
52 *
d5e2b67a
MN
53 * There is support for multiple logical units (LUNs), each of which has
54 * its own backing file. The number of LUNs can be set using the optional
55 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
56 * files are specified using comma-separated lists for "file" and "ro".
57 * The default number of LUNs is taken from the number of "file" elements;
58 * it is 1 if "file" is not given. If "removable" is not set then a backing
59 * file must be specified for each LUN. If it is set, then an unspecified
60 * or empty backing filename means the LUN's medium is not loaded. Ideally
61 * each LUN would be settable independently as a disk drive or a CD-ROM
62 * drive, but currently all LUNs have to be the same type. The CD-ROM
63 * emulation includes a single data track and no audio tracks; hence there
64 * need be only one backing file per LUN. Note also that the CD-ROM block
65 * length is set to 512 rather than the more common value 2048.
66 *
67 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
68 * needed (an interrupt-out endpoint is also needed for CBI). The memory
69 * requirement amounts to two 16K buffers, size configurable by a parameter.
70 * Support is included for both full-speed and high-speed operation.
71 *
72 * Note that the driver is slightly non-portable in that it assumes a
73 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
74 * interrupt-in endpoints. With most device controllers this isn't an
75 * issue, but there may be some with hardware restrictions that prevent
76 * a buffer from being used by more than one endpoint.
77 *
78 * Module options:
79 *
80 * file=filename[,filename...]
81 * Required if "removable" is not set, names of
82 * the files or block devices used for
83 * backing storage
84 * ro=b[,b...] Default false, booleans for read-only access
85 * removable Default false, boolean for removable media
86 * luns=N Default N = number of filenames, number of
87 * LUNs to support
88 * stall Default determined according to the type of
89 * USB device controller (usually true),
90 * boolean to permit the driver to halt
91 * bulk endpoints
92 * cdrom Default false, boolean for whether to emulate
93 * a CD-ROM drive
d5e2b67a
MN
94 *
95 * The pathnames of the backing files and the ro settings are available in
96 * the attribute files "file" and "ro" in the lun<n> subdirectory of the
97 * gadget's sysfs directory. If the "removable" option is set, writing to
98 * these files will simulate ejecting/loading the medium (writing an empty
99 * line means eject) and adjusting a write-enable tab. Changes to the ro
100 * setting are not allowed when the medium is loaded or if CD-ROM emulation
101 * is being used.
102 *
103 * This gadget driver is heavily based on "Gadget Zero" by David Brownell.
104 * The driver's SCSI command interface was based on the "Information
105 * technology - Small Computer System Interface - 2" document from
106 * X3T9.2 Project 375D, Revision 10L, 7-SEP-93, available at
107 * <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. The single exception
108 * is opcode 0x23 (READ FORMAT CAPACITIES), which was based on the
109 * "Universal Serial Bus Mass Storage Class UFI Command Specification"
110 * document, Revision 1.0, December 14, 1998, available at
111 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
112 */
113
114
115/*
116 * Driver Design
117 *
118 * The FSG driver is fairly straightforward. There is a main kernel
119 * thread that handles most of the work. Interrupt routines field
120 * callbacks from the controller driver: bulk- and interrupt-request
121 * completion notifications, endpoint-0 events, and disconnect events.
122 * Completion events are passed to the main thread by wakeup calls. Many
123 * ep0 requests are handled at interrupt time, but SetInterface,
124 * SetConfiguration, and device reset requests are forwarded to the
125 * thread in the form of "exceptions" using SIGUSR1 signals (since they
126 * should interrupt any ongoing file I/O operations).
127 *
128 * The thread's main routine implements the standard command/data/status
129 * parts of a SCSI interaction. It and its subroutines are full of tests
130 * for pending signals/exceptions -- all this polling is necessary since
131 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
132 * indication that the driver really wants to be running in userspace.)
133 * An important point is that so long as the thread is alive it keeps an
134 * open reference to the backing file. This will prevent unmounting
135 * the backing file's underlying filesystem and could cause problems
136 * during system shutdown, for example. To prevent such problems, the
137 * thread catches INT, TERM, and KILL signals and converts them into
138 * an EXIT exception.
139 *
140 * In normal operation the main thread is started during the gadget's
141 * fsg_bind() callback and stopped during fsg_unbind(). But it can also
142 * exit when it receives a signal, and there's no point leaving the
143 * gadget running when the thread is dead. So just before the thread
144 * exits, it deregisters the gadget driver. This makes things a little
145 * tricky: The driver is deregistered at two places, and the exiting
146 * thread can indirectly call fsg_unbind() which in turn can tell the
147 * thread to exit. The first problem is resolved through the use of the
148 * REGISTERED atomic bitflag; the driver will only be deregistered once.
149 * The second problem is resolved by having fsg_unbind() check
150 * fsg->state; it won't try to stop the thread if the state is already
151 * FSG_STATE_TERMINATED.
152 *
153 * To provide maximum throughput, the driver uses a circular pipeline of
154 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
155 * arbitrarily long; in practice the benefits don't justify having more
156 * than 2 stages (i.e., double buffering). But it helps to think of the
157 * pipeline as being a long one. Each buffer head contains a bulk-in and
158 * a bulk-out request pointer (since the buffer can be used for both
159 * output and input -- directions always are given from the host's
160 * point of view) as well as a pointer to the buffer and various state
161 * variables.
162 *
163 * Use of the pipeline follows a simple protocol. There is a variable
164 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
165 * At any time that buffer head may still be in use from an earlier
166 * request, so each buffer head has a state variable indicating whether
167 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
168 * buffer head to be EMPTY, filling the buffer either by file I/O or by
169 * USB I/O (during which the buffer head is BUSY), and marking the buffer
170 * head FULL when the I/O is complete. Then the buffer will be emptied
171 * (again possibly by USB I/O, during which it is marked BUSY) and
172 * finally marked EMPTY again (possibly by a completion routine).
173 *
174 * A module parameter tells the driver to avoid stalling the bulk
175 * endpoints wherever the transport specification allows. This is
176 * necessary for some UDCs like the SuperH, which cannot reliably clear a
177 * halt on a bulk endpoint. However, under certain circumstances the
178 * Bulk-only specification requires a stall. In such cases the driver
179 * will halt the endpoint and set a flag indicating that it should clear
180 * the halt in software during the next device reset. Hopefully this
181 * will permit everything to work correctly. Furthermore, although the
182 * specification allows the bulk-out endpoint to halt when the host sends
183 * too much data, implementing this would cause an unavoidable race.
184 * The driver will always use the "no-stall" approach for OUT transfers.
185 *
186 * One subtle point concerns sending status-stage responses for ep0
187 * requests. Some of these requests, such as device reset, can involve
188 * interrupting an ongoing file I/O operation, which might take an
189 * arbitrarily long time. During that delay the host might give up on
190 * the original ep0 request and issue a new one. When that happens the
191 * driver should not notify the host about completion of the original
192 * request, as the host will no longer be waiting for it. So the driver
193 * assigns to each ep0 request a unique tag, and it keeps track of the
194 * tag value of the request associated with a long-running exception
195 * (device-reset, interface-change, or configuration-change). When the
196 * exception handler is finished, the status-stage response is submitted
197 * only if the current ep0 request tag is equal to the exception request
198 * tag. Thus only the most recently received ep0 request will get a
199 * status-stage response.
200 *
201 * Warning: This driver source file is too long. It ought to be split up
202 * into a header file plus about 3 separate .c files, to handle the details
203 * of the Gadget, USB Mass Storage, and SCSI protocols.
204 */
205
206
207/* #define VERBOSE_DEBUG */
208/* #define DUMP_MSGS */
209
210
211#include <linux/blkdev.h>
212#include <linux/completion.h>
213#include <linux/dcache.h>
214#include <linux/delay.h>
215#include <linux/device.h>
216#include <linux/fcntl.h>
217#include <linux/file.h>
218#include <linux/fs.h>
219#include <linux/kref.h>
220#include <linux/kthread.h>
221#include <linux/limits.h>
222#include <linux/rwsem.h>
223#include <linux/slab.h>
224#include <linux/spinlock.h>
225#include <linux/string.h>
226#include <linux/freezer.h>
227#include <linux/utsname.h>
228
229#include <linux/usb/ch9.h>
230#include <linux/usb/gadget.h>
231
232#include "gadget_chips.h"
233
234
235
236/*
237 * Kbuild is not very cooperative with respect to linking separately
238 * compiled library objects into one module. So for now we won't use
239 * separate compilation ... ensuring init/exit sections work to shrink
240 * the runtime footprint, and giving us at least some parts of what
241 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
242 */
243#include "usbstring.c"
244#include "config.c"
245#include "epautoconf.c"
246
247/*-------------------------------------------------------------------------*/
248
249#define DRIVER_DESC "File-backed Storage Gadget"
250#define DRIVER_NAME "g_file_storage"
251#define DRIVER_VERSION "20 November 2008"
252
253static char fsg_string_manufacturer[64];
254static const char fsg_string_product[] = DRIVER_DESC;
255static char fsg_string_serial[13];
256static const char fsg_string_config[] = "Self-powered";
257static const char fsg_string_interface[] = "Mass Storage";
258
259
93bcf12e 260#define FSG_NO_INTR_EP 1
606206c2 261#define FSG_BUFFHD_STATIC_BUFFER 1
93bcf12e 262
d5e2b67a
MN
263#include "storage_common.c"
264
265
266MODULE_DESCRIPTION(DRIVER_DESC);
267MODULE_AUTHOR("Alan Stern");
268MODULE_LICENSE("Dual BSD/GPL");
269
270/*
271 * This driver assumes self-powered hardware and has no way for users to
272 * trigger remote wakeup. It uses autoconfiguration to select endpoints
273 * and endpoint addresses.
274 */
275
276
277/*-------------------------------------------------------------------------*/
278
279
280/* Encapsulate the module parameter settings */
281
282static struct {
283 char *file[FSG_MAX_LUNS];
284 int ro[FSG_MAX_LUNS];
285 unsigned int num_filenames;
286 unsigned int num_ros;
287 unsigned int nluns;
288
289 int removable;
290 int can_stall;
291 int cdrom;
292
d5e2b67a 293 unsigned short release;
d5e2b67a 294} mod_data = { // Default values
d5e2b67a
MN
295 .removable = 0,
296 .can_stall = 1,
297 .cdrom = 0,
d5e2b67a
MN
298 };
299
300
301module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
302 S_IRUGO);
303MODULE_PARM_DESC(file, "names of backing files or devices");
304
305module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
306MODULE_PARM_DESC(ro, "true to force read-only");
307
308module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
309MODULE_PARM_DESC(luns, "number of LUNs");
310
311module_param_named(removable, mod_data.removable, bool, S_IRUGO);
312MODULE_PARM_DESC(removable, "true to simulate removable media");
313
314module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
315MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
316
317module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
318MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
319
320
d5e2b67a
MN
321/*-------------------------------------------------------------------------*/
322
323
a41ae418
MN
324/* Data shared by all the FSG instances. */
325struct fsg_common {
9c610213
MN
326 struct usb_gadget *gadget;
327
a41ae418
MN
328 /* filesem protects: backing files in use */
329 struct rw_semaphore filesem;
330
331 struct fsg_buffhd *next_buffhd_to_fill;
332 struct fsg_buffhd *next_buffhd_to_drain;
333 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
334
335 int cmnd_size;
336 u8 cmnd[MAX_COMMAND_SIZE];
337
338 unsigned int nluns;
339 unsigned int lun;
340 struct fsg_lun *luns;
341 struct fsg_lun *curlun;
9c610213
MN
342
343 unsigned int free_storage_on_release:1;
344
345 struct kref ref;
a41ae418
MN
346};
347
348
d5e2b67a 349struct fsg_dev {
a41ae418
MN
350 struct fsg_common *common;
351
352 /* lock protects: state, all the req_busy's */
d5e2b67a
MN
353 spinlock_t lock;
354 struct usb_gadget *gadget;
355
d5e2b67a
MN
356 struct usb_ep *ep0; // Handy copy of gadget->ep0
357 struct usb_request *ep0req; // For control responses
358 unsigned int ep0_req_tag;
359 const char *ep0req_name;
360
d5e2b67a
MN
361 unsigned int bulk_out_maxpacket;
362 enum fsg_state state; // For exception handling
363 unsigned int exception_req_tag;
364
365 u8 config, new_config;
366
367 unsigned int running : 1;
368 unsigned int bulk_in_enabled : 1;
369 unsigned int bulk_out_enabled : 1;
d5e2b67a
MN
370 unsigned int phase_error : 1;
371 unsigned int short_packet_received : 1;
372 unsigned int bad_lun_okay : 1;
373
374 unsigned long atomic_bitflags;
375#define REGISTERED 0
376#define IGNORE_BULK_OUT 1
d5e2b67a
MN
377
378 struct usb_ep *bulk_in;
379 struct usb_ep *bulk_out;
d5e2b67a 380
d5e2b67a
MN
381 int thread_wakeup_needed;
382 struct completion thread_notifier;
383 struct task_struct *thread_task;
384
d5e2b67a
MN
385 enum data_direction data_dir;
386 u32 data_size;
387 u32 data_size_from_cmnd;
388 u32 tag;
d5e2b67a
MN
389 u32 residue;
390 u32 usb_amount_left;
d5e2b67a
MN
391};
392
393typedef void (*fsg_routine_t)(struct fsg_dev *);
394
395static int exception_in_progress(struct fsg_dev *fsg)
396{
397 return (fsg->state > FSG_STATE_IDLE);
398}
399
400/* Make bulk-out requests be divisible by the maxpacket size */
401static void set_bulk_out_req_length(struct fsg_dev *fsg,
402 struct fsg_buffhd *bh, unsigned int length)
403{
404 unsigned int rem;
405
406 bh->bulk_out_intended_length = length;
407 rem = length % fsg->bulk_out_maxpacket;
408 if (rem > 0)
409 length += fsg->bulk_out_maxpacket - rem;
410 bh->outreq->length = length;
411}
412
413static struct fsg_dev *the_fsg;
414static struct usb_gadget_driver fsg_driver;
415
416
417/*-------------------------------------------------------------------------*/
418
419static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
420{
421 const char *name;
422
423 if (ep == fsg->bulk_in)
424 name = "bulk-in";
425 else if (ep == fsg->bulk_out)
426 name = "bulk-out";
427 else
428 name = ep->name;
429 DBG(fsg, "%s set halt\n", name);
430 return usb_ep_set_halt(ep);
431}
432
433
434/*-------------------------------------------------------------------------*/
435
436/*
437 * DESCRIPTORS ... most are static, but strings and (full) configuration
438 * descriptors are built on demand. Also the (static) config and interface
439 * descriptors are adjusted during fsg_bind().
440 */
441
442/* There is only one configuration. */
443#define CONFIG_VALUE 1
444
445static struct usb_device_descriptor
446device_desc = {
447 .bLength = sizeof device_desc,
448 .bDescriptorType = USB_DT_DEVICE,
449
450 .bcdUSB = cpu_to_le16(0x0200),
451 .bDeviceClass = USB_CLASS_PER_INTERFACE,
452
453 /* The next three values can be overridden by module parameters */
454 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
455 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
456 .bcdDevice = cpu_to_le16(0xffff),
457
458 .iManufacturer = FSG_STRING_MANUFACTURER,
459 .iProduct = FSG_STRING_PRODUCT,
460 .iSerialNumber = FSG_STRING_SERIAL,
461 .bNumConfigurations = 1,
462};
463
464static struct usb_config_descriptor
465config_desc = {
466 .bLength = sizeof config_desc,
467 .bDescriptorType = USB_DT_CONFIG,
468
469 /* wTotalLength computed by usb_gadget_config_buf() */
470 .bNumInterfaces = 1,
471 .bConfigurationValue = CONFIG_VALUE,
472 .iConfiguration = FSG_STRING_CONFIG,
473 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
474 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
475};
476
477
478static struct usb_qualifier_descriptor
479dev_qualifier = {
480 .bLength = sizeof dev_qualifier,
481 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
482
483 .bcdUSB = cpu_to_le16(0x0200),
484 .bDeviceClass = USB_CLASS_PER_INTERFACE,
485
486 .bNumConfigurations = 1,
487};
488
489
490
491/*
492 * Config descriptors must agree with the code that sets configurations
493 * and with code managing interfaces and their altsettings. They must
494 * also handle different speeds and other-speed requests.
495 */
496static int populate_config_buf(struct usb_gadget *gadget,
497 u8 *buf, u8 type, unsigned index)
498{
499 enum usb_device_speed speed = gadget->speed;
500 int len;
501 const struct usb_descriptor_header **function;
502
503 if (index > 0)
504 return -EINVAL;
505
506 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
507 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
508 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
509 function = fsg_hs_function;
510 else
511 function = fsg_fs_function;
512
513 /* for now, don't advertise srp-only devices */
514 if (!gadget_is_otg(gadget))
515 function++;
516
517 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
518 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
519 return len;
520}
521
522
523/*-------------------------------------------------------------------------*/
524
525/* These routines may be called in process context or in_irq */
526
527/* Caller must hold fsg->lock */
528static void wakeup_thread(struct fsg_dev *fsg)
529{
530 /* Tell the main thread that something has happened */
531 fsg->thread_wakeup_needed = 1;
532 if (fsg->thread_task)
533 wake_up_process(fsg->thread_task);
534}
535
536
537static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
538{
539 unsigned long flags;
540
541 /* Do nothing if a higher-priority exception is already in progress.
542 * If a lower-or-equal priority exception is in progress, preempt it
543 * and notify the main thread by sending it a signal. */
544 spin_lock_irqsave(&fsg->lock, flags);
545 if (fsg->state <= new_state) {
546 fsg->exception_req_tag = fsg->ep0_req_tag;
547 fsg->state = new_state;
548 if (fsg->thread_task)
549 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
550 fsg->thread_task);
551 }
552 spin_unlock_irqrestore(&fsg->lock, flags);
553}
554
555
556/*-------------------------------------------------------------------------*/
557
558/* The disconnect callback and ep0 routines. These always run in_irq,
559 * except that ep0_queue() is called in the main thread to acknowledge
560 * completion of various requests: set config, set interface, and
561 * Bulk-only device reset. */
562
563static void fsg_disconnect(struct usb_gadget *gadget)
564{
565 struct fsg_dev *fsg = get_gadget_data(gadget);
566
567 DBG(fsg, "disconnect or port reset\n");
568 raise_exception(fsg, FSG_STATE_DISCONNECT);
569}
570
571
572static int ep0_queue(struct fsg_dev *fsg)
573{
574 int rc;
575
576 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
577 if (rc != 0 && rc != -ESHUTDOWN) {
578
579 /* We can't do much more than wait for a reset */
580 WARNING(fsg, "error in submission: %s --> %d\n",
581 fsg->ep0->name, rc);
582 }
583 return rc;
584}
585
586static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
587{
588 struct fsg_dev *fsg = ep->driver_data;
589
590 if (req->actual > 0)
591 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
592 if (req->status || req->actual != req->length)
593 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
594 req->status, req->actual, req->length);
595 if (req->status == -ECONNRESET) // Request was cancelled
596 usb_ep_fifo_flush(ep);
597
598 if (req->status == 0 && req->context)
599 ((fsg_routine_t) (req->context))(fsg);
600}
601
602
603/*-------------------------------------------------------------------------*/
604
605/* Bulk and interrupt endpoint completion handlers.
606 * These always run in_irq. */
607
608static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
609{
610 struct fsg_dev *fsg = ep->driver_data;
611 struct fsg_buffhd *bh = req->context;
612
613 if (req->status || req->actual != req->length)
614 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
615 req->status, req->actual, req->length);
616 if (req->status == -ECONNRESET) // Request was cancelled
617 usb_ep_fifo_flush(ep);
618
619 /* Hold the lock while we update the request and buffer states */
620 smp_wmb();
621 spin_lock(&fsg->lock);
622 bh->inreq_busy = 0;
623 bh->state = BUF_STATE_EMPTY;
624 wakeup_thread(fsg);
625 spin_unlock(&fsg->lock);
626}
627
628static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
629{
630 struct fsg_dev *fsg = ep->driver_data;
631 struct fsg_buffhd *bh = req->context;
632
633 dump_msg(fsg, "bulk-out", req->buf, req->actual);
634 if (req->status || req->actual != bh->bulk_out_intended_length)
635 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
636 req->status, req->actual,
637 bh->bulk_out_intended_length);
638 if (req->status == -ECONNRESET) // Request was cancelled
639 usb_ep_fifo_flush(ep);
640
641 /* Hold the lock while we update the request and buffer states */
642 smp_wmb();
643 spin_lock(&fsg->lock);
644 bh->outreq_busy = 0;
645 bh->state = BUF_STATE_FULL;
646 wakeup_thread(fsg);
647 spin_unlock(&fsg->lock);
648}
649
650
d5e2b67a
MN
651/*-------------------------------------------------------------------------*/
652
653/* Ep0 class-specific handlers. These always run in_irq. */
654
d5e2b67a
MN
655static int class_setup_req(struct fsg_dev *fsg,
656 const struct usb_ctrlrequest *ctrl)
657{
658 struct usb_request *req = fsg->ep0req;
d5e2b67a 659 u16 w_index = le16_to_cpu(ctrl->wIndex);
93bcf12e 660 u16 w_value = le16_to_cpu(ctrl->wValue);
d5e2b67a
MN
661 u16 w_length = le16_to_cpu(ctrl->wLength);
662
663 if (!fsg->config)
93bcf12e 664 return -EOPNOTSUPP;
d5e2b67a 665
93bcf12e 666 switch (ctrl->bRequest) {
d5e2b67a 667
93bcf12e
MN
668 case USB_BULK_RESET_REQUEST:
669 if (ctrl->bRequestType !=
670 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
d5e2b67a 671 break;
93bcf12e
MN
672 if (w_index != 0 || w_value != 0)
673 return -EDOM;
d5e2b67a 674
93bcf12e
MN
675 /* Raise an exception to stop the current operation
676 * and reinitialize our state. */
677 DBG(fsg, "bulk reset request\n");
678 raise_exception(fsg, FSG_STATE_RESET);
679 return DELAYED_STATUS;
d5e2b67a 680
93bcf12e
MN
681 case USB_BULK_GET_MAX_LUN_REQUEST:
682 if (ctrl->bRequestType !=
683 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
d5e2b67a 684 break;
93bcf12e
MN
685 if (w_index != 0 || w_value != 0)
686 return -EDOM;
687 VDBG(fsg, "get max LUN\n");
a41ae418 688 *(u8 *) req->buf = fsg->common->nluns - 1;
93bcf12e
MN
689 return 1;
690 }
691
692 VDBG(fsg,
693 "unknown class-specific control req "
694 "%02x.%02x v%04x i%04x l%u\n",
695 ctrl->bRequestType, ctrl->bRequest,
696 le16_to_cpu(ctrl->wValue), w_index, w_length);
697 return -EOPNOTSUPP;
d5e2b67a
MN
698}
699
700
701/*-------------------------------------------------------------------------*/
702
703/* Ep0 standard request handlers. These always run in_irq. */
704
705static int standard_setup_req(struct fsg_dev *fsg,
706 const struct usb_ctrlrequest *ctrl)
707{
708 struct usb_request *req = fsg->ep0req;
709 int value = -EOPNOTSUPP;
710 u16 w_index = le16_to_cpu(ctrl->wIndex);
711 u16 w_value = le16_to_cpu(ctrl->wValue);
712
713 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
714 * but config change events will also reconfigure hardware. */
715 switch (ctrl->bRequest) {
716
717 case USB_REQ_GET_DESCRIPTOR:
718 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
719 USB_RECIP_DEVICE))
720 break;
721 switch (w_value >> 8) {
722
723 case USB_DT_DEVICE:
724 VDBG(fsg, "get device descriptor\n");
725 value = sizeof device_desc;
726 memcpy(req->buf, &device_desc, value);
727 break;
728 case USB_DT_DEVICE_QUALIFIER:
729 VDBG(fsg, "get device qualifier\n");
730 if (!gadget_is_dualspeed(fsg->gadget))
731 break;
732 value = sizeof dev_qualifier;
733 memcpy(req->buf, &dev_qualifier, value);
734 break;
735
736 case USB_DT_OTHER_SPEED_CONFIG:
737 VDBG(fsg, "get other-speed config descriptor\n");
738 if (!gadget_is_dualspeed(fsg->gadget))
739 break;
740 goto get_config;
741 case USB_DT_CONFIG:
742 VDBG(fsg, "get configuration descriptor\n");
743get_config:
744 value = populate_config_buf(fsg->gadget,
745 req->buf,
746 w_value >> 8,
747 w_value & 0xff);
748 break;
749
750 case USB_DT_STRING:
751 VDBG(fsg, "get string descriptor\n");
752
753 /* wIndex == language code */
754 value = usb_gadget_get_string(&fsg_stringtab,
755 w_value & 0xff, req->buf);
756 break;
757 }
758 break;
759
760 /* One config, two speeds */
761 case USB_REQ_SET_CONFIGURATION:
762 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
763 USB_RECIP_DEVICE))
764 break;
765 VDBG(fsg, "set configuration\n");
766 if (w_value == CONFIG_VALUE || w_value == 0) {
767 fsg->new_config = w_value;
768
769 /* Raise an exception to wipe out previous transaction
770 * state (queued bufs, etc) and set the new config. */
771 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
772 value = DELAYED_STATUS;
773 }
774 break;
775 case USB_REQ_GET_CONFIGURATION:
776 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
777 USB_RECIP_DEVICE))
778 break;
779 VDBG(fsg, "get configuration\n");
780 *(u8 *) req->buf = fsg->config;
781 value = 1;
782 break;
783
784 case USB_REQ_SET_INTERFACE:
785 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
786 USB_RECIP_INTERFACE))
787 break;
788 if (fsg->config && w_index == 0) {
789
790 /* Raise an exception to wipe out previous transaction
791 * state (queued bufs, etc) and install the new
792 * interface altsetting. */
793 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
794 value = DELAYED_STATUS;
795 }
796 break;
797 case USB_REQ_GET_INTERFACE:
798 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
799 USB_RECIP_INTERFACE))
800 break;
801 if (!fsg->config)
802 break;
803 if (w_index != 0) {
804 value = -EDOM;
805 break;
806 }
807 VDBG(fsg, "get interface\n");
808 *(u8 *) req->buf = 0;
809 value = 1;
810 break;
811
812 default:
813 VDBG(fsg,
814 "unknown control req %02x.%02x v%04x i%04x l%u\n",
815 ctrl->bRequestType, ctrl->bRequest,
816 w_value, w_index, le16_to_cpu(ctrl->wLength));
817 }
818
819 return value;
820}
821
822
823static int fsg_setup(struct usb_gadget *gadget,
824 const struct usb_ctrlrequest *ctrl)
825{
826 struct fsg_dev *fsg = get_gadget_data(gadget);
827 int rc;
828 int w_length = le16_to_cpu(ctrl->wLength);
829
830 ++fsg->ep0_req_tag; // Record arrival of a new request
831 fsg->ep0req->context = NULL;
832 fsg->ep0req->length = 0;
833 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
834
835 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
836 rc = class_setup_req(fsg, ctrl);
837 else
838 rc = standard_setup_req(fsg, ctrl);
839
840 /* Respond with data/status or defer until later? */
841 if (rc >= 0 && rc != DELAYED_STATUS) {
842 rc = min(rc, w_length);
843 fsg->ep0req->length = rc;
844 fsg->ep0req->zero = rc < w_length;
845 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
846 "ep0-in" : "ep0-out");
847 rc = ep0_queue(fsg);
848 }
849
850 /* Device either stalls (rc < 0) or reports success */
851 return rc;
852}
853
854
855/*-------------------------------------------------------------------------*/
856
857/* All the following routines run in process context */
858
859
860/* Use this for bulk or interrupt transfers, not ep0 */
861static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
862 struct usb_request *req, int *pbusy,
863 enum fsg_buffer_state *state)
864{
865 int rc;
866
867 if (ep == fsg->bulk_in)
868 dump_msg(fsg, "bulk-in", req->buf, req->length);
d5e2b67a
MN
869
870 spin_lock_irq(&fsg->lock);
871 *pbusy = 1;
872 *state = BUF_STATE_BUSY;
873 spin_unlock_irq(&fsg->lock);
874 rc = usb_ep_queue(ep, req, GFP_KERNEL);
875 if (rc != 0) {
876 *pbusy = 0;
877 *state = BUF_STATE_EMPTY;
878
879 /* We can't do much more than wait for a reset */
880
881 /* Note: currently the net2280 driver fails zero-length
882 * submissions if DMA is enabled. */
883 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
884 req->length == 0))
885 WARNING(fsg, "error in submission: %s --> %d\n",
886 ep->name, rc);
887 }
888}
889
890
891static int sleep_thread(struct fsg_dev *fsg)
892{
893 int rc = 0;
894
895 /* Wait until a signal arrives or we are woken up */
896 for (;;) {
897 try_to_freeze();
898 set_current_state(TASK_INTERRUPTIBLE);
899 if (signal_pending(current)) {
900 rc = -EINTR;
901 break;
902 }
903 if (fsg->thread_wakeup_needed)
904 break;
905 schedule();
906 }
907 __set_current_state(TASK_RUNNING);
908 fsg->thread_wakeup_needed = 0;
909 return rc;
910}
911
912
913/*-------------------------------------------------------------------------*/
914
915static int do_read(struct fsg_dev *fsg)
916{
a41ae418 917 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
918 u32 lba;
919 struct fsg_buffhd *bh;
920 int rc;
921 u32 amount_left;
922 loff_t file_offset, file_offset_tmp;
923 unsigned int amount;
924 unsigned int partial_page;
925 ssize_t nread;
926
927 /* Get the starting Logical Block Address and check that it's
928 * not too big */
a41ae418
MN
929 if (fsg->common->cmnd[0] == SC_READ_6)
930 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
d5e2b67a 931 else {
a41ae418 932 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
d5e2b67a
MN
933
934 /* We allow DPO (Disable Page Out = don't save data in the
935 * cache) and FUA (Force Unit Access = don't read from the
936 * cache), but we don't implement them. */
a41ae418 937 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
d5e2b67a
MN
938 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
939 return -EINVAL;
940 }
941 }
942 if (lba >= curlun->num_sectors) {
943 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
944 return -EINVAL;
945 }
946 file_offset = ((loff_t) lba) << 9;
947
948 /* Carry out the file reads */
949 amount_left = fsg->data_size_from_cmnd;
950 if (unlikely(amount_left == 0))
951 return -EIO; // No default reply
952
953 for (;;) {
954
955 /* Figure out how much we need to read:
956 * Try to read the remaining amount.
957 * But don't read more than the buffer size.
958 * And don't try to read past the end of the file.
959 * Finally, if we're not at a page boundary, don't read past
960 * the next page.
961 * If this means reading 0 then we were asked to read past
962 * the end of file. */
93bcf12e 963 amount = min(amount_left, FSG_BUFLEN);
d5e2b67a
MN
964 amount = min((loff_t) amount,
965 curlun->file_length - file_offset);
966 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
967 if (partial_page > 0)
968 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
969 partial_page);
970
971 /* Wait for the next buffer to become available */
a41ae418 972 bh = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
973 while (bh->state != BUF_STATE_EMPTY) {
974 rc = sleep_thread(fsg);
975 if (rc)
976 return rc;
977 }
978
979 /* If we were asked to read past the end of file,
980 * end with an empty buffer. */
981 if (amount == 0) {
982 curlun->sense_data =
983 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
984 curlun->sense_data_info = file_offset >> 9;
985 curlun->info_valid = 1;
986 bh->inreq->length = 0;
987 bh->state = BUF_STATE_FULL;
988 break;
989 }
990
991 /* Perform the read */
992 file_offset_tmp = file_offset;
993 nread = vfs_read(curlun->filp,
994 (char __user *) bh->buf,
995 amount, &file_offset_tmp);
996 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
997 (unsigned long long) file_offset,
998 (int) nread);
999 if (signal_pending(current))
1000 return -EINTR;
1001
1002 if (nread < 0) {
1003 LDBG(curlun, "error in file read: %d\n",
1004 (int) nread);
1005 nread = 0;
1006 } else if (nread < amount) {
1007 LDBG(curlun, "partial file read: %d/%u\n",
1008 (int) nread, amount);
1009 nread -= (nread & 511); // Round down to a block
1010 }
1011 file_offset += nread;
1012 amount_left -= nread;
1013 fsg->residue -= nread;
1014 bh->inreq->length = nread;
1015 bh->state = BUF_STATE_FULL;
1016
1017 /* If an error occurred, report it and its position */
1018 if (nread < amount) {
1019 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1020 curlun->sense_data_info = file_offset >> 9;
1021 curlun->info_valid = 1;
1022 break;
1023 }
1024
1025 if (amount_left == 0)
1026 break; // No more left to read
1027
1028 /* Send this buffer and go read some more */
1029 bh->inreq->zero = 0;
1030 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1031 &bh->inreq_busy, &bh->state);
a41ae418 1032 fsg->common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1033 }
1034
1035 return -EIO; // No default reply
1036}
1037
1038
1039/*-------------------------------------------------------------------------*/
1040
1041static int do_write(struct fsg_dev *fsg)
1042{
a41ae418 1043 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
1044 u32 lba;
1045 struct fsg_buffhd *bh;
1046 int get_some_more;
1047 u32 amount_left_to_req, amount_left_to_write;
1048 loff_t usb_offset, file_offset, file_offset_tmp;
1049 unsigned int amount;
1050 unsigned int partial_page;
1051 ssize_t nwritten;
1052 int rc;
1053
1054 if (curlun->ro) {
1055 curlun->sense_data = SS_WRITE_PROTECTED;
1056 return -EINVAL;
1057 }
1058 spin_lock(&curlun->filp->f_lock);
1059 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1060 spin_unlock(&curlun->filp->f_lock);
1061
1062 /* Get the starting Logical Block Address and check that it's
1063 * not too big */
a41ae418
MN
1064 if (fsg->common->cmnd[0] == SC_WRITE_6)
1065 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
d5e2b67a 1066 else {
a41ae418 1067 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
d5e2b67a
MN
1068
1069 /* We allow DPO (Disable Page Out = don't save data in the
1070 * cache) and FUA (Force Unit Access = write directly to the
1071 * medium). We don't implement DPO; we implement FUA by
1072 * performing synchronous output. */
a41ae418 1073 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
d5e2b67a
MN
1074 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1075 return -EINVAL;
1076 }
a41ae418 1077 if (fsg->common->cmnd[1] & 0x08) { // FUA
d5e2b67a
MN
1078 spin_lock(&curlun->filp->f_lock);
1079 curlun->filp->f_flags |= O_SYNC;
1080 spin_unlock(&curlun->filp->f_lock);
1081 }
1082 }
1083 if (lba >= curlun->num_sectors) {
1084 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1085 return -EINVAL;
1086 }
1087
1088 /* Carry out the file writes */
1089 get_some_more = 1;
1090 file_offset = usb_offset = ((loff_t) lba) << 9;
1091 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1092
1093 while (amount_left_to_write > 0) {
1094
1095 /* Queue a request for more data from the host */
a41ae418 1096 bh = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
1097 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1098
1099 /* Figure out how much we want to get:
1100 * Try to get the remaining amount.
1101 * But don't get more than the buffer size.
1102 * And don't try to go past the end of the file.
1103 * If we're not at a page boundary,
1104 * don't go past the next page.
1105 * If this means getting 0, then we were asked
1106 * to write past the end of file.
1107 * Finally, round down to a block boundary. */
93bcf12e 1108 amount = min(amount_left_to_req, FSG_BUFLEN);
d5e2b67a
MN
1109 amount = min((loff_t) amount, curlun->file_length -
1110 usb_offset);
1111 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1112 if (partial_page > 0)
1113 amount = min(amount,
1114 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1115
1116 if (amount == 0) {
1117 get_some_more = 0;
1118 curlun->sense_data =
1119 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1120 curlun->sense_data_info = usb_offset >> 9;
1121 curlun->info_valid = 1;
1122 continue;
1123 }
1124 amount -= (amount & 511);
1125 if (amount == 0) {
1126
1127 /* Why were we were asked to transfer a
1128 * partial block? */
1129 get_some_more = 0;
1130 continue;
1131 }
1132
1133 /* Get the next buffer */
1134 usb_offset += amount;
1135 fsg->usb_amount_left -= amount;
1136 amount_left_to_req -= amount;
1137 if (amount_left_to_req == 0)
1138 get_some_more = 0;
1139
1140 /* amount is always divisible by 512, hence by
1141 * the bulk-out maxpacket size */
1142 bh->outreq->length = bh->bulk_out_intended_length =
1143 amount;
1144 bh->outreq->short_not_ok = 1;
1145 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1146 &bh->outreq_busy, &bh->state);
a41ae418 1147 fsg->common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1148 continue;
1149 }
1150
1151 /* Write the received data to the backing file */
a41ae418 1152 bh = fsg->common->next_buffhd_to_drain;
d5e2b67a
MN
1153 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1154 break; // We stopped early
1155 if (bh->state == BUF_STATE_FULL) {
1156 smp_rmb();
a41ae418 1157 fsg->common->next_buffhd_to_drain = bh->next;
d5e2b67a
MN
1158 bh->state = BUF_STATE_EMPTY;
1159
1160 /* Did something go wrong with the transfer? */
1161 if (bh->outreq->status != 0) {
1162 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1163 curlun->sense_data_info = file_offset >> 9;
1164 curlun->info_valid = 1;
1165 break;
1166 }
1167
1168 amount = bh->outreq->actual;
1169 if (curlun->file_length - file_offset < amount) {
1170 LERROR(curlun,
1171 "write %u @ %llu beyond end %llu\n",
1172 amount, (unsigned long long) file_offset,
1173 (unsigned long long) curlun->file_length);
1174 amount = curlun->file_length - file_offset;
1175 }
1176
1177 /* Perform the write */
1178 file_offset_tmp = file_offset;
1179 nwritten = vfs_write(curlun->filp,
1180 (char __user *) bh->buf,
1181 amount, &file_offset_tmp);
1182 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1183 (unsigned long long) file_offset,
1184 (int) nwritten);
1185 if (signal_pending(current))
1186 return -EINTR; // Interrupted!
1187
1188 if (nwritten < 0) {
1189 LDBG(curlun, "error in file write: %d\n",
1190 (int) nwritten);
1191 nwritten = 0;
1192 } else if (nwritten < amount) {
1193 LDBG(curlun, "partial file write: %d/%u\n",
1194 (int) nwritten, amount);
1195 nwritten -= (nwritten & 511);
1196 // Round down to a block
1197 }
1198 file_offset += nwritten;
1199 amount_left_to_write -= nwritten;
1200 fsg->residue -= nwritten;
1201
1202 /* If an error occurred, report it and its position */
1203 if (nwritten < amount) {
1204 curlun->sense_data = SS_WRITE_ERROR;
1205 curlun->sense_data_info = file_offset >> 9;
1206 curlun->info_valid = 1;
1207 break;
1208 }
1209
1210 /* Did the host decide to stop early? */
1211 if (bh->outreq->actual != bh->outreq->length) {
1212 fsg->short_packet_received = 1;
1213 break;
1214 }
1215 continue;
1216 }
1217
1218 /* Wait for something to happen */
1219 rc = sleep_thread(fsg);
1220 if (rc)
1221 return rc;
1222 }
1223
1224 return -EIO; // No default reply
1225}
1226
1227
1228/*-------------------------------------------------------------------------*/
1229
1230static int do_synchronize_cache(struct fsg_dev *fsg)
1231{
a41ae418 1232 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
1233 int rc;
1234
1235 /* We ignore the requested LBA and write out all file's
1236 * dirty data buffers. */
1237 rc = fsg_lun_fsync_sub(curlun);
1238 if (rc)
1239 curlun->sense_data = SS_WRITE_ERROR;
1240 return 0;
1241}
1242
1243
1244/*-------------------------------------------------------------------------*/
1245
1246static void invalidate_sub(struct fsg_lun *curlun)
1247{
1248 struct file *filp = curlun->filp;
1249 struct inode *inode = filp->f_path.dentry->d_inode;
1250 unsigned long rc;
1251
1252 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1253 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1254}
1255
1256static int do_verify(struct fsg_dev *fsg)
1257{
a41ae418 1258 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
1259 u32 lba;
1260 u32 verification_length;
a41ae418 1261 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
1262 loff_t file_offset, file_offset_tmp;
1263 u32 amount_left;
1264 unsigned int amount;
1265 ssize_t nread;
1266
1267 /* Get the starting Logical Block Address and check that it's
1268 * not too big */
a41ae418 1269 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
d5e2b67a
MN
1270 if (lba >= curlun->num_sectors) {
1271 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1272 return -EINVAL;
1273 }
1274
1275 /* We allow DPO (Disable Page Out = don't save data in the
1276 * cache) but we don't implement it. */
a41ae418 1277 if ((fsg->common->cmnd[1] & ~0x10) != 0) {
d5e2b67a
MN
1278 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1279 return -EINVAL;
1280 }
1281
a41ae418 1282 verification_length = get_unaligned_be16(&fsg->common->cmnd[7]);
d5e2b67a
MN
1283 if (unlikely(verification_length == 0))
1284 return -EIO; // No default reply
1285
1286 /* Prepare to carry out the file verify */
1287 amount_left = verification_length << 9;
1288 file_offset = ((loff_t) lba) << 9;
1289
1290 /* Write out all the dirty buffers before invalidating them */
1291 fsg_lun_fsync_sub(curlun);
1292 if (signal_pending(current))
1293 return -EINTR;
1294
1295 invalidate_sub(curlun);
1296 if (signal_pending(current))
1297 return -EINTR;
1298
1299 /* Just try to read the requested blocks */
1300 while (amount_left > 0) {
1301
1302 /* Figure out how much we need to read:
1303 * Try to read the remaining amount, but not more than
1304 * the buffer size.
1305 * And don't try to read past the end of the file.
1306 * If this means reading 0 then we were asked to read
1307 * past the end of file. */
93bcf12e 1308 amount = min(amount_left, FSG_BUFLEN);
d5e2b67a
MN
1309 amount = min((loff_t) amount,
1310 curlun->file_length - file_offset);
1311 if (amount == 0) {
1312 curlun->sense_data =
1313 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1314 curlun->sense_data_info = file_offset >> 9;
1315 curlun->info_valid = 1;
1316 break;
1317 }
1318
1319 /* Perform the read */
1320 file_offset_tmp = file_offset;
1321 nread = vfs_read(curlun->filp,
1322 (char __user *) bh->buf,
1323 amount, &file_offset_tmp);
1324 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1325 (unsigned long long) file_offset,
1326 (int) nread);
1327 if (signal_pending(current))
1328 return -EINTR;
1329
1330 if (nread < 0) {
1331 LDBG(curlun, "error in file verify: %d\n",
1332 (int) nread);
1333 nread = 0;
1334 } else if (nread < amount) {
1335 LDBG(curlun, "partial file verify: %d/%u\n",
1336 (int) nread, amount);
1337 nread -= (nread & 511); // Round down to a sector
1338 }
1339 if (nread == 0) {
1340 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1341 curlun->sense_data_info = file_offset >> 9;
1342 curlun->info_valid = 1;
1343 break;
1344 }
1345 file_offset += nread;
1346 amount_left -= nread;
1347 }
1348 return 0;
1349}
1350
1351
1352/*-------------------------------------------------------------------------*/
1353
1354static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1355{
1356 u8 *buf = (u8 *) bh->buf;
1357
1358 static char vendor_id[] = "Linux ";
1359 static char product_disk_id[] = "File-Stor Gadget";
1360 static char product_cdrom_id[] = "File-CD Gadget ";
1361
a41ae418 1362 if (!fsg->common->curlun) { // Unsupported LUNs are okay
d5e2b67a
MN
1363 fsg->bad_lun_okay = 1;
1364 memset(buf, 0, 36);
1365 buf[0] = 0x7f; // Unsupported, no device-type
1366 buf[4] = 31; // Additional length
1367 return 36;
1368 }
1369
1370 memset(buf, 0, 8);
1371 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
1372 if (mod_data.removable)
1373 buf[1] = 0x80;
1374 buf[2] = 2; // ANSI SCSI level 2
1375 buf[3] = 2; // SCSI-2 INQUIRY data format
1376 buf[4] = 31; // Additional length
1377 // No special options
1378 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1379 (mod_data.cdrom ? product_cdrom_id :
1380 product_disk_id),
1381 mod_data.release);
1382 return 36;
1383}
1384
1385
1386static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1387{
a41ae418 1388 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
1389 u8 *buf = (u8 *) bh->buf;
1390 u32 sd, sdinfo;
1391 int valid;
1392
1393 /*
1394 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1395 *
1396 * If a REQUEST SENSE command is received from an initiator
1397 * with a pending unit attention condition (before the target
1398 * generates the contingent allegiance condition), then the
1399 * target shall either:
1400 * a) report any pending sense data and preserve the unit
1401 * attention condition on the logical unit, or,
1402 * b) report the unit attention condition, may discard any
1403 * pending sense data, and clear the unit attention
1404 * condition on the logical unit for that initiator.
1405 *
1406 * FSG normally uses option a); enable this code to use option b).
1407 */
1408#if 0
1409 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1410 curlun->sense_data = curlun->unit_attention_data;
1411 curlun->unit_attention_data = SS_NO_SENSE;
1412 }
1413#endif
1414
1415 if (!curlun) { // Unsupported LUNs are okay
1416 fsg->bad_lun_okay = 1;
1417 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1418 sdinfo = 0;
1419 valid = 0;
1420 } else {
1421 sd = curlun->sense_data;
1422 sdinfo = curlun->sense_data_info;
1423 valid = curlun->info_valid << 7;
1424 curlun->sense_data = SS_NO_SENSE;
1425 curlun->sense_data_info = 0;
1426 curlun->info_valid = 0;
1427 }
1428
1429 memset(buf, 0, 18);
1430 buf[0] = valid | 0x70; // Valid, current error
1431 buf[2] = SK(sd);
1432 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1433 buf[7] = 18 - 8; // Additional sense length
1434 buf[12] = ASC(sd);
1435 buf[13] = ASCQ(sd);
1436 return 18;
1437}
1438
1439
1440static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1441{
a41ae418
MN
1442 struct fsg_lun *curlun = fsg->common->curlun;
1443 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1444 int pmi = fsg->common->cmnd[8];
d5e2b67a
MN
1445 u8 *buf = (u8 *) bh->buf;
1446
1447 /* Check the PMI and LBA fields */
1448 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1449 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1450 return -EINVAL;
1451 }
1452
1453 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1454 /* Max logical block */
1455 put_unaligned_be32(512, &buf[4]); /* Block length */
1456 return 8;
1457}
1458
1459
1460static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1461{
a41ae418
MN
1462 struct fsg_lun *curlun = fsg->common->curlun;
1463 int msf = fsg->common->cmnd[1] & 0x02;
1464 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
d5e2b67a
MN
1465 u8 *buf = (u8 *) bh->buf;
1466
a41ae418 1467 if ((fsg->common->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
d5e2b67a
MN
1468 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1469 return -EINVAL;
1470 }
1471 if (lba >= curlun->num_sectors) {
1472 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1473 return -EINVAL;
1474 }
1475
1476 memset(buf, 0, 8);
1477 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1478 store_cdrom_address(&buf[4], msf, lba);
1479 return 8;
1480}
1481
1482
1483static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1484{
a41ae418
MN
1485 struct fsg_lun *curlun = fsg->common->curlun;
1486 int msf = fsg->common->cmnd[1] & 0x02;
1487 int start_track = fsg->common->cmnd[6];
d5e2b67a
MN
1488 u8 *buf = (u8 *) bh->buf;
1489
a41ae418 1490 if ((fsg->common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
d5e2b67a
MN
1491 start_track > 1) {
1492 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1493 return -EINVAL;
1494 }
1495
1496 memset(buf, 0, 20);
1497 buf[1] = (20-2); /* TOC data length */
1498 buf[2] = 1; /* First track number */
1499 buf[3] = 1; /* Last track number */
1500 buf[5] = 0x16; /* Data track, copying allowed */
1501 buf[6] = 0x01; /* Only track is number 1 */
1502 store_cdrom_address(&buf[8], msf, 0);
1503
1504 buf[13] = 0x16; /* Lead-out track is data */
1505 buf[14] = 0xAA; /* Lead-out track number */
1506 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1507 return 20;
1508}
1509
1510
1511static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1512{
a41ae418
MN
1513 struct fsg_lun *curlun = fsg->common->curlun;
1514 int mscmnd = fsg->common->cmnd[0];
d5e2b67a
MN
1515 u8 *buf = (u8 *) bh->buf;
1516 u8 *buf0 = buf;
1517 int pc, page_code;
1518 int changeable_values, all_pages;
1519 int valid_page = 0;
1520 int len, limit;
1521
a41ae418 1522 if ((fsg->common->cmnd[1] & ~0x08) != 0) { // Mask away DBD
d5e2b67a
MN
1523 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1524 return -EINVAL;
1525 }
a41ae418
MN
1526 pc = fsg->common->cmnd[2] >> 6;
1527 page_code = fsg->common->cmnd[2] & 0x3f;
d5e2b67a
MN
1528 if (pc == 3) {
1529 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1530 return -EINVAL;
1531 }
1532 changeable_values = (pc == 1);
1533 all_pages = (page_code == 0x3f);
1534
1535 /* Write the mode parameter header. Fixed values are: default
1536 * medium type, no cache control (DPOFUA), and no block descriptors.
1537 * The only variable value is the WriteProtect bit. We will fill in
1538 * the mode data length later. */
1539 memset(buf, 0, 8);
1540 if (mscmnd == SC_MODE_SENSE_6) {
1541 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1542 buf += 4;
1543 limit = 255;
1544 } else { // SC_MODE_SENSE_10
1545 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1546 buf += 8;
93bcf12e 1547 limit = 65535; // Should really be FSG_BUFLEN
d5e2b67a
MN
1548 }
1549
1550 /* No block descriptors */
1551
1552 /* The mode pages, in numerical order. The only page we support
1553 * is the Caching page. */
1554 if (page_code == 0x08 || all_pages) {
1555 valid_page = 1;
1556 buf[0] = 0x08; // Page code
1557 buf[1] = 10; // Page length
1558 memset(buf+2, 0, 10); // None of the fields are changeable
1559
1560 if (!changeable_values) {
1561 buf[2] = 0x04; // Write cache enable,
1562 // Read cache not disabled
1563 // No cache retention priorities
1564 put_unaligned_be16(0xffff, &buf[4]);
1565 /* Don't disable prefetch */
1566 /* Minimum prefetch = 0 */
1567 put_unaligned_be16(0xffff, &buf[8]);
1568 /* Maximum prefetch */
1569 put_unaligned_be16(0xffff, &buf[10]);
1570 /* Maximum prefetch ceiling */
1571 }
1572 buf += 12;
1573 }
1574
1575 /* Check that a valid page was requested and the mode data length
1576 * isn't too long. */
1577 len = buf - buf0;
1578 if (!valid_page || len > limit) {
1579 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1580 return -EINVAL;
1581 }
1582
1583 /* Store the mode data length */
1584 if (mscmnd == SC_MODE_SENSE_6)
1585 buf0[0] = len - 1;
1586 else
1587 put_unaligned_be16(len - 2, buf0);
1588 return len;
1589}
1590
1591
1592static int do_start_stop(struct fsg_dev *fsg)
1593{
d5e2b67a 1594 if (!mod_data.removable) {
a41ae418 1595 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
1596 return -EINVAL;
1597 }
d5e2b67a
MN
1598 return 0;
1599}
1600
1601
1602static int do_prevent_allow(struct fsg_dev *fsg)
1603{
a41ae418 1604 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
1605 int prevent;
1606
1607 if (!mod_data.removable) {
1608 curlun->sense_data = SS_INVALID_COMMAND;
1609 return -EINVAL;
1610 }
1611
a41ae418
MN
1612 prevent = fsg->common->cmnd[4] & 0x01;
1613 if ((fsg->common->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
d5e2b67a
MN
1614 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1615 return -EINVAL;
1616 }
1617
1618 if (curlun->prevent_medium_removal && !prevent)
1619 fsg_lun_fsync_sub(curlun);
1620 curlun->prevent_medium_removal = prevent;
1621 return 0;
1622}
1623
1624
1625static int do_read_format_capacities(struct fsg_dev *fsg,
1626 struct fsg_buffhd *bh)
1627{
a41ae418 1628 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
1629 u8 *buf = (u8 *) bh->buf;
1630
1631 buf[0] = buf[1] = buf[2] = 0;
1632 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1633 buf += 4;
1634
1635 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1636 /* Number of blocks */
1637 put_unaligned_be32(512, &buf[4]); /* Block length */
1638 buf[4] = 0x02; /* Current capacity */
1639 return 12;
1640}
1641
1642
1643static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1644{
a41ae418 1645 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a
MN
1646
1647 /* We don't support MODE SELECT */
1648 curlun->sense_data = SS_INVALID_COMMAND;
1649 return -EINVAL;
1650}
1651
1652
1653/*-------------------------------------------------------------------------*/
1654
1655static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1656{
1657 int rc;
1658
1659 rc = fsg_set_halt(fsg, fsg->bulk_in);
1660 if (rc == -EAGAIN)
1661 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1662 while (rc != 0) {
1663 if (rc != -EAGAIN) {
1664 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1665 rc = 0;
1666 break;
1667 }
1668
1669 /* Wait for a short time and then try again */
1670 if (msleep_interruptible(100) != 0)
1671 return -EINTR;
1672 rc = usb_ep_set_halt(fsg->bulk_in);
1673 }
1674 return rc;
1675}
1676
1677static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1678{
1679 int rc;
1680
1681 DBG(fsg, "bulk-in set wedge\n");
1682 rc = usb_ep_set_wedge(fsg->bulk_in);
1683 if (rc == -EAGAIN)
1684 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1685 while (rc != 0) {
1686 if (rc != -EAGAIN) {
1687 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1688 rc = 0;
1689 break;
1690 }
1691
1692 /* Wait for a short time and then try again */
1693 if (msleep_interruptible(100) != 0)
1694 return -EINTR;
1695 rc = usb_ep_set_wedge(fsg->bulk_in);
1696 }
1697 return rc;
1698}
1699
1700static int pad_with_zeros(struct fsg_dev *fsg)
1701{
a41ae418 1702 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
1703 u32 nkeep = bh->inreq->length;
1704 u32 nsend;
1705 int rc;
1706
1707 bh->state = BUF_STATE_EMPTY; // For the first iteration
1708 fsg->usb_amount_left = nkeep + fsg->residue;
1709 while (fsg->usb_amount_left > 0) {
1710
1711 /* Wait for the next buffer to be free */
1712 while (bh->state != BUF_STATE_EMPTY) {
1713 rc = sleep_thread(fsg);
1714 if (rc)
1715 return rc;
1716 }
1717
93bcf12e 1718 nsend = min(fsg->usb_amount_left, FSG_BUFLEN);
d5e2b67a
MN
1719 memset(bh->buf + nkeep, 0, nsend - nkeep);
1720 bh->inreq->length = nsend;
1721 bh->inreq->zero = 0;
1722 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1723 &bh->inreq_busy, &bh->state);
a41ae418 1724 bh = fsg->common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1725 fsg->usb_amount_left -= nsend;
1726 nkeep = 0;
1727 }
1728 return 0;
1729}
1730
1731static int throw_away_data(struct fsg_dev *fsg)
1732{
1733 struct fsg_buffhd *bh;
1734 u32 amount;
1735 int rc;
1736
a41ae418
MN
1737 for (bh = fsg->common->next_buffhd_to_drain;
1738 bh->state != BUF_STATE_EMPTY || fsg->usb_amount_left > 0;
1739 bh = fsg->common->next_buffhd_to_drain) {
d5e2b67a
MN
1740
1741 /* Throw away the data in a filled buffer */
1742 if (bh->state == BUF_STATE_FULL) {
1743 smp_rmb();
1744 bh->state = BUF_STATE_EMPTY;
a41ae418 1745 fsg->common->next_buffhd_to_drain = bh->next;
d5e2b67a
MN
1746
1747 /* A short packet or an error ends everything */
1748 if (bh->outreq->actual != bh->outreq->length ||
1749 bh->outreq->status != 0) {
1750 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1751 return -EINTR;
1752 }
1753 continue;
1754 }
1755
1756 /* Try to submit another request if we need one */
a41ae418 1757 bh = fsg->common->next_buffhd_to_fill;
d5e2b67a 1758 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
93bcf12e 1759 amount = min(fsg->usb_amount_left, FSG_BUFLEN);
d5e2b67a
MN
1760
1761 /* amount is always divisible by 512, hence by
1762 * the bulk-out maxpacket size */
1763 bh->outreq->length = bh->bulk_out_intended_length =
1764 amount;
1765 bh->outreq->short_not_ok = 1;
1766 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1767 &bh->outreq_busy, &bh->state);
a41ae418 1768 fsg->common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1769 fsg->usb_amount_left -= amount;
1770 continue;
1771 }
1772
1773 /* Otherwise wait for something to happen */
1774 rc = sleep_thread(fsg);
1775 if (rc)
1776 return rc;
1777 }
1778 return 0;
1779}
1780
1781
1782static int finish_reply(struct fsg_dev *fsg)
1783{
a41ae418 1784 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
1785 int rc = 0;
1786
1787 switch (fsg->data_dir) {
1788 case DATA_DIR_NONE:
1789 break; // Nothing to send
1790
1791 /* If we don't know whether the host wants to read or write,
1792 * this must be CB or CBI with an unknown command. We mustn't
1793 * try to send or receive any data. So stall both bulk pipes
1794 * if we can and wait for a reset. */
1795 case DATA_DIR_UNKNOWN:
1796 if (mod_data.can_stall) {
1797 fsg_set_halt(fsg, fsg->bulk_out);
1798 rc = halt_bulk_in_endpoint(fsg);
1799 }
1800 break;
1801
1802 /* All but the last buffer of data must have already been sent */
1803 case DATA_DIR_TO_HOST:
93bcf12e
MN
1804 if (fsg->data_size == 0) {
1805 /* Nothing to send */
d5e2b67a
MN
1806
1807 /* If there's no residue, simply send the last buffer */
93bcf12e 1808 } else if (fsg->residue == 0) {
d5e2b67a
MN
1809 bh->inreq->zero = 0;
1810 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1811 &bh->inreq_busy, &bh->state);
a41ae418 1812 fsg->common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1813
1814 /* For Bulk-only, if we're allowed to stall then send the
1815 * short packet and halt the bulk-in endpoint. If we can't
1816 * stall, pad out the remaining data with 0's. */
93bcf12e
MN
1817 } else if (mod_data.can_stall) {
1818 bh->inreq->zero = 1;
1819 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1820 &bh->inreq_busy, &bh->state);
a41ae418 1821 fsg->common->next_buffhd_to_fill = bh->next;
93bcf12e
MN
1822 rc = halt_bulk_in_endpoint(fsg);
1823 } else {
1824 rc = pad_with_zeros(fsg);
d5e2b67a
MN
1825 }
1826 break;
1827
1828 /* We have processed all we want from the data the host has sent.
1829 * There may still be outstanding bulk-out requests. */
1830 case DATA_DIR_FROM_HOST:
1831 if (fsg->residue == 0)
1832 ; // Nothing to receive
1833
1834 /* Did the host stop sending unexpectedly early? */
1835 else if (fsg->short_packet_received) {
1836 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1837 rc = -EINTR;
1838 }
1839
1840 /* We haven't processed all the incoming data. Even though
1841 * we may be allowed to stall, doing so would cause a race.
1842 * The controller may already have ACK'ed all the remaining
1843 * bulk-out packets, in which case the host wouldn't see a
1844 * STALL. Not realizing the endpoint was halted, it wouldn't
1845 * clear the halt -- leading to problems later on. */
1846#if 0
1847 else if (mod_data.can_stall) {
1848 fsg_set_halt(fsg, fsg->bulk_out);
1849 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1850 rc = -EINTR;
1851 }
1852#endif
1853
1854 /* We can't stall. Read in the excess data and throw it
1855 * all away. */
1856 else
1857 rc = throw_away_data(fsg);
1858 break;
1859 }
1860 return rc;
1861}
1862
1863
1864static int send_status(struct fsg_dev *fsg)
1865{
a41ae418 1866 struct fsg_lun *curlun = fsg->common->curlun;
d5e2b67a 1867 struct fsg_buffhd *bh;
93bcf12e 1868 struct bulk_cs_wrap *csw;
d5e2b67a
MN
1869 int rc;
1870 u8 status = USB_STATUS_PASS;
1871 u32 sd, sdinfo = 0;
1872
1873 /* Wait for the next buffer to become available */
a41ae418 1874 bh = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
1875 while (bh->state != BUF_STATE_EMPTY) {
1876 rc = sleep_thread(fsg);
1877 if (rc)
1878 return rc;
1879 }
1880
1881 if (curlun) {
1882 sd = curlun->sense_data;
1883 sdinfo = curlun->sense_data_info;
1884 } else if (fsg->bad_lun_okay)
1885 sd = SS_NO_SENSE;
1886 else
1887 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1888
1889 if (fsg->phase_error) {
1890 DBG(fsg, "sending phase-error status\n");
1891 status = USB_STATUS_PHASE_ERROR;
1892 sd = SS_INVALID_COMMAND;
1893 } else if (sd != SS_NO_SENSE) {
1894 DBG(fsg, "sending command-failure status\n");
1895 status = USB_STATUS_FAIL;
1896 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1897 " info x%x\n",
1898 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1899 }
1900
93bcf12e 1901 /* Store and send the Bulk-only CSW */
606206c2 1902 csw = (void*)bh->buf;
d5e2b67a 1903
93bcf12e
MN
1904 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1905 csw->Tag = fsg->tag;
1906 csw->Residue = cpu_to_le32(fsg->residue);
1907 csw->Status = status;
d5e2b67a 1908
93bcf12e
MN
1909 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1910 bh->inreq->zero = 0;
1911 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1912 &bh->inreq_busy, &bh->state);
d5e2b67a 1913
a41ae418 1914 fsg->common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1915 return 0;
1916}
1917
1918
1919/*-------------------------------------------------------------------------*/
1920
1921/* Check whether the command is properly formed and whether its data size
1922 * and direction agree with the values we already have. */
1923static int check_command(struct fsg_dev *fsg, int cmnd_size,
1924 enum data_direction data_dir, unsigned int mask,
1925 int needs_medium, const char *name)
1926{
1927 int i;
a41ae418 1928 int lun = fsg->common->cmnd[1] >> 5;
d5e2b67a
MN
1929 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1930 char hdlen[20];
1931 struct fsg_lun *curlun;
1932
d5e2b67a
MN
1933 hdlen[0] = 0;
1934 if (fsg->data_dir != DATA_DIR_UNKNOWN)
1935 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1936 fsg->data_size);
1937 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1938 name, cmnd_size, dirletter[(int) data_dir],
a41ae418 1939 fsg->data_size_from_cmnd, fsg->common->cmnd_size, hdlen);
d5e2b67a
MN
1940
1941 /* We can't reply at all until we know the correct data direction
1942 * and size. */
1943 if (fsg->data_size_from_cmnd == 0)
1944 data_dir = DATA_DIR_NONE;
1945 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
1946 fsg->data_dir = data_dir;
1947 fsg->data_size = fsg->data_size_from_cmnd;
1948
1949 } else { // Bulk-only
1950 if (fsg->data_size < fsg->data_size_from_cmnd) {
1951
1952 /* Host data size < Device data size is a phase error.
1953 * Carry out the command, but only transfer as much
1954 * as we are allowed. */
1955 fsg->data_size_from_cmnd = fsg->data_size;
1956 fsg->phase_error = 1;
1957 }
1958 }
1959 fsg->residue = fsg->usb_amount_left = fsg->data_size;
1960
1961 /* Conflicting data directions is a phase error */
1962 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
1963 fsg->phase_error = 1;
1964 return -EINVAL;
1965 }
1966
1967 /* Verify the length of the command itself */
a41ae418 1968 if (cmnd_size != fsg->common->cmnd_size) {
d5e2b67a
MN
1969
1970 /* Special case workaround: There are plenty of buggy SCSI
1971 * implementations. Many have issues with cbw->Length
1972 * field passing a wrong command size. For those cases we
1973 * always try to work around the problem by using the length
1974 * sent by the host side provided it is at least as large
1975 * as the correct command length.
1976 * Examples of such cases would be MS-Windows, which issues
1977 * REQUEST SENSE with cbw->Length == 12 where it should
1978 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1979 * REQUEST SENSE with cbw->Length == 10 where it should
1980 * be 6 as well.
1981 */
a41ae418 1982 if (cmnd_size <= fsg->common->cmnd_size) {
d5e2b67a 1983 DBG(fsg, "%s is buggy! Expected length %d "
a41ae418
MN
1984 "but we got %d\n", name,
1985 cmnd_size, fsg->common->cmnd_size);
1986 cmnd_size = fsg->common->cmnd_size;
d5e2b67a
MN
1987 } else {
1988 fsg->phase_error = 1;
1989 return -EINVAL;
1990 }
1991 }
1992
1993 /* Check that the LUN values are consistent */
a41ae418 1994 if (fsg->common->lun != lun)
93bcf12e 1995 DBG(fsg, "using LUN %d from CBW, not LUN %d from CDB\n",
a41ae418 1996 fsg->common->lun, lun);
d5e2b67a
MN
1997
1998 /* Check the LUN */
a41ae418
MN
1999 if (fsg->common->lun >= 0 && fsg->common->lun < fsg->common->nluns) {
2000 fsg->common->curlun = curlun = &fsg->common->luns[fsg->common->lun];
2001 if (fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
d5e2b67a
MN
2002 curlun->sense_data = SS_NO_SENSE;
2003 curlun->sense_data_info = 0;
2004 curlun->info_valid = 0;
2005 }
2006 } else {
a41ae418 2007 fsg->common->curlun = curlun = NULL;
d5e2b67a
MN
2008 fsg->bad_lun_okay = 0;
2009
2010 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2011 * to use unsupported LUNs; all others may not. */
a41ae418
MN
2012 if (fsg->common->cmnd[0] != SC_INQUIRY &&
2013 fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2014 DBG(fsg, "unsupported LUN %d\n", fsg->common->lun);
d5e2b67a
MN
2015 return -EINVAL;
2016 }
2017 }
2018
2019 /* If a unit attention condition exists, only INQUIRY and
2020 * REQUEST SENSE commands are allowed; anything else must fail. */
2021 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
a41ae418
MN
2022 fsg->common->cmnd[0] != SC_INQUIRY &&
2023 fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
d5e2b67a
MN
2024 curlun->sense_data = curlun->unit_attention_data;
2025 curlun->unit_attention_data = SS_NO_SENSE;
2026 return -EINVAL;
2027 }
2028
2029 /* Check that only command bytes listed in the mask are non-zero */
a41ae418 2030 fsg->common->cmnd[1] &= 0x1f; // Mask away the LUN
d5e2b67a 2031 for (i = 1; i < cmnd_size; ++i) {
a41ae418 2032 if (fsg->common->cmnd[i] && !(mask & (1 << i))) {
d5e2b67a
MN
2033 if (curlun)
2034 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2035 return -EINVAL;
2036 }
2037 }
2038
2039 /* If the medium isn't mounted and the command needs to access
2040 * it, return an error. */
2041 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
2042 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2043 return -EINVAL;
2044 }
2045
2046 return 0;
2047}
2048
2049
2050static int do_scsi_command(struct fsg_dev *fsg)
2051{
2052 struct fsg_buffhd *bh;
2053 int rc;
2054 int reply = -EINVAL;
2055 int i;
2056 static char unknown[16];
2057
a41ae418 2058 dump_cdb(fsg->common);
d5e2b67a
MN
2059
2060 /* Wait for the next buffer to become available for data or status */
a41ae418 2061 bh = fsg->common->next_buffhd_to_drain = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
2062 while (bh->state != BUF_STATE_EMPTY) {
2063 rc = sleep_thread(fsg);
2064 if (rc)
2065 return rc;
2066 }
2067 fsg->phase_error = 0;
2068 fsg->short_packet_received = 0;
2069
a41ae418
MN
2070 down_read(&fsg->common->filesem); // We're using the backing file
2071 switch (fsg->common->cmnd[0]) {
d5e2b67a
MN
2072
2073 case SC_INQUIRY:
a41ae418 2074 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
d5e2b67a
MN
2075 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2076 (1<<4), 0,
2077 "INQUIRY")) == 0)
2078 reply = do_inquiry(fsg, bh);
2079 break;
2080
2081 case SC_MODE_SELECT_6:
a41ae418 2082 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
d5e2b67a
MN
2083 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2084 (1<<1) | (1<<4), 0,
2085 "MODE SELECT(6)")) == 0)
2086 reply = do_mode_select(fsg, bh);
2087 break;
2088
2089 case SC_MODE_SELECT_10:
a41ae418 2090 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
d5e2b67a
MN
2091 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2092 (1<<1) | (3<<7), 0,
2093 "MODE SELECT(10)")) == 0)
2094 reply = do_mode_select(fsg, bh);
2095 break;
2096
2097 case SC_MODE_SENSE_6:
a41ae418 2098 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
d5e2b67a
MN
2099 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2100 (1<<1) | (1<<2) | (1<<4), 0,
2101 "MODE SENSE(6)")) == 0)
2102 reply = do_mode_sense(fsg, bh);
2103 break;
2104
2105 case SC_MODE_SENSE_10:
a41ae418 2106 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
d5e2b67a
MN
2107 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2108 (1<<1) | (1<<2) | (3<<7), 0,
2109 "MODE SENSE(10)")) == 0)
2110 reply = do_mode_sense(fsg, bh);
2111 break;
2112
2113 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2114 fsg->data_size_from_cmnd = 0;
2115 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2116 (1<<4), 0,
2117 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2118 reply = do_prevent_allow(fsg);
2119 break;
2120
2121 case SC_READ_6:
a41ae418 2122 i = fsg->common->cmnd[4];
d5e2b67a
MN
2123 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2124 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2125 (7<<1) | (1<<4), 1,
2126 "READ(6)")) == 0)
2127 reply = do_read(fsg);
2128 break;
2129
2130 case SC_READ_10:
2131 fsg->data_size_from_cmnd =
a41ae418 2132 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
d5e2b67a
MN
2133 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2134 (1<<1) | (0xf<<2) | (3<<7), 1,
2135 "READ(10)")) == 0)
2136 reply = do_read(fsg);
2137 break;
2138
2139 case SC_READ_12:
2140 fsg->data_size_from_cmnd =
a41ae418 2141 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
d5e2b67a
MN
2142 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2143 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2144 "READ(12)")) == 0)
2145 reply = do_read(fsg);
2146 break;
2147
2148 case SC_READ_CAPACITY:
2149 fsg->data_size_from_cmnd = 8;
2150 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2151 (0xf<<2) | (1<<8), 1,
2152 "READ CAPACITY")) == 0)
2153 reply = do_read_capacity(fsg, bh);
2154 break;
2155
2156 case SC_READ_HEADER:
2157 if (!mod_data.cdrom)
2158 goto unknown_cmnd;
a41ae418 2159 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
d5e2b67a
MN
2160 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2161 (3<<7) | (0x1f<<1), 1,
2162 "READ HEADER")) == 0)
2163 reply = do_read_header(fsg, bh);
2164 break;
2165
2166 case SC_READ_TOC:
2167 if (!mod_data.cdrom)
2168 goto unknown_cmnd;
a41ae418 2169 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
d5e2b67a
MN
2170 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2171 (7<<6) | (1<<1), 1,
2172 "READ TOC")) == 0)
2173 reply = do_read_toc(fsg, bh);
2174 break;
2175
2176 case SC_READ_FORMAT_CAPACITIES:
a41ae418 2177 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
d5e2b67a
MN
2178 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2179 (3<<7), 1,
2180 "READ FORMAT CAPACITIES")) == 0)
2181 reply = do_read_format_capacities(fsg, bh);
2182 break;
2183
2184 case SC_REQUEST_SENSE:
a41ae418 2185 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
d5e2b67a
MN
2186 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2187 (1<<4), 0,
2188 "REQUEST SENSE")) == 0)
2189 reply = do_request_sense(fsg, bh);
2190 break;
2191
2192 case SC_START_STOP_UNIT:
2193 fsg->data_size_from_cmnd = 0;
2194 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2195 (1<<1) | (1<<4), 0,
2196 "START-STOP UNIT")) == 0)
2197 reply = do_start_stop(fsg);
2198 break;
2199
2200 case SC_SYNCHRONIZE_CACHE:
2201 fsg->data_size_from_cmnd = 0;
2202 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2203 (0xf<<2) | (3<<7), 1,
2204 "SYNCHRONIZE CACHE")) == 0)
2205 reply = do_synchronize_cache(fsg);
2206 break;
2207
2208 case SC_TEST_UNIT_READY:
2209 fsg->data_size_from_cmnd = 0;
2210 reply = check_command(fsg, 6, DATA_DIR_NONE,
2211 0, 1,
2212 "TEST UNIT READY");
2213 break;
2214
2215 /* Although optional, this command is used by MS-Windows. We
2216 * support a minimal version: BytChk must be 0. */
2217 case SC_VERIFY:
2218 fsg->data_size_from_cmnd = 0;
2219 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2220 (1<<1) | (0xf<<2) | (3<<7), 1,
2221 "VERIFY")) == 0)
2222 reply = do_verify(fsg);
2223 break;
2224
2225 case SC_WRITE_6:
a41ae418 2226 i = fsg->common->cmnd[4];
d5e2b67a
MN
2227 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2228 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2229 (7<<1) | (1<<4), 1,
2230 "WRITE(6)")) == 0)
2231 reply = do_write(fsg);
2232 break;
2233
2234 case SC_WRITE_10:
2235 fsg->data_size_from_cmnd =
a41ae418 2236 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
d5e2b67a
MN
2237 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2238 (1<<1) | (0xf<<2) | (3<<7), 1,
2239 "WRITE(10)")) == 0)
2240 reply = do_write(fsg);
2241 break;
2242
2243 case SC_WRITE_12:
2244 fsg->data_size_from_cmnd =
a41ae418 2245 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
d5e2b67a
MN
2246 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2247 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2248 "WRITE(12)")) == 0)
2249 reply = do_write(fsg);
2250 break;
2251
2252 /* Some mandatory commands that we recognize but don't implement.
2253 * They don't mean much in this setting. It's left as an exercise
2254 * for anyone interested to implement RESERVE and RELEASE in terms
2255 * of Posix locks. */
2256 case SC_FORMAT_UNIT:
2257 case SC_RELEASE:
2258 case SC_RESERVE:
2259 case SC_SEND_DIAGNOSTIC:
2260 // Fall through
2261
2262 default:
2263 unknown_cmnd:
2264 fsg->data_size_from_cmnd = 0;
a41ae418
MN
2265 sprintf(unknown, "Unknown x%02x", fsg->common->cmnd[0]);
2266 if ((reply = check_command(fsg, fsg->common->cmnd_size,
d5e2b67a 2267 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
a41ae418 2268 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
2269 reply = -EINVAL;
2270 }
2271 break;
2272 }
a41ae418 2273 up_read(&fsg->common->filesem);
d5e2b67a
MN
2274
2275 if (reply == -EINTR || signal_pending(current))
2276 return -EINTR;
2277
2278 /* Set up the single reply buffer for finish_reply() */
2279 if (reply == -EINVAL)
2280 reply = 0; // Error reply length
2281 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2282 reply = min((u32) reply, fsg->data_size_from_cmnd);
2283 bh->inreq->length = reply;
2284 bh->state = BUF_STATE_FULL;
2285 fsg->residue -= reply;
2286 } // Otherwise it's already set
2287
2288 return 0;
2289}
2290
2291
2292/*-------------------------------------------------------------------------*/
2293
2294static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2295{
2296 struct usb_request *req = bh->outreq;
2297 struct fsg_bulk_cb_wrap *cbw = req->buf;
2298
2299 /* Was this a real packet? Should it be ignored? */
2300 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2301 return -EINVAL;
2302
2303 /* Is the CBW valid? */
2304 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2305 cbw->Signature != cpu_to_le32(
2306 USB_BULK_CB_SIG)) {
2307 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2308 req->actual,
2309 le32_to_cpu(cbw->Signature));
2310
2311 /* The Bulk-only spec says we MUST stall the IN endpoint
2312 * (6.6.1), so it's unavoidable. It also says we must
2313 * retain this state until the next reset, but there's
2314 * no way to tell the controller driver it should ignore
2315 * Clear-Feature(HALT) requests.
2316 *
2317 * We aren't required to halt the OUT endpoint; instead
2318 * we can simply accept and discard any data received
2319 * until the next reset. */
2320 wedge_bulk_in_endpoint(fsg);
2321 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2322 return -EINVAL;
2323 }
2324
2325 /* Is the CBW meaningful? */
2326 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2327 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2328 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2329 "cmdlen %u\n",
2330 cbw->Lun, cbw->Flags, cbw->Length);
2331
2332 /* We can do anything we want here, so let's stall the
2333 * bulk pipes if we are allowed to. */
2334 if (mod_data.can_stall) {
2335 fsg_set_halt(fsg, fsg->bulk_out);
2336 halt_bulk_in_endpoint(fsg);
2337 }
2338 return -EINVAL;
2339 }
2340
2341 /* Save the command for later */
a41ae418
MN
2342 fsg->common->cmnd_size = cbw->Length;
2343 memcpy(fsg->common->cmnd, cbw->CDB, fsg->common->cmnd_size);
d5e2b67a
MN
2344 if (cbw->Flags & USB_BULK_IN_FLAG)
2345 fsg->data_dir = DATA_DIR_TO_HOST;
2346 else
2347 fsg->data_dir = DATA_DIR_FROM_HOST;
2348 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2349 if (fsg->data_size == 0)
2350 fsg->data_dir = DATA_DIR_NONE;
a41ae418 2351 fsg->common->lun = cbw->Lun;
d5e2b67a
MN
2352 fsg->tag = cbw->Tag;
2353 return 0;
2354}
2355
2356
2357static int get_next_command(struct fsg_dev *fsg)
2358{
2359 struct fsg_buffhd *bh;
2360 int rc = 0;
2361
93bcf12e 2362 /* Wait for the next buffer to become available */
a41ae418 2363 bh = fsg->common->next_buffhd_to_fill;
93bcf12e
MN
2364 while (bh->state != BUF_STATE_EMPTY) {
2365 rc = sleep_thread(fsg);
2366 if (rc)
2367 return rc;
2368 }
d5e2b67a 2369
93bcf12e
MN
2370 /* Queue a request to read a Bulk-only CBW */
2371 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2372 bh->outreq->short_not_ok = 1;
2373 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2374 &bh->outreq_busy, &bh->state);
d5e2b67a 2375
93bcf12e
MN
2376 /* We will drain the buffer in software, which means we
2377 * can reuse it for the next filling. No need to advance
2378 * next_buffhd_to_fill. */
d5e2b67a 2379
93bcf12e
MN
2380 /* Wait for the CBW to arrive */
2381 while (bh->state != BUF_STATE_FULL) {
2382 rc = sleep_thread(fsg);
2383 if (rc)
2384 return rc;
d5e2b67a 2385 }
93bcf12e
MN
2386 smp_rmb();
2387 rc = received_cbw(fsg, bh);
2388 bh->state = BUF_STATE_EMPTY;
2389
d5e2b67a
MN
2390 return rc;
2391}
2392
2393
2394/*-------------------------------------------------------------------------*/
2395
2396static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2397 const struct usb_endpoint_descriptor *d)
2398{
2399 int rc;
2400
2401 ep->driver_data = fsg;
2402 rc = usb_ep_enable(ep, d);
2403 if (rc)
2404 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2405 return rc;
2406}
2407
2408static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2409 struct usb_request **preq)
2410{
2411 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2412 if (*preq)
2413 return 0;
2414 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2415 return -ENOMEM;
2416}
2417
2418/*
2419 * Reset interface setting and re-init endpoint state (toggle etc).
2420 * Call with altsetting < 0 to disable the interface. The only other
2421 * available altsetting is 0, which enables the interface.
2422 */
2423static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2424{
2425 int rc = 0;
2426 int i;
2427 const struct usb_endpoint_descriptor *d;
2428
2429 if (fsg->running)
2430 DBG(fsg, "reset interface\n");
2431
2432reset:
2433 /* Deallocate the requests */
2434 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
a41ae418 2435 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
d5e2b67a
MN
2436
2437 if (bh->inreq) {
2438 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2439 bh->inreq = NULL;
2440 }
2441 if (bh->outreq) {
2442 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2443 bh->outreq = NULL;
2444 }
2445 }
d5e2b67a
MN
2446
2447 /* Disable the endpoints */
2448 if (fsg->bulk_in_enabled) {
2449 usb_ep_disable(fsg->bulk_in);
2450 fsg->bulk_in_enabled = 0;
2451 }
2452 if (fsg->bulk_out_enabled) {
2453 usb_ep_disable(fsg->bulk_out);
2454 fsg->bulk_out_enabled = 0;
2455 }
d5e2b67a
MN
2456
2457 fsg->running = 0;
2458 if (altsetting < 0 || rc != 0)
2459 return rc;
2460
2461 DBG(fsg, "set interface %d\n", altsetting);
2462
2463 /* Enable the endpoints */
2464 d = fsg_ep_desc(fsg->gadget,
2465 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2466 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2467 goto reset;
2468 fsg->bulk_in_enabled = 1;
2469
2470 d = fsg_ep_desc(fsg->gadget,
2471 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2472 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2473 goto reset;
2474 fsg->bulk_out_enabled = 1;
2475 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2476 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2477
d5e2b67a
MN
2478 /* Allocate the requests */
2479 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
a41ae418 2480 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
d5e2b67a
MN
2481
2482 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2483 goto reset;
2484 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2485 goto reset;
2486 bh->inreq->buf = bh->outreq->buf = bh->buf;
2487 bh->inreq->context = bh->outreq->context = bh;
2488 bh->inreq->complete = bulk_in_complete;
2489 bh->outreq->complete = bulk_out_complete;
2490 }
d5e2b67a
MN
2491
2492 fsg->running = 1;
a41ae418
MN
2493 for (i = 0; i < fsg->common->nluns; ++i)
2494 fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
d5e2b67a
MN
2495 return rc;
2496}
2497
2498
2499/*
2500 * Change our operational configuration. This code must agree with the code
2501 * that returns config descriptors, and with interface altsetting code.
2502 *
2503 * It's also responsible for power management interactions. Some
2504 * configurations might not work with our current power sources.
2505 * For now we just assume the gadget is always self-powered.
2506 */
2507static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2508{
2509 int rc = 0;
2510
2511 /* Disable the single interface */
2512 if (fsg->config != 0) {
2513 DBG(fsg, "reset config\n");
2514 fsg->config = 0;
2515 rc = do_set_interface(fsg, -1);
2516 }
2517
2518 /* Enable the interface */
2519 if (new_config != 0) {
2520 fsg->config = new_config;
2521 if ((rc = do_set_interface(fsg, 0)) != 0)
2522 fsg->config = 0; // Reset on errors
2523 else {
2524 char *speed;
2525
2526 switch (fsg->gadget->speed) {
2527 case USB_SPEED_LOW: speed = "low"; break;
2528 case USB_SPEED_FULL: speed = "full"; break;
2529 case USB_SPEED_HIGH: speed = "high"; break;
2530 default: speed = "?"; break;
2531 }
2532 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2533 }
2534 }
2535 return rc;
2536}
2537
2538
2539/*-------------------------------------------------------------------------*/
2540
2541static void handle_exception(struct fsg_dev *fsg)
2542{
2543 siginfo_t info;
2544 int sig;
2545 int i;
d5e2b67a
MN
2546 struct fsg_buffhd *bh;
2547 enum fsg_state old_state;
2548 u8 new_config;
2549 struct fsg_lun *curlun;
2550 unsigned int exception_req_tag;
2551 int rc;
2552
2553 /* Clear the existing signals. Anything but SIGUSR1 is converted
2554 * into a high-priority EXIT exception. */
2555 for (;;) {
2556 sig = dequeue_signal_lock(current, &current->blocked, &info);
2557 if (!sig)
2558 break;
2559 if (sig != SIGUSR1) {
2560 if (fsg->state < FSG_STATE_EXIT)
2561 DBG(fsg, "Main thread exiting on signal\n");
2562 raise_exception(fsg, FSG_STATE_EXIT);
2563 }
2564 }
2565
2566 /* Cancel all the pending transfers */
d5e2b67a 2567 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
a41ae418 2568 bh = &fsg->common->buffhds[i];
d5e2b67a
MN
2569 if (bh->inreq_busy)
2570 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2571 if (bh->outreq_busy)
2572 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2573 }
2574
2575 /* Wait until everything is idle */
2576 for (;;) {
a41ae418 2577 int num_active = 0;
d5e2b67a 2578 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
a41ae418 2579 bh = &fsg->common->buffhds[i];
d5e2b67a
MN
2580 num_active += bh->inreq_busy + bh->outreq_busy;
2581 }
2582 if (num_active == 0)
2583 break;
2584 if (sleep_thread(fsg))
2585 return;
2586 }
2587
2588 /* Clear out the controller's fifos */
2589 if (fsg->bulk_in_enabled)
2590 usb_ep_fifo_flush(fsg->bulk_in);
2591 if (fsg->bulk_out_enabled)
2592 usb_ep_fifo_flush(fsg->bulk_out);
d5e2b67a
MN
2593
2594 /* Reset the I/O buffer states and pointers, the SCSI
2595 * state, and the exception. Then invoke the handler. */
2596 spin_lock_irq(&fsg->lock);
2597
2598 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
a41ae418 2599 bh = &fsg->common->buffhds[i];
d5e2b67a
MN
2600 bh->state = BUF_STATE_EMPTY;
2601 }
a41ae418
MN
2602 fsg->common->next_buffhd_to_fill = fsg->common->next_buffhd_to_drain =
2603 &fsg->common->buffhds[0];
d5e2b67a
MN
2604
2605 exception_req_tag = fsg->exception_req_tag;
2606 new_config = fsg->new_config;
2607 old_state = fsg->state;
2608
2609 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2610 fsg->state = FSG_STATE_STATUS_PHASE;
2611 else {
a41ae418
MN
2612 for (i = 0; i < fsg->common->nluns; ++i) {
2613 curlun = &fsg->common->luns[i];
d5e2b67a
MN
2614 curlun->prevent_medium_removal = 0;
2615 curlun->sense_data = curlun->unit_attention_data =
2616 SS_NO_SENSE;
2617 curlun->sense_data_info = 0;
2618 curlun->info_valid = 0;
2619 }
2620 fsg->state = FSG_STATE_IDLE;
2621 }
2622 spin_unlock_irq(&fsg->lock);
2623
2624 /* Carry out any extra actions required for the exception */
2625 switch (old_state) {
2626 default:
2627 break;
2628
2629 case FSG_STATE_ABORT_BULK_OUT:
2630 send_status(fsg);
2631 spin_lock_irq(&fsg->lock);
2632 if (fsg->state == FSG_STATE_STATUS_PHASE)
2633 fsg->state = FSG_STATE_IDLE;
2634 spin_unlock_irq(&fsg->lock);
2635 break;
2636
2637 case FSG_STATE_RESET:
2638 /* In case we were forced against our will to halt a
2639 * bulk endpoint, clear the halt now. (The SuperH UDC
2640 * requires this.) */
2641 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2642 usb_ep_clear_halt(fsg->bulk_in);
2643
93bcf12e
MN
2644 if (fsg->ep0_req_tag == exception_req_tag)
2645 ep0_queue(fsg); // Complete the status stage
d5e2b67a
MN
2646
2647 /* Technically this should go here, but it would only be
2648 * a waste of time. Ditto for the INTERFACE_CHANGE and
2649 * CONFIG_CHANGE cases. */
a41ae418
MN
2650 // for (i = 0; i < fsg->common->nluns; ++i)
2651 // fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
d5e2b67a
MN
2652 break;
2653
2654 case FSG_STATE_INTERFACE_CHANGE:
2655 rc = do_set_interface(fsg, 0);
2656 if (fsg->ep0_req_tag != exception_req_tag)
2657 break;
2658 if (rc != 0) // STALL on errors
2659 fsg_set_halt(fsg, fsg->ep0);
2660 else // Complete the status stage
2661 ep0_queue(fsg);
2662 break;
2663
2664 case FSG_STATE_CONFIG_CHANGE:
2665 rc = do_set_config(fsg, new_config);
2666 if (fsg->ep0_req_tag != exception_req_tag)
2667 break;
2668 if (rc != 0) // STALL on errors
2669 fsg_set_halt(fsg, fsg->ep0);
2670 else // Complete the status stage
2671 ep0_queue(fsg);
2672 break;
2673
2674 case FSG_STATE_DISCONNECT:
a41ae418
MN
2675 for (i = 0; i < fsg->common->nluns; ++i)
2676 fsg_lun_fsync_sub(&fsg->common->luns[i]);
d5e2b67a
MN
2677 do_set_config(fsg, 0); // Unconfigured state
2678 break;
2679
2680 case FSG_STATE_EXIT:
2681 case FSG_STATE_TERMINATED:
2682 do_set_config(fsg, 0); // Free resources
2683 spin_lock_irq(&fsg->lock);
2684 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
2685 spin_unlock_irq(&fsg->lock);
2686 break;
2687 }
2688}
2689
2690
2691/*-------------------------------------------------------------------------*/
2692
2693static int fsg_main_thread(void *fsg_)
2694{
2695 struct fsg_dev *fsg = fsg_;
2696
2697 /* Allow the thread to be killed by a signal, but set the signal mask
2698 * to block everything but INT, TERM, KILL, and USR1. */
2699 allow_signal(SIGINT);
2700 allow_signal(SIGTERM);
2701 allow_signal(SIGKILL);
2702 allow_signal(SIGUSR1);
2703
2704 /* Allow the thread to be frozen */
2705 set_freezable();
2706
2707 /* Arrange for userspace references to be interpreted as kernel
2708 * pointers. That way we can pass a kernel pointer to a routine
2709 * that expects a __user pointer and it will work okay. */
2710 set_fs(get_ds());
2711
2712 /* The main loop */
2713 while (fsg->state != FSG_STATE_TERMINATED) {
2714 if (exception_in_progress(fsg) || signal_pending(current)) {
2715 handle_exception(fsg);
2716 continue;
2717 }
2718
2719 if (!fsg->running) {
2720 sleep_thread(fsg);
2721 continue;
2722 }
2723
2724 if (get_next_command(fsg))
2725 continue;
2726
2727 spin_lock_irq(&fsg->lock);
2728 if (!exception_in_progress(fsg))
2729 fsg->state = FSG_STATE_DATA_PHASE;
2730 spin_unlock_irq(&fsg->lock);
2731
2732 if (do_scsi_command(fsg) || finish_reply(fsg))
2733 continue;
2734
2735 spin_lock_irq(&fsg->lock);
2736 if (!exception_in_progress(fsg))
2737 fsg->state = FSG_STATE_STATUS_PHASE;
2738 spin_unlock_irq(&fsg->lock);
2739
2740 if (send_status(fsg))
2741 continue;
2742
2743 spin_lock_irq(&fsg->lock);
2744 if (!exception_in_progress(fsg))
2745 fsg->state = FSG_STATE_IDLE;
2746 spin_unlock_irq(&fsg->lock);
2747 }
2748
2749 spin_lock_irq(&fsg->lock);
2750 fsg->thread_task = NULL;
2751 spin_unlock_irq(&fsg->lock);
2752
2753 /* If we are exiting because of a signal, unregister the
2754 * gadget driver. */
2755 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2756 usb_gadget_unregister_driver(&fsg_driver);
2757
2758 /* Let the unbind and cleanup routines know the thread has exited */
2759 complete_and_exit(&fsg->thread_notifier, 0);
2760}
2761
2762
9c610213 2763/*************************** DEVICE ATTRIBUTES ***************************/
d5e2b67a
MN
2764
2765
2766/* The write permissions and store_xxx pointers are set in fsg_bind() */
2767static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
2768static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
2769
2770
9c610213
MN
2771/****************************** FSG COMMON ******************************/
2772
2773static void fsg_common_release(struct kref *ref);
d5e2b67a 2774
9c610213 2775static void fsg_lun_release(struct device *dev)
d5e2b67a 2776{
9c610213 2777 /* Nothing needs to be done */
d5e2b67a
MN
2778}
2779
9c610213 2780static inline void fsg_common_get(struct fsg_common *common)
d5e2b67a 2781{
9c610213 2782 kref_get(&common->ref);
d5e2b67a
MN
2783}
2784
9c610213
MN
2785static inline void fsg_common_put(struct fsg_common *common)
2786{
2787 kref_put(&common->ref, fsg_common_release);
2788}
2789
2790
2791static struct fsg_common *fsg_common_init(struct fsg_common *common,
2792 struct usb_gadget *gadget)
2793{
2794 struct fsg_buffhd *bh;
2795 struct fsg_lun *curlun;
2796 int nluns, i, rc;
2797
2798 /* Find out how many LUNs there should be */
2799 nluns = mod_data.nluns;
2800 if (nluns == 0)
2801 nluns = max(mod_data.num_filenames, 1u);
2802 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2803 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2804 return ERR_PTR(-EINVAL);
2805 }
2806
2807 /* Allocate? */
2808 if (!common) {
2809 common = kzalloc(sizeof *common, GFP_KERNEL);
2810 if (!common)
2811 return ERR_PTR(-ENOMEM);
2812 common->free_storage_on_release = 1;
2813 } else {
2814 memset(common, 0, sizeof common);
2815 common->free_storage_on_release = 0;
2816 }
2817 common->gadget = gadget;
2818
2819 /* Create the LUNs, open their backing files, and register the
2820 * LUN devices in sysfs. */
2821 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2822 if (!curlun) {
2823 kfree(common);
2824 return ERR_PTR(-ENOMEM);
2825 }
2826 common->luns = curlun;
2827
2828 init_rwsem(&common->filesem);
2829
2830 for (i = 0; i < nluns; ++i, ++curlun) {
2831 curlun->cdrom = !!mod_data.cdrom;
2832 curlun->ro = mod_data.cdrom || mod_data.ro[i];
2833 curlun->removable = mod_data.removable;
2834 curlun->dev.release = fsg_lun_release;
2835 curlun->dev.parent = &gadget->dev;
2836 curlun->dev.driver = &fsg_driver.driver;
2837 dev_set_drvdata(&curlun->dev, &common->filesem);
2838 dev_set_name(&curlun->dev,"%s-lun%d",
2839 dev_name(&gadget->dev), i);
2840
2841 rc = device_register(&curlun->dev);
2842 if (rc) {
2843 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2844 common->nluns = i;
2845 goto error_release;
2846 }
2847
2848 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2849 if (rc)
2850 goto error_luns;
2851 rc = device_create_file(&curlun->dev, &dev_attr_file);
2852 if (rc)
2853 goto error_luns;
2854
2855 if (mod_data.file[i] && *mod_data.file[i]) {
2856 rc = fsg_lun_open(curlun, mod_data.file[i]);
2857 if (rc)
2858 goto error_luns;
2859 } else if (!mod_data.removable) {
2860 ERROR(common, "no file given for LUN%d\n", i);
2861 rc = -EINVAL;
2862 goto error_luns;
2863 }
2864 }
2865 common->nluns = nluns;
2866
2867
2868 /* Data buffers cyclic list */
2869 /* Buffers in buffhds are static -- no need for additional
2870 * allocation. */
2871 bh = common->buffhds;
2872 i = FSG_NUM_BUFFERS - 1;
2873 do {
2874 bh->next = bh + 1;
2875 } while (++bh, --i);
2876 bh->next = common->buffhds;
2877
2878
2879 /* Release */
2880 if (mod_data.release == 0xffff) { // Parameter wasn't set
2881 int gcnum;
2882
2883 /* The sa1100 controller is not supported */
2884 if (gadget_is_sa1100(gadget))
2885 gcnum = -1;
2886 else
2887 gcnum = usb_gadget_controller_number(gadget);
2888 if (gcnum >= 0)
2889 mod_data.release = 0x0300 + gcnum;
2890 else {
2891 WARNING(common, "controller '%s' not recognized\n",
2892 gadget->name);
2893 WARNING(common, "controller '%s' not recognized\n",
2894 gadget->name);
2895 mod_data.release = 0x0399;
2896 }
2897 }
2898
2899
2900 /* Some peripheral controllers are known not to be able to
2901 * halt bulk endpoints correctly. If one of them is present,
2902 * disable stalls.
2903 */
2904 if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
2905 mod_data.can_stall = 0;
2906
2907
2908 kref_init(&common->ref);
2909 return common;
2910
2911
2912error_luns:
2913 common->nluns = i + 1;
2914error_release:
2915 /* Call fsg_common_release() directly, ref is not initialised */
2916 fsg_common_release(&common->ref);
2917 return ERR_PTR(rc);
2918}
2919
2920
2921static void fsg_common_release(struct kref *ref)
2922{
2923 struct fsg_common *common =
2924 container_of(ref, struct fsg_common, ref);
2925 unsigned i = common->nluns;
2926 struct fsg_lun *lun = common->luns;
2927
2928 /* Beware tempting for -> do-while optimization: when in error
2929 * recovery nluns may be zero. */
2930
2931 for (; i; --i, ++lun) {
2932 device_remove_file(&lun->dev, &dev_attr_ro);
2933 device_remove_file(&lun->dev, &dev_attr_file);
2934 fsg_lun_close(lun);
2935 device_unregister(&lun->dev);
2936 }
2937
2938 kfree(common->luns);
2939 if (common->free_storage_on_release)
2940 kfree(common);
2941}
2942
2943
2944/*-------------------------------------------------------------------------*/
2945
2946
d5e2b67a
MN
2947static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
2948{
2949 struct fsg_dev *fsg = get_gadget_data(gadget);
d5e2b67a
MN
2950 struct usb_request *req = fsg->ep0req;
2951
2952 DBG(fsg, "unbind\n");
2953 clear_bit(REGISTERED, &fsg->atomic_bitflags);
2954
d5e2b67a
MN
2955 /* If the thread isn't already dead, tell it to exit now */
2956 if (fsg->state != FSG_STATE_TERMINATED) {
2957 raise_exception(fsg, FSG_STATE_EXIT);
2958 wait_for_completion(&fsg->thread_notifier);
2959
2960 /* The cleanup routine waits for this completion also */
2961 complete(&fsg->thread_notifier);
2962 }
2963
d5e2b67a
MN
2964 /* Free the request and buffer for endpoint 0 */
2965 if (req) {
2966 kfree(req->buf);
2967 usb_ep_free_request(fsg->ep0, req);
2968 }
2969
9c610213
MN
2970 fsg_common_put(fsg->common);
2971 kfree(fsg);
d5e2b67a
MN
2972 set_gadget_data(gadget, NULL);
2973}
2974
2975
d5e2b67a
MN
2976static int __init fsg_bind(struct usb_gadget *gadget)
2977{
9c610213 2978 struct fsg_dev *fsg;
d5e2b67a
MN
2979 int rc;
2980 int i;
2981 struct fsg_lun *curlun;
2982 struct usb_ep *ep;
2983 struct usb_request *req;
2984 char *pathbuf, *p;
2985
9c610213
MN
2986 /* Allocate */
2987 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
2988 if (!fsg)
2989 return -ENOMEM;
2990
2991 /* Initialise common */
2992 fsg->common = fsg_common_init(0, gadget);
2993 if (IS_ERR(fsg->common))
2994 return PTR_ERR(fsg->common);
2995
2996 /* Basic parameters */
d5e2b67a
MN
2997 fsg->gadget = gadget;
2998 set_gadget_data(gadget, fsg);
2999 fsg->ep0 = gadget->ep0;
3000 fsg->ep0->driver_data = fsg;
3001
9c610213
MN
3002 spin_lock_init(&fsg->lock);
3003 init_completion(&fsg->thread_notifier);
d5e2b67a 3004
9c610213
MN
3005 /* Enable the store_xxx attributes */
3006 if (mod_data.removable) {
d5e2b67a
MN
3007 dev_attr_file.attr.mode = 0644;
3008 dev_attr_file.store = fsg_store_file;
3009 if (!mod_data.cdrom) {
3010 dev_attr_ro.attr.mode = 0644;
3011 dev_attr_ro.store = fsg_store_ro;
3012 }
3013 }
3014
d5e2b67a
MN
3015 /* Find all the endpoints we will use */
3016 usb_ep_autoconfig_reset(gadget);
3017 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3018 if (!ep)
3019 goto autoconf_fail;
3020 ep->driver_data = fsg; // claim the endpoint
3021 fsg->bulk_in = ep;
3022
3023 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3024 if (!ep)
3025 goto autoconf_fail;
3026 ep->driver_data = fsg; // claim the endpoint
3027 fsg->bulk_out = ep;
3028
d5e2b67a
MN
3029 /* Fix up the descriptors */
3030 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
d5e2b67a
MN
3031 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3032
d5e2b67a 3033 if (gadget_is_dualspeed(gadget)) {
d5e2b67a
MN
3034 /* Assume ep0 uses the same maxpacket value for both speeds */
3035 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3036
3037 /* Assume endpoint addresses are the same for both speeds */
3038 fsg_hs_bulk_in_desc.bEndpointAddress =
3039 fsg_fs_bulk_in_desc.bEndpointAddress;
3040 fsg_hs_bulk_out_desc.bEndpointAddress =
3041 fsg_fs_bulk_out_desc.bEndpointAddress;
d5e2b67a
MN
3042 }
3043
3044 if (gadget_is_otg(gadget))
3045 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
3046
3047 rc = -ENOMEM;
3048
3049 /* Allocate the request and buffer for endpoint 0 */
3050 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3051 if (!req)
3052 goto out;
3053 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
3054 if (!req->buf)
3055 goto out;
3056 req->complete = ep0_complete;
3057
d5e2b67a
MN
3058 /* This should reflect the actual gadget power source */
3059 usb_gadget_set_selfpowered(gadget);
3060
3061 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3062 "%s %s with %s",
3063 init_utsname()->sysname, init_utsname()->release,
3064 gadget->name);
3065
3066 /* On a real device, serial[] would be loaded from permanent
3067 * storage. We just encode it from the driver version string. */
3068 for (i = 0; i < sizeof fsg_string_serial - 2; i += 2) {
3069 unsigned char c = DRIVER_VERSION[i / 2];
3070
3071 if (!c)
3072 break;
3073 sprintf(&fsg_string_serial[i], "%02X", c);
3074 }
3075
3076 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3077 "file-storage-gadget");
3078 if (IS_ERR(fsg->thread_task)) {
3079 rc = PTR_ERR(fsg->thread_task);
3080 goto out;
3081 }
3082
3083 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
a41ae418 3084 INFO(fsg, "Number of LUNs=%d\n", fsg->common->nluns);
d5e2b67a
MN
3085
3086 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
a41ae418
MN
3087 for (i = 0; i < fsg->common->nluns; ++i) {
3088 curlun = &fsg->common->luns[i];
d5e2b67a
MN
3089 if (fsg_lun_is_open(curlun)) {
3090 p = NULL;
3091 if (pathbuf) {
3092 p = d_path(&curlun->filp->f_path,
3093 pathbuf, PATH_MAX);
3094 if (IS_ERR(p))
3095 p = NULL;
3096 }
3097 LINFO(curlun, "ro=%d, file: %s\n",
3098 curlun->ro, (p ? p : "(error)"));
3099 }
3100 }
3101 kfree(pathbuf);
3102
d5e2b67a
MN
3103 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3104 mod_data.removable, mod_data.can_stall,
93bcf12e 3105 mod_data.cdrom, FSG_BUFLEN);
d5e2b67a
MN
3106 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
3107
3108 set_bit(REGISTERED, &fsg->atomic_bitflags);
3109
3110 /* Tell the thread to start working */
3111 wake_up_process(fsg->thread_task);
9c610213
MN
3112
3113 the_fsg = fsg;
d5e2b67a
MN
3114 return 0;
3115
3116autoconf_fail:
3117 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3118 rc = -ENOTSUPP;
3119
3120out:
3121 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3122 fsg_unbind(gadget);
3123 complete(&fsg->thread_notifier);
3124 return rc;
3125}
3126
3127
d5e2b67a
MN
3128/*-------------------------------------------------------------------------*/
3129
3130static struct usb_gadget_driver fsg_driver = {
3131#ifdef CONFIG_USB_GADGET_DUALSPEED
3132 .speed = USB_SPEED_HIGH,
3133#else
3134 .speed = USB_SPEED_FULL,
3135#endif
3136 .function = (char *) fsg_string_product,
3137 .bind = fsg_bind,
3138 .unbind = fsg_unbind,
3139 .disconnect = fsg_disconnect,
3140 .setup = fsg_setup,
d5e2b67a
MN
3141
3142 .driver = {
3143 .name = DRIVER_NAME,
3144 .owner = THIS_MODULE,
3145 // .release = ...
3146 // .suspend = ...
3147 // .resume = ...
3148 },
3149};
3150
3151
d5e2b67a
MN
3152static int __init fsg_init(void)
3153{
9c610213 3154 return usb_gadget_register_driver(&fsg_driver);
d5e2b67a
MN
3155}
3156module_init(fsg_init);
3157
3158
3159static void __exit fsg_cleanup(void)
3160{
d5e2b67a 3161 /* Unregister the driver iff the thread hasn't already done so */
9c610213
MN
3162 if (the_fsg &&
3163 test_and_clear_bit(REGISTERED, &the_fsg->atomic_bitflags))
d5e2b67a 3164 usb_gadget_unregister_driver(&fsg_driver);
d5e2b67a
MN
3165}
3166module_exit(fsg_cleanup);