2 * file_storage.c -- File-backed USB Storage Gadget, for USB development
4 * Copyright (C) 2003-2008 Alan Stern
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
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.
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.
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.
53 * There is support for multiple logical units (LUNs), each of which has
54 * its own backing file. The number of LUNs can be set using the optional
55 * "luns" module parameter (anywhere from 1 to 8), and the corresponding
56 * files are specified using comma-separated lists for "file" and "ro".
57 * The default number of LUNs is taken from the number of "file" elements;
58 * it is 1 if "file" is not given. If "removable" is not set then a backing
59 * file must be specified for each LUN. If it is set, then an unspecified
60 * or empty backing filename means the LUN's medium is not loaded. Ideally
61 * each LUN would be settable independently as a disk drive or a CD-ROM
62 * drive, but currently all LUNs have to be the same type. The CD-ROM
63 * emulation includes a single data track and no audio tracks; hence there
64 * need be only one backing file per LUN. Note also that the CD-ROM block
65 * length is set to 512 rather than the more common value 2048.
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.
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.
80 * file=filename[,filename...]
81 * Required if "removable" is not set, names of
82 * the files or block devices used for
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
88 * stall Default determined according to the type of
89 * USB device controller (usually true),
90 * boolean to permit the driver to halt
92 * cdrom Default false, boolean for whether to emulate
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
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>.
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).
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
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.
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
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).
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.
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.
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.
207 /* #define VERBOSE_DEBUG */
208 /* #define DUMP_MSGS */
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>
229 #include <linux/usb/ch9.h>
230 #include <linux/usb/gadget.h>
232 #include "gadget_chips.h"
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.
243 #include "usbstring.c"
245 #include "epautoconf.c"
247 /*-------------------------------------------------------------------------*/
249 #define DRIVER_DESC "File-backed Storage Gadget"
250 #define DRIVER_NAME "g_file_storage"
251 #define DRIVER_VERSION "20 November 2008"
253 static char fsg_string_manufacturer[64];
254 static const char fsg_string_product[] = DRIVER_DESC;
255 static char fsg_string_serial[13];
256 static const char fsg_string_config[] = "Self-powered";
257 static const char fsg_string_interface[] = "Mass Storage";
260 #define FSG_NO_INTR_EP 1
261 #define FSG_BUFFHD_STATIC_BUFFER 1
263 #include "storage_common.c"
266 MODULE_DESCRIPTION(DRIVER_DESC);
267 MODULE_AUTHOR("Alan Stern");
268 MODULE_LICENSE("Dual BSD/GPL");
271 * This driver assumes self-powered hardware and has no way for users to
272 * trigger remote wakeup. It uses autoconfiguration to select endpoints
273 * and endpoint addresses.
277 /*-------------------------------------------------------------------------*/
280 /* Encapsulate the module parameter settings */
283 char *file[FSG_MAX_LUNS];
284 int ro[FSG_MAX_LUNS];
285 unsigned int num_filenames;
286 unsigned int num_ros;
293 unsigned short release;
294 } mod_data = { // Default values
301 module_param_array_named(file, mod_data.file, charp, &mod_data.num_filenames,
303 MODULE_PARM_DESC(file, "names of backing files or devices");
305 module_param_array_named(ro, mod_data.ro, bool, &mod_data.num_ros, S_IRUGO);
306 MODULE_PARM_DESC(ro, "true to force read-only");
308 module_param_named(luns, mod_data.nluns, uint, S_IRUGO);
309 MODULE_PARM_DESC(luns, "number of LUNs");
311 module_param_named(removable, mod_data.removable, bool, S_IRUGO);
312 MODULE_PARM_DESC(removable, "true to simulate removable media");
314 module_param_named(stall, mod_data.can_stall, bool, S_IRUGO);
315 MODULE_PARM_DESC(stall, "false to prevent bulk stalls");
317 module_param_named(cdrom, mod_data.cdrom, bool, S_IRUGO);
318 MODULE_PARM_DESC(cdrom, "true to emulate cdrom instead of disk");
321 /*-------------------------------------------------------------------------*/
324 /* Data shared by all the FSG instances. */
326 /* filesem protects: backing files in use */
327 struct rw_semaphore filesem;
329 struct fsg_buffhd *next_buffhd_to_fill;
330 struct fsg_buffhd *next_buffhd_to_drain;
331 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
334 u8 cmnd[MAX_COMMAND_SIZE];
338 struct fsg_lun *luns;
339 struct fsg_lun *curlun;
344 struct fsg_common *common;
346 /* lock protects: state, all the req_busy's */
348 struct usb_gadget *gadget;
350 /* reference counting: wait until all LUNs are released */
353 struct usb_ep *ep0; // Handy copy of gadget->ep0
354 struct usb_request *ep0req; // For control responses
355 unsigned int ep0_req_tag;
356 const char *ep0req_name;
358 unsigned int bulk_out_maxpacket;
359 enum fsg_state state; // For exception handling
360 unsigned int exception_req_tag;
362 u8 config, new_config;
364 unsigned int running : 1;
365 unsigned int bulk_in_enabled : 1;
366 unsigned int bulk_out_enabled : 1;
367 unsigned int phase_error : 1;
368 unsigned int short_packet_received : 1;
369 unsigned int bad_lun_okay : 1;
371 unsigned long atomic_bitflags;
373 #define IGNORE_BULK_OUT 1
375 struct usb_ep *bulk_in;
376 struct usb_ep *bulk_out;
378 int thread_wakeup_needed;
379 struct completion thread_notifier;
380 struct task_struct *thread_task;
382 enum data_direction data_dir;
384 u32 data_size_from_cmnd;
390 typedef void (*fsg_routine_t)(struct fsg_dev *);
392 static int exception_in_progress(struct fsg_dev *fsg)
394 return (fsg->state > FSG_STATE_IDLE);
397 /* Make bulk-out requests be divisible by the maxpacket size */
398 static void set_bulk_out_req_length(struct fsg_dev *fsg,
399 struct fsg_buffhd *bh, unsigned int length)
403 bh->bulk_out_intended_length = length;
404 rem = length % fsg->bulk_out_maxpacket;
406 length += fsg->bulk_out_maxpacket - rem;
407 bh->outreq->length = length;
410 static struct fsg_dev *the_fsg;
411 static struct usb_gadget_driver fsg_driver;
414 /*-------------------------------------------------------------------------*/
416 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
420 if (ep == fsg->bulk_in)
422 else if (ep == fsg->bulk_out)
426 DBG(fsg, "%s set halt\n", name);
427 return usb_ep_set_halt(ep);
431 /*-------------------------------------------------------------------------*/
434 * DESCRIPTORS ... most are static, but strings and (full) configuration
435 * descriptors are built on demand. Also the (static) config and interface
436 * descriptors are adjusted during fsg_bind().
439 /* There is only one configuration. */
440 #define CONFIG_VALUE 1
442 static struct usb_device_descriptor
444 .bLength = sizeof device_desc,
445 .bDescriptorType = USB_DT_DEVICE,
447 .bcdUSB = cpu_to_le16(0x0200),
448 .bDeviceClass = USB_CLASS_PER_INTERFACE,
450 /* The next three values can be overridden by module parameters */
451 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
452 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
453 .bcdDevice = cpu_to_le16(0xffff),
455 .iManufacturer = FSG_STRING_MANUFACTURER,
456 .iProduct = FSG_STRING_PRODUCT,
457 .iSerialNumber = FSG_STRING_SERIAL,
458 .bNumConfigurations = 1,
461 static struct usb_config_descriptor
463 .bLength = sizeof config_desc,
464 .bDescriptorType = USB_DT_CONFIG,
466 /* wTotalLength computed by usb_gadget_config_buf() */
468 .bConfigurationValue = CONFIG_VALUE,
469 .iConfiguration = FSG_STRING_CONFIG,
470 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
471 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
475 static struct usb_qualifier_descriptor
477 .bLength = sizeof dev_qualifier,
478 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
480 .bcdUSB = cpu_to_le16(0x0200),
481 .bDeviceClass = USB_CLASS_PER_INTERFACE,
483 .bNumConfigurations = 1,
489 * Config descriptors must agree with the code that sets configurations
490 * and with code managing interfaces and their altsettings. They must
491 * also handle different speeds and other-speed requests.
493 static int populate_config_buf(struct usb_gadget *gadget,
494 u8 *buf, u8 type, unsigned index)
496 enum usb_device_speed speed = gadget->speed;
498 const struct usb_descriptor_header **function;
503 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
504 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
505 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
506 function = fsg_hs_function;
508 function = fsg_fs_function;
510 /* for now, don't advertise srp-only devices */
511 if (!gadget_is_otg(gadget))
514 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
515 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
520 /*-------------------------------------------------------------------------*/
522 /* These routines may be called in process context or in_irq */
524 /* Caller must hold fsg->lock */
525 static void wakeup_thread(struct fsg_dev *fsg)
527 /* Tell the main thread that something has happened */
528 fsg->thread_wakeup_needed = 1;
529 if (fsg->thread_task)
530 wake_up_process(fsg->thread_task);
534 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
538 /* Do nothing if a higher-priority exception is already in progress.
539 * If a lower-or-equal priority exception is in progress, preempt it
540 * and notify the main thread by sending it a signal. */
541 spin_lock_irqsave(&fsg->lock, flags);
542 if (fsg->state <= new_state) {
543 fsg->exception_req_tag = fsg->ep0_req_tag;
544 fsg->state = new_state;
545 if (fsg->thread_task)
546 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
549 spin_unlock_irqrestore(&fsg->lock, flags);
553 /*-------------------------------------------------------------------------*/
555 /* The disconnect callback and ep0 routines. These always run in_irq,
556 * except that ep0_queue() is called in the main thread to acknowledge
557 * completion of various requests: set config, set interface, and
558 * Bulk-only device reset. */
560 static void fsg_disconnect(struct usb_gadget *gadget)
562 struct fsg_dev *fsg = get_gadget_data(gadget);
564 DBG(fsg, "disconnect or port reset\n");
565 raise_exception(fsg, FSG_STATE_DISCONNECT);
569 static int ep0_queue(struct fsg_dev *fsg)
573 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
574 if (rc != 0 && rc != -ESHUTDOWN) {
576 /* We can't do much more than wait for a reset */
577 WARNING(fsg, "error in submission: %s --> %d\n",
583 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
585 struct fsg_dev *fsg = ep->driver_data;
588 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
589 if (req->status || req->actual != req->length)
590 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
591 req->status, req->actual, req->length);
592 if (req->status == -ECONNRESET) // Request was cancelled
593 usb_ep_fifo_flush(ep);
595 if (req->status == 0 && req->context)
596 ((fsg_routine_t) (req->context))(fsg);
600 /*-------------------------------------------------------------------------*/
602 /* Bulk and interrupt endpoint completion handlers.
603 * These always run in_irq. */
605 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
607 struct fsg_dev *fsg = ep->driver_data;
608 struct fsg_buffhd *bh = req->context;
610 if (req->status || req->actual != req->length)
611 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
612 req->status, req->actual, req->length);
613 if (req->status == -ECONNRESET) // Request was cancelled
614 usb_ep_fifo_flush(ep);
616 /* Hold the lock while we update the request and buffer states */
618 spin_lock(&fsg->lock);
620 bh->state = BUF_STATE_EMPTY;
622 spin_unlock(&fsg->lock);
625 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
627 struct fsg_dev *fsg = ep->driver_data;
628 struct fsg_buffhd *bh = req->context;
630 dump_msg(fsg, "bulk-out", req->buf, req->actual);
631 if (req->status || req->actual != bh->bulk_out_intended_length)
632 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
633 req->status, req->actual,
634 bh->bulk_out_intended_length);
635 if (req->status == -ECONNRESET) // Request was cancelled
636 usb_ep_fifo_flush(ep);
638 /* Hold the lock while we update the request and buffer states */
640 spin_lock(&fsg->lock);
642 bh->state = BUF_STATE_FULL;
644 spin_unlock(&fsg->lock);
648 /*-------------------------------------------------------------------------*/
650 /* Ep0 class-specific handlers. These always run in_irq. */
652 static int class_setup_req(struct fsg_dev *fsg,
653 const struct usb_ctrlrequest *ctrl)
655 struct usb_request *req = fsg->ep0req;
656 u16 w_index = le16_to_cpu(ctrl->wIndex);
657 u16 w_value = le16_to_cpu(ctrl->wValue);
658 u16 w_length = le16_to_cpu(ctrl->wLength);
663 switch (ctrl->bRequest) {
665 case USB_BULK_RESET_REQUEST:
666 if (ctrl->bRequestType !=
667 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
669 if (w_index != 0 || w_value != 0)
672 /* Raise an exception to stop the current operation
673 * and reinitialize our state. */
674 DBG(fsg, "bulk reset request\n");
675 raise_exception(fsg, FSG_STATE_RESET);
676 return DELAYED_STATUS;
678 case USB_BULK_GET_MAX_LUN_REQUEST:
679 if (ctrl->bRequestType !=
680 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
682 if (w_index != 0 || w_value != 0)
684 VDBG(fsg, "get max LUN\n");
685 *(u8 *) req->buf = fsg->common->nluns - 1;
690 "unknown class-specific control req "
691 "%02x.%02x v%04x i%04x l%u\n",
692 ctrl->bRequestType, ctrl->bRequest,
693 le16_to_cpu(ctrl->wValue), w_index, w_length);
698 /*-------------------------------------------------------------------------*/
700 /* Ep0 standard request handlers. These always run in_irq. */
702 static int standard_setup_req(struct fsg_dev *fsg,
703 const struct usb_ctrlrequest *ctrl)
705 struct usb_request *req = fsg->ep0req;
706 int value = -EOPNOTSUPP;
707 u16 w_index = le16_to_cpu(ctrl->wIndex);
708 u16 w_value = le16_to_cpu(ctrl->wValue);
710 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
711 * but config change events will also reconfigure hardware. */
712 switch (ctrl->bRequest) {
714 case USB_REQ_GET_DESCRIPTOR:
715 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
718 switch (w_value >> 8) {
721 VDBG(fsg, "get device descriptor\n");
722 value = sizeof device_desc;
723 memcpy(req->buf, &device_desc, value);
725 case USB_DT_DEVICE_QUALIFIER:
726 VDBG(fsg, "get device qualifier\n");
727 if (!gadget_is_dualspeed(fsg->gadget))
729 value = sizeof dev_qualifier;
730 memcpy(req->buf, &dev_qualifier, value);
733 case USB_DT_OTHER_SPEED_CONFIG:
734 VDBG(fsg, "get other-speed config descriptor\n");
735 if (!gadget_is_dualspeed(fsg->gadget))
739 VDBG(fsg, "get configuration descriptor\n");
741 value = populate_config_buf(fsg->gadget,
748 VDBG(fsg, "get string descriptor\n");
750 /* wIndex == language code */
751 value = usb_gadget_get_string(&fsg_stringtab,
752 w_value & 0xff, req->buf);
757 /* One config, two speeds */
758 case USB_REQ_SET_CONFIGURATION:
759 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
762 VDBG(fsg, "set configuration\n");
763 if (w_value == CONFIG_VALUE || w_value == 0) {
764 fsg->new_config = w_value;
766 /* Raise an exception to wipe out previous transaction
767 * state (queued bufs, etc) and set the new config. */
768 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
769 value = DELAYED_STATUS;
772 case USB_REQ_GET_CONFIGURATION:
773 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
776 VDBG(fsg, "get configuration\n");
777 *(u8 *) req->buf = fsg->config;
781 case USB_REQ_SET_INTERFACE:
782 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
783 USB_RECIP_INTERFACE))
785 if (fsg->config && w_index == 0) {
787 /* Raise an exception to wipe out previous transaction
788 * state (queued bufs, etc) and install the new
789 * interface altsetting. */
790 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
791 value = DELAYED_STATUS;
794 case USB_REQ_GET_INTERFACE:
795 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
796 USB_RECIP_INTERFACE))
804 VDBG(fsg, "get interface\n");
805 *(u8 *) req->buf = 0;
811 "unknown control req %02x.%02x v%04x i%04x l%u\n",
812 ctrl->bRequestType, ctrl->bRequest,
813 w_value, w_index, le16_to_cpu(ctrl->wLength));
820 static int fsg_setup(struct usb_gadget *gadget,
821 const struct usb_ctrlrequest *ctrl)
823 struct fsg_dev *fsg = get_gadget_data(gadget);
825 int w_length = le16_to_cpu(ctrl->wLength);
827 ++fsg->ep0_req_tag; // Record arrival of a new request
828 fsg->ep0req->context = NULL;
829 fsg->ep0req->length = 0;
830 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
832 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
833 rc = class_setup_req(fsg, ctrl);
835 rc = standard_setup_req(fsg, ctrl);
837 /* Respond with data/status or defer until later? */
838 if (rc >= 0 && rc != DELAYED_STATUS) {
839 rc = min(rc, w_length);
840 fsg->ep0req->length = rc;
841 fsg->ep0req->zero = rc < w_length;
842 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
843 "ep0-in" : "ep0-out");
847 /* Device either stalls (rc < 0) or reports success */
852 /*-------------------------------------------------------------------------*/
854 /* All the following routines run in process context */
857 /* Use this for bulk or interrupt transfers, not ep0 */
858 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
859 struct usb_request *req, int *pbusy,
860 enum fsg_buffer_state *state)
864 if (ep == fsg->bulk_in)
865 dump_msg(fsg, "bulk-in", req->buf, req->length);
867 spin_lock_irq(&fsg->lock);
869 *state = BUF_STATE_BUSY;
870 spin_unlock_irq(&fsg->lock);
871 rc = usb_ep_queue(ep, req, GFP_KERNEL);
874 *state = BUF_STATE_EMPTY;
876 /* We can't do much more than wait for a reset */
878 /* Note: currently the net2280 driver fails zero-length
879 * submissions if DMA is enabled. */
880 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
882 WARNING(fsg, "error in submission: %s --> %d\n",
888 static int sleep_thread(struct fsg_dev *fsg)
892 /* Wait until a signal arrives or we are woken up */
895 set_current_state(TASK_INTERRUPTIBLE);
896 if (signal_pending(current)) {
900 if (fsg->thread_wakeup_needed)
904 __set_current_state(TASK_RUNNING);
905 fsg->thread_wakeup_needed = 0;
910 /*-------------------------------------------------------------------------*/
912 static int do_read(struct fsg_dev *fsg)
914 struct fsg_lun *curlun = fsg->common->curlun;
916 struct fsg_buffhd *bh;
919 loff_t file_offset, file_offset_tmp;
921 unsigned int partial_page;
924 /* Get the starting Logical Block Address and check that it's
926 if (fsg->common->cmnd[0] == SC_READ_6)
927 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
929 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
931 /* We allow DPO (Disable Page Out = don't save data in the
932 * cache) and FUA (Force Unit Access = don't read from the
933 * cache), but we don't implement them. */
934 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
935 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
939 if (lba >= curlun->num_sectors) {
940 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
943 file_offset = ((loff_t) lba) << 9;
945 /* Carry out the file reads */
946 amount_left = fsg->data_size_from_cmnd;
947 if (unlikely(amount_left == 0))
948 return -EIO; // No default reply
952 /* Figure out how much we need to read:
953 * Try to read the remaining amount.
954 * But don't read more than the buffer size.
955 * And don't try to read past the end of the file.
956 * Finally, if we're not at a page boundary, don't read past
958 * If this means reading 0 then we were asked to read past
959 * the end of file. */
960 amount = min(amount_left, FSG_BUFLEN);
961 amount = min((loff_t) amount,
962 curlun->file_length - file_offset);
963 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
964 if (partial_page > 0)
965 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
968 /* Wait for the next buffer to become available */
969 bh = fsg->common->next_buffhd_to_fill;
970 while (bh->state != BUF_STATE_EMPTY) {
971 rc = sleep_thread(fsg);
976 /* If we were asked to read past the end of file,
977 * end with an empty buffer. */
980 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
981 curlun->sense_data_info = file_offset >> 9;
982 curlun->info_valid = 1;
983 bh->inreq->length = 0;
984 bh->state = BUF_STATE_FULL;
988 /* Perform the read */
989 file_offset_tmp = file_offset;
990 nread = vfs_read(curlun->filp,
991 (char __user *) bh->buf,
992 amount, &file_offset_tmp);
993 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
994 (unsigned long long) file_offset,
996 if (signal_pending(current))
1000 LDBG(curlun, "error in file read: %d\n",
1003 } else if (nread < amount) {
1004 LDBG(curlun, "partial file read: %d/%u\n",
1005 (int) nread, amount);
1006 nread -= (nread & 511); // Round down to a block
1008 file_offset += nread;
1009 amount_left -= nread;
1010 fsg->residue -= nread;
1011 bh->inreq->length = nread;
1012 bh->state = BUF_STATE_FULL;
1014 /* If an error occurred, report it and its position */
1015 if (nread < amount) {
1016 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1017 curlun->sense_data_info = file_offset >> 9;
1018 curlun->info_valid = 1;
1022 if (amount_left == 0)
1023 break; // No more left to read
1025 /* Send this buffer and go read some more */
1026 bh->inreq->zero = 0;
1027 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1028 &bh->inreq_busy, &bh->state);
1029 fsg->common->next_buffhd_to_fill = bh->next;
1032 return -EIO; // No default reply
1036 /*-------------------------------------------------------------------------*/
1038 static int do_write(struct fsg_dev *fsg)
1040 struct fsg_lun *curlun = fsg->common->curlun;
1042 struct fsg_buffhd *bh;
1044 u32 amount_left_to_req, amount_left_to_write;
1045 loff_t usb_offset, file_offset, file_offset_tmp;
1046 unsigned int amount;
1047 unsigned int partial_page;
1052 curlun->sense_data = SS_WRITE_PROTECTED;
1055 spin_lock(&curlun->filp->f_lock);
1056 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1057 spin_unlock(&curlun->filp->f_lock);
1059 /* Get the starting Logical Block Address and check that it's
1061 if (fsg->common->cmnd[0] == SC_WRITE_6)
1062 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
1064 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1066 /* We allow DPO (Disable Page Out = don't save data in the
1067 * cache) and FUA (Force Unit Access = write directly to the
1068 * medium). We don't implement DPO; we implement FUA by
1069 * performing synchronous output. */
1070 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
1071 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1074 if (fsg->common->cmnd[1] & 0x08) { // FUA
1075 spin_lock(&curlun->filp->f_lock);
1076 curlun->filp->f_flags |= O_SYNC;
1077 spin_unlock(&curlun->filp->f_lock);
1080 if (lba >= curlun->num_sectors) {
1081 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1085 /* Carry out the file writes */
1087 file_offset = usb_offset = ((loff_t) lba) << 9;
1088 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1090 while (amount_left_to_write > 0) {
1092 /* Queue a request for more data from the host */
1093 bh = fsg->common->next_buffhd_to_fill;
1094 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1096 /* Figure out how much we want to get:
1097 * Try to get the remaining amount.
1098 * But don't get more than the buffer size.
1099 * And don't try to go past the end of the file.
1100 * If we're not at a page boundary,
1101 * don't go past the next page.
1102 * If this means getting 0, then we were asked
1103 * to write past the end of file.
1104 * Finally, round down to a block boundary. */
1105 amount = min(amount_left_to_req, FSG_BUFLEN);
1106 amount = min((loff_t) amount, curlun->file_length -
1108 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1109 if (partial_page > 0)
1110 amount = min(amount,
1111 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1115 curlun->sense_data =
1116 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1117 curlun->sense_data_info = usb_offset >> 9;
1118 curlun->info_valid = 1;
1121 amount -= (amount & 511);
1124 /* Why were we were asked to transfer a
1130 /* Get the next buffer */
1131 usb_offset += amount;
1132 fsg->usb_amount_left -= amount;
1133 amount_left_to_req -= amount;
1134 if (amount_left_to_req == 0)
1137 /* amount is always divisible by 512, hence by
1138 * the bulk-out maxpacket size */
1139 bh->outreq->length = bh->bulk_out_intended_length =
1141 bh->outreq->short_not_ok = 1;
1142 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1143 &bh->outreq_busy, &bh->state);
1144 fsg->common->next_buffhd_to_fill = bh->next;
1148 /* Write the received data to the backing file */
1149 bh = fsg->common->next_buffhd_to_drain;
1150 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1151 break; // We stopped early
1152 if (bh->state == BUF_STATE_FULL) {
1154 fsg->common->next_buffhd_to_drain = bh->next;
1155 bh->state = BUF_STATE_EMPTY;
1157 /* Did something go wrong with the transfer? */
1158 if (bh->outreq->status != 0) {
1159 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1160 curlun->sense_data_info = file_offset >> 9;
1161 curlun->info_valid = 1;
1165 amount = bh->outreq->actual;
1166 if (curlun->file_length - file_offset < amount) {
1168 "write %u @ %llu beyond end %llu\n",
1169 amount, (unsigned long long) file_offset,
1170 (unsigned long long) curlun->file_length);
1171 amount = curlun->file_length - file_offset;
1174 /* Perform the write */
1175 file_offset_tmp = file_offset;
1176 nwritten = vfs_write(curlun->filp,
1177 (char __user *) bh->buf,
1178 amount, &file_offset_tmp);
1179 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1180 (unsigned long long) file_offset,
1182 if (signal_pending(current))
1183 return -EINTR; // Interrupted!
1186 LDBG(curlun, "error in file write: %d\n",
1189 } else if (nwritten < amount) {
1190 LDBG(curlun, "partial file write: %d/%u\n",
1191 (int) nwritten, amount);
1192 nwritten -= (nwritten & 511);
1193 // Round down to a block
1195 file_offset += nwritten;
1196 amount_left_to_write -= nwritten;
1197 fsg->residue -= nwritten;
1199 /* If an error occurred, report it and its position */
1200 if (nwritten < amount) {
1201 curlun->sense_data = SS_WRITE_ERROR;
1202 curlun->sense_data_info = file_offset >> 9;
1203 curlun->info_valid = 1;
1207 /* Did the host decide to stop early? */
1208 if (bh->outreq->actual != bh->outreq->length) {
1209 fsg->short_packet_received = 1;
1215 /* Wait for something to happen */
1216 rc = sleep_thread(fsg);
1221 return -EIO; // No default reply
1225 /*-------------------------------------------------------------------------*/
1227 static int do_synchronize_cache(struct fsg_dev *fsg)
1229 struct fsg_lun *curlun = fsg->common->curlun;
1232 /* We ignore the requested LBA and write out all file's
1233 * dirty data buffers. */
1234 rc = fsg_lun_fsync_sub(curlun);
1236 curlun->sense_data = SS_WRITE_ERROR;
1241 /*-------------------------------------------------------------------------*/
1243 static void invalidate_sub(struct fsg_lun *curlun)
1245 struct file *filp = curlun->filp;
1246 struct inode *inode = filp->f_path.dentry->d_inode;
1249 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1250 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1253 static int do_verify(struct fsg_dev *fsg)
1255 struct fsg_lun *curlun = fsg->common->curlun;
1257 u32 verification_length;
1258 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1259 loff_t file_offset, file_offset_tmp;
1261 unsigned int amount;
1264 /* Get the starting Logical Block Address and check that it's
1266 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1267 if (lba >= curlun->num_sectors) {
1268 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1272 /* We allow DPO (Disable Page Out = don't save data in the
1273 * cache) but we don't implement it. */
1274 if ((fsg->common->cmnd[1] & ~0x10) != 0) {
1275 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1279 verification_length = get_unaligned_be16(&fsg->common->cmnd[7]);
1280 if (unlikely(verification_length == 0))
1281 return -EIO; // No default reply
1283 /* Prepare to carry out the file verify */
1284 amount_left = verification_length << 9;
1285 file_offset = ((loff_t) lba) << 9;
1287 /* Write out all the dirty buffers before invalidating them */
1288 fsg_lun_fsync_sub(curlun);
1289 if (signal_pending(current))
1292 invalidate_sub(curlun);
1293 if (signal_pending(current))
1296 /* Just try to read the requested blocks */
1297 while (amount_left > 0) {
1299 /* Figure out how much we need to read:
1300 * Try to read the remaining amount, but not more than
1302 * And don't try to read past the end of the file.
1303 * If this means reading 0 then we were asked to read
1304 * past the end of file. */
1305 amount = min(amount_left, FSG_BUFLEN);
1306 amount = min((loff_t) amount,
1307 curlun->file_length - file_offset);
1309 curlun->sense_data =
1310 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1311 curlun->sense_data_info = file_offset >> 9;
1312 curlun->info_valid = 1;
1316 /* Perform the read */
1317 file_offset_tmp = file_offset;
1318 nread = vfs_read(curlun->filp,
1319 (char __user *) bh->buf,
1320 amount, &file_offset_tmp);
1321 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1322 (unsigned long long) file_offset,
1324 if (signal_pending(current))
1328 LDBG(curlun, "error in file verify: %d\n",
1331 } else if (nread < amount) {
1332 LDBG(curlun, "partial file verify: %d/%u\n",
1333 (int) nread, amount);
1334 nread -= (nread & 511); // Round down to a sector
1337 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1338 curlun->sense_data_info = file_offset >> 9;
1339 curlun->info_valid = 1;
1342 file_offset += nread;
1343 amount_left -= nread;
1349 /*-------------------------------------------------------------------------*/
1351 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1353 u8 *buf = (u8 *) bh->buf;
1355 static char vendor_id[] = "Linux ";
1356 static char product_disk_id[] = "File-Stor Gadget";
1357 static char product_cdrom_id[] = "File-CD Gadget ";
1359 if (!fsg->common->curlun) { // Unsupported LUNs are okay
1360 fsg->bad_lun_okay = 1;
1362 buf[0] = 0x7f; // Unsupported, no device-type
1363 buf[4] = 31; // Additional length
1368 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
1369 if (mod_data.removable)
1371 buf[2] = 2; // ANSI SCSI level 2
1372 buf[3] = 2; // SCSI-2 INQUIRY data format
1373 buf[4] = 31; // Additional length
1374 // No special options
1375 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1376 (mod_data.cdrom ? product_cdrom_id :
1383 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1385 struct fsg_lun *curlun = fsg->common->curlun;
1386 u8 *buf = (u8 *) bh->buf;
1391 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1393 * If a REQUEST SENSE command is received from an initiator
1394 * with a pending unit attention condition (before the target
1395 * generates the contingent allegiance condition), then the
1396 * target shall either:
1397 * a) report any pending sense data and preserve the unit
1398 * attention condition on the logical unit, or,
1399 * b) report the unit attention condition, may discard any
1400 * pending sense data, and clear the unit attention
1401 * condition on the logical unit for that initiator.
1403 * FSG normally uses option a); enable this code to use option b).
1406 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1407 curlun->sense_data = curlun->unit_attention_data;
1408 curlun->unit_attention_data = SS_NO_SENSE;
1412 if (!curlun) { // Unsupported LUNs are okay
1413 fsg->bad_lun_okay = 1;
1414 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1418 sd = curlun->sense_data;
1419 sdinfo = curlun->sense_data_info;
1420 valid = curlun->info_valid << 7;
1421 curlun->sense_data = SS_NO_SENSE;
1422 curlun->sense_data_info = 0;
1423 curlun->info_valid = 0;
1427 buf[0] = valid | 0x70; // Valid, current error
1429 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1430 buf[7] = 18 - 8; // Additional sense length
1437 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1439 struct fsg_lun *curlun = fsg->common->curlun;
1440 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1441 int pmi = fsg->common->cmnd[8];
1442 u8 *buf = (u8 *) bh->buf;
1444 /* Check the PMI and LBA fields */
1445 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1446 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1450 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1451 /* Max logical block */
1452 put_unaligned_be32(512, &buf[4]); /* Block length */
1457 static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1459 struct fsg_lun *curlun = fsg->common->curlun;
1460 int msf = fsg->common->cmnd[1] & 0x02;
1461 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1462 u8 *buf = (u8 *) bh->buf;
1464 if ((fsg->common->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1465 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1468 if (lba >= curlun->num_sectors) {
1469 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1474 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1475 store_cdrom_address(&buf[4], msf, lba);
1480 static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1482 struct fsg_lun *curlun = fsg->common->curlun;
1483 int msf = fsg->common->cmnd[1] & 0x02;
1484 int start_track = fsg->common->cmnd[6];
1485 u8 *buf = (u8 *) bh->buf;
1487 if ((fsg->common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1489 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1494 buf[1] = (20-2); /* TOC data length */
1495 buf[2] = 1; /* First track number */
1496 buf[3] = 1; /* Last track number */
1497 buf[5] = 0x16; /* Data track, copying allowed */
1498 buf[6] = 0x01; /* Only track is number 1 */
1499 store_cdrom_address(&buf[8], msf, 0);
1501 buf[13] = 0x16; /* Lead-out track is data */
1502 buf[14] = 0xAA; /* Lead-out track number */
1503 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1508 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1510 struct fsg_lun *curlun = fsg->common->curlun;
1511 int mscmnd = fsg->common->cmnd[0];
1512 u8 *buf = (u8 *) bh->buf;
1515 int changeable_values, all_pages;
1519 if ((fsg->common->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1520 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1523 pc = fsg->common->cmnd[2] >> 6;
1524 page_code = fsg->common->cmnd[2] & 0x3f;
1526 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1529 changeable_values = (pc == 1);
1530 all_pages = (page_code == 0x3f);
1532 /* Write the mode parameter header. Fixed values are: default
1533 * medium type, no cache control (DPOFUA), and no block descriptors.
1534 * The only variable value is the WriteProtect bit. We will fill in
1535 * the mode data length later. */
1537 if (mscmnd == SC_MODE_SENSE_6) {
1538 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1541 } else { // SC_MODE_SENSE_10
1542 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1544 limit = 65535; // Should really be FSG_BUFLEN
1547 /* No block descriptors */
1549 /* The mode pages, in numerical order. The only page we support
1550 * is the Caching page. */
1551 if (page_code == 0x08 || all_pages) {
1553 buf[0] = 0x08; // Page code
1554 buf[1] = 10; // Page length
1555 memset(buf+2, 0, 10); // None of the fields are changeable
1557 if (!changeable_values) {
1558 buf[2] = 0x04; // Write cache enable,
1559 // Read cache not disabled
1560 // No cache retention priorities
1561 put_unaligned_be16(0xffff, &buf[4]);
1562 /* Don't disable prefetch */
1563 /* Minimum prefetch = 0 */
1564 put_unaligned_be16(0xffff, &buf[8]);
1565 /* Maximum prefetch */
1566 put_unaligned_be16(0xffff, &buf[10]);
1567 /* Maximum prefetch ceiling */
1572 /* Check that a valid page was requested and the mode data length
1573 * isn't too long. */
1575 if (!valid_page || len > limit) {
1576 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1580 /* Store the mode data length */
1581 if (mscmnd == SC_MODE_SENSE_6)
1584 put_unaligned_be16(len - 2, buf0);
1589 static int do_start_stop(struct fsg_dev *fsg)
1591 if (!mod_data.removable) {
1592 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
1599 static int do_prevent_allow(struct fsg_dev *fsg)
1601 struct fsg_lun *curlun = fsg->common->curlun;
1604 if (!mod_data.removable) {
1605 curlun->sense_data = SS_INVALID_COMMAND;
1609 prevent = fsg->common->cmnd[4] & 0x01;
1610 if ((fsg->common->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1611 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1615 if (curlun->prevent_medium_removal && !prevent)
1616 fsg_lun_fsync_sub(curlun);
1617 curlun->prevent_medium_removal = prevent;
1622 static int do_read_format_capacities(struct fsg_dev *fsg,
1623 struct fsg_buffhd *bh)
1625 struct fsg_lun *curlun = fsg->common->curlun;
1626 u8 *buf = (u8 *) bh->buf;
1628 buf[0] = buf[1] = buf[2] = 0;
1629 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1632 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1633 /* Number of blocks */
1634 put_unaligned_be32(512, &buf[4]); /* Block length */
1635 buf[4] = 0x02; /* Current capacity */
1640 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1642 struct fsg_lun *curlun = fsg->common->curlun;
1644 /* We don't support MODE SELECT */
1645 curlun->sense_data = SS_INVALID_COMMAND;
1650 /*-------------------------------------------------------------------------*/
1652 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1656 rc = fsg_set_halt(fsg, fsg->bulk_in);
1658 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1660 if (rc != -EAGAIN) {
1661 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1666 /* Wait for a short time and then try again */
1667 if (msleep_interruptible(100) != 0)
1669 rc = usb_ep_set_halt(fsg->bulk_in);
1674 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1678 DBG(fsg, "bulk-in set wedge\n");
1679 rc = usb_ep_set_wedge(fsg->bulk_in);
1681 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1683 if (rc != -EAGAIN) {
1684 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1689 /* Wait for a short time and then try again */
1690 if (msleep_interruptible(100) != 0)
1692 rc = usb_ep_set_wedge(fsg->bulk_in);
1697 static int pad_with_zeros(struct fsg_dev *fsg)
1699 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1700 u32 nkeep = bh->inreq->length;
1704 bh->state = BUF_STATE_EMPTY; // For the first iteration
1705 fsg->usb_amount_left = nkeep + fsg->residue;
1706 while (fsg->usb_amount_left > 0) {
1708 /* Wait for the next buffer to be free */
1709 while (bh->state != BUF_STATE_EMPTY) {
1710 rc = sleep_thread(fsg);
1715 nsend = min(fsg->usb_amount_left, FSG_BUFLEN);
1716 memset(bh->buf + nkeep, 0, nsend - nkeep);
1717 bh->inreq->length = nsend;
1718 bh->inreq->zero = 0;
1719 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1720 &bh->inreq_busy, &bh->state);
1721 bh = fsg->common->next_buffhd_to_fill = bh->next;
1722 fsg->usb_amount_left -= nsend;
1728 static int throw_away_data(struct fsg_dev *fsg)
1730 struct fsg_buffhd *bh;
1734 for (bh = fsg->common->next_buffhd_to_drain;
1735 bh->state != BUF_STATE_EMPTY || fsg->usb_amount_left > 0;
1736 bh = fsg->common->next_buffhd_to_drain) {
1738 /* Throw away the data in a filled buffer */
1739 if (bh->state == BUF_STATE_FULL) {
1741 bh->state = BUF_STATE_EMPTY;
1742 fsg->common->next_buffhd_to_drain = bh->next;
1744 /* A short packet or an error ends everything */
1745 if (bh->outreq->actual != bh->outreq->length ||
1746 bh->outreq->status != 0) {
1747 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1753 /* Try to submit another request if we need one */
1754 bh = fsg->common->next_buffhd_to_fill;
1755 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1756 amount = min(fsg->usb_amount_left, FSG_BUFLEN);
1758 /* amount is always divisible by 512, hence by
1759 * the bulk-out maxpacket size */
1760 bh->outreq->length = bh->bulk_out_intended_length =
1762 bh->outreq->short_not_ok = 1;
1763 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1764 &bh->outreq_busy, &bh->state);
1765 fsg->common->next_buffhd_to_fill = bh->next;
1766 fsg->usb_amount_left -= amount;
1770 /* Otherwise wait for something to happen */
1771 rc = sleep_thread(fsg);
1779 static int finish_reply(struct fsg_dev *fsg)
1781 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1784 switch (fsg->data_dir) {
1786 break; // Nothing to send
1788 /* If we don't know whether the host wants to read or write,
1789 * this must be CB or CBI with an unknown command. We mustn't
1790 * try to send or receive any data. So stall both bulk pipes
1791 * if we can and wait for a reset. */
1792 case DATA_DIR_UNKNOWN:
1793 if (mod_data.can_stall) {
1794 fsg_set_halt(fsg, fsg->bulk_out);
1795 rc = halt_bulk_in_endpoint(fsg);
1799 /* All but the last buffer of data must have already been sent */
1800 case DATA_DIR_TO_HOST:
1801 if (fsg->data_size == 0) {
1802 /* Nothing to send */
1804 /* If there's no residue, simply send the last buffer */
1805 } else if (fsg->residue == 0) {
1806 bh->inreq->zero = 0;
1807 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1808 &bh->inreq_busy, &bh->state);
1809 fsg->common->next_buffhd_to_fill = bh->next;
1811 /* For Bulk-only, if we're allowed to stall then send the
1812 * short packet and halt the bulk-in endpoint. If we can't
1813 * stall, pad out the remaining data with 0's. */
1814 } else if (mod_data.can_stall) {
1815 bh->inreq->zero = 1;
1816 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1817 &bh->inreq_busy, &bh->state);
1818 fsg->common->next_buffhd_to_fill = bh->next;
1819 rc = halt_bulk_in_endpoint(fsg);
1821 rc = pad_with_zeros(fsg);
1825 /* We have processed all we want from the data the host has sent.
1826 * There may still be outstanding bulk-out requests. */
1827 case DATA_DIR_FROM_HOST:
1828 if (fsg->residue == 0)
1829 ; // Nothing to receive
1831 /* Did the host stop sending unexpectedly early? */
1832 else if (fsg->short_packet_received) {
1833 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1837 /* We haven't processed all the incoming data. Even though
1838 * we may be allowed to stall, doing so would cause a race.
1839 * The controller may already have ACK'ed all the remaining
1840 * bulk-out packets, in which case the host wouldn't see a
1841 * STALL. Not realizing the endpoint was halted, it wouldn't
1842 * clear the halt -- leading to problems later on. */
1844 else if (mod_data.can_stall) {
1845 fsg_set_halt(fsg, fsg->bulk_out);
1846 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1851 /* We can't stall. Read in the excess data and throw it
1854 rc = throw_away_data(fsg);
1861 static int send_status(struct fsg_dev *fsg)
1863 struct fsg_lun *curlun = fsg->common->curlun;
1864 struct fsg_buffhd *bh;
1865 struct bulk_cs_wrap *csw;
1867 u8 status = USB_STATUS_PASS;
1870 /* Wait for the next buffer to become available */
1871 bh = fsg->common->next_buffhd_to_fill;
1872 while (bh->state != BUF_STATE_EMPTY) {
1873 rc = sleep_thread(fsg);
1879 sd = curlun->sense_data;
1880 sdinfo = curlun->sense_data_info;
1881 } else if (fsg->bad_lun_okay)
1884 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1886 if (fsg->phase_error) {
1887 DBG(fsg, "sending phase-error status\n");
1888 status = USB_STATUS_PHASE_ERROR;
1889 sd = SS_INVALID_COMMAND;
1890 } else if (sd != SS_NO_SENSE) {
1891 DBG(fsg, "sending command-failure status\n");
1892 status = USB_STATUS_FAIL;
1893 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1895 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1898 /* Store and send the Bulk-only CSW */
1899 csw = (void*)bh->buf;
1901 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;
1906 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);
1911 fsg->common->next_buffhd_to_fill = bh->next;
1916 /*-------------------------------------------------------------------------*/
1918 /* Check whether the command is properly formed and whether its data size
1919 * and direction agree with the values we already have. */
1920 static 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)
1925 int lun = fsg->common->cmnd[1] >> 5;
1926 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1928 struct fsg_lun *curlun;
1931 if (fsg->data_dir != DATA_DIR_UNKNOWN)
1932 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1934 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1935 name, cmnd_size, dirletter[(int) data_dir],
1936 fsg->data_size_from_cmnd, fsg->common->cmnd_size, hdlen);
1938 /* We can't reply at all until we know the correct data direction
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;
1946 } else { // Bulk-only
1947 if (fsg->data_size < fsg->data_size_from_cmnd) {
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;
1956 fsg->residue = fsg->usb_amount_left = fsg->data_size;
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;
1964 /* Verify the length of the command itself */
1965 if (cmnd_size != fsg->common->cmnd_size) {
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
1979 if (cmnd_size <= fsg->common->cmnd_size) {
1980 DBG(fsg, "%s is buggy! Expected length %d "
1981 "but we got %d\n", name,
1982 cmnd_size, fsg->common->cmnd_size);
1983 cmnd_size = fsg->common->cmnd_size;
1985 fsg->phase_error = 1;
1990 /* Check that the LUN values are consistent */
1991 if (fsg->common->lun != lun)
1992 DBG(fsg, "using LUN %d from CBW, not LUN %d from CDB\n",
1993 fsg->common->lun, lun);
1996 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) {
1999 curlun->sense_data = SS_NO_SENSE;
2000 curlun->sense_data_info = 0;
2001 curlun->info_valid = 0;
2004 fsg->common->curlun = curlun = NULL;
2005 fsg->bad_lun_okay = 0;
2007 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2008 * to use unsupported LUNs; all others may not. */
2009 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);
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 &&
2019 fsg->common->cmnd[0] != SC_INQUIRY &&
2020 fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2021 curlun->sense_data = curlun->unit_attention_data;
2022 curlun->unit_attention_data = SS_NO_SENSE;
2026 /* Check that only command bytes listed in the mask are non-zero */
2027 fsg->common->cmnd[1] &= 0x1f; // Mask away the LUN
2028 for (i = 1; i < cmnd_size; ++i) {
2029 if (fsg->common->cmnd[i] && !(mask & (1 << i))) {
2031 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
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;
2047 static int do_scsi_command(struct fsg_dev *fsg)
2049 struct fsg_buffhd *bh;
2051 int reply = -EINVAL;
2053 static char unknown[16];
2055 dump_cdb(fsg->common);
2057 /* Wait for the next buffer to become available for data or status */
2058 bh = fsg->common->next_buffhd_to_drain = fsg->common->next_buffhd_to_fill;
2059 while (bh->state != BUF_STATE_EMPTY) {
2060 rc = sleep_thread(fsg);
2064 fsg->phase_error = 0;
2065 fsg->short_packet_received = 0;
2067 down_read(&fsg->common->filesem); // We're using the backing file
2068 switch (fsg->common->cmnd[0]) {
2071 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2072 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2075 reply = do_inquiry(fsg, bh);
2078 case SC_MODE_SELECT_6:
2079 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2080 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2082 "MODE SELECT(6)")) == 0)
2083 reply = do_mode_select(fsg, bh);
2086 case SC_MODE_SELECT_10:
2087 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2088 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2090 "MODE SELECT(10)")) == 0)
2091 reply = do_mode_select(fsg, bh);
2094 case SC_MODE_SENSE_6:
2095 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2096 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);
2102 case SC_MODE_SENSE_10:
2103 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2104 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);
2110 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2111 fsg->data_size_from_cmnd = 0;
2112 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2114 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2115 reply = do_prevent_allow(fsg);
2119 i = fsg->common->cmnd[4];
2120 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2121 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2124 reply = do_read(fsg);
2128 fsg->data_size_from_cmnd =
2129 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
2130 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2131 (1<<1) | (0xf<<2) | (3<<7), 1,
2133 reply = do_read(fsg);
2137 fsg->data_size_from_cmnd =
2138 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
2139 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2140 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2142 reply = do_read(fsg);
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);
2153 case SC_READ_HEADER:
2154 if (!mod_data.cdrom)
2156 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2157 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);
2164 if (!mod_data.cdrom)
2166 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2167 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2170 reply = do_read_toc(fsg, bh);
2173 case SC_READ_FORMAT_CAPACITIES:
2174 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2175 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2177 "READ FORMAT CAPACITIES")) == 0)
2178 reply = do_read_format_capacities(fsg, bh);
2181 case SC_REQUEST_SENSE:
2182 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2183 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2185 "REQUEST SENSE")) == 0)
2186 reply = do_request_sense(fsg, bh);
2189 case SC_START_STOP_UNIT:
2190 fsg->data_size_from_cmnd = 0;
2191 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2193 "START-STOP UNIT")) == 0)
2194 reply = do_start_stop(fsg);
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);
2205 case SC_TEST_UNIT_READY:
2206 fsg->data_size_from_cmnd = 0;
2207 reply = check_command(fsg, 6, DATA_DIR_NONE,
2212 /* Although optional, this command is used by MS-Windows. We
2213 * support a minimal version: BytChk must be 0. */
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,
2219 reply = do_verify(fsg);
2223 i = fsg->common->cmnd[4];
2224 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2225 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2228 reply = do_write(fsg);
2232 fsg->data_size_from_cmnd =
2233 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
2234 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2235 (1<<1) | (0xf<<2) | (3<<7), 1,
2237 reply = do_write(fsg);
2241 fsg->data_size_from_cmnd =
2242 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
2243 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2244 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2246 reply = do_write(fsg);
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:
2256 case SC_SEND_DIAGNOSTIC:
2261 fsg->data_size_from_cmnd = 0;
2262 sprintf(unknown, "Unknown x%02x", fsg->common->cmnd[0]);
2263 if ((reply = check_command(fsg, fsg->common->cmnd_size,
2264 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2265 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
2270 up_read(&fsg->common->filesem);
2272 if (reply == -EINTR || signal_pending(current))
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
2289 /*-------------------------------------------------------------------------*/
2291 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2293 struct usb_request *req = bh->outreq;
2294 struct fsg_bulk_cb_wrap *cbw = req->buf;
2296 /* Was this a real packet? Should it be ignored? */
2297 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2300 /* Is the CBW valid? */
2301 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2302 cbw->Signature != cpu_to_le32(
2304 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2306 le32_to_cpu(cbw->Signature));
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.
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);
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, "
2327 cbw->Lun, cbw->Flags, cbw->Length);
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);
2338 /* Save the command for later */
2339 fsg->common->cmnd_size = cbw->Length;
2340 memcpy(fsg->common->cmnd, cbw->CDB, fsg->common->cmnd_size);
2341 if (cbw->Flags & USB_BULK_IN_FLAG)
2342 fsg->data_dir = DATA_DIR_TO_HOST;
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;
2348 fsg->common->lun = cbw->Lun;
2349 fsg->tag = cbw->Tag;
2354 static int get_next_command(struct fsg_dev *fsg)
2356 struct fsg_buffhd *bh;
2359 /* Wait for the next buffer to become available */
2360 bh = fsg->common->next_buffhd_to_fill;
2361 while (bh->state != BUF_STATE_EMPTY) {
2362 rc = sleep_thread(fsg);
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);
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. */
2377 /* Wait for the CBW to arrive */
2378 while (bh->state != BUF_STATE_FULL) {
2379 rc = sleep_thread(fsg);
2384 rc = received_cbw(fsg, bh);
2385 bh->state = BUF_STATE_EMPTY;
2391 /*-------------------------------------------------------------------------*/
2393 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2394 const struct usb_endpoint_descriptor *d)
2398 ep->driver_data = fsg;
2399 rc = usb_ep_enable(ep, d);
2401 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2405 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2406 struct usb_request **preq)
2408 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2411 ERROR(fsg, "can't allocate request for %s\n", ep->name);
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.
2420 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2424 const struct usb_endpoint_descriptor *d;
2427 DBG(fsg, "reset interface\n");
2430 /* Deallocate the requests */
2431 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2432 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
2435 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2439 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2444 /* Disable the endpoints */
2445 if (fsg->bulk_in_enabled) {
2446 usb_ep_disable(fsg->bulk_in);
2447 fsg->bulk_in_enabled = 0;
2449 if (fsg->bulk_out_enabled) {
2450 usb_ep_disable(fsg->bulk_out);
2451 fsg->bulk_out_enabled = 0;
2455 if (altsetting < 0 || rc != 0)
2458 DBG(fsg, "set interface %d\n", altsetting);
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)
2465 fsg->bulk_in_enabled = 1;
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)
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);
2475 /* Allocate the requests */
2476 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2477 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
2479 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2481 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
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;
2490 for (i = 0; i < fsg->common->nluns; ++i)
2491 fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2497 * Change our operational configuration. This code must agree with the code
2498 * that returns config descriptors, and with interface altsetting code.
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.
2504 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2508 /* Disable the single interface */
2509 if (fsg->config != 0) {
2510 DBG(fsg, "reset config\n");
2512 rc = do_set_interface(fsg, -1);
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
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;
2529 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2536 /*-------------------------------------------------------------------------*/
2538 static void handle_exception(struct fsg_dev *fsg)
2543 struct fsg_buffhd *bh;
2544 enum fsg_state old_state;
2546 struct fsg_lun *curlun;
2547 unsigned int exception_req_tag;
2550 /* Clear the existing signals. Anything but SIGUSR1 is converted
2551 * into a high-priority EXIT exception. */
2553 sig = dequeue_signal_lock(current, ¤t->blocked, &info);
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);
2563 /* Cancel all the pending transfers */
2564 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2565 bh = &fsg->common->buffhds[i];
2567 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2568 if (bh->outreq_busy)
2569 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2572 /* Wait until everything is idle */
2575 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2576 bh = &fsg->common->buffhds[i];
2577 num_active += bh->inreq_busy + bh->outreq_busy;
2579 if (num_active == 0)
2581 if (sleep_thread(fsg))
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);
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);
2595 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2596 bh = &fsg->common->buffhds[i];
2597 bh->state = BUF_STATE_EMPTY;
2599 fsg->common->next_buffhd_to_fill = fsg->common->next_buffhd_to_drain =
2600 &fsg->common->buffhds[0];
2602 exception_req_tag = fsg->exception_req_tag;
2603 new_config = fsg->new_config;
2604 old_state = fsg->state;
2606 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2607 fsg->state = FSG_STATE_STATUS_PHASE;
2609 for (i = 0; i < fsg->common->nluns; ++i) {
2610 curlun = &fsg->common->luns[i];
2611 curlun->prevent_medium_removal = 0;
2612 curlun->sense_data = curlun->unit_attention_data =
2614 curlun->sense_data_info = 0;
2615 curlun->info_valid = 0;
2617 fsg->state = FSG_STATE_IDLE;
2619 spin_unlock_irq(&fsg->lock);
2621 /* Carry out any extra actions required for the exception */
2622 switch (old_state) {
2626 case FSG_STATE_ABORT_BULK_OUT:
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);
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);
2641 if (fsg->ep0_req_tag == exception_req_tag)
2642 ep0_queue(fsg); // Complete the status stage
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. */
2647 // for (i = 0; i < fsg->common->nluns; ++i)
2648 // fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2651 case FSG_STATE_INTERFACE_CHANGE:
2652 rc = do_set_interface(fsg, 0);
2653 if (fsg->ep0_req_tag != exception_req_tag)
2655 if (rc != 0) // STALL on errors
2656 fsg_set_halt(fsg, fsg->ep0);
2657 else // Complete the status stage
2661 case FSG_STATE_CONFIG_CHANGE:
2662 rc = do_set_config(fsg, new_config);
2663 if (fsg->ep0_req_tag != exception_req_tag)
2665 if (rc != 0) // STALL on errors
2666 fsg_set_halt(fsg, fsg->ep0);
2667 else // Complete the status stage
2671 case FSG_STATE_DISCONNECT:
2672 for (i = 0; i < fsg->common->nluns; ++i)
2673 fsg_lun_fsync_sub(&fsg->common->luns[i]);
2674 do_set_config(fsg, 0); // Unconfigured state
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);
2688 /*-------------------------------------------------------------------------*/
2690 static int fsg_main_thread(void *fsg_)
2692 struct fsg_dev *fsg = fsg_;
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);
2701 /* Allow the thread to be frozen */
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. */
2710 while (fsg->state != FSG_STATE_TERMINATED) {
2711 if (exception_in_progress(fsg) || signal_pending(current)) {
2712 handle_exception(fsg);
2716 if (!fsg->running) {
2721 if (get_next_command(fsg))
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);
2729 if (do_scsi_command(fsg) || finish_reply(fsg))
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);
2737 if (send_status(fsg))
2740 spin_lock_irq(&fsg->lock);
2741 if (!exception_in_progress(fsg))
2742 fsg->state = FSG_STATE_IDLE;
2743 spin_unlock_irq(&fsg->lock);
2746 spin_lock_irq(&fsg->lock);
2747 fsg->thread_task = NULL;
2748 spin_unlock_irq(&fsg->lock);
2750 /* If we are exiting because of a signal, unregister the
2752 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2753 usb_gadget_unregister_driver(&fsg_driver);
2755 /* Let the unbind and cleanup routines know the thread has exited */
2756 complete_and_exit(&fsg->thread_notifier, 0);
2760 /*-------------------------------------------------------------------------*/
2763 /* The write permissions and store_xxx pointers are set in fsg_bind() */
2764 static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
2765 static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
2768 /*-------------------------------------------------------------------------*/
2770 static void fsg_release(struct fsg_dev *fsg)
2772 kfree(fsg->common->luns);
2776 static void lun_release(struct device *dev)
2780 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
2782 struct fsg_dev *fsg = get_gadget_data(gadget);
2784 struct fsg_lun *curlun;
2785 struct usb_request *req = fsg->ep0req;
2787 DBG(fsg, "unbind\n");
2788 clear_bit(REGISTERED, &fsg->atomic_bitflags);
2790 /* Unregister the sysfs attribute files and the LUNs */
2791 for (i = 0; i < fsg->common->nluns; ++i) {
2792 curlun = &fsg->common->luns[i];
2793 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;
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);
2807 /* The cleanup routine waits for this completion also */
2808 complete(&fsg->thread_notifier);
2811 /* Free the request and buffer for endpoint 0 */
2814 usb_ep_free_request(fsg->ep0, req);
2817 set_gadget_data(gadget, NULL);
2821 static int __init check_parameters(struct fsg_dev *fsg)
2825 /* Some peripheral controllers are known not to be able to
2826 * halt bulk endpoints correctly. If one of them is present,
2829 if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
2830 mod_data.can_stall = 0;
2832 if (mod_data.release == 0xffff) { // Parameter wasn't set
2833 /* The sa1100 controller is not supported */
2834 if (gadget_is_sa1100(fsg->gadget))
2837 gcnum = usb_gadget_controller_number(fsg->gadget);
2839 mod_data.release = 0x0300 + gcnum;
2841 WARNING(fsg, "controller '%s' not recognized\n",
2843 mod_data.release = 0x0399;
2851 static int __init fsg_bind(struct usb_gadget *gadget)
2853 struct fsg_dev *fsg = the_fsg;
2856 struct fsg_lun *curlun;
2858 struct usb_request *req;
2861 fsg->gadget = gadget;
2862 set_gadget_data(gadget, fsg);
2863 fsg->ep0 = gadget->ep0;
2864 fsg->ep0->driver_data = fsg;
2866 if ((rc = check_parameters(fsg)) != 0)
2869 if (mod_data.removable) { // Enable the store_xxx attributes
2870 dev_attr_file.attr.mode = 0644;
2871 dev_attr_file.store = fsg_store_file;
2872 if (!mod_data.cdrom) {
2873 dev_attr_ro.attr.mode = 0644;
2874 dev_attr_ro.store = fsg_store_ro;
2878 /* Find out how many LUNs there should be */
2881 i = max(mod_data.num_filenames, 1u);
2882 if (i > FSG_MAX_LUNS) {
2883 ERROR(fsg, "invalid number of LUNs: %d\n", i);
2888 /* Create the LUNs, open their backing files, and register the
2889 * LUN devices in sysfs. */
2890 fsg->common->luns = kzalloc(i * sizeof(struct fsg_lun), GFP_KERNEL);
2891 if (!fsg->common->luns) {
2895 fsg->common->nluns = i;
2897 for (i = 0; i < fsg->common->nluns; ++i) {
2898 curlun = &fsg->common->luns[i];
2899 curlun->cdrom = !!mod_data.cdrom;
2900 curlun->ro = mod_data.cdrom || mod_data.ro[i];
2901 curlun->initially_ro = curlun->ro;
2902 curlun->removable = mod_data.removable;
2903 curlun->dev.release = lun_release;
2904 curlun->dev.parent = &gadget->dev;
2905 curlun->dev.driver = &fsg_driver.driver;
2906 dev_set_drvdata(&curlun->dev, &fsg->common->filesem);
2907 dev_set_name(&curlun->dev,"%s-lun%d",
2908 dev_name(&gadget->dev), i);
2910 if ((rc = device_register(&curlun->dev)) != 0) {
2911 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
2914 if ((rc = device_create_file(&curlun->dev,
2915 &dev_attr_ro)) != 0 ||
2916 (rc = device_create_file(&curlun->dev,
2917 &dev_attr_file)) != 0) {
2918 device_unregister(&curlun->dev);
2921 curlun->registered = 1;
2923 if (mod_data.file[i] && *mod_data.file[i]) {
2924 if ((rc = fsg_lun_open(curlun,
2925 mod_data.file[i])) != 0)
2927 } else if (!mod_data.removable) {
2928 ERROR(fsg, "no file given for LUN%d\n", i);
2934 /* Find all the endpoints we will use */
2935 usb_ep_autoconfig_reset(gadget);
2936 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2939 ep->driver_data = fsg; // claim the endpoint
2942 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2945 ep->driver_data = fsg; // claim the endpoint
2948 /* Fix up the descriptors */
2949 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
2950 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
2952 if (gadget_is_dualspeed(gadget)) {
2953 /* Assume ep0 uses the same maxpacket value for both speeds */
2954 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
2956 /* Assume endpoint addresses are the same for both speeds */
2957 fsg_hs_bulk_in_desc.bEndpointAddress =
2958 fsg_fs_bulk_in_desc.bEndpointAddress;
2959 fsg_hs_bulk_out_desc.bEndpointAddress =
2960 fsg_fs_bulk_out_desc.bEndpointAddress;
2963 if (gadget_is_otg(gadget))
2964 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
2968 /* Allocate the request and buffer for endpoint 0 */
2969 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
2972 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
2975 req->complete = ep0_complete;
2977 /* This should reflect the actual gadget power source */
2978 usb_gadget_set_selfpowered(gadget);
2980 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
2982 init_utsname()->sysname, init_utsname()->release,
2985 /* On a real device, serial[] would be loaded from permanent
2986 * storage. We just encode it from the driver version string. */
2987 for (i = 0; i < sizeof fsg_string_serial - 2; i += 2) {
2988 unsigned char c = DRIVER_VERSION[i / 2];
2992 sprintf(&fsg_string_serial[i], "%02X", c);
2995 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
2996 "file-storage-gadget");
2997 if (IS_ERR(fsg->thread_task)) {
2998 rc = PTR_ERR(fsg->thread_task);
3002 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3003 INFO(fsg, "Number of LUNs=%d\n", fsg->common->nluns);
3005 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3006 for (i = 0; i < fsg->common->nluns; ++i) {
3007 curlun = &fsg->common->luns[i];
3008 if (fsg_lun_is_open(curlun)) {
3011 p = d_path(&curlun->filp->f_path,
3016 LINFO(curlun, "ro=%d, file: %s\n",
3017 curlun->ro, (p ? p : "(error)"));
3022 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3023 mod_data.removable, mod_data.can_stall,
3024 mod_data.cdrom, FSG_BUFLEN);
3025 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
3027 set_bit(REGISTERED, &fsg->atomic_bitflags);
3029 /* Tell the thread to start working */
3030 wake_up_process(fsg->thread_task);
3034 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3038 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3040 complete(&fsg->thread_notifier);
3045 /*-------------------------------------------------------------------------*/
3047 static struct usb_gadget_driver fsg_driver = {
3048 #ifdef CONFIG_USB_GADGET_DUALSPEED
3049 .speed = USB_SPEED_HIGH,
3051 .speed = USB_SPEED_FULL,
3053 .function = (char *) fsg_string_product,
3055 .unbind = fsg_unbind,
3056 .disconnect = fsg_disconnect,
3060 .name = DRIVER_NAME,
3061 .owner = THIS_MODULE,
3069 static int __init fsg_alloc(void)
3071 struct fsg_dev *fsg;
3072 struct fsg_buffhd *bh;
3075 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3079 fsg->common = kzalloc(sizeof *fsg->common, GFP_KERNEL);
3085 bh = fsg->common->buffhds;
3086 i = FSG_NUM_BUFFERS - 1;
3089 } while (++bh, --i);
3090 bh->next = fsg->common->buffhds;
3092 spin_lock_init(&fsg->lock);
3093 init_rwsem(&fsg->common->filesem);
3094 init_completion(&fsg->thread_notifier);
3101 static int __init fsg_init(void)
3104 struct fsg_dev *fsg;
3106 if ((rc = fsg_alloc()) != 0)
3109 if ((rc = usb_gadget_register_driver(&fsg_driver)) != 0)
3113 module_init(fsg_init);
3116 static void __exit fsg_cleanup(void)
3118 struct fsg_dev *fsg = the_fsg;
3120 /* Unregister the driver iff the thread hasn't already done so */
3121 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
3122 usb_gadget_unregister_driver(&fsg_driver);
3124 /* Wait for the thread to finish up */
3125 wait_for_completion(&fsg->thread_notifier);
3129 module_exit(fsg_cleanup);