blob: 7750346b696c6e728ad4981aa01d64d0eb678249 [file] [log] [blame]
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001/*
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 *
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +010053 * 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
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +010094 *
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
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100260#define FSG_NO_INTR_EP 1
261
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100262#include "storage_common.c"
263
264
265MODULE_DESCRIPTION(DRIVER_DESC);
266MODULE_AUTHOR("Alan Stern");
267MODULE_LICENSE("Dual BSD/GPL");
268
269/*
270 * This driver assumes self-powered hardware and has no way for users to
271 * trigger remote wakeup. It uses autoconfiguration to select endpoints
272 * and endpoint addresses.
273 */
274
275
276/*-------------------------------------------------------------------------*/
277
278
279/* Encapsulate the module parameter settings */
280
281static struct {
282 char *file[FSG_MAX_LUNS];
283 int ro[FSG_MAX_LUNS];
284 unsigned int num_filenames;
285 unsigned int num_ros;
286 unsigned int nluns;
287
288 int removable;
289 int can_stall;
290 int cdrom;
291
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100292 unsigned short release;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100293} mod_data = { // Default values
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100294 .removable = 0,
295 .can_stall = 1,
296 .cdrom = 0,
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100297 };
298
299
300module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
301 S_IRUGO);
302MODULE_PARM_DESC(file, "names of backing files or devices");
303
304module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
305MODULE_PARM_DESC(ro, "true to force read-only");
306
307module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
308MODULE_PARM_DESC(luns, "number of LUNs");
309
310module_param_named(removable, mod_data.removable, bool, S_IRUGO);
311MODULE_PARM_DESC(removable, "true to simulate removable media");
312
313module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
314MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
315
316module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
317MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
318
319
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100320/*-------------------------------------------------------------------------*/
321
322
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100323/* Data shared by all the FSG instances. */
324struct fsg_common {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100325 /* filesem protects: backing files in use */
326 struct rw_semaphore filesem;
327
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100328 struct fsg_buffhd *next_buffhd_to_fill;
329 struct fsg_buffhd *next_buffhd_to_drain;
330 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
331
332 int cmnd_size;
333 u8 cmnd[MAX_COMMAND_SIZE];
334
335 unsigned int nluns;
336 unsigned int lun;
337 struct fsg_lun *luns;
338 struct fsg_lun *curlun;
339};
340
341
342struct fsg_dev {
343 struct fsg_common *common;
344
345 /* lock protects: state, all the req_busy's */
346 spinlock_t lock;
347 struct usb_gadget *gadget;
348
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100349 /* reference counting: wait until all LUNs are released */
350 struct kref ref;
351
352 struct usb_ep *ep0; // Handy copy of gadget->ep0
353 struct usb_request *ep0req; // For control responses
354 unsigned int ep0_req_tag;
355 const char *ep0req_name;
356
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100357 unsigned int bulk_out_maxpacket;
358 enum fsg_state state; // For exception handling
359 unsigned int exception_req_tag;
360
361 u8 config, new_config;
362
363 unsigned int running : 1;
364 unsigned int bulk_in_enabled : 1;
365 unsigned int bulk_out_enabled : 1;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100366 unsigned int phase_error : 1;
367 unsigned int short_packet_received : 1;
368 unsigned int bad_lun_okay : 1;
369
370 unsigned long atomic_bitflags;
371#define REGISTERED 0
372#define IGNORE_BULK_OUT 1
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100373
374 struct usb_ep *bulk_in;
375 struct usb_ep *bulk_out;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100376
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100377 int thread_wakeup_needed;
378 struct completion thread_notifier;
379 struct task_struct *thread_task;
380
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100381 enum data_direction data_dir;
382 u32 data_size;
383 u32 data_size_from_cmnd;
384 u32 tag;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100385 u32 residue;
386 u32 usb_amount_left;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100387};
388
389typedef void (*fsg_routine_t)(struct fsg_dev *);
390
391static int exception_in_progress(struct fsg_dev *fsg)
392{
393 return (fsg->state > FSG_STATE_IDLE);
394}
395
396/* Make bulk-out requests be divisible by the maxpacket size */
397static void set_bulk_out_req_length(struct fsg_dev *fsg,
398 struct fsg_buffhd *bh, unsigned int length)
399{
400 unsigned int rem;
401
402 bh->bulk_out_intended_length = length;
403 rem = length % fsg->bulk_out_maxpacket;
404 if (rem > 0)
405 length += fsg->bulk_out_maxpacket - rem;
406 bh->outreq->length = length;
407}
408
409static struct fsg_dev *the_fsg;
410static struct usb_gadget_driver fsg_driver;
411
412
413/*-------------------------------------------------------------------------*/
414
415static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
416{
417 const char *name;
418
419 if (ep == fsg->bulk_in)
420 name = "bulk-in";
421 else if (ep == fsg->bulk_out)
422 name = "bulk-out";
423 else
424 name = ep->name;
425 DBG(fsg, "%s set halt\n", name);
426 return usb_ep_set_halt(ep);
427}
428
429
430/*-------------------------------------------------------------------------*/
431
432/*
433 * DESCRIPTORS ... most are static, but strings and (full) configuration
434 * descriptors are built on demand. Also the (static) config and interface
435 * descriptors are adjusted during fsg_bind().
436 */
437
438/* There is only one configuration. */
439#define CONFIG_VALUE 1
440
441static struct usb_device_descriptor
442device_desc = {
443 .bLength = sizeof device_desc,
444 .bDescriptorType = USB_DT_DEVICE,
445
446 .bcdUSB = cpu_to_le16(0x0200),
447 .bDeviceClass = USB_CLASS_PER_INTERFACE,
448
449 /* The next three values can be overridden by module parameters */
450 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
451 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
452 .bcdDevice = cpu_to_le16(0xffff),
453
454 .iManufacturer = FSG_STRING_MANUFACTURER,
455 .iProduct = FSG_STRING_PRODUCT,
456 .iSerialNumber = FSG_STRING_SERIAL,
457 .bNumConfigurations = 1,
458};
459
460static struct usb_config_descriptor
461config_desc = {
462 .bLength = sizeof config_desc,
463 .bDescriptorType = USB_DT_CONFIG,
464
465 /* wTotalLength computed by usb_gadget_config_buf() */
466 .bNumInterfaces = 1,
467 .bConfigurationValue = CONFIG_VALUE,
468 .iConfiguration = FSG_STRING_CONFIG,
469 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
470 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
471};
472
473
474static struct usb_qualifier_descriptor
475dev_qualifier = {
476 .bLength = sizeof dev_qualifier,
477 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
478
479 .bcdUSB = cpu_to_le16(0x0200),
480 .bDeviceClass = USB_CLASS_PER_INTERFACE,
481
482 .bNumConfigurations = 1,
483};
484
485
486
487/*
488 * Config descriptors must agree with the code that sets configurations
489 * and with code managing interfaces and their altsettings. They must
490 * also handle different speeds and other-speed requests.
491 */
492static int populate_config_buf(struct usb_gadget *gadget,
493 u8 *buf, u8 type, unsigned index)
494{
495 enum usb_device_speed speed = gadget->speed;
496 int len;
497 const struct usb_descriptor_header **function;
498
499 if (index > 0)
500 return -EINVAL;
501
502 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
503 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
504 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
505 function = fsg_hs_function;
506 else
507 function = fsg_fs_function;
508
509 /* for now, don't advertise srp-only devices */
510 if (!gadget_is_otg(gadget))
511 function++;
512
513 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
514 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
515 return len;
516}
517
518
519/*-------------------------------------------------------------------------*/
520
521/* These routines may be called in process context or in_irq */
522
523/* Caller must hold fsg->lock */
524static void wakeup_thread(struct fsg_dev *fsg)
525{
526 /* Tell the main thread that something has happened */
527 fsg->thread_wakeup_needed = 1;
528 if (fsg->thread_task)
529 wake_up_process(fsg->thread_task);
530}
531
532
533static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
534{
535 unsigned long flags;
536
537 /* Do nothing if a higher-priority exception is already in progress.
538 * If a lower-or-equal priority exception is in progress, preempt it
539 * and notify the main thread by sending it a signal. */
540 spin_lock_irqsave(&fsg->lock, flags);
541 if (fsg->state <= new_state) {
542 fsg->exception_req_tag = fsg->ep0_req_tag;
543 fsg->state = new_state;
544 if (fsg->thread_task)
545 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
546 fsg->thread_task);
547 }
548 spin_unlock_irqrestore(&fsg->lock, flags);
549}
550
551
552/*-------------------------------------------------------------------------*/
553
554/* The disconnect callback and ep0 routines. These always run in_irq,
555 * except that ep0_queue() is called in the main thread to acknowledge
556 * completion of various requests: set config, set interface, and
557 * Bulk-only device reset. */
558
559static void fsg_disconnect(struct usb_gadget *gadget)
560{
561 struct fsg_dev *fsg = get_gadget_data(gadget);
562
563 DBG(fsg, "disconnect or port reset\n");
564 raise_exception(fsg, FSG_STATE_DISCONNECT);
565}
566
567
568static int ep0_queue(struct fsg_dev *fsg)
569{
570 int rc;
571
572 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
573 if (rc != 0 && rc != -ESHUTDOWN) {
574
575 /* We can't do much more than wait for a reset */
576 WARNING(fsg, "error in submission: %s --> %d\n",
577 fsg->ep0->name, rc);
578 }
579 return rc;
580}
581
582static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
583{
584 struct fsg_dev *fsg = ep->driver_data;
585
586 if (req->actual > 0)
587 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
588 if (req->status || req->actual != req->length)
589 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
590 req->status, req->actual, req->length);
591 if (req->status == -ECONNRESET) // Request was cancelled
592 usb_ep_fifo_flush(ep);
593
594 if (req->status == 0 && req->context)
595 ((fsg_routine_t) (req->context))(fsg);
596}
597
598
599/*-------------------------------------------------------------------------*/
600
601/* Bulk and interrupt endpoint completion handlers.
602 * These always run in_irq. */
603
604static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
605{
606 struct fsg_dev *fsg = ep->driver_data;
607 struct fsg_buffhd *bh = req->context;
608
609 if (req->status || req->actual != req->length)
610 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
611 req->status, req->actual, req->length);
612 if (req->status == -ECONNRESET) // Request was cancelled
613 usb_ep_fifo_flush(ep);
614
615 /* Hold the lock while we update the request and buffer states */
616 smp_wmb();
617 spin_lock(&fsg->lock);
618 bh->inreq_busy = 0;
619 bh->state = BUF_STATE_EMPTY;
620 wakeup_thread(fsg);
621 spin_unlock(&fsg->lock);
622}
623
624static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
625{
626 struct fsg_dev *fsg = ep->driver_data;
627 struct fsg_buffhd *bh = req->context;
628
629 dump_msg(fsg, "bulk-out", req->buf, req->actual);
630 if (req->status || req->actual != bh->bulk_out_intended_length)
631 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
632 req->status, req->actual,
633 bh->bulk_out_intended_length);
634 if (req->status == -ECONNRESET) // Request was cancelled
635 usb_ep_fifo_flush(ep);
636
637 /* Hold the lock while we update the request and buffer states */
638 smp_wmb();
639 spin_lock(&fsg->lock);
640 bh->outreq_busy = 0;
641 bh->state = BUF_STATE_FULL;
642 wakeup_thread(fsg);
643 spin_unlock(&fsg->lock);
644}
645
646
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100647/*-------------------------------------------------------------------------*/
648
649/* Ep0 class-specific handlers. These always run in_irq. */
650
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100651static int class_setup_req(struct fsg_dev *fsg,
652 const struct usb_ctrlrequest *ctrl)
653{
654 struct usb_request *req = fsg->ep0req;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100655 u16 w_index = le16_to_cpu(ctrl->wIndex);
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100656 u16 w_value = le16_to_cpu(ctrl->wValue);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100657 u16 w_length = le16_to_cpu(ctrl->wLength);
658
659 if (!fsg->config)
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100660 return -EOPNOTSUPP;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100661
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100662 switch (ctrl->bRequest) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100663
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100664 case USB_BULK_RESET_REQUEST:
665 if (ctrl->bRequestType !=
666 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100667 break;
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100668 if (w_index != 0 || w_value != 0)
669 return -EDOM;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100670
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100671 /* Raise an exception to stop the current operation
672 * and reinitialize our state. */
673 DBG(fsg, "bulk reset request\n");
674 raise_exception(fsg, FSG_STATE_RESET);
675 return DELAYED_STATUS;
676
677 case USB_BULK_GET_MAX_LUN_REQUEST:
678 if (ctrl->bRequestType !=
679 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100680 break;
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100681 if (w_index != 0 || w_value != 0)
682 return -EDOM;
683 VDBG(fsg, "get max LUN\n");
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100684 *(u8 *) req->buf = fsg->common->nluns - 1;
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100685 return 1;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100686 }
687
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100688 VDBG(fsg,
689 "unknown class-specific control req "
690 "%02x.%02x v%04x i%04x l%u\n",
691 ctrl->bRequestType, ctrl->bRequest,
692 le16_to_cpu(ctrl->wValue), w_index, w_length);
693 return -EOPNOTSUPP;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100694}
695
696
697/*-------------------------------------------------------------------------*/
698
699/* Ep0 standard request handlers. These always run in_irq. */
700
701static int standard_setup_req(struct fsg_dev *fsg,
702 const struct usb_ctrlrequest *ctrl)
703{
704 struct usb_request *req = fsg->ep0req;
705 int value = -EOPNOTSUPP;
706 u16 w_index = le16_to_cpu(ctrl->wIndex);
707 u16 w_value = le16_to_cpu(ctrl->wValue);
708
709 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
710 * but config change events will also reconfigure hardware. */
711 switch (ctrl->bRequest) {
712
713 case USB_REQ_GET_DESCRIPTOR:
714 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
715 USB_RECIP_DEVICE))
716 break;
717 switch (w_value >> 8) {
718
719 case USB_DT_DEVICE:
720 VDBG(fsg, "get device descriptor\n");
721 value = sizeof device_desc;
722 memcpy(req->buf, &device_desc, value);
723 break;
724 case USB_DT_DEVICE_QUALIFIER:
725 VDBG(fsg, "get device qualifier\n");
726 if (!gadget_is_dualspeed(fsg->gadget))
727 break;
728 value = sizeof dev_qualifier;
729 memcpy(req->buf, &dev_qualifier, value);
730 break;
731
732 case USB_DT_OTHER_SPEED_CONFIG:
733 VDBG(fsg, "get other-speed config descriptor\n");
734 if (!gadget_is_dualspeed(fsg->gadget))
735 break;
736 goto get_config;
737 case USB_DT_CONFIG:
738 VDBG(fsg, "get configuration descriptor\n");
739get_config:
740 value = populate_config_buf(fsg->gadget,
741 req->buf,
742 w_value >> 8,
743 w_value & 0xff);
744 break;
745
746 case USB_DT_STRING:
747 VDBG(fsg, "get string descriptor\n");
748
749 /* wIndex == language code */
750 value = usb_gadget_get_string(&fsg_stringtab,
751 w_value & 0xff, req->buf);
752 break;
753 }
754 break;
755
756 /* One config, two speeds */
757 case USB_REQ_SET_CONFIGURATION:
758 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
759 USB_RECIP_DEVICE))
760 break;
761 VDBG(fsg, "set configuration\n");
762 if (w_value == CONFIG_VALUE || w_value == 0) {
763 fsg->new_config = w_value;
764
765 /* Raise an exception to wipe out previous transaction
766 * state (queued bufs, etc) and set the new config. */
767 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
768 value = DELAYED_STATUS;
769 }
770 break;
771 case USB_REQ_GET_CONFIGURATION:
772 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
773 USB_RECIP_DEVICE))
774 break;
775 VDBG(fsg, "get configuration\n");
776 *(u8 *) req->buf = fsg->config;
777 value = 1;
778 break;
779
780 case USB_REQ_SET_INTERFACE:
781 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
782 USB_RECIP_INTERFACE))
783 break;
784 if (fsg->config && w_index == 0) {
785
786 /* Raise an exception to wipe out previous transaction
787 * state (queued bufs, etc) and install the new
788 * interface altsetting. */
789 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
790 value = DELAYED_STATUS;
791 }
792 break;
793 case USB_REQ_GET_INTERFACE:
794 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
795 USB_RECIP_INTERFACE))
796 break;
797 if (!fsg->config)
798 break;
799 if (w_index != 0) {
800 value = -EDOM;
801 break;
802 }
803 VDBG(fsg, "get interface\n");
804 *(u8 *) req->buf = 0;
805 value = 1;
806 break;
807
808 default:
809 VDBG(fsg,
810 "unknown control req %02x.%02x v%04x i%04x l%u\n",
811 ctrl->bRequestType, ctrl->bRequest,
812 w_value, w_index, le16_to_cpu(ctrl->wLength));
813 }
814
815 return value;
816}
817
818
819static int fsg_setup(struct usb_gadget *gadget,
820 const struct usb_ctrlrequest *ctrl)
821{
822 struct fsg_dev *fsg = get_gadget_data(gadget);
823 int rc;
824 int w_length = le16_to_cpu(ctrl->wLength);
825
826 ++fsg->ep0_req_tag; // Record arrival of a new request
827 fsg->ep0req->context = NULL;
828 fsg->ep0req->length = 0;
829 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
830
831 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
832 rc = class_setup_req(fsg, ctrl);
833 else
834 rc = standard_setup_req(fsg, ctrl);
835
836 /* Respond with data/status or defer until later? */
837 if (rc >= 0 && rc != DELAYED_STATUS) {
838 rc = min(rc, w_length);
839 fsg->ep0req->length = rc;
840 fsg->ep0req->zero = rc < w_length;
841 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
842 "ep0-in" : "ep0-out");
843 rc = ep0_queue(fsg);
844 }
845
846 /* Device either stalls (rc < 0) or reports success */
847 return rc;
848}
849
850
851/*-------------------------------------------------------------------------*/
852
853/* All the following routines run in process context */
854
855
856/* Use this for bulk or interrupt transfers, not ep0 */
857static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
858 struct usb_request *req, int *pbusy,
859 enum fsg_buffer_state *state)
860{
861 int rc;
862
863 if (ep == fsg->bulk_in)
864 dump_msg(fsg, "bulk-in", req->buf, req->length);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100865
866 spin_lock_irq(&fsg->lock);
867 *pbusy = 1;
868 *state = BUF_STATE_BUSY;
869 spin_unlock_irq(&fsg->lock);
870 rc = usb_ep_queue(ep, req, GFP_KERNEL);
871 if (rc != 0) {
872 *pbusy = 0;
873 *state = BUF_STATE_EMPTY;
874
875 /* We can't do much more than wait for a reset */
876
877 /* Note: currently the net2280 driver fails zero-length
878 * submissions if DMA is enabled. */
879 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
880 req->length == 0))
881 WARNING(fsg, "error in submission: %s --> %d\n",
882 ep->name, rc);
883 }
884}
885
886
887static int sleep_thread(struct fsg_dev *fsg)
888{
889 int rc = 0;
890
891 /* Wait until a signal arrives or we are woken up */
892 for (;;) {
893 try_to_freeze();
894 set_current_state(TASK_INTERRUPTIBLE);
895 if (signal_pending(current)) {
896 rc = -EINTR;
897 break;
898 }
899 if (fsg->thread_wakeup_needed)
900 break;
901 schedule();
902 }
903 __set_current_state(TASK_RUNNING);
904 fsg->thread_wakeup_needed = 0;
905 return rc;
906}
907
908
909/*-------------------------------------------------------------------------*/
910
911static int do_read(struct fsg_dev *fsg)
912{
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100913 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100914 u32 lba;
915 struct fsg_buffhd *bh;
916 int rc;
917 u32 amount_left;
918 loff_t file_offset, file_offset_tmp;
919 unsigned int amount;
920 unsigned int partial_page;
921 ssize_t nread;
922
923 /* Get the starting Logical Block Address and check that it's
924 * not too big */
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100925 if (fsg->common->cmnd[0] == SC_READ_6)
926 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100927 else {
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100928 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100929
930 /* We allow DPO (Disable Page Out = don't save data in the
931 * cache) and FUA (Force Unit Access = don't read from the
932 * cache), but we don't implement them. */
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100933 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100934 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
935 return -EINVAL;
936 }
937 }
938 if (lba >= curlun->num_sectors) {
939 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
940 return -EINVAL;
941 }
942 file_offset = ((loff_t) lba) << 9;
943
944 /* Carry out the file reads */
945 amount_left = fsg->data_size_from_cmnd;
946 if (unlikely(amount_left == 0))
947 return -EIO; // No default reply
948
949 for (;;) {
950
951 /* Figure out how much we need to read:
952 * Try to read the remaining amount.
953 * But don't read more than the buffer size.
954 * And don't try to read past the end of the file.
955 * Finally, if we're not at a page boundary, don't read past
956 * the next page.
957 * If this means reading 0 then we were asked to read past
958 * the end of file. */
Michal Nazarewicz93bcf122009-10-28 16:57:19 +0100959 amount = min(amount_left, FSG_BUFLEN);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100960 amount = min((loff_t) amount,
961 curlun->file_length - file_offset);
962 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
963 if (partial_page > 0)
964 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
965 partial_page);
966
967 /* Wait for the next buffer to become available */
Michal Nazarewicza41ae412009-10-28 16:57:20 +0100968 bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +0100969 while (bh->state != BUF_STATE_EMPTY) {
970 rc = sleep_thread(fsg);
971 if (rc)
972 return rc;
973 }
974
975 /* If we were asked to read past the end of file,
976 * end with an empty buffer. */
977 if (amount == 0) {
978 curlun->sense_data =
979 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
980 curlun->sense_data_info = file_offset >> 9;
981 curlun->info_valid = 1;
982 bh->inreq->length = 0;
983 bh->state = BUF_STATE_FULL;
984 break;
985 }
986
987 /* Perform the read */
988 file_offset_tmp = file_offset;
989 nread = vfs_read(curlun->filp,
990 (char __user *) bh->buf,
991 amount, &file_offset_tmp);
992 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
993 (unsigned long long) file_offset,
994 (int) nread);
995 if (signal_pending(current))
996 return -EINTR;
997
998 if (nread < 0) {
999 LDBG(curlun, "error in file read: %d\n",
1000 (int) nread);
1001 nread = 0;
1002 } else if (nread < amount) {
1003 LDBG(curlun, "partial file read: %d/%u\n",
1004 (int) nread, amount);
1005 nread -= (nread & 511); // Round down to a block
1006 }
1007 file_offset += nread;
1008 amount_left -= nread;
1009 fsg->residue -= nread;
1010 bh->inreq->length = nread;
1011 bh->state = BUF_STATE_FULL;
1012
1013 /* If an error occurred, report it and its position */
1014 if (nread < amount) {
1015 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1016 curlun->sense_data_info = file_offset >> 9;
1017 curlun->info_valid = 1;
1018 break;
1019 }
1020
1021 if (amount_left == 0)
1022 break; // No more left to read
1023
1024 /* Send this buffer and go read some more */
1025 bh->inreq->zero = 0;
1026 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1027 &bh->inreq_busy, &bh->state);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001028 fsg->common->next_buffhd_to_fill = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001029 }
1030
1031 return -EIO; // No default reply
1032}
1033
1034
1035/*-------------------------------------------------------------------------*/
1036
1037static int do_write(struct fsg_dev *fsg)
1038{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001039 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001040 u32 lba;
1041 struct fsg_buffhd *bh;
1042 int get_some_more;
1043 u32 amount_left_to_req, amount_left_to_write;
1044 loff_t usb_offset, file_offset, file_offset_tmp;
1045 unsigned int amount;
1046 unsigned int partial_page;
1047 ssize_t nwritten;
1048 int rc;
1049
1050 if (curlun->ro) {
1051 curlun->sense_data = SS_WRITE_PROTECTED;
1052 return -EINVAL;
1053 }
1054 spin_lock(&curlun->filp->f_lock);
1055 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1056 spin_unlock(&curlun->filp->f_lock);
1057
1058 /* Get the starting Logical Block Address and check that it's
1059 * not too big */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001060 if (fsg->common->cmnd[0] == SC_WRITE_6)
1061 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001062 else {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001063 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001064
1065 /* We allow DPO (Disable Page Out = don't save data in the
1066 * cache) and FUA (Force Unit Access = write directly to the
1067 * medium). We don't implement DPO; we implement FUA by
1068 * performing synchronous output. */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001069 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001070 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1071 return -EINVAL;
1072 }
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001073 if (fsg->common->cmnd[1] & 0x08) { // FUA
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001074 spin_lock(&curlun->filp->f_lock);
1075 curlun->filp->f_flags |= O_SYNC;
1076 spin_unlock(&curlun->filp->f_lock);
1077 }
1078 }
1079 if (lba >= curlun->num_sectors) {
1080 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1081 return -EINVAL;
1082 }
1083
1084 /* Carry out the file writes */
1085 get_some_more = 1;
1086 file_offset = usb_offset = ((loff_t) lba) << 9;
1087 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1088
1089 while (amount_left_to_write > 0) {
1090
1091 /* Queue a request for more data from the host */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001092 bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001093 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1094
1095 /* Figure out how much we want to get:
1096 * Try to get the remaining amount.
1097 * But don't get more than the buffer size.
1098 * And don't try to go past the end of the file.
1099 * If we're not at a page boundary,
1100 * don't go past the next page.
1101 * If this means getting 0, then we were asked
1102 * to write past the end of file.
1103 * Finally, round down to a block boundary. */
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001104 amount = min(amount_left_to_req, FSG_BUFLEN);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001105 amount = min((loff_t) amount, curlun->file_length -
1106 usb_offset);
1107 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1108 if (partial_page > 0)
1109 amount = min(amount,
1110 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1111
1112 if (amount == 0) {
1113 get_some_more = 0;
1114 curlun->sense_data =
1115 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1116 curlun->sense_data_info = usb_offset >> 9;
1117 curlun->info_valid = 1;
1118 continue;
1119 }
1120 amount -= (amount & 511);
1121 if (amount == 0) {
1122
1123 /* Why were we were asked to transfer a
1124 * partial block? */
1125 get_some_more = 0;
1126 continue;
1127 }
1128
1129 /* Get the next buffer */
1130 usb_offset += amount;
1131 fsg->usb_amount_left -= amount;
1132 amount_left_to_req -= amount;
1133 if (amount_left_to_req == 0)
1134 get_some_more = 0;
1135
1136 /* amount is always divisible by 512, hence by
1137 * the bulk-out maxpacket size */
1138 bh->outreq->length = bh->bulk_out_intended_length =
1139 amount;
1140 bh->outreq->short_not_ok = 1;
1141 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1142 &bh->outreq_busy, &bh->state);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001143 fsg->common->next_buffhd_to_fill = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001144 continue;
1145 }
1146
1147 /* Write the received data to the backing file */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001148 bh = fsg->common->next_buffhd_to_drain;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001149 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1150 break; // We stopped early
1151 if (bh->state == BUF_STATE_FULL) {
1152 smp_rmb();
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001153 fsg->common->next_buffhd_to_drain = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001154 bh->state = BUF_STATE_EMPTY;
1155
1156 /* Did something go wrong with the transfer? */
1157 if (bh->outreq->status != 0) {
1158 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1159 curlun->sense_data_info = file_offset >> 9;
1160 curlun->info_valid = 1;
1161 break;
1162 }
1163
1164 amount = bh->outreq->actual;
1165 if (curlun->file_length - file_offset < amount) {
1166 LERROR(curlun,
1167 "write %u @ %llu beyond end %llu\n",
1168 amount, (unsigned long long) file_offset,
1169 (unsigned long long) curlun->file_length);
1170 amount = curlun->file_length - file_offset;
1171 }
1172
1173 /* Perform the write */
1174 file_offset_tmp = file_offset;
1175 nwritten = vfs_write(curlun->filp,
1176 (char __user *) bh->buf,
1177 amount, &file_offset_tmp);
1178 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1179 (unsigned long long) file_offset,
1180 (int) nwritten);
1181 if (signal_pending(current))
1182 return -EINTR; // Interrupted!
1183
1184 if (nwritten < 0) {
1185 LDBG(curlun, "error in file write: %d\n",
1186 (int) nwritten);
1187 nwritten = 0;
1188 } else if (nwritten < amount) {
1189 LDBG(curlun, "partial file write: %d/%u\n",
1190 (int) nwritten, amount);
1191 nwritten -= (nwritten & 511);
1192 // Round down to a block
1193 }
1194 file_offset += nwritten;
1195 amount_left_to_write -= nwritten;
1196 fsg->residue -= nwritten;
1197
1198 /* If an error occurred, report it and its position */
1199 if (nwritten < amount) {
1200 curlun->sense_data = SS_WRITE_ERROR;
1201 curlun->sense_data_info = file_offset >> 9;
1202 curlun->info_valid = 1;
1203 break;
1204 }
1205
1206 /* Did the host decide to stop early? */
1207 if (bh->outreq->actual != bh->outreq->length) {
1208 fsg->short_packet_received = 1;
1209 break;
1210 }
1211 continue;
1212 }
1213
1214 /* Wait for something to happen */
1215 rc = sleep_thread(fsg);
1216 if (rc)
1217 return rc;
1218 }
1219
1220 return -EIO; // No default reply
1221}
1222
1223
1224/*-------------------------------------------------------------------------*/
1225
1226static int do_synchronize_cache(struct fsg_dev *fsg)
1227{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001228 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001229 int rc;
1230
1231 /* We ignore the requested LBA and write out all file's
1232 * dirty data buffers. */
1233 rc = fsg_lun_fsync_sub(curlun);
1234 if (rc)
1235 curlun->sense_data = SS_WRITE_ERROR;
1236 return 0;
1237}
1238
1239
1240/*-------------------------------------------------------------------------*/
1241
1242static void invalidate_sub(struct fsg_lun *curlun)
1243{
1244 struct file *filp = curlun->filp;
1245 struct inode *inode = filp->f_path.dentry->d_inode;
1246 unsigned long rc;
1247
1248 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1249 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1250}
1251
1252static int do_verify(struct fsg_dev *fsg)
1253{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001254 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001255 u32 lba;
1256 u32 verification_length;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001257 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001258 loff_t file_offset, file_offset_tmp;
1259 u32 amount_left;
1260 unsigned int amount;
1261 ssize_t nread;
1262
1263 /* Get the starting Logical Block Address and check that it's
1264 * not too big */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001265 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001266 if (lba >= curlun->num_sectors) {
1267 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1268 return -EINVAL;
1269 }
1270
1271 /* We allow DPO (Disable Page Out = don't save data in the
1272 * cache) but we don't implement it. */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001273 if ((fsg->common->cmnd[1] & ~0x10) != 0) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001274 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1275 return -EINVAL;
1276 }
1277
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001278 verification_length = get_unaligned_be16(&fsg->common->cmnd[7]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001279 if (unlikely(verification_length == 0))
1280 return -EIO; // No default reply
1281
1282 /* Prepare to carry out the file verify */
1283 amount_left = verification_length << 9;
1284 file_offset = ((loff_t) lba) << 9;
1285
1286 /* Write out all the dirty buffers before invalidating them */
1287 fsg_lun_fsync_sub(curlun);
1288 if (signal_pending(current))
1289 return -EINTR;
1290
1291 invalidate_sub(curlun);
1292 if (signal_pending(current))
1293 return -EINTR;
1294
1295 /* Just try to read the requested blocks */
1296 while (amount_left > 0) {
1297
1298 /* Figure out how much we need to read:
1299 * Try to read the remaining amount, but not more than
1300 * the buffer size.
1301 * And don't try to read past the end of the file.
1302 * If this means reading 0 then we were asked to read
1303 * past the end of file. */
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001304 amount = min(amount_left, FSG_BUFLEN);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001305 amount = min((loff_t) amount,
1306 curlun->file_length - file_offset);
1307 if (amount == 0) {
1308 curlun->sense_data =
1309 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1310 curlun->sense_data_info = file_offset >> 9;
1311 curlun->info_valid = 1;
1312 break;
1313 }
1314
1315 /* Perform the read */
1316 file_offset_tmp = file_offset;
1317 nread = vfs_read(curlun->filp,
1318 (char __user *) bh->buf,
1319 amount, &file_offset_tmp);
1320 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1321 (unsigned long long) file_offset,
1322 (int) nread);
1323 if (signal_pending(current))
1324 return -EINTR;
1325
1326 if (nread < 0) {
1327 LDBG(curlun, "error in file verify: %d\n",
1328 (int) nread);
1329 nread = 0;
1330 } else if (nread < amount) {
1331 LDBG(curlun, "partial file verify: %d/%u\n",
1332 (int) nread, amount);
1333 nread -= (nread & 511); // Round down to a sector
1334 }
1335 if (nread == 0) {
1336 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1337 curlun->sense_data_info = file_offset >> 9;
1338 curlun->info_valid = 1;
1339 break;
1340 }
1341 file_offset += nread;
1342 amount_left -= nread;
1343 }
1344 return 0;
1345}
1346
1347
1348/*-------------------------------------------------------------------------*/
1349
1350static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1351{
1352 u8 *buf = (u8 *) bh->buf;
1353
1354 static char vendor_id[] = "Linux ";
1355 static char product_disk_id[] = "File-Stor Gadget";
1356 static char product_cdrom_id[] = "File-CD Gadget ";
1357
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001358 if (!fsg->common->curlun) { // Unsupported LUNs are okay
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001359 fsg->bad_lun_okay = 1;
1360 memset(buf, 0, 36);
1361 buf[0] = 0x7f; // Unsupported, no device-type
1362 buf[4] = 31; // Additional length
1363 return 36;
1364 }
1365
1366 memset(buf, 0, 8);
1367 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
1368 if (mod_data.removable)
1369 buf[1] = 0x80;
1370 buf[2] = 2; // ANSI SCSI level 2
1371 buf[3] = 2; // SCSI-2 INQUIRY data format
1372 buf[4] = 31; // Additional length
1373 // No special options
1374 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1375 (mod_data.cdrom ? product_cdrom_id :
1376 product_disk_id),
1377 mod_data.release);
1378 return 36;
1379}
1380
1381
1382static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1383{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001384 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001385 u8 *buf = (u8 *) bh->buf;
1386 u32 sd, sdinfo;
1387 int valid;
1388
1389 /*
1390 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1391 *
1392 * If a REQUEST SENSE command is received from an initiator
1393 * with a pending unit attention condition (before the target
1394 * generates the contingent allegiance condition), then the
1395 * target shall either:
1396 * a) report any pending sense data and preserve the unit
1397 * attention condition on the logical unit, or,
1398 * b) report the unit attention condition, may discard any
1399 * pending sense data, and clear the unit attention
1400 * condition on the logical unit for that initiator.
1401 *
1402 * FSG normally uses option a); enable this code to use option b).
1403 */
1404#if 0
1405 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1406 curlun->sense_data = curlun->unit_attention_data;
1407 curlun->unit_attention_data = SS_NO_SENSE;
1408 }
1409#endif
1410
1411 if (!curlun) { // Unsupported LUNs are okay
1412 fsg->bad_lun_okay = 1;
1413 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1414 sdinfo = 0;
1415 valid = 0;
1416 } else {
1417 sd = curlun->sense_data;
1418 sdinfo = curlun->sense_data_info;
1419 valid = curlun->info_valid << 7;
1420 curlun->sense_data = SS_NO_SENSE;
1421 curlun->sense_data_info = 0;
1422 curlun->info_valid = 0;
1423 }
1424
1425 memset(buf, 0, 18);
1426 buf[0] = valid | 0x70; // Valid, current error
1427 buf[2] = SK(sd);
1428 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1429 buf[7] = 18 - 8; // Additional sense length
1430 buf[12] = ASC(sd);
1431 buf[13] = ASCQ(sd);
1432 return 18;
1433}
1434
1435
1436static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1437{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001438 struct fsg_lun *curlun = fsg->common->curlun;
1439 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1440 int pmi = fsg->common->cmnd[8];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001441 u8 *buf = (u8 *) bh->buf;
1442
1443 /* Check the PMI and LBA fields */
1444 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1445 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1446 return -EINVAL;
1447 }
1448
1449 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1450 /* Max logical block */
1451 put_unaligned_be32(512, &buf[4]); /* Block length */
1452 return 8;
1453}
1454
1455
1456static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1457{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001458 struct fsg_lun *curlun = fsg->common->curlun;
1459 int msf = fsg->common->cmnd[1] & 0x02;
1460 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001461 u8 *buf = (u8 *) bh->buf;
1462
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001463 if ((fsg->common->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001464 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1465 return -EINVAL;
1466 }
1467 if (lba >= curlun->num_sectors) {
1468 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1469 return -EINVAL;
1470 }
1471
1472 memset(buf, 0, 8);
1473 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1474 store_cdrom_address(&buf[4], msf, lba);
1475 return 8;
1476}
1477
1478
1479static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1480{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001481 struct fsg_lun *curlun = fsg->common->curlun;
1482 int msf = fsg->common->cmnd[1] & 0x02;
1483 int start_track = fsg->common->cmnd[6];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001484 u8 *buf = (u8 *) bh->buf;
1485
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001486 if ((fsg->common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001487 start_track > 1) {
1488 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1489 return -EINVAL;
1490 }
1491
1492 memset(buf, 0, 20);
1493 buf[1] = (20-2); /* TOC data length */
1494 buf[2] = 1; /* First track number */
1495 buf[3] = 1; /* Last track number */
1496 buf[5] = 0x16; /* Data track, copying allowed */
1497 buf[6] = 0x01; /* Only track is number 1 */
1498 store_cdrom_address(&buf[8], msf, 0);
1499
1500 buf[13] = 0x16; /* Lead-out track is data */
1501 buf[14] = 0xAA; /* Lead-out track number */
1502 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1503 return 20;
1504}
1505
1506
1507static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1508{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001509 struct fsg_lun *curlun = fsg->common->curlun;
1510 int mscmnd = fsg->common->cmnd[0];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001511 u8 *buf = (u8 *) bh->buf;
1512 u8 *buf0 = buf;
1513 int pc, page_code;
1514 int changeable_values, all_pages;
1515 int valid_page = 0;
1516 int len, limit;
1517
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001518 if ((fsg->common->cmnd[1] & ~0x08) != 0) { // Mask away DBD
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001519 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1520 return -EINVAL;
1521 }
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001522 pc = fsg->common->cmnd[2] >> 6;
1523 page_code = fsg->common->cmnd[2] & 0x3f;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001524 if (pc == 3) {
1525 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1526 return -EINVAL;
1527 }
1528 changeable_values = (pc == 1);
1529 all_pages = (page_code == 0x3f);
1530
1531 /* Write the mode parameter header. Fixed values are: default
1532 * medium type, no cache control (DPOFUA), and no block descriptors.
1533 * The only variable value is the WriteProtect bit. We will fill in
1534 * the mode data length later. */
1535 memset(buf, 0, 8);
1536 if (mscmnd == SC_MODE_SENSE_6) {
1537 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1538 buf += 4;
1539 limit = 255;
1540 } else { // SC_MODE_SENSE_10
1541 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1542 buf += 8;
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001543 limit = 65535; // Should really be FSG_BUFLEN
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001544 }
1545
1546 /* No block descriptors */
1547
1548 /* The mode pages, in numerical order. The only page we support
1549 * is the Caching page. */
1550 if (page_code == 0x08 || all_pages) {
1551 valid_page = 1;
1552 buf[0] = 0x08; // Page code
1553 buf[1] = 10; // Page length
1554 memset(buf+2, 0, 10); // None of the fields are changeable
1555
1556 if (!changeable_values) {
1557 buf[2] = 0x04; // Write cache enable,
1558 // Read cache not disabled
1559 // No cache retention priorities
1560 put_unaligned_be16(0xffff, &buf[4]);
1561 /* Don't disable prefetch */
1562 /* Minimum prefetch = 0 */
1563 put_unaligned_be16(0xffff, &buf[8]);
1564 /* Maximum prefetch */
1565 put_unaligned_be16(0xffff, &buf[10]);
1566 /* Maximum prefetch ceiling */
1567 }
1568 buf += 12;
1569 }
1570
1571 /* Check that a valid page was requested and the mode data length
1572 * isn't too long. */
1573 len = buf - buf0;
1574 if (!valid_page || len > limit) {
1575 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1576 return -EINVAL;
1577 }
1578
1579 /* Store the mode data length */
1580 if (mscmnd == SC_MODE_SENSE_6)
1581 buf0[0] = len - 1;
1582 else
1583 put_unaligned_be16(len - 2, buf0);
1584 return len;
1585}
1586
1587
1588static int do_start_stop(struct fsg_dev *fsg)
1589{
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001590 if (!mod_data.removable) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001591 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001592 return -EINVAL;
1593 }
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001594 return 0;
1595}
1596
1597
1598static int do_prevent_allow(struct fsg_dev *fsg)
1599{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001600 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001601 int prevent;
1602
1603 if (!mod_data.removable) {
1604 curlun->sense_data = SS_INVALID_COMMAND;
1605 return -EINVAL;
1606 }
1607
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001608 prevent = fsg->common->cmnd[4] & 0x01;
1609 if ((fsg->common->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001610 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1611 return -EINVAL;
1612 }
1613
1614 if (curlun->prevent_medium_removal && !prevent)
1615 fsg_lun_fsync_sub(curlun);
1616 curlun->prevent_medium_removal = prevent;
1617 return 0;
1618}
1619
1620
1621static int do_read_format_capacities(struct fsg_dev *fsg,
1622 struct fsg_buffhd *bh)
1623{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001624 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001625 u8 *buf = (u8 *) bh->buf;
1626
1627 buf[0] = buf[1] = buf[2] = 0;
1628 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1629 buf += 4;
1630
1631 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1632 /* Number of blocks */
1633 put_unaligned_be32(512, &buf[4]); /* Block length */
1634 buf[4] = 0x02; /* Current capacity */
1635 return 12;
1636}
1637
1638
1639static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1640{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001641 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001642
1643 /* We don't support MODE SELECT */
1644 curlun->sense_data = SS_INVALID_COMMAND;
1645 return -EINVAL;
1646}
1647
1648
1649/*-------------------------------------------------------------------------*/
1650
1651static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1652{
1653 int rc;
1654
1655 rc = fsg_set_halt(fsg, fsg->bulk_in);
1656 if (rc == -EAGAIN)
1657 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1658 while (rc != 0) {
1659 if (rc != -EAGAIN) {
1660 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1661 rc = 0;
1662 break;
1663 }
1664
1665 /* Wait for a short time and then try again */
1666 if (msleep_interruptible(100) != 0)
1667 return -EINTR;
1668 rc = usb_ep_set_halt(fsg->bulk_in);
1669 }
1670 return rc;
1671}
1672
1673static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1674{
1675 int rc;
1676
1677 DBG(fsg, "bulk-in set wedge\n");
1678 rc = usb_ep_set_wedge(fsg->bulk_in);
1679 if (rc == -EAGAIN)
1680 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1681 while (rc != 0) {
1682 if (rc != -EAGAIN) {
1683 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1684 rc = 0;
1685 break;
1686 }
1687
1688 /* Wait for a short time and then try again */
1689 if (msleep_interruptible(100) != 0)
1690 return -EINTR;
1691 rc = usb_ep_set_wedge(fsg->bulk_in);
1692 }
1693 return rc;
1694}
1695
1696static int pad_with_zeros(struct fsg_dev *fsg)
1697{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001698 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001699 u32 nkeep = bh->inreq->length;
1700 u32 nsend;
1701 int rc;
1702
1703 bh->state = BUF_STATE_EMPTY; // For the first iteration
1704 fsg->usb_amount_left = nkeep + fsg->residue;
1705 while (fsg->usb_amount_left > 0) {
1706
1707 /* Wait for the next buffer to be free */
1708 while (bh->state != BUF_STATE_EMPTY) {
1709 rc = sleep_thread(fsg);
1710 if (rc)
1711 return rc;
1712 }
1713
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001714 nsend = min(fsg->usb_amount_left, FSG_BUFLEN);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001715 memset(bh->buf + nkeep, 0, nsend - nkeep);
1716 bh->inreq->length = nsend;
1717 bh->inreq->zero = 0;
1718 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1719 &bh->inreq_busy, &bh->state);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001720 bh = fsg->common->next_buffhd_to_fill = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001721 fsg->usb_amount_left -= nsend;
1722 nkeep = 0;
1723 }
1724 return 0;
1725}
1726
1727static int throw_away_data(struct fsg_dev *fsg)
1728{
1729 struct fsg_buffhd *bh;
1730 u32 amount;
1731 int rc;
1732
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001733 for (bh = fsg->common->next_buffhd_to_drain;
1734 bh->state != BUF_STATE_EMPTY || fsg->usb_amount_left > 0;
1735 bh = fsg->common->next_buffhd_to_drain) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001736
1737 /* Throw away the data in a filled buffer */
1738 if (bh->state == BUF_STATE_FULL) {
1739 smp_rmb();
1740 bh->state = BUF_STATE_EMPTY;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001741 fsg->common->next_buffhd_to_drain = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001742
1743 /* A short packet or an error ends everything */
1744 if (bh->outreq->actual != bh->outreq->length ||
1745 bh->outreq->status != 0) {
1746 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1747 return -EINTR;
1748 }
1749 continue;
1750 }
1751
1752 /* Try to submit another request if we need one */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001753 bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001754 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001755 amount = min(fsg->usb_amount_left, FSG_BUFLEN);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001756
1757 /* amount is always divisible by 512, hence by
1758 * the bulk-out maxpacket size */
1759 bh->outreq->length = bh->bulk_out_intended_length =
1760 amount;
1761 bh->outreq->short_not_ok = 1;
1762 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1763 &bh->outreq_busy, &bh->state);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001764 fsg->common->next_buffhd_to_fill = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001765 fsg->usb_amount_left -= amount;
1766 continue;
1767 }
1768
1769 /* Otherwise wait for something to happen */
1770 rc = sleep_thread(fsg);
1771 if (rc)
1772 return rc;
1773 }
1774 return 0;
1775}
1776
1777
1778static int finish_reply(struct fsg_dev *fsg)
1779{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001780 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001781 int rc = 0;
1782
1783 switch (fsg->data_dir) {
1784 case DATA_DIR_NONE:
1785 break; // Nothing to send
1786
1787 /* If we don't know whether the host wants to read or write,
1788 * this must be CB or CBI with an unknown command. We mustn't
1789 * try to send or receive any data. So stall both bulk pipes
1790 * if we can and wait for a reset. */
1791 case DATA_DIR_UNKNOWN:
1792 if (mod_data.can_stall) {
1793 fsg_set_halt(fsg, fsg->bulk_out);
1794 rc = halt_bulk_in_endpoint(fsg);
1795 }
1796 break;
1797
1798 /* All but the last buffer of data must have already been sent */
1799 case DATA_DIR_TO_HOST:
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001800 if (fsg->data_size == 0) {
1801 /* Nothing to send */
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001802
1803 /* If there's no residue, simply send the last buffer */
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001804 } else if (fsg->residue == 0) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001805 bh->inreq->zero = 0;
1806 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1807 &bh->inreq_busy, &bh->state);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001808 fsg->common->next_buffhd_to_fill = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001809
1810 /* For Bulk-only, if we're allowed to stall then send the
1811 * short packet and halt the bulk-in endpoint. If we can't
1812 * stall, pad out the remaining data with 0's. */
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001813 } else if (mod_data.can_stall) {
1814 bh->inreq->zero = 1;
1815 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1816 &bh->inreq_busy, &bh->state);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001817 fsg->common->next_buffhd_to_fill = bh->next;
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001818 rc = halt_bulk_in_endpoint(fsg);
1819 } else {
1820 rc = pad_with_zeros(fsg);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001821 }
1822 break;
1823
1824 /* We have processed all we want from the data the host has sent.
1825 * There may still be outstanding bulk-out requests. */
1826 case DATA_DIR_FROM_HOST:
1827 if (fsg->residue == 0)
1828 ; // Nothing to receive
1829
1830 /* Did the host stop sending unexpectedly early? */
1831 else if (fsg->short_packet_received) {
1832 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1833 rc = -EINTR;
1834 }
1835
1836 /* We haven't processed all the incoming data. Even though
1837 * we may be allowed to stall, doing so would cause a race.
1838 * The controller may already have ACK'ed all the remaining
1839 * bulk-out packets, in which case the host wouldn't see a
1840 * STALL. Not realizing the endpoint was halted, it wouldn't
1841 * clear the halt -- leading to problems later on. */
1842#if 0
1843 else if (mod_data.can_stall) {
1844 fsg_set_halt(fsg, fsg->bulk_out);
1845 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1846 rc = -EINTR;
1847 }
1848#endif
1849
1850 /* We can't stall. Read in the excess data and throw it
1851 * all away. */
1852 else
1853 rc = throw_away_data(fsg);
1854 break;
1855 }
1856 return rc;
1857}
1858
1859
1860static int send_status(struct fsg_dev *fsg)
1861{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001862 struct fsg_lun *curlun = fsg->common->curlun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001863 struct fsg_buffhd *bh;
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001864 struct bulk_cs_wrap *csw;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001865 int rc;
1866 u8 status = USB_STATUS_PASS;
1867 u32 sd, sdinfo = 0;
1868
1869 /* Wait for the next buffer to become available */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001870 bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001871 while (bh->state != BUF_STATE_EMPTY) {
1872 rc = sleep_thread(fsg);
1873 if (rc)
1874 return rc;
1875 }
1876
1877 if (curlun) {
1878 sd = curlun->sense_data;
1879 sdinfo = curlun->sense_data_info;
1880 } else if (fsg->bad_lun_okay)
1881 sd = SS_NO_SENSE;
1882 else
1883 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1884
1885 if (fsg->phase_error) {
1886 DBG(fsg, "sending phase-error status\n");
1887 status = USB_STATUS_PHASE_ERROR;
1888 sd = SS_INVALID_COMMAND;
1889 } else if (sd != SS_NO_SENSE) {
1890 DBG(fsg, "sending command-failure status\n");
1891 status = USB_STATUS_FAIL;
1892 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1893 " info x%x\n",
1894 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1895 }
1896
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001897
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001898 /* Store and send the Bulk-only CSW */
1899 csw = bh->buf;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001900
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001901 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1902 csw->Tag = fsg->tag;
1903 csw->Residue = cpu_to_le32(fsg->residue);
1904 csw->Status = status;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001905
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001906 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1907 bh->inreq->zero = 0;
1908 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1909 &bh->inreq_busy, &bh->state);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001910
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001911 fsg->common->next_buffhd_to_fill = bh->next;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001912 return 0;
1913}
1914
1915
1916/*-------------------------------------------------------------------------*/
1917
1918/* Check whether the command is properly formed and whether its data size
1919 * and direction agree with the values we already have. */
1920static int check_command(struct fsg_dev *fsg, int cmnd_size,
1921 enum data_direction data_dir, unsigned int mask,
1922 int needs_medium, const char *name)
1923{
1924 int i;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001925 int lun = fsg->common->cmnd[1] >> 5;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001926 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1927 char hdlen[20];
1928 struct fsg_lun *curlun;
1929
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001930 hdlen[0] = 0;
1931 if (fsg->data_dir != DATA_DIR_UNKNOWN)
1932 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1933 fsg->data_size);
1934 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1935 name, cmnd_size, dirletter[(int) data_dir],
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001936 fsg->data_size_from_cmnd, fsg->common->cmnd_size, hdlen);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001937
1938 /* We can't reply at all until we know the correct data direction
1939 * and size. */
1940 if (fsg->data_size_from_cmnd == 0)
1941 data_dir = DATA_DIR_NONE;
1942 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
1943 fsg->data_dir = data_dir;
1944 fsg->data_size = fsg->data_size_from_cmnd;
1945
1946 } else { // Bulk-only
1947 if (fsg->data_size < fsg->data_size_from_cmnd) {
1948
1949 /* Host data size < Device data size is a phase error.
1950 * Carry out the command, but only transfer as much
1951 * as we are allowed. */
1952 fsg->data_size_from_cmnd = fsg->data_size;
1953 fsg->phase_error = 1;
1954 }
1955 }
1956 fsg->residue = fsg->usb_amount_left = fsg->data_size;
1957
1958 /* Conflicting data directions is a phase error */
1959 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
1960 fsg->phase_error = 1;
1961 return -EINVAL;
1962 }
1963
1964 /* Verify the length of the command itself */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001965 if (cmnd_size != fsg->common->cmnd_size) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001966
1967 /* Special case workaround: There are plenty of buggy SCSI
1968 * implementations. Many have issues with cbw->Length
1969 * field passing a wrong command size. For those cases we
1970 * always try to work around the problem by using the length
1971 * sent by the host side provided it is at least as large
1972 * as the correct command length.
1973 * Examples of such cases would be MS-Windows, which issues
1974 * REQUEST SENSE with cbw->Length == 12 where it should
1975 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1976 * REQUEST SENSE with cbw->Length == 10 where it should
1977 * be 6 as well.
1978 */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001979 if (cmnd_size <= fsg->common->cmnd_size) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001980 DBG(fsg, "%s is buggy! Expected length %d "
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001981 "but we got %d\n", name,
1982 cmnd_size, fsg->common->cmnd_size);
1983 cmnd_size = fsg->common->cmnd_size;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001984 } else {
1985 fsg->phase_error = 1;
1986 return -EINVAL;
1987 }
1988 }
1989
1990 /* Check that the LUN values are consistent */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001991 if (fsg->common->lun != lun)
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01001992 DBG(fsg, "using LUN %d from CBW, not LUN %d from CDB\n",
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001993 fsg->common->lun, lun);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001994
1995 /* Check the LUN */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01001996 if (fsg->common->lun >= 0 && fsg->common->lun < fsg->common->nluns) {
1997 fsg->common->curlun = curlun = &fsg->common->luns[fsg->common->lun];
1998 if (fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01001999 curlun->sense_data = SS_NO_SENSE;
2000 curlun->sense_data_info = 0;
2001 curlun->info_valid = 0;
2002 }
2003 } else {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002004 fsg->common->curlun = curlun = NULL;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002005 fsg->bad_lun_okay = 0;
2006
2007 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2008 * to use unsupported LUNs; all others may not. */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002009 if (fsg->common->cmnd[0] != SC_INQUIRY &&
2010 fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2011 DBG(fsg, "unsupported LUN %d\n", fsg->common->lun);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002012 return -EINVAL;
2013 }
2014 }
2015
2016 /* If a unit attention condition exists, only INQUIRY and
2017 * REQUEST SENSE commands are allowed; anything else must fail. */
2018 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002019 fsg->common->cmnd[0] != SC_INQUIRY &&
2020 fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002021 curlun->sense_data = curlun->unit_attention_data;
2022 curlun->unit_attention_data = SS_NO_SENSE;
2023 return -EINVAL;
2024 }
2025
2026 /* Check that only command bytes listed in the mask are non-zero */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002027 fsg->common->cmnd[1] &= 0x1f; // Mask away the LUN
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002028 for (i = 1; i < cmnd_size; ++i) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002029 if (fsg->common->cmnd[i] && !(mask & (1 << i))) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002030 if (curlun)
2031 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2032 return -EINVAL;
2033 }
2034 }
2035
2036 /* If the medium isn't mounted and the command needs to access
2037 * it, return an error. */
2038 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
2039 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2040 return -EINVAL;
2041 }
2042
2043 return 0;
2044}
2045
2046
2047static int do_scsi_command(struct fsg_dev *fsg)
2048{
2049 struct fsg_buffhd *bh;
2050 int rc;
2051 int reply = -EINVAL;
2052 int i;
2053 static char unknown[16];
2054
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002055 dump_cdb(fsg->common);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002056
2057 /* Wait for the next buffer to become available for data or status */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002058 bh = fsg->common->next_buffhd_to_drain = fsg->common->next_buffhd_to_fill;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002059 while (bh->state != BUF_STATE_EMPTY) {
2060 rc = sleep_thread(fsg);
2061 if (rc)
2062 return rc;
2063 }
2064 fsg->phase_error = 0;
2065 fsg->short_packet_received = 0;
2066
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002067 down_read(&fsg->common->filesem); // We're using the backing file
2068 switch (fsg->common->cmnd[0]) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002069
2070 case SC_INQUIRY:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002071 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002072 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2073 (1<<4), 0,
2074 "INQUIRY")) == 0)
2075 reply = do_inquiry(fsg, bh);
2076 break;
2077
2078 case SC_MODE_SELECT_6:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002079 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002080 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2081 (1<<1) | (1<<4), 0,
2082 "MODE SELECT(6)")) == 0)
2083 reply = do_mode_select(fsg, bh);
2084 break;
2085
2086 case SC_MODE_SELECT_10:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002087 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002088 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2089 (1<<1) | (3<<7), 0,
2090 "MODE SELECT(10)")) == 0)
2091 reply = do_mode_select(fsg, bh);
2092 break;
2093
2094 case SC_MODE_SENSE_6:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002095 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002096 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2097 (1<<1) | (1<<2) | (1<<4), 0,
2098 "MODE SENSE(6)")) == 0)
2099 reply = do_mode_sense(fsg, bh);
2100 break;
2101
2102 case SC_MODE_SENSE_10:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002103 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002104 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2105 (1<<1) | (1<<2) | (3<<7), 0,
2106 "MODE SENSE(10)")) == 0)
2107 reply = do_mode_sense(fsg, bh);
2108 break;
2109
2110 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2111 fsg->data_size_from_cmnd = 0;
2112 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2113 (1<<4), 0,
2114 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2115 reply = do_prevent_allow(fsg);
2116 break;
2117
2118 case SC_READ_6:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002119 i = fsg->common->cmnd[4];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002120 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2121 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2122 (7<<1) | (1<<4), 1,
2123 "READ(6)")) == 0)
2124 reply = do_read(fsg);
2125 break;
2126
2127 case SC_READ_10:
2128 fsg->data_size_from_cmnd =
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002129 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002130 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2131 (1<<1) | (0xf<<2) | (3<<7), 1,
2132 "READ(10)")) == 0)
2133 reply = do_read(fsg);
2134 break;
2135
2136 case SC_READ_12:
2137 fsg->data_size_from_cmnd =
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002138 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002139 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2140 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2141 "READ(12)")) == 0)
2142 reply = do_read(fsg);
2143 break;
2144
2145 case SC_READ_CAPACITY:
2146 fsg->data_size_from_cmnd = 8;
2147 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2148 (0xf<<2) | (1<<8), 1,
2149 "READ CAPACITY")) == 0)
2150 reply = do_read_capacity(fsg, bh);
2151 break;
2152
2153 case SC_READ_HEADER:
2154 if (!mod_data.cdrom)
2155 goto unknown_cmnd;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002156 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002157 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2158 (3<<7) | (0x1f<<1), 1,
2159 "READ HEADER")) == 0)
2160 reply = do_read_header(fsg, bh);
2161 break;
2162
2163 case SC_READ_TOC:
2164 if (!mod_data.cdrom)
2165 goto unknown_cmnd;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002166 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002167 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2168 (7<<6) | (1<<1), 1,
2169 "READ TOC")) == 0)
2170 reply = do_read_toc(fsg, bh);
2171 break;
2172
2173 case SC_READ_FORMAT_CAPACITIES:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002174 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002175 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2176 (3<<7), 1,
2177 "READ FORMAT CAPACITIES")) == 0)
2178 reply = do_read_format_capacities(fsg, bh);
2179 break;
2180
2181 case SC_REQUEST_SENSE:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002182 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002183 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2184 (1<<4), 0,
2185 "REQUEST SENSE")) == 0)
2186 reply = do_request_sense(fsg, bh);
2187 break;
2188
2189 case SC_START_STOP_UNIT:
2190 fsg->data_size_from_cmnd = 0;
2191 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2192 (1<<1) | (1<<4), 0,
2193 "START-STOP UNIT")) == 0)
2194 reply = do_start_stop(fsg);
2195 break;
2196
2197 case SC_SYNCHRONIZE_CACHE:
2198 fsg->data_size_from_cmnd = 0;
2199 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2200 (0xf<<2) | (3<<7), 1,
2201 "SYNCHRONIZE CACHE")) == 0)
2202 reply = do_synchronize_cache(fsg);
2203 break;
2204
2205 case SC_TEST_UNIT_READY:
2206 fsg->data_size_from_cmnd = 0;
2207 reply = check_command(fsg, 6, DATA_DIR_NONE,
2208 0, 1,
2209 "TEST UNIT READY");
2210 break;
2211
2212 /* Although optional, this command is used by MS-Windows. We
2213 * support a minimal version: BytChk must be 0. */
2214 case SC_VERIFY:
2215 fsg->data_size_from_cmnd = 0;
2216 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2217 (1<<1) | (0xf<<2) | (3<<7), 1,
2218 "VERIFY")) == 0)
2219 reply = do_verify(fsg);
2220 break;
2221
2222 case SC_WRITE_6:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002223 i = fsg->common->cmnd[4];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002224 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2225 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2226 (7<<1) | (1<<4), 1,
2227 "WRITE(6)")) == 0)
2228 reply = do_write(fsg);
2229 break;
2230
2231 case SC_WRITE_10:
2232 fsg->data_size_from_cmnd =
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002233 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002234 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2235 (1<<1) | (0xf<<2) | (3<<7), 1,
2236 "WRITE(10)")) == 0)
2237 reply = do_write(fsg);
2238 break;
2239
2240 case SC_WRITE_12:
2241 fsg->data_size_from_cmnd =
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002242 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002243 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2244 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2245 "WRITE(12)")) == 0)
2246 reply = do_write(fsg);
2247 break;
2248
2249 /* Some mandatory commands that we recognize but don't implement.
2250 * They don't mean much in this setting. It's left as an exercise
2251 * for anyone interested to implement RESERVE and RELEASE in terms
2252 * of Posix locks. */
2253 case SC_FORMAT_UNIT:
2254 case SC_RELEASE:
2255 case SC_RESERVE:
2256 case SC_SEND_DIAGNOSTIC:
2257 // Fall through
2258
2259 default:
2260 unknown_cmnd:
2261 fsg->data_size_from_cmnd = 0;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002262 sprintf(unknown, "Unknown x%02x", fsg->common->cmnd[0]);
2263 if ((reply = check_command(fsg, fsg->common->cmnd_size,
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002264 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002265 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002266 reply = -EINVAL;
2267 }
2268 break;
2269 }
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002270 up_read(&fsg->common->filesem);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002271
2272 if (reply == -EINTR || signal_pending(current))
2273 return -EINTR;
2274
2275 /* Set up the single reply buffer for finish_reply() */
2276 if (reply == -EINVAL)
2277 reply = 0; // Error reply length
2278 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2279 reply = min((u32) reply, fsg->data_size_from_cmnd);
2280 bh->inreq->length = reply;
2281 bh->state = BUF_STATE_FULL;
2282 fsg->residue -= reply;
2283 } // Otherwise it's already set
2284
2285 return 0;
2286}
2287
2288
2289/*-------------------------------------------------------------------------*/
2290
2291static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2292{
2293 struct usb_request *req = bh->outreq;
2294 struct fsg_bulk_cb_wrap *cbw = req->buf;
2295
2296 /* Was this a real packet? Should it be ignored? */
2297 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2298 return -EINVAL;
2299
2300 /* Is the CBW valid? */
2301 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2302 cbw->Signature != cpu_to_le32(
2303 USB_BULK_CB_SIG)) {
2304 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2305 req->actual,
2306 le32_to_cpu(cbw->Signature));
2307
2308 /* The Bulk-only spec says we MUST stall the IN endpoint
2309 * (6.6.1), so it's unavoidable. It also says we must
2310 * retain this state until the next reset, but there's
2311 * no way to tell the controller driver it should ignore
2312 * Clear-Feature(HALT) requests.
2313 *
2314 * We aren't required to halt the OUT endpoint; instead
2315 * we can simply accept and discard any data received
2316 * until the next reset. */
2317 wedge_bulk_in_endpoint(fsg);
2318 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2319 return -EINVAL;
2320 }
2321
2322 /* Is the CBW meaningful? */
2323 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2324 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2325 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2326 "cmdlen %u\n",
2327 cbw->Lun, cbw->Flags, cbw->Length);
2328
2329 /* We can do anything we want here, so let's stall the
2330 * bulk pipes if we are allowed to. */
2331 if (mod_data.can_stall) {
2332 fsg_set_halt(fsg, fsg->bulk_out);
2333 halt_bulk_in_endpoint(fsg);
2334 }
2335 return -EINVAL;
2336 }
2337
2338 /* Save the command for later */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002339 fsg->common->cmnd_size = cbw->Length;
2340 memcpy(fsg->common->cmnd, cbw->CDB, fsg->common->cmnd_size);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002341 if (cbw->Flags & USB_BULK_IN_FLAG)
2342 fsg->data_dir = DATA_DIR_TO_HOST;
2343 else
2344 fsg->data_dir = DATA_DIR_FROM_HOST;
2345 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2346 if (fsg->data_size == 0)
2347 fsg->data_dir = DATA_DIR_NONE;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002348 fsg->common->lun = cbw->Lun;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002349 fsg->tag = cbw->Tag;
2350 return 0;
2351}
2352
2353
2354static int get_next_command(struct fsg_dev *fsg)
2355{
2356 struct fsg_buffhd *bh;
2357 int rc = 0;
2358
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01002359 /* Wait for the next buffer to become available */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002360 bh = fsg->common->next_buffhd_to_fill;
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01002361 while (bh->state != BUF_STATE_EMPTY) {
2362 rc = sleep_thread(fsg);
2363 if (rc)
2364 return rc;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002365 }
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01002366
2367 /* Queue a request to read a Bulk-only CBW */
2368 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2369 bh->outreq->short_not_ok = 1;
2370 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2371 &bh->outreq_busy, &bh->state);
2372
2373 /* We will drain the buffer in software, which means we
2374 * can reuse it for the next filling. No need to advance
2375 * next_buffhd_to_fill. */
2376
2377 /* Wait for the CBW to arrive */
2378 while (bh->state != BUF_STATE_FULL) {
2379 rc = sleep_thread(fsg);
2380 if (rc)
2381 return rc;
2382 }
2383 smp_rmb();
2384 rc = received_cbw(fsg, bh);
2385 bh->state = BUF_STATE_EMPTY;
2386
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002387 return rc;
2388}
2389
2390
2391/*-------------------------------------------------------------------------*/
2392
2393static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2394 const struct usb_endpoint_descriptor *d)
2395{
2396 int rc;
2397
2398 ep->driver_data = fsg;
2399 rc = usb_ep_enable(ep, d);
2400 if (rc)
2401 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2402 return rc;
2403}
2404
2405static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2406 struct usb_request **preq)
2407{
2408 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2409 if (*preq)
2410 return 0;
2411 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2412 return -ENOMEM;
2413}
2414
2415/*
2416 * Reset interface setting and re-init endpoint state (toggle etc).
2417 * Call with altsetting < 0 to disable the interface. The only other
2418 * available altsetting is 0, which enables the interface.
2419 */
2420static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2421{
2422 int rc = 0;
2423 int i;
2424 const struct usb_endpoint_descriptor *d;
2425
2426 if (fsg->running)
2427 DBG(fsg, "reset interface\n");
2428
2429reset:
2430 /* Deallocate the requests */
2431 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002432 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002433
2434 if (bh->inreq) {
2435 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2436 bh->inreq = NULL;
2437 }
2438 if (bh->outreq) {
2439 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2440 bh->outreq = NULL;
2441 }
2442 }
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002443
2444 /* Disable the endpoints */
2445 if (fsg->bulk_in_enabled) {
2446 usb_ep_disable(fsg->bulk_in);
2447 fsg->bulk_in_enabled = 0;
2448 }
2449 if (fsg->bulk_out_enabled) {
2450 usb_ep_disable(fsg->bulk_out);
2451 fsg->bulk_out_enabled = 0;
2452 }
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002453
2454 fsg->running = 0;
2455 if (altsetting < 0 || rc != 0)
2456 return rc;
2457
2458 DBG(fsg, "set interface %d\n", altsetting);
2459
2460 /* Enable the endpoints */
2461 d = fsg_ep_desc(fsg->gadget,
2462 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2463 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2464 goto reset;
2465 fsg->bulk_in_enabled = 1;
2466
2467 d = fsg_ep_desc(fsg->gadget,
2468 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2469 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2470 goto reset;
2471 fsg->bulk_out_enabled = 1;
2472 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2473 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2474
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002475 /* Allocate the requests */
2476 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002477 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002478
2479 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2480 goto reset;
2481 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2482 goto reset;
2483 bh->inreq->buf = bh->outreq->buf = bh->buf;
2484 bh->inreq->context = bh->outreq->context = bh;
2485 bh->inreq->complete = bulk_in_complete;
2486 bh->outreq->complete = bulk_out_complete;
2487 }
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002488
2489 fsg->running = 1;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002490 for (i = 0; i < fsg->common->nluns; ++i)
2491 fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002492 return rc;
2493}
2494
2495
2496/*
2497 * Change our operational configuration. This code must agree with the code
2498 * that returns config descriptors, and with interface altsetting code.
2499 *
2500 * It's also responsible for power management interactions. Some
2501 * configurations might not work with our current power sources.
2502 * For now we just assume the gadget is always self-powered.
2503 */
2504static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2505{
2506 int rc = 0;
2507
2508 /* Disable the single interface */
2509 if (fsg->config != 0) {
2510 DBG(fsg, "reset config\n");
2511 fsg->config = 0;
2512 rc = do_set_interface(fsg, -1);
2513 }
2514
2515 /* Enable the interface */
2516 if (new_config != 0) {
2517 fsg->config = new_config;
2518 if ((rc = do_set_interface(fsg, 0)) != 0)
2519 fsg->config = 0; // Reset on errors
2520 else {
2521 char *speed;
2522
2523 switch (fsg->gadget->speed) {
2524 case USB_SPEED_LOW: speed = "low"; break;
2525 case USB_SPEED_FULL: speed = "full"; break;
2526 case USB_SPEED_HIGH: speed = "high"; break;
2527 default: speed = "?"; break;
2528 }
2529 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2530 }
2531 }
2532 return rc;
2533}
2534
2535
2536/*-------------------------------------------------------------------------*/
2537
2538static void handle_exception(struct fsg_dev *fsg)
2539{
2540 siginfo_t info;
2541 int sig;
2542 int i;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002543 struct fsg_buffhd *bh;
2544 enum fsg_state old_state;
2545 u8 new_config;
2546 struct fsg_lun *curlun;
2547 unsigned int exception_req_tag;
2548 int rc;
2549
2550 /* Clear the existing signals. Anything but SIGUSR1 is converted
2551 * into a high-priority EXIT exception. */
2552 for (;;) {
2553 sig = dequeue_signal_lock(current, &current->blocked, &info);
2554 if (!sig)
2555 break;
2556 if (sig != SIGUSR1) {
2557 if (fsg->state < FSG_STATE_EXIT)
2558 DBG(fsg, "Main thread exiting on signal\n");
2559 raise_exception(fsg, FSG_STATE_EXIT);
2560 }
2561 }
2562
2563 /* Cancel all the pending transfers */
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002564 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002565 bh = &fsg->common->buffhds[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002566 if (bh->inreq_busy)
2567 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2568 if (bh->outreq_busy)
2569 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2570 }
2571
2572 /* Wait until everything is idle */
2573 for (;;) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002574 int num_active = 0;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002575 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002576 bh = &fsg->common->buffhds[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002577 num_active += bh->inreq_busy + bh->outreq_busy;
2578 }
2579 if (num_active == 0)
2580 break;
2581 if (sleep_thread(fsg))
2582 return;
2583 }
2584
2585 /* Clear out the controller's fifos */
2586 if (fsg->bulk_in_enabled)
2587 usb_ep_fifo_flush(fsg->bulk_in);
2588 if (fsg->bulk_out_enabled)
2589 usb_ep_fifo_flush(fsg->bulk_out);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002590
2591 /* Reset the I/O buffer states and pointers, the SCSI
2592 * state, and the exception. Then invoke the handler. */
2593 spin_lock_irq(&fsg->lock);
2594
2595 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002596 bh = &fsg->common->buffhds[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002597 bh->state = BUF_STATE_EMPTY;
2598 }
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002599 fsg->common->next_buffhd_to_fill = fsg->common->next_buffhd_to_drain =
2600 &fsg->common->buffhds[0];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002601
2602 exception_req_tag = fsg->exception_req_tag;
2603 new_config = fsg->new_config;
2604 old_state = fsg->state;
2605
2606 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2607 fsg->state = FSG_STATE_STATUS_PHASE;
2608 else {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002609 for (i = 0; i < fsg->common->nluns; ++i) {
2610 curlun = &fsg->common->luns[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002611 curlun->prevent_medium_removal = 0;
2612 curlun->sense_data = curlun->unit_attention_data =
2613 SS_NO_SENSE;
2614 curlun->sense_data_info = 0;
2615 curlun->info_valid = 0;
2616 }
2617 fsg->state = FSG_STATE_IDLE;
2618 }
2619 spin_unlock_irq(&fsg->lock);
2620
2621 /* Carry out any extra actions required for the exception */
2622 switch (old_state) {
2623 default:
2624 break;
2625
2626 case FSG_STATE_ABORT_BULK_OUT:
2627 send_status(fsg);
2628 spin_lock_irq(&fsg->lock);
2629 if (fsg->state == FSG_STATE_STATUS_PHASE)
2630 fsg->state = FSG_STATE_IDLE;
2631 spin_unlock_irq(&fsg->lock);
2632 break;
2633
2634 case FSG_STATE_RESET:
2635 /* In case we were forced against our will to halt a
2636 * bulk endpoint, clear the halt now. (The SuperH UDC
2637 * requires this.) */
2638 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2639 usb_ep_clear_halt(fsg->bulk_in);
2640
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01002641 if (fsg->ep0_req_tag == exception_req_tag)
2642 ep0_queue(fsg); // Complete the status stage
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002643
2644 /* Technically this should go here, but it would only be
2645 * a waste of time. Ditto for the INTERFACE_CHANGE and
2646 * CONFIG_CHANGE cases. */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002647 // for (i = 0; i < fsg->common->nluns; ++i)
2648 // fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002649 break;
2650
2651 case FSG_STATE_INTERFACE_CHANGE:
2652 rc = do_set_interface(fsg, 0);
2653 if (fsg->ep0_req_tag != exception_req_tag)
2654 break;
2655 if (rc != 0) // STALL on errors
2656 fsg_set_halt(fsg, fsg->ep0);
2657 else // Complete the status stage
2658 ep0_queue(fsg);
2659 break;
2660
2661 case FSG_STATE_CONFIG_CHANGE:
2662 rc = do_set_config(fsg, new_config);
2663 if (fsg->ep0_req_tag != exception_req_tag)
2664 break;
2665 if (rc != 0) // STALL on errors
2666 fsg_set_halt(fsg, fsg->ep0);
2667 else // Complete the status stage
2668 ep0_queue(fsg);
2669 break;
2670
2671 case FSG_STATE_DISCONNECT:
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002672 for (i = 0; i < fsg->common->nluns; ++i)
2673 fsg_lun_fsync_sub(&fsg->common->luns[i]);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002674 do_set_config(fsg, 0); // Unconfigured state
2675 break;
2676
2677 case FSG_STATE_EXIT:
2678 case FSG_STATE_TERMINATED:
2679 do_set_config(fsg, 0); // Free resources
2680 spin_lock_irq(&fsg->lock);
2681 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
2682 spin_unlock_irq(&fsg->lock);
2683 break;
2684 }
2685}
2686
2687
2688/*-------------------------------------------------------------------------*/
2689
2690static int fsg_main_thread(void *fsg_)
2691{
2692 struct fsg_dev *fsg = fsg_;
2693
2694 /* Allow the thread to be killed by a signal, but set the signal mask
2695 * to block everything but INT, TERM, KILL, and USR1. */
2696 allow_signal(SIGINT);
2697 allow_signal(SIGTERM);
2698 allow_signal(SIGKILL);
2699 allow_signal(SIGUSR1);
2700
2701 /* Allow the thread to be frozen */
2702 set_freezable();
2703
2704 /* Arrange for userspace references to be interpreted as kernel
2705 * pointers. That way we can pass a kernel pointer to a routine
2706 * that expects a __user pointer and it will work okay. */
2707 set_fs(get_ds());
2708
2709 /* The main loop */
2710 while (fsg->state != FSG_STATE_TERMINATED) {
2711 if (exception_in_progress(fsg) || signal_pending(current)) {
2712 handle_exception(fsg);
2713 continue;
2714 }
2715
2716 if (!fsg->running) {
2717 sleep_thread(fsg);
2718 continue;
2719 }
2720
2721 if (get_next_command(fsg))
2722 continue;
2723
2724 spin_lock_irq(&fsg->lock);
2725 if (!exception_in_progress(fsg))
2726 fsg->state = FSG_STATE_DATA_PHASE;
2727 spin_unlock_irq(&fsg->lock);
2728
2729 if (do_scsi_command(fsg) || finish_reply(fsg))
2730 continue;
2731
2732 spin_lock_irq(&fsg->lock);
2733 if (!exception_in_progress(fsg))
2734 fsg->state = FSG_STATE_STATUS_PHASE;
2735 spin_unlock_irq(&fsg->lock);
2736
2737 if (send_status(fsg))
2738 continue;
2739
2740 spin_lock_irq(&fsg->lock);
2741 if (!exception_in_progress(fsg))
2742 fsg->state = FSG_STATE_IDLE;
2743 spin_unlock_irq(&fsg->lock);
2744 }
2745
2746 spin_lock_irq(&fsg->lock);
2747 fsg->thread_task = NULL;
2748 spin_unlock_irq(&fsg->lock);
2749
2750 /* If we are exiting because of a signal, unregister the
2751 * gadget driver. */
2752 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2753 usb_gadget_unregister_driver(&fsg_driver);
2754
2755 /* Let the unbind and cleanup routines know the thread has exited */
2756 complete_and_exit(&fsg->thread_notifier, 0);
2757}
2758
2759
2760/*-------------------------------------------------------------------------*/
2761
2762
2763/* The write permissions and store_xxx pointers are set in fsg_bind() */
2764static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
2765static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
2766
2767
2768/*-------------------------------------------------------------------------*/
2769
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002770static void fsg_release(struct fsg_dev *fsg)
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002771{
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002772 kfree(fsg->common->luns);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002773 kfree(fsg);
2774}
2775
2776static void lun_release(struct device *dev)
2777{
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002778}
2779
2780static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
2781{
2782 struct fsg_dev *fsg = get_gadget_data(gadget);
2783 int i;
2784 struct fsg_lun *curlun;
2785 struct usb_request *req = fsg->ep0req;
2786
2787 DBG(fsg, "unbind\n");
2788 clear_bit(REGISTERED, &fsg->atomic_bitflags);
2789
2790 /* Unregister the sysfs attribute files and the LUNs */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002791 for (i = 0; i < fsg->common->nluns; ++i) {
2792 curlun = &fsg->common->luns[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002793 if (curlun->registered) {
2794 device_remove_file(&curlun->dev, &dev_attr_ro);
2795 device_remove_file(&curlun->dev, &dev_attr_file);
2796 fsg_lun_close(curlun);
2797 device_unregister(&curlun->dev);
2798 curlun->registered = 0;
2799 }
2800 }
2801
2802 /* If the thread isn't already dead, tell it to exit now */
2803 if (fsg->state != FSG_STATE_TERMINATED) {
2804 raise_exception(fsg, FSG_STATE_EXIT);
2805 wait_for_completion(&fsg->thread_notifier);
2806
2807 /* The cleanup routine waits for this completion also */
2808 complete(&fsg->thread_notifier);
2809 }
2810
2811 /* Free the data buffers */
2812 for (i = 0; i < FSG_NUM_BUFFERS; ++i)
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002813 kfree(fsg->common->buffhds[i].buf);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002814
2815 /* Free the request and buffer for endpoint 0 */
2816 if (req) {
2817 kfree(req->buf);
2818 usb_ep_free_request(fsg->ep0, req);
2819 }
2820
2821 set_gadget_data(gadget, NULL);
2822}
2823
2824
2825static int __init check_parameters(struct fsg_dev *fsg)
2826{
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002827 int gcnum;
2828
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002829 /* Some peripheral controllers are known not to be able to
2830 * halt bulk endpoints correctly. If one of them is present,
2831 * disable stalls.
2832 */
2833 if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
2834 mod_data.can_stall = 0;
2835
2836 if (mod_data.release == 0xffff) { // Parameter wasn't set
2837 /* The sa1100 controller is not supported */
2838 if (gadget_is_sa1100(fsg->gadget))
2839 gcnum = -1;
2840 else
2841 gcnum = usb_gadget_controller_number(fsg->gadget);
2842 if (gcnum >= 0)
2843 mod_data.release = 0x0300 + gcnum;
2844 else {
2845 WARNING(fsg, "controller '%s' not recognized\n",
2846 fsg->gadget->name);
2847 mod_data.release = 0x0399;
2848 }
2849 }
2850
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002851 return 0;
2852}
2853
2854
2855static int __init fsg_bind(struct usb_gadget *gadget)
2856{
2857 struct fsg_dev *fsg = the_fsg;
2858 int rc;
2859 int i;
2860 struct fsg_lun *curlun;
2861 struct usb_ep *ep;
2862 struct usb_request *req;
2863 char *pathbuf, *p;
2864
2865 fsg->gadget = gadget;
2866 set_gadget_data(gadget, fsg);
2867 fsg->ep0 = gadget->ep0;
2868 fsg->ep0->driver_data = fsg;
2869
2870 if ((rc = check_parameters(fsg)) != 0)
2871 goto out;
2872
2873 if (mod_data.removable) { // Enable the store_xxx attributes
2874 dev_attr_file.attr.mode = 0644;
2875 dev_attr_file.store = fsg_store_file;
2876 if (!mod_data.cdrom) {
2877 dev_attr_ro.attr.mode = 0644;
2878 dev_attr_ro.store = fsg_store_ro;
2879 }
2880 }
2881
2882 /* Find out how many LUNs there should be */
2883 i = mod_data.nluns;
2884 if (i == 0)
2885 i = max(mod_data.num_filenames, 1u);
2886 if (i > FSG_MAX_LUNS) {
2887 ERROR(fsg, "invalid number of LUNs: %d\n", i);
2888 rc = -EINVAL;
2889 goto out;
2890 }
2891
2892 /* Create the LUNs, open their backing files, and register the
2893 * LUN devices in sysfs. */
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002894 fsg->common->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
2895 if (!fsg->common->luns) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002896 rc = -ENOMEM;
2897 goto out;
2898 }
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002899 fsg->common->nluns = i;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002900
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002901 for (i = 0; i < fsg->common->nluns; ++i) {
2902 curlun = &fsg->common->luns[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002903 curlun->cdrom = !!mod_data.cdrom;
2904 curlun->ro = mod_data.cdrom || mod_data.ro[i];
2905 curlun->initially_ro = curlun->ro;
2906 curlun->removable = mod_data.removable;
2907 curlun->dev.release = lun_release;
2908 curlun->dev.parent = &gadget->dev;
2909 curlun->dev.driver = &fsg_driver.driver;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002910 dev_set_drvdata(&curlun->dev, &fsg->common->filesem);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002911 dev_set_name(&curlun->dev,"%s-lun%d",
2912 dev_name(&gadget->dev), i);
2913
2914 if ((rc = device_register(&curlun->dev)) != 0) {
2915 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
2916 goto out;
2917 }
2918 if ((rc = device_create_file(&curlun->dev,
2919 &dev_attr_ro)) != 0 ||
2920 (rc = device_create_file(&curlun->dev,
2921 &dev_attr_file)) != 0) {
2922 device_unregister(&curlun->dev);
2923 goto out;
2924 }
2925 curlun->registered = 1;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002926
2927 if (mod_data.file[i] && *mod_data.file[i]) {
2928 if ((rc = fsg_lun_open(curlun,
2929 mod_data.file[i])) != 0)
2930 goto out;
2931 } else if (!mod_data.removable) {
2932 ERROR(fsg, "no file given for LUN%d\n", i);
2933 rc = -EINVAL;
2934 goto out;
2935 }
2936 }
2937
2938 /* Find all the endpoints we will use */
2939 usb_ep_autoconfig_reset(gadget);
2940 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2941 if (!ep)
2942 goto autoconf_fail;
2943 ep->driver_data = fsg; // claim the endpoint
2944 fsg->bulk_in = ep;
2945
2946 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2947 if (!ep)
2948 goto autoconf_fail;
2949 ep->driver_data = fsg; // claim the endpoint
2950 fsg->bulk_out = ep;
2951
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002952 /* Fix up the descriptors */
2953 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002954 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
2955
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002956 if (gadget_is_dualspeed(gadget)) {
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002957 /* Assume ep0 uses the same maxpacket value for both speeds */
2958 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
2959
2960 /* Assume endpoint addresses are the same for both speeds */
2961 fsg_hs_bulk_in_desc.bEndpointAddress =
2962 fsg_fs_bulk_in_desc.bEndpointAddress;
2963 fsg_hs_bulk_out_desc.bEndpointAddress =
2964 fsg_fs_bulk_out_desc.bEndpointAddress;
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002965 }
2966
2967 if (gadget_is_otg(gadget))
2968 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
2969
2970 rc = -ENOMEM;
2971
2972 /* Allocate the request and buffer for endpoint 0 */
2973 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
2974 if (!req)
2975 goto out;
2976 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
2977 if (!req->buf)
2978 goto out;
2979 req->complete = ep0_complete;
2980
2981 /* Allocate the data buffers */
2982 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002983 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002984
2985 /* Allocate for the bulk-in endpoint. We assume that
2986 * the buffer will also work with the bulk-out (and
2987 * interrupt-in) endpoint. */
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01002988 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002989 if (!bh->buf)
2990 goto out;
2991 bh->next = bh + 1;
2992 }
Michal Nazarewicza41ae412009-10-28 16:57:20 +01002993 fsg->common->buffhds[FSG_NUM_BUFFERS - 1].next = &fsg->common->buffhds[0];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01002994
2995 /* This should reflect the actual gadget power source */
2996 usb_gadget_set_selfpowered(gadget);
2997
2998 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
2999 "%s %s with %s",
3000 init_utsname()->sysname, init_utsname()->release,
3001 gadget->name);
3002
3003 /* On a real device, serial[] would be loaded from permanent
3004 * storage. We just encode it from the driver version string. */
3005 for (i = 0; i < sizeof fsg_string_serial - 2; i += 2) {
3006 unsigned char c = DRIVER_VERSION[i / 2];
3007
3008 if (!c)
3009 break;
3010 sprintf(&fsg_string_serial[i], "%02X", c);
3011 }
3012
3013 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3014 "file-storage-gadget");
3015 if (IS_ERR(fsg->thread_task)) {
3016 rc = PTR_ERR(fsg->thread_task);
3017 goto out;
3018 }
3019
3020 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
Michal Nazarewicza41ae412009-10-28 16:57:20 +01003021 INFO(fsg, "Number of LUNs=%d\n", fsg->common->nluns);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003022
3023 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01003024 for (i = 0; i < fsg->common->nluns; ++i) {
3025 curlun = &fsg->common->luns[i];
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003026 if (fsg_lun_is_open(curlun)) {
3027 p = NULL;
3028 if (pathbuf) {
3029 p = d_path(&curlun->filp->f_path,
3030 pathbuf, PATH_MAX);
3031 if (IS_ERR(p))
3032 p = NULL;
3033 }
3034 LINFO(curlun, "ro=%d, file: %s\n",
3035 curlun->ro, (p ? p : "(error)"));
3036 }
3037 }
3038 kfree(pathbuf);
3039
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003040 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3041 mod_data.removable, mod_data.can_stall,
Michal Nazarewicz93bcf122009-10-28 16:57:19 +01003042 mod_data.cdrom, FSG_BUFLEN);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003043 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
3044
3045 set_bit(REGISTERED, &fsg->atomic_bitflags);
3046
3047 /* Tell the thread to start working */
3048 wake_up_process(fsg->thread_task);
3049 return 0;
3050
3051autoconf_fail:
3052 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3053 rc = -ENOTSUPP;
3054
3055out:
3056 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3057 fsg_unbind(gadget);
3058 complete(&fsg->thread_notifier);
3059 return rc;
3060}
3061
3062
3063/*-------------------------------------------------------------------------*/
3064
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003065static struct usb_gadget_driver fsg_driver = {
3066#ifdef CONFIG_USB_GADGET_DUALSPEED
3067 .speed = USB_SPEED_HIGH,
3068#else
3069 .speed = USB_SPEED_FULL,
3070#endif
3071 .function = (char *) fsg_string_product,
3072 .bind = fsg_bind,
3073 .unbind = fsg_unbind,
3074 .disconnect = fsg_disconnect,
3075 .setup = fsg_setup,
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003076
3077 .driver = {
3078 .name = DRIVER_NAME,
3079 .owner = THIS_MODULE,
3080 // .release = ...
3081 // .suspend = ...
3082 // .resume = ...
3083 },
3084};
3085
3086
3087static int __init fsg_alloc(void)
3088{
3089 struct fsg_dev *fsg;
3090
3091 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3092 if (!fsg)
3093 return -ENOMEM;
Michal Nazarewicza41ae412009-10-28 16:57:20 +01003094
3095 fsg->common = kzalloc(sizeof *fsg->common, GFP_KERNEL);
3096 if (!fsg->common) {
3097 kfree(fsg);
3098 return -ENOMEM;
3099 }
3100
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003101 spin_lock_init(&fsg->lock);
Michal Nazarewicza41ae412009-10-28 16:57:20 +01003102 init_rwsem(&fsg->common->filesem);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003103 init_completion(&fsg->thread_notifier);
3104
3105 the_fsg = fsg;
3106 return 0;
3107}
3108
3109
3110static int __init fsg_init(void)
3111{
3112 int rc;
3113 struct fsg_dev *fsg;
3114
3115 if ((rc = fsg_alloc()) != 0)
3116 return rc;
3117 fsg = the_fsg;
3118 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
Michal Nazarewicza41ae412009-10-28 16:57:20 +01003119 fsg_release(fsg);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003120 return rc;
3121}
3122module_init(fsg_init);
3123
3124
3125static void __exit fsg_cleanup(void)
3126{
3127 struct fsg_dev *fsg = the_fsg;
3128
3129 /* Unregister the driver iff the thread hasn't already done so */
3130 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3131 usb_gadget_unregister_driver(&fsg_driver);
3132
3133 /* Wait for the thread to finish up */
3134 wait_for_completion(&fsg->thread_notifier);
3135
Michal Nazarewicza41ae412009-10-28 16:57:20 +01003136 fsg_release(fsg);
Michal Nazarewiczd5e2b672009-10-28 16:57:18 +01003137}
3138module_exit(fsg_cleanup);