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 struct usb_gadget *gadget;
328 /* filesem protects: backing files in use */
329 struct rw_semaphore filesem;
331 struct fsg_buffhd *next_buffhd_to_fill;
332 struct fsg_buffhd *next_buffhd_to_drain;
333 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
336 u8 cmnd[MAX_COMMAND_SIZE];
340 struct fsg_lun *luns;
341 struct fsg_lun *curlun;
343 unsigned int free_storage_on_release:1;
350 struct fsg_common *common;
352 /* lock protects: state, all the req_busy's */
354 struct usb_gadget *gadget;
356 struct usb_ep *ep0; // Handy copy of gadget->ep0
357 struct usb_request *ep0req; // For control responses
358 unsigned int ep0_req_tag;
359 const char *ep0req_name;
361 unsigned int bulk_out_maxpacket;
362 enum fsg_state state; // For exception handling
363 unsigned int exception_req_tag;
365 u8 config, new_config;
367 unsigned int running : 1;
368 unsigned int bulk_in_enabled : 1;
369 unsigned int bulk_out_enabled : 1;
370 unsigned int phase_error : 1;
371 unsigned int short_packet_received : 1;
372 unsigned int bad_lun_okay : 1;
374 unsigned long atomic_bitflags;
376 #define IGNORE_BULK_OUT 1
378 struct usb_ep *bulk_in;
379 struct usb_ep *bulk_out;
381 int thread_wakeup_needed;
382 struct completion thread_notifier;
383 struct task_struct *thread_task;
385 enum data_direction data_dir;
387 u32 data_size_from_cmnd;
393 typedef void (*fsg_routine_t)(struct fsg_dev *);
395 static int exception_in_progress(struct fsg_dev *fsg)
397 return (fsg->state > FSG_STATE_IDLE);
400 /* Make bulk-out requests be divisible by the maxpacket size */
401 static void set_bulk_out_req_length(struct fsg_dev *fsg,
402 struct fsg_buffhd *bh, unsigned int length)
406 bh->bulk_out_intended_length = length;
407 rem = length % fsg->bulk_out_maxpacket;
409 length += fsg->bulk_out_maxpacket - rem;
410 bh->outreq->length = length;
413 static struct fsg_dev *the_fsg;
414 static struct usb_gadget_driver fsg_driver;
417 /*-------------------------------------------------------------------------*/
419 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
423 if (ep == fsg->bulk_in)
425 else if (ep == fsg->bulk_out)
429 DBG(fsg, "%s set halt\n", name);
430 return usb_ep_set_halt(ep);
434 /*-------------------------------------------------------------------------*/
437 * DESCRIPTORS ... most are static, but strings and (full) configuration
438 * descriptors are built on demand. Also the (static) config and interface
439 * descriptors are adjusted during fsg_bind().
442 /* There is only one configuration. */
443 #define CONFIG_VALUE 1
445 static struct usb_device_descriptor
447 .bLength = sizeof device_desc,
448 .bDescriptorType = USB_DT_DEVICE,
450 .bcdUSB = cpu_to_le16(0x0200),
451 .bDeviceClass = USB_CLASS_PER_INTERFACE,
453 /* The next three values can be overridden by module parameters */
454 .idVendor = cpu_to_le16(FSG_VENDOR_ID),
455 .idProduct = cpu_to_le16(FSG_PRODUCT_ID),
456 .bcdDevice = cpu_to_le16(0xffff),
458 .iManufacturer = FSG_STRING_MANUFACTURER,
459 .iProduct = FSG_STRING_PRODUCT,
460 .iSerialNumber = FSG_STRING_SERIAL,
461 .bNumConfigurations = 1,
464 static struct usb_config_descriptor
466 .bLength = sizeof config_desc,
467 .bDescriptorType = USB_DT_CONFIG,
469 /* wTotalLength computed by usb_gadget_config_buf() */
471 .bConfigurationValue = CONFIG_VALUE,
472 .iConfiguration = FSG_STRING_CONFIG,
473 .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
474 .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
478 static struct usb_qualifier_descriptor
480 .bLength = sizeof dev_qualifier,
481 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
483 .bcdUSB = cpu_to_le16(0x0200),
484 .bDeviceClass = USB_CLASS_PER_INTERFACE,
486 .bNumConfigurations = 1,
492 * Config descriptors must agree with the code that sets configurations
493 * and with code managing interfaces and their altsettings. They must
494 * also handle different speeds and other-speed requests.
496 static int populate_config_buf(struct usb_gadget *gadget,
497 u8 *buf, u8 type, unsigned index)
499 enum usb_device_speed speed = gadget->speed;
501 const struct usb_descriptor_header **function;
506 if (gadget_is_dualspeed(gadget) && type == USB_DT_OTHER_SPEED_CONFIG)
507 speed = (USB_SPEED_FULL + USB_SPEED_HIGH) - speed;
508 if (gadget_is_dualspeed(gadget) && speed == USB_SPEED_HIGH)
509 function = fsg_hs_function;
511 function = fsg_fs_function;
513 /* for now, don't advertise srp-only devices */
514 if (!gadget_is_otg(gadget))
517 len = usb_gadget_config_buf(&config_desc, buf, EP0_BUFSIZE, function);
518 ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
523 /*-------------------------------------------------------------------------*/
525 /* These routines may be called in process context or in_irq */
527 /* Caller must hold fsg->lock */
528 static void wakeup_thread(struct fsg_dev *fsg)
530 /* Tell the main thread that something has happened */
531 fsg->thread_wakeup_needed = 1;
532 if (fsg->thread_task)
533 wake_up_process(fsg->thread_task);
537 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
541 /* Do nothing if a higher-priority exception is already in progress.
542 * If a lower-or-equal priority exception is in progress, preempt it
543 * and notify the main thread by sending it a signal. */
544 spin_lock_irqsave(&fsg->lock, flags);
545 if (fsg->state <= new_state) {
546 fsg->exception_req_tag = fsg->ep0_req_tag;
547 fsg->state = new_state;
548 if (fsg->thread_task)
549 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
552 spin_unlock_irqrestore(&fsg->lock, flags);
556 /*-------------------------------------------------------------------------*/
558 /* The disconnect callback and ep0 routines. These always run in_irq,
559 * except that ep0_queue() is called in the main thread to acknowledge
560 * completion of various requests: set config, set interface, and
561 * Bulk-only device reset. */
563 static void fsg_disconnect(struct usb_gadget *gadget)
565 struct fsg_dev *fsg = get_gadget_data(gadget);
567 DBG(fsg, "disconnect or port reset\n");
568 raise_exception(fsg, FSG_STATE_DISCONNECT);
572 static int ep0_queue(struct fsg_dev *fsg)
576 rc = usb_ep_queue(fsg->ep0, fsg->ep0req, GFP_ATOMIC);
577 if (rc != 0 && rc != -ESHUTDOWN) {
579 /* We can't do much more than wait for a reset */
580 WARNING(fsg, "error in submission: %s --> %d\n",
586 static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
588 struct fsg_dev *fsg = ep->driver_data;
591 dump_msg(fsg, fsg->ep0req_name, req->buf, req->actual);
592 if (req->status || req->actual != req->length)
593 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
594 req->status, req->actual, req->length);
595 if (req->status == -ECONNRESET) // Request was cancelled
596 usb_ep_fifo_flush(ep);
598 if (req->status == 0 && req->context)
599 ((fsg_routine_t) (req->context))(fsg);
603 /*-------------------------------------------------------------------------*/
605 /* Bulk and interrupt endpoint completion handlers.
606 * These always run in_irq. */
608 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
610 struct fsg_dev *fsg = ep->driver_data;
611 struct fsg_buffhd *bh = req->context;
613 if (req->status || req->actual != req->length)
614 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
615 req->status, req->actual, req->length);
616 if (req->status == -ECONNRESET) // Request was cancelled
617 usb_ep_fifo_flush(ep);
619 /* Hold the lock while we update the request and buffer states */
621 spin_lock(&fsg->lock);
623 bh->state = BUF_STATE_EMPTY;
625 spin_unlock(&fsg->lock);
628 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
630 struct fsg_dev *fsg = ep->driver_data;
631 struct fsg_buffhd *bh = req->context;
633 dump_msg(fsg, "bulk-out", req->buf, req->actual);
634 if (req->status || req->actual != bh->bulk_out_intended_length)
635 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
636 req->status, req->actual,
637 bh->bulk_out_intended_length);
638 if (req->status == -ECONNRESET) // Request was cancelled
639 usb_ep_fifo_flush(ep);
641 /* Hold the lock while we update the request and buffer states */
643 spin_lock(&fsg->lock);
645 bh->state = BUF_STATE_FULL;
647 spin_unlock(&fsg->lock);
651 /*-------------------------------------------------------------------------*/
653 /* Ep0 class-specific handlers. These always run in_irq. */
655 static int class_setup_req(struct fsg_dev *fsg,
656 const struct usb_ctrlrequest *ctrl)
658 struct usb_request *req = fsg->ep0req;
659 u16 w_index = le16_to_cpu(ctrl->wIndex);
660 u16 w_value = le16_to_cpu(ctrl->wValue);
661 u16 w_length = le16_to_cpu(ctrl->wLength);
666 switch (ctrl->bRequest) {
668 case USB_BULK_RESET_REQUEST:
669 if (ctrl->bRequestType !=
670 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
672 if (w_index != 0 || w_value != 0)
675 /* Raise an exception to stop the current operation
676 * and reinitialize our state. */
677 DBG(fsg, "bulk reset request\n");
678 raise_exception(fsg, FSG_STATE_RESET);
679 return DELAYED_STATUS;
681 case USB_BULK_GET_MAX_LUN_REQUEST:
682 if (ctrl->bRequestType !=
683 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
685 if (w_index != 0 || w_value != 0)
687 VDBG(fsg, "get max LUN\n");
688 *(u8 *) req->buf = fsg->common->nluns - 1;
693 "unknown class-specific control req "
694 "%02x.%02x v%04x i%04x l%u\n",
695 ctrl->bRequestType, ctrl->bRequest,
696 le16_to_cpu(ctrl->wValue), w_index, w_length);
701 /*-------------------------------------------------------------------------*/
703 /* Ep0 standard request handlers. These always run in_irq. */
705 static int standard_setup_req(struct fsg_dev *fsg,
706 const struct usb_ctrlrequest *ctrl)
708 struct usb_request *req = fsg->ep0req;
709 int value = -EOPNOTSUPP;
710 u16 w_index = le16_to_cpu(ctrl->wIndex);
711 u16 w_value = le16_to_cpu(ctrl->wValue);
713 /* Usually this just stores reply data in the pre-allocated ep0 buffer,
714 * but config change events will also reconfigure hardware. */
715 switch (ctrl->bRequest) {
717 case USB_REQ_GET_DESCRIPTOR:
718 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
721 switch (w_value >> 8) {
724 VDBG(fsg, "get device descriptor\n");
725 value = sizeof device_desc;
726 memcpy(req->buf, &device_desc, value);
728 case USB_DT_DEVICE_QUALIFIER:
729 VDBG(fsg, "get device qualifier\n");
730 if (!gadget_is_dualspeed(fsg->gadget))
732 value = sizeof dev_qualifier;
733 memcpy(req->buf, &dev_qualifier, value);
736 case USB_DT_OTHER_SPEED_CONFIG:
737 VDBG(fsg, "get other-speed config descriptor\n");
738 if (!gadget_is_dualspeed(fsg->gadget))
742 VDBG(fsg, "get configuration descriptor\n");
744 value = populate_config_buf(fsg->gadget,
751 VDBG(fsg, "get string descriptor\n");
753 /* wIndex == language code */
754 value = usb_gadget_get_string(&fsg_stringtab,
755 w_value & 0xff, req->buf);
760 /* One config, two speeds */
761 case USB_REQ_SET_CONFIGURATION:
762 if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD |
765 VDBG(fsg, "set configuration\n");
766 if (w_value == CONFIG_VALUE || w_value == 0) {
767 fsg->new_config = w_value;
769 /* Raise an exception to wipe out previous transaction
770 * state (queued bufs, etc) and set the new config. */
771 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
772 value = DELAYED_STATUS;
775 case USB_REQ_GET_CONFIGURATION:
776 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
779 VDBG(fsg, "get configuration\n");
780 *(u8 *) req->buf = fsg->config;
784 case USB_REQ_SET_INTERFACE:
785 if (ctrl->bRequestType != (USB_DIR_OUT| USB_TYPE_STANDARD |
786 USB_RECIP_INTERFACE))
788 if (fsg->config && w_index == 0) {
790 /* Raise an exception to wipe out previous transaction
791 * state (queued bufs, etc) and install the new
792 * interface altsetting. */
793 raise_exception(fsg, FSG_STATE_INTERFACE_CHANGE);
794 value = DELAYED_STATUS;
797 case USB_REQ_GET_INTERFACE:
798 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_STANDARD |
799 USB_RECIP_INTERFACE))
807 VDBG(fsg, "get interface\n");
808 *(u8 *) req->buf = 0;
814 "unknown control req %02x.%02x v%04x i%04x l%u\n",
815 ctrl->bRequestType, ctrl->bRequest,
816 w_value, w_index, le16_to_cpu(ctrl->wLength));
823 static int fsg_setup(struct usb_gadget *gadget,
824 const struct usb_ctrlrequest *ctrl)
826 struct fsg_dev *fsg = get_gadget_data(gadget);
828 int w_length = le16_to_cpu(ctrl->wLength);
830 ++fsg->ep0_req_tag; // Record arrival of a new request
831 fsg->ep0req->context = NULL;
832 fsg->ep0req->length = 0;
833 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
835 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS)
836 rc = class_setup_req(fsg, ctrl);
838 rc = standard_setup_req(fsg, ctrl);
840 /* Respond with data/status or defer until later? */
841 if (rc >= 0 && rc != DELAYED_STATUS) {
842 rc = min(rc, w_length);
843 fsg->ep0req->length = rc;
844 fsg->ep0req->zero = rc < w_length;
845 fsg->ep0req_name = (ctrl->bRequestType & USB_DIR_IN ?
846 "ep0-in" : "ep0-out");
850 /* Device either stalls (rc < 0) or reports success */
855 /*-------------------------------------------------------------------------*/
857 /* All the following routines run in process context */
860 /* Use this for bulk or interrupt transfers, not ep0 */
861 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
862 struct usb_request *req, int *pbusy,
863 enum fsg_buffer_state *state)
867 if (ep == fsg->bulk_in)
868 dump_msg(fsg, "bulk-in", req->buf, req->length);
870 spin_lock_irq(&fsg->lock);
872 *state = BUF_STATE_BUSY;
873 spin_unlock_irq(&fsg->lock);
874 rc = usb_ep_queue(ep, req, GFP_KERNEL);
877 *state = BUF_STATE_EMPTY;
879 /* We can't do much more than wait for a reset */
881 /* Note: currently the net2280 driver fails zero-length
882 * submissions if DMA is enabled. */
883 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
885 WARNING(fsg, "error in submission: %s --> %d\n",
891 static int sleep_thread(struct fsg_dev *fsg)
895 /* Wait until a signal arrives or we are woken up */
898 set_current_state(TASK_INTERRUPTIBLE);
899 if (signal_pending(current)) {
903 if (fsg->thread_wakeup_needed)
907 __set_current_state(TASK_RUNNING);
908 fsg->thread_wakeup_needed = 0;
913 /*-------------------------------------------------------------------------*/
915 static int do_read(struct fsg_dev *fsg)
917 struct fsg_lun *curlun = fsg->common->curlun;
919 struct fsg_buffhd *bh;
922 loff_t file_offset, file_offset_tmp;
924 unsigned int partial_page;
927 /* Get the starting Logical Block Address and check that it's
929 if (fsg->common->cmnd[0] == SC_READ_6)
930 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
932 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
934 /* We allow DPO (Disable Page Out = don't save data in the
935 * cache) and FUA (Force Unit Access = don't read from the
936 * cache), but we don't implement them. */
937 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
938 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
942 if (lba >= curlun->num_sectors) {
943 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
946 file_offset = ((loff_t) lba) << 9;
948 /* Carry out the file reads */
949 amount_left = fsg->data_size_from_cmnd;
950 if (unlikely(amount_left == 0))
951 return -EIO; // No default reply
955 /* Figure out how much we need to read:
956 * Try to read the remaining amount.
957 * But don't read more than the buffer size.
958 * And don't try to read past the end of the file.
959 * Finally, if we're not at a page boundary, don't read past
961 * If this means reading 0 then we were asked to read past
962 * the end of file. */
963 amount = min(amount_left, FSG_BUFLEN);
964 amount = min((loff_t) amount,
965 curlun->file_length - file_offset);
966 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
967 if (partial_page > 0)
968 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
971 /* Wait for the next buffer to become available */
972 bh = fsg->common->next_buffhd_to_fill;
973 while (bh->state != BUF_STATE_EMPTY) {
974 rc = sleep_thread(fsg);
979 /* If we were asked to read past the end of file,
980 * end with an empty buffer. */
983 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
984 curlun->sense_data_info = file_offset >> 9;
985 curlun->info_valid = 1;
986 bh->inreq->length = 0;
987 bh->state = BUF_STATE_FULL;
991 /* Perform the read */
992 file_offset_tmp = file_offset;
993 nread = vfs_read(curlun->filp,
994 (char __user *) bh->buf,
995 amount, &file_offset_tmp);
996 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
997 (unsigned long long) file_offset,
999 if (signal_pending(current))
1003 LDBG(curlun, "error in file read: %d\n",
1006 } else if (nread < amount) {
1007 LDBG(curlun, "partial file read: %d/%u\n",
1008 (int) nread, amount);
1009 nread -= (nread & 511); // Round down to a block
1011 file_offset += nread;
1012 amount_left -= nread;
1013 fsg->residue -= nread;
1014 bh->inreq->length = nread;
1015 bh->state = BUF_STATE_FULL;
1017 /* If an error occurred, report it and its position */
1018 if (nread < amount) {
1019 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1020 curlun->sense_data_info = file_offset >> 9;
1021 curlun->info_valid = 1;
1025 if (amount_left == 0)
1026 break; // No more left to read
1028 /* Send this buffer and go read some more */
1029 bh->inreq->zero = 0;
1030 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1031 &bh->inreq_busy, &bh->state);
1032 fsg->common->next_buffhd_to_fill = bh->next;
1035 return -EIO; // No default reply
1039 /*-------------------------------------------------------------------------*/
1041 static int do_write(struct fsg_dev *fsg)
1043 struct fsg_lun *curlun = fsg->common->curlun;
1045 struct fsg_buffhd *bh;
1047 u32 amount_left_to_req, amount_left_to_write;
1048 loff_t usb_offset, file_offset, file_offset_tmp;
1049 unsigned int amount;
1050 unsigned int partial_page;
1055 curlun->sense_data = SS_WRITE_PROTECTED;
1058 spin_lock(&curlun->filp->f_lock);
1059 curlun->filp->f_flags &= ~O_SYNC; // Default is not to wait
1060 spin_unlock(&curlun->filp->f_lock);
1062 /* Get the starting Logical Block Address and check that it's
1064 if (fsg->common->cmnd[0] == SC_WRITE_6)
1065 lba = get_unaligned_be24(&fsg->common->cmnd[1]);
1067 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1069 /* We allow DPO (Disable Page Out = don't save data in the
1070 * cache) and FUA (Force Unit Access = write directly to the
1071 * medium). We don't implement DPO; we implement FUA by
1072 * performing synchronous output. */
1073 if ((fsg->common->cmnd[1] & ~0x18) != 0) {
1074 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1077 if (fsg->common->cmnd[1] & 0x08) { // FUA
1078 spin_lock(&curlun->filp->f_lock);
1079 curlun->filp->f_flags |= O_SYNC;
1080 spin_unlock(&curlun->filp->f_lock);
1083 if (lba >= curlun->num_sectors) {
1084 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1088 /* Carry out the file writes */
1090 file_offset = usb_offset = ((loff_t) lba) << 9;
1091 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
1093 while (amount_left_to_write > 0) {
1095 /* Queue a request for more data from the host */
1096 bh = fsg->common->next_buffhd_to_fill;
1097 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
1099 /* Figure out how much we want to get:
1100 * Try to get the remaining amount.
1101 * But don't get more than the buffer size.
1102 * And don't try to go past the end of the file.
1103 * If we're not at a page boundary,
1104 * don't go past the next page.
1105 * If this means getting 0, then we were asked
1106 * to write past the end of file.
1107 * Finally, round down to a block boundary. */
1108 amount = min(amount_left_to_req, FSG_BUFLEN);
1109 amount = min((loff_t) amount, curlun->file_length -
1111 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
1112 if (partial_page > 0)
1113 amount = min(amount,
1114 (unsigned int) PAGE_CACHE_SIZE - partial_page);
1118 curlun->sense_data =
1119 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1120 curlun->sense_data_info = usb_offset >> 9;
1121 curlun->info_valid = 1;
1124 amount -= (amount & 511);
1127 /* Why were we were asked to transfer a
1133 /* Get the next buffer */
1134 usb_offset += amount;
1135 fsg->usb_amount_left -= amount;
1136 amount_left_to_req -= amount;
1137 if (amount_left_to_req == 0)
1140 /* amount is always divisible by 512, hence by
1141 * the bulk-out maxpacket size */
1142 bh->outreq->length = bh->bulk_out_intended_length =
1144 bh->outreq->short_not_ok = 1;
1145 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1146 &bh->outreq_busy, &bh->state);
1147 fsg->common->next_buffhd_to_fill = bh->next;
1151 /* Write the received data to the backing file */
1152 bh = fsg->common->next_buffhd_to_drain;
1153 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1154 break; // We stopped early
1155 if (bh->state == BUF_STATE_FULL) {
1157 fsg->common->next_buffhd_to_drain = bh->next;
1158 bh->state = BUF_STATE_EMPTY;
1160 /* Did something go wrong with the transfer? */
1161 if (bh->outreq->status != 0) {
1162 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1163 curlun->sense_data_info = file_offset >> 9;
1164 curlun->info_valid = 1;
1168 amount = bh->outreq->actual;
1169 if (curlun->file_length - file_offset < amount) {
1171 "write %u @ %llu beyond end %llu\n",
1172 amount, (unsigned long long) file_offset,
1173 (unsigned long long) curlun->file_length);
1174 amount = curlun->file_length - file_offset;
1177 /* Perform the write */
1178 file_offset_tmp = file_offset;
1179 nwritten = vfs_write(curlun->filp,
1180 (char __user *) bh->buf,
1181 amount, &file_offset_tmp);
1182 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1183 (unsigned long long) file_offset,
1185 if (signal_pending(current))
1186 return -EINTR; // Interrupted!
1189 LDBG(curlun, "error in file write: %d\n",
1192 } else if (nwritten < amount) {
1193 LDBG(curlun, "partial file write: %d/%u\n",
1194 (int) nwritten, amount);
1195 nwritten -= (nwritten & 511);
1196 // Round down to a block
1198 file_offset += nwritten;
1199 amount_left_to_write -= nwritten;
1200 fsg->residue -= nwritten;
1202 /* If an error occurred, report it and its position */
1203 if (nwritten < amount) {
1204 curlun->sense_data = SS_WRITE_ERROR;
1205 curlun->sense_data_info = file_offset >> 9;
1206 curlun->info_valid = 1;
1210 /* Did the host decide to stop early? */
1211 if (bh->outreq->actual != bh->outreq->length) {
1212 fsg->short_packet_received = 1;
1218 /* Wait for something to happen */
1219 rc = sleep_thread(fsg);
1224 return -EIO; // No default reply
1228 /*-------------------------------------------------------------------------*/
1230 static int do_synchronize_cache(struct fsg_dev *fsg)
1232 struct fsg_lun *curlun = fsg->common->curlun;
1235 /* We ignore the requested LBA and write out all file's
1236 * dirty data buffers. */
1237 rc = fsg_lun_fsync_sub(curlun);
1239 curlun->sense_data = SS_WRITE_ERROR;
1244 /*-------------------------------------------------------------------------*/
1246 static void invalidate_sub(struct fsg_lun *curlun)
1248 struct file *filp = curlun->filp;
1249 struct inode *inode = filp->f_path.dentry->d_inode;
1252 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1253 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1256 static int do_verify(struct fsg_dev *fsg)
1258 struct fsg_lun *curlun = fsg->common->curlun;
1260 u32 verification_length;
1261 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1262 loff_t file_offset, file_offset_tmp;
1264 unsigned int amount;
1267 /* Get the starting Logical Block Address and check that it's
1269 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1270 if (lba >= curlun->num_sectors) {
1271 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1275 /* We allow DPO (Disable Page Out = don't save data in the
1276 * cache) but we don't implement it. */
1277 if ((fsg->common->cmnd[1] & ~0x10) != 0) {
1278 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1282 verification_length = get_unaligned_be16(&fsg->common->cmnd[7]);
1283 if (unlikely(verification_length == 0))
1284 return -EIO; // No default reply
1286 /* Prepare to carry out the file verify */
1287 amount_left = verification_length << 9;
1288 file_offset = ((loff_t) lba) << 9;
1290 /* Write out all the dirty buffers before invalidating them */
1291 fsg_lun_fsync_sub(curlun);
1292 if (signal_pending(current))
1295 invalidate_sub(curlun);
1296 if (signal_pending(current))
1299 /* Just try to read the requested blocks */
1300 while (amount_left > 0) {
1302 /* Figure out how much we need to read:
1303 * Try to read the remaining amount, but not more than
1305 * And don't try to read past the end of the file.
1306 * If this means reading 0 then we were asked to read
1307 * past the end of file. */
1308 amount = min(amount_left, FSG_BUFLEN);
1309 amount = min((loff_t) amount,
1310 curlun->file_length - file_offset);
1312 curlun->sense_data =
1313 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1314 curlun->sense_data_info = file_offset >> 9;
1315 curlun->info_valid = 1;
1319 /* Perform the read */
1320 file_offset_tmp = file_offset;
1321 nread = vfs_read(curlun->filp,
1322 (char __user *) bh->buf,
1323 amount, &file_offset_tmp);
1324 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1325 (unsigned long long) file_offset,
1327 if (signal_pending(current))
1331 LDBG(curlun, "error in file verify: %d\n",
1334 } else if (nread < amount) {
1335 LDBG(curlun, "partial file verify: %d/%u\n",
1336 (int) nread, amount);
1337 nread -= (nread & 511); // Round down to a sector
1340 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1341 curlun->sense_data_info = file_offset >> 9;
1342 curlun->info_valid = 1;
1345 file_offset += nread;
1346 amount_left -= nread;
1352 /*-------------------------------------------------------------------------*/
1354 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1356 u8 *buf = (u8 *) bh->buf;
1358 static char vendor_id[] = "Linux ";
1359 static char product_disk_id[] = "File-Stor Gadget";
1360 static char product_cdrom_id[] = "File-CD Gadget ";
1362 if (!fsg->common->curlun) { // Unsupported LUNs are okay
1363 fsg->bad_lun_okay = 1;
1365 buf[0] = 0x7f; // Unsupported, no device-type
1366 buf[4] = 31; // Additional length
1371 buf[0] = (mod_data.cdrom ? TYPE_CDROM : TYPE_DISK);
1372 if (mod_data.removable)
1374 buf[2] = 2; // ANSI SCSI level 2
1375 buf[3] = 2; // SCSI-2 INQUIRY data format
1376 buf[4] = 31; // Additional length
1377 // No special options
1378 sprintf(buf + 8, "%-8s%-16s%04x", vendor_id,
1379 (mod_data.cdrom ? product_cdrom_id :
1386 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1388 struct fsg_lun *curlun = fsg->common->curlun;
1389 u8 *buf = (u8 *) bh->buf;
1394 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1396 * If a REQUEST SENSE command is received from an initiator
1397 * with a pending unit attention condition (before the target
1398 * generates the contingent allegiance condition), then the
1399 * target shall either:
1400 * a) report any pending sense data and preserve the unit
1401 * attention condition on the logical unit, or,
1402 * b) report the unit attention condition, may discard any
1403 * pending sense data, and clear the unit attention
1404 * condition on the logical unit for that initiator.
1406 * FSG normally uses option a); enable this code to use option b).
1409 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1410 curlun->sense_data = curlun->unit_attention_data;
1411 curlun->unit_attention_data = SS_NO_SENSE;
1415 if (!curlun) { // Unsupported LUNs are okay
1416 fsg->bad_lun_okay = 1;
1417 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1421 sd = curlun->sense_data;
1422 sdinfo = curlun->sense_data_info;
1423 valid = curlun->info_valid << 7;
1424 curlun->sense_data = SS_NO_SENSE;
1425 curlun->sense_data_info = 0;
1426 curlun->info_valid = 0;
1430 buf[0] = valid | 0x70; // Valid, current error
1432 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1433 buf[7] = 18 - 8; // Additional sense length
1440 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1442 struct fsg_lun *curlun = fsg->common->curlun;
1443 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1444 int pmi = fsg->common->cmnd[8];
1445 u8 *buf = (u8 *) bh->buf;
1447 /* Check the PMI and LBA fields */
1448 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1449 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1453 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1454 /* Max logical block */
1455 put_unaligned_be32(512, &buf[4]); /* Block length */
1460 static int do_read_header(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1462 struct fsg_lun *curlun = fsg->common->curlun;
1463 int msf = fsg->common->cmnd[1] & 0x02;
1464 u32 lba = get_unaligned_be32(&fsg->common->cmnd[2]);
1465 u8 *buf = (u8 *) bh->buf;
1467 if ((fsg->common->cmnd[1] & ~0x02) != 0) { /* Mask away MSF */
1468 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1471 if (lba >= curlun->num_sectors) {
1472 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1477 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1478 store_cdrom_address(&buf[4], msf, lba);
1483 static int do_read_toc(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1485 struct fsg_lun *curlun = fsg->common->curlun;
1486 int msf = fsg->common->cmnd[1] & 0x02;
1487 int start_track = fsg->common->cmnd[6];
1488 u8 *buf = (u8 *) bh->buf;
1490 if ((fsg->common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1492 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1497 buf[1] = (20-2); /* TOC data length */
1498 buf[2] = 1; /* First track number */
1499 buf[3] = 1; /* Last track number */
1500 buf[5] = 0x16; /* Data track, copying allowed */
1501 buf[6] = 0x01; /* Only track is number 1 */
1502 store_cdrom_address(&buf[8], msf, 0);
1504 buf[13] = 0x16; /* Lead-out track is data */
1505 buf[14] = 0xAA; /* Lead-out track number */
1506 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1511 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1513 struct fsg_lun *curlun = fsg->common->curlun;
1514 int mscmnd = fsg->common->cmnd[0];
1515 u8 *buf = (u8 *) bh->buf;
1518 int changeable_values, all_pages;
1522 if ((fsg->common->cmnd[1] & ~0x08) != 0) { // Mask away DBD
1523 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1526 pc = fsg->common->cmnd[2] >> 6;
1527 page_code = fsg->common->cmnd[2] & 0x3f;
1529 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1532 changeable_values = (pc == 1);
1533 all_pages = (page_code == 0x3f);
1535 /* Write the mode parameter header. Fixed values are: default
1536 * medium type, no cache control (DPOFUA), and no block descriptors.
1537 * The only variable value is the WriteProtect bit. We will fill in
1538 * the mode data length later. */
1540 if (mscmnd == SC_MODE_SENSE_6) {
1541 buf[2] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1544 } else { // SC_MODE_SENSE_10
1545 buf[3] = (curlun->ro ? 0x80 : 0x00); // WP, DPOFUA
1547 limit = 65535; // Should really be FSG_BUFLEN
1550 /* No block descriptors */
1552 /* The mode pages, in numerical order. The only page we support
1553 * is the Caching page. */
1554 if (page_code == 0x08 || all_pages) {
1556 buf[0] = 0x08; // Page code
1557 buf[1] = 10; // Page length
1558 memset(buf+2, 0, 10); // None of the fields are changeable
1560 if (!changeable_values) {
1561 buf[2] = 0x04; // Write cache enable,
1562 // Read cache not disabled
1563 // No cache retention priorities
1564 put_unaligned_be16(0xffff, &buf[4]);
1565 /* Don't disable prefetch */
1566 /* Minimum prefetch = 0 */
1567 put_unaligned_be16(0xffff, &buf[8]);
1568 /* Maximum prefetch */
1569 put_unaligned_be16(0xffff, &buf[10]);
1570 /* Maximum prefetch ceiling */
1575 /* Check that a valid page was requested and the mode data length
1576 * isn't too long. */
1578 if (!valid_page || len > limit) {
1579 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1583 /* Store the mode data length */
1584 if (mscmnd == SC_MODE_SENSE_6)
1587 put_unaligned_be16(len - 2, buf0);
1592 static int do_start_stop(struct fsg_dev *fsg)
1594 if (!mod_data.removable) {
1595 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
1602 static int do_prevent_allow(struct fsg_dev *fsg)
1604 struct fsg_lun *curlun = fsg->common->curlun;
1607 if (!mod_data.removable) {
1608 curlun->sense_data = SS_INVALID_COMMAND;
1612 prevent = fsg->common->cmnd[4] & 0x01;
1613 if ((fsg->common->cmnd[4] & ~0x01) != 0) { // Mask away Prevent
1614 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1618 if (curlun->prevent_medium_removal && !prevent)
1619 fsg_lun_fsync_sub(curlun);
1620 curlun->prevent_medium_removal = prevent;
1625 static int do_read_format_capacities(struct fsg_dev *fsg,
1626 struct fsg_buffhd *bh)
1628 struct fsg_lun *curlun = fsg->common->curlun;
1629 u8 *buf = (u8 *) bh->buf;
1631 buf[0] = buf[1] = buf[2] = 0;
1632 buf[3] = 8; // Only the Current/Maximum Capacity Descriptor
1635 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1636 /* Number of blocks */
1637 put_unaligned_be32(512, &buf[4]); /* Block length */
1638 buf[4] = 0x02; /* Current capacity */
1643 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1645 struct fsg_lun *curlun = fsg->common->curlun;
1647 /* We don't support MODE SELECT */
1648 curlun->sense_data = SS_INVALID_COMMAND;
1653 /*-------------------------------------------------------------------------*/
1655 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1659 rc = fsg_set_halt(fsg, fsg->bulk_in);
1661 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1663 if (rc != -EAGAIN) {
1664 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1669 /* Wait for a short time and then try again */
1670 if (msleep_interruptible(100) != 0)
1672 rc = usb_ep_set_halt(fsg->bulk_in);
1677 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1681 DBG(fsg, "bulk-in set wedge\n");
1682 rc = usb_ep_set_wedge(fsg->bulk_in);
1684 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1686 if (rc != -EAGAIN) {
1687 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1692 /* Wait for a short time and then try again */
1693 if (msleep_interruptible(100) != 0)
1695 rc = usb_ep_set_wedge(fsg->bulk_in);
1700 static int pad_with_zeros(struct fsg_dev *fsg)
1702 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1703 u32 nkeep = bh->inreq->length;
1707 bh->state = BUF_STATE_EMPTY; // For the first iteration
1708 fsg->usb_amount_left = nkeep + fsg->residue;
1709 while (fsg->usb_amount_left > 0) {
1711 /* Wait for the next buffer to be free */
1712 while (bh->state != BUF_STATE_EMPTY) {
1713 rc = sleep_thread(fsg);
1718 nsend = min(fsg->usb_amount_left, FSG_BUFLEN);
1719 memset(bh->buf + nkeep, 0, nsend - nkeep);
1720 bh->inreq->length = nsend;
1721 bh->inreq->zero = 0;
1722 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1723 &bh->inreq_busy, &bh->state);
1724 bh = fsg->common->next_buffhd_to_fill = bh->next;
1725 fsg->usb_amount_left -= nsend;
1731 static int throw_away_data(struct fsg_dev *fsg)
1733 struct fsg_buffhd *bh;
1737 for (bh = fsg->common->next_buffhd_to_drain;
1738 bh->state != BUF_STATE_EMPTY || fsg->usb_amount_left > 0;
1739 bh = fsg->common->next_buffhd_to_drain) {
1741 /* Throw away the data in a filled buffer */
1742 if (bh->state == BUF_STATE_FULL) {
1744 bh->state = BUF_STATE_EMPTY;
1745 fsg->common->next_buffhd_to_drain = bh->next;
1747 /* A short packet or an error ends everything */
1748 if (bh->outreq->actual != bh->outreq->length ||
1749 bh->outreq->status != 0) {
1750 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1756 /* Try to submit another request if we need one */
1757 bh = fsg->common->next_buffhd_to_fill;
1758 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1759 amount = min(fsg->usb_amount_left, FSG_BUFLEN);
1761 /* amount is always divisible by 512, hence by
1762 * the bulk-out maxpacket size */
1763 bh->outreq->length = bh->bulk_out_intended_length =
1765 bh->outreq->short_not_ok = 1;
1766 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1767 &bh->outreq_busy, &bh->state);
1768 fsg->common->next_buffhd_to_fill = bh->next;
1769 fsg->usb_amount_left -= amount;
1773 /* Otherwise wait for something to happen */
1774 rc = sleep_thread(fsg);
1782 static int finish_reply(struct fsg_dev *fsg)
1784 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1787 switch (fsg->data_dir) {
1789 break; // Nothing to send
1791 /* If we don't know whether the host wants to read or write,
1792 * this must be CB or CBI with an unknown command. We mustn't
1793 * try to send or receive any data. So stall both bulk pipes
1794 * if we can and wait for a reset. */
1795 case DATA_DIR_UNKNOWN:
1796 if (mod_data.can_stall) {
1797 fsg_set_halt(fsg, fsg->bulk_out);
1798 rc = halt_bulk_in_endpoint(fsg);
1802 /* All but the last buffer of data must have already been sent */
1803 case DATA_DIR_TO_HOST:
1804 if (fsg->data_size == 0) {
1805 /* Nothing to send */
1807 /* If there's no residue, simply send the last buffer */
1808 } else if (fsg->residue == 0) {
1809 bh->inreq->zero = 0;
1810 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1811 &bh->inreq_busy, &bh->state);
1812 fsg->common->next_buffhd_to_fill = bh->next;
1814 /* For Bulk-only, if we're allowed to stall then send the
1815 * short packet and halt the bulk-in endpoint. If we can't
1816 * stall, pad out the remaining data with 0's. */
1817 } else if (mod_data.can_stall) {
1818 bh->inreq->zero = 1;
1819 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1820 &bh->inreq_busy, &bh->state);
1821 fsg->common->next_buffhd_to_fill = bh->next;
1822 rc = halt_bulk_in_endpoint(fsg);
1824 rc = pad_with_zeros(fsg);
1828 /* We have processed all we want from the data the host has sent.
1829 * There may still be outstanding bulk-out requests. */
1830 case DATA_DIR_FROM_HOST:
1831 if (fsg->residue == 0)
1832 ; // Nothing to receive
1834 /* Did the host stop sending unexpectedly early? */
1835 else if (fsg->short_packet_received) {
1836 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1840 /* We haven't processed all the incoming data. Even though
1841 * we may be allowed to stall, doing so would cause a race.
1842 * The controller may already have ACK'ed all the remaining
1843 * bulk-out packets, in which case the host wouldn't see a
1844 * STALL. Not realizing the endpoint was halted, it wouldn't
1845 * clear the halt -- leading to problems later on. */
1847 else if (mod_data.can_stall) {
1848 fsg_set_halt(fsg, fsg->bulk_out);
1849 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1854 /* We can't stall. Read in the excess data and throw it
1857 rc = throw_away_data(fsg);
1864 static int send_status(struct fsg_dev *fsg)
1866 struct fsg_lun *curlun = fsg->common->curlun;
1867 struct fsg_buffhd *bh;
1868 struct bulk_cs_wrap *csw;
1870 u8 status = USB_STATUS_PASS;
1873 /* Wait for the next buffer to become available */
1874 bh = fsg->common->next_buffhd_to_fill;
1875 while (bh->state != BUF_STATE_EMPTY) {
1876 rc = sleep_thread(fsg);
1882 sd = curlun->sense_data;
1883 sdinfo = curlun->sense_data_info;
1884 } else if (fsg->bad_lun_okay)
1887 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1889 if (fsg->phase_error) {
1890 DBG(fsg, "sending phase-error status\n");
1891 status = USB_STATUS_PHASE_ERROR;
1892 sd = SS_INVALID_COMMAND;
1893 } else if (sd != SS_NO_SENSE) {
1894 DBG(fsg, "sending command-failure status\n");
1895 status = USB_STATUS_FAIL;
1896 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1898 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1901 /* Store and send the Bulk-only CSW */
1902 csw = (void*)bh->buf;
1904 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1905 csw->Tag = fsg->tag;
1906 csw->Residue = cpu_to_le32(fsg->residue);
1907 csw->Status = status;
1909 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1910 bh->inreq->zero = 0;
1911 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1912 &bh->inreq_busy, &bh->state);
1914 fsg->common->next_buffhd_to_fill = bh->next;
1919 /*-------------------------------------------------------------------------*/
1921 /* Check whether the command is properly formed and whether its data size
1922 * and direction agree with the values we already have. */
1923 static int check_command(struct fsg_dev *fsg, int cmnd_size,
1924 enum data_direction data_dir, unsigned int mask,
1925 int needs_medium, const char *name)
1928 int lun = fsg->common->cmnd[1] >> 5;
1929 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1931 struct fsg_lun *curlun;
1934 if (fsg->data_dir != DATA_DIR_UNKNOWN)
1935 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1937 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1938 name, cmnd_size, dirletter[(int) data_dir],
1939 fsg->data_size_from_cmnd, fsg->common->cmnd_size, hdlen);
1941 /* We can't reply at all until we know the correct data direction
1943 if (fsg->data_size_from_cmnd == 0)
1944 data_dir = DATA_DIR_NONE;
1945 if (fsg->data_dir == DATA_DIR_UNKNOWN) { // CB or CBI
1946 fsg->data_dir = data_dir;
1947 fsg->data_size = fsg->data_size_from_cmnd;
1949 } else { // Bulk-only
1950 if (fsg->data_size < fsg->data_size_from_cmnd) {
1952 /* Host data size < Device data size is a phase error.
1953 * Carry out the command, but only transfer as much
1954 * as we are allowed. */
1955 fsg->data_size_from_cmnd = fsg->data_size;
1956 fsg->phase_error = 1;
1959 fsg->residue = fsg->usb_amount_left = fsg->data_size;
1961 /* Conflicting data directions is a phase error */
1962 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
1963 fsg->phase_error = 1;
1967 /* Verify the length of the command itself */
1968 if (cmnd_size != fsg->common->cmnd_size) {
1970 /* Special case workaround: There are plenty of buggy SCSI
1971 * implementations. Many have issues with cbw->Length
1972 * field passing a wrong command size. For those cases we
1973 * always try to work around the problem by using the length
1974 * sent by the host side provided it is at least as large
1975 * as the correct command length.
1976 * Examples of such cases would be MS-Windows, which issues
1977 * REQUEST SENSE with cbw->Length == 12 where it should
1978 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1979 * REQUEST SENSE with cbw->Length == 10 where it should
1982 if (cmnd_size <= fsg->common->cmnd_size) {
1983 DBG(fsg, "%s is buggy! Expected length %d "
1984 "but we got %d\n", name,
1985 cmnd_size, fsg->common->cmnd_size);
1986 cmnd_size = fsg->common->cmnd_size;
1988 fsg->phase_error = 1;
1993 /* Check that the LUN values are consistent */
1994 if (fsg->common->lun != lun)
1995 DBG(fsg, "using LUN %d from CBW, not LUN %d from CDB\n",
1996 fsg->common->lun, lun);
1999 if (fsg->common->lun >= 0 && fsg->common->lun < fsg->common->nluns) {
2000 fsg->common->curlun = curlun = &fsg->common->luns[fsg->common->lun];
2001 if (fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2002 curlun->sense_data = SS_NO_SENSE;
2003 curlun->sense_data_info = 0;
2004 curlun->info_valid = 0;
2007 fsg->common->curlun = curlun = NULL;
2008 fsg->bad_lun_okay = 0;
2010 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
2011 * to use unsupported LUNs; all others may not. */
2012 if (fsg->common->cmnd[0] != SC_INQUIRY &&
2013 fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2014 DBG(fsg, "unsupported LUN %d\n", fsg->common->lun);
2019 /* If a unit attention condition exists, only INQUIRY and
2020 * REQUEST SENSE commands are allowed; anything else must fail. */
2021 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
2022 fsg->common->cmnd[0] != SC_INQUIRY &&
2023 fsg->common->cmnd[0] != SC_REQUEST_SENSE) {
2024 curlun->sense_data = curlun->unit_attention_data;
2025 curlun->unit_attention_data = SS_NO_SENSE;
2029 /* Check that only command bytes listed in the mask are non-zero */
2030 fsg->common->cmnd[1] &= 0x1f; // Mask away the LUN
2031 for (i = 1; i < cmnd_size; ++i) {
2032 if (fsg->common->cmnd[i] && !(mask & (1 << i))) {
2034 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
2039 /* If the medium isn't mounted and the command needs to access
2040 * it, return an error. */
2041 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
2042 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
2050 static int do_scsi_command(struct fsg_dev *fsg)
2052 struct fsg_buffhd *bh;
2054 int reply = -EINVAL;
2056 static char unknown[16];
2058 dump_cdb(fsg->common);
2060 /* Wait for the next buffer to become available for data or status */
2061 bh = fsg->common->next_buffhd_to_drain = fsg->common->next_buffhd_to_fill;
2062 while (bh->state != BUF_STATE_EMPTY) {
2063 rc = sleep_thread(fsg);
2067 fsg->phase_error = 0;
2068 fsg->short_packet_received = 0;
2070 down_read(&fsg->common->filesem); // We're using the backing file
2071 switch (fsg->common->cmnd[0]) {
2074 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2075 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2078 reply = do_inquiry(fsg, bh);
2081 case SC_MODE_SELECT_6:
2082 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2083 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2085 "MODE SELECT(6)")) == 0)
2086 reply = do_mode_select(fsg, bh);
2089 case SC_MODE_SELECT_10:
2090 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2091 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2093 "MODE SELECT(10)")) == 0)
2094 reply = do_mode_select(fsg, bh);
2097 case SC_MODE_SENSE_6:
2098 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2099 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2100 (1<<1) | (1<<2) | (1<<4), 0,
2101 "MODE SENSE(6)")) == 0)
2102 reply = do_mode_sense(fsg, bh);
2105 case SC_MODE_SENSE_10:
2106 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2107 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2108 (1<<1) | (1<<2) | (3<<7), 0,
2109 "MODE SENSE(10)")) == 0)
2110 reply = do_mode_sense(fsg, bh);
2113 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2114 fsg->data_size_from_cmnd = 0;
2115 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2117 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
2118 reply = do_prevent_allow(fsg);
2122 i = fsg->common->cmnd[4];
2123 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2124 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2127 reply = do_read(fsg);
2131 fsg->data_size_from_cmnd =
2132 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
2133 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2134 (1<<1) | (0xf<<2) | (3<<7), 1,
2136 reply = do_read(fsg);
2140 fsg->data_size_from_cmnd =
2141 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
2142 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
2143 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2145 reply = do_read(fsg);
2148 case SC_READ_CAPACITY:
2149 fsg->data_size_from_cmnd = 8;
2150 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2151 (0xf<<2) | (1<<8), 1,
2152 "READ CAPACITY")) == 0)
2153 reply = do_read_capacity(fsg, bh);
2156 case SC_READ_HEADER:
2157 if (!mod_data.cdrom)
2159 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2160 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2161 (3<<7) | (0x1f<<1), 1,
2162 "READ HEADER")) == 0)
2163 reply = do_read_header(fsg, bh);
2167 if (!mod_data.cdrom)
2169 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2170 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2173 reply = do_read_toc(fsg, bh);
2176 case SC_READ_FORMAT_CAPACITIES:
2177 fsg->data_size_from_cmnd = get_unaligned_be16(&fsg->common->cmnd[7]);
2178 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
2180 "READ FORMAT CAPACITIES")) == 0)
2181 reply = do_read_format_capacities(fsg, bh);
2184 case SC_REQUEST_SENSE:
2185 fsg->data_size_from_cmnd = fsg->common->cmnd[4];
2186 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
2188 "REQUEST SENSE")) == 0)
2189 reply = do_request_sense(fsg, bh);
2192 case SC_START_STOP_UNIT:
2193 fsg->data_size_from_cmnd = 0;
2194 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
2196 "START-STOP UNIT")) == 0)
2197 reply = do_start_stop(fsg);
2200 case SC_SYNCHRONIZE_CACHE:
2201 fsg->data_size_from_cmnd = 0;
2202 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2203 (0xf<<2) | (3<<7), 1,
2204 "SYNCHRONIZE CACHE")) == 0)
2205 reply = do_synchronize_cache(fsg);
2208 case SC_TEST_UNIT_READY:
2209 fsg->data_size_from_cmnd = 0;
2210 reply = check_command(fsg, 6, DATA_DIR_NONE,
2215 /* Although optional, this command is used by MS-Windows. We
2216 * support a minimal version: BytChk must be 0. */
2218 fsg->data_size_from_cmnd = 0;
2219 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2220 (1<<1) | (0xf<<2) | (3<<7), 1,
2222 reply = do_verify(fsg);
2226 i = fsg->common->cmnd[4];
2227 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2228 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2231 reply = do_write(fsg);
2235 fsg->data_size_from_cmnd =
2236 get_unaligned_be16(&fsg->common->cmnd[7]) << 9;
2237 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2238 (1<<1) | (0xf<<2) | (3<<7), 1,
2240 reply = do_write(fsg);
2244 fsg->data_size_from_cmnd =
2245 get_unaligned_be32(&fsg->common->cmnd[6]) << 9;
2246 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2247 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2249 reply = do_write(fsg);
2252 /* Some mandatory commands that we recognize but don't implement.
2253 * They don't mean much in this setting. It's left as an exercise
2254 * for anyone interested to implement RESERVE and RELEASE in terms
2255 * of Posix locks. */
2256 case SC_FORMAT_UNIT:
2259 case SC_SEND_DIAGNOSTIC:
2264 fsg->data_size_from_cmnd = 0;
2265 sprintf(unknown, "Unknown x%02x", fsg->common->cmnd[0]);
2266 if ((reply = check_command(fsg, fsg->common->cmnd_size,
2267 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2268 fsg->common->curlun->sense_data = SS_INVALID_COMMAND;
2273 up_read(&fsg->common->filesem);
2275 if (reply == -EINTR || signal_pending(current))
2278 /* Set up the single reply buffer for finish_reply() */
2279 if (reply == -EINVAL)
2280 reply = 0; // Error reply length
2281 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2282 reply = min((u32) reply, fsg->data_size_from_cmnd);
2283 bh->inreq->length = reply;
2284 bh->state = BUF_STATE_FULL;
2285 fsg->residue -= reply;
2286 } // Otherwise it's already set
2292 /*-------------------------------------------------------------------------*/
2294 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2296 struct usb_request *req = bh->outreq;
2297 struct fsg_bulk_cb_wrap *cbw = req->buf;
2299 /* Was this a real packet? Should it be ignored? */
2300 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2303 /* Is the CBW valid? */
2304 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2305 cbw->Signature != cpu_to_le32(
2307 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2309 le32_to_cpu(cbw->Signature));
2311 /* The Bulk-only spec says we MUST stall the IN endpoint
2312 * (6.6.1), so it's unavoidable. It also says we must
2313 * retain this state until the next reset, but there's
2314 * no way to tell the controller driver it should ignore
2315 * Clear-Feature(HALT) requests.
2317 * We aren't required to halt the OUT endpoint; instead
2318 * we can simply accept and discard any data received
2319 * until the next reset. */
2320 wedge_bulk_in_endpoint(fsg);
2321 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2325 /* Is the CBW meaningful? */
2326 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2327 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2328 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2330 cbw->Lun, cbw->Flags, cbw->Length);
2332 /* We can do anything we want here, so let's stall the
2333 * bulk pipes if we are allowed to. */
2334 if (mod_data.can_stall) {
2335 fsg_set_halt(fsg, fsg->bulk_out);
2336 halt_bulk_in_endpoint(fsg);
2341 /* Save the command for later */
2342 fsg->common->cmnd_size = cbw->Length;
2343 memcpy(fsg->common->cmnd, cbw->CDB, fsg->common->cmnd_size);
2344 if (cbw->Flags & USB_BULK_IN_FLAG)
2345 fsg->data_dir = DATA_DIR_TO_HOST;
2347 fsg->data_dir = DATA_DIR_FROM_HOST;
2348 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2349 if (fsg->data_size == 0)
2350 fsg->data_dir = DATA_DIR_NONE;
2351 fsg->common->lun = cbw->Lun;
2352 fsg->tag = cbw->Tag;
2357 static int get_next_command(struct fsg_dev *fsg)
2359 struct fsg_buffhd *bh;
2362 /* Wait for the next buffer to become available */
2363 bh = fsg->common->next_buffhd_to_fill;
2364 while (bh->state != BUF_STATE_EMPTY) {
2365 rc = sleep_thread(fsg);
2370 /* Queue a request to read a Bulk-only CBW */
2371 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2372 bh->outreq->short_not_ok = 1;
2373 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2374 &bh->outreq_busy, &bh->state);
2376 /* We will drain the buffer in software, which means we
2377 * can reuse it for the next filling. No need to advance
2378 * next_buffhd_to_fill. */
2380 /* Wait for the CBW to arrive */
2381 while (bh->state != BUF_STATE_FULL) {
2382 rc = sleep_thread(fsg);
2387 rc = received_cbw(fsg, bh);
2388 bh->state = BUF_STATE_EMPTY;
2394 /*-------------------------------------------------------------------------*/
2396 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2397 const struct usb_endpoint_descriptor *d)
2401 ep->driver_data = fsg;
2402 rc = usb_ep_enable(ep, d);
2404 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2408 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2409 struct usb_request **preq)
2411 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2414 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2419 * Reset interface setting and re-init endpoint state (toggle etc).
2420 * Call with altsetting < 0 to disable the interface. The only other
2421 * available altsetting is 0, which enables the interface.
2423 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2427 const struct usb_endpoint_descriptor *d;
2430 DBG(fsg, "reset interface\n");
2433 /* Deallocate the requests */
2434 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2435 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
2438 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2442 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2447 /* Disable the endpoints */
2448 if (fsg->bulk_in_enabled) {
2449 usb_ep_disable(fsg->bulk_in);
2450 fsg->bulk_in_enabled = 0;
2452 if (fsg->bulk_out_enabled) {
2453 usb_ep_disable(fsg->bulk_out);
2454 fsg->bulk_out_enabled = 0;
2458 if (altsetting < 0 || rc != 0)
2461 DBG(fsg, "set interface %d\n", altsetting);
2463 /* Enable the endpoints */
2464 d = fsg_ep_desc(fsg->gadget,
2465 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2466 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2468 fsg->bulk_in_enabled = 1;
2470 d = fsg_ep_desc(fsg->gadget,
2471 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2472 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2474 fsg->bulk_out_enabled = 1;
2475 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2476 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2478 /* Allocate the requests */
2479 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2480 struct fsg_buffhd *bh = &fsg->common->buffhds[i];
2482 if ((rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq)) != 0)
2484 if ((rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq)) != 0)
2486 bh->inreq->buf = bh->outreq->buf = bh->buf;
2487 bh->inreq->context = bh->outreq->context = bh;
2488 bh->inreq->complete = bulk_in_complete;
2489 bh->outreq->complete = bulk_out_complete;
2493 for (i = 0; i < fsg->common->nluns; ++i)
2494 fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2500 * Change our operational configuration. This code must agree with the code
2501 * that returns config descriptors, and with interface altsetting code.
2503 * It's also responsible for power management interactions. Some
2504 * configurations might not work with our current power sources.
2505 * For now we just assume the gadget is always self-powered.
2507 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2511 /* Disable the single interface */
2512 if (fsg->config != 0) {
2513 DBG(fsg, "reset config\n");
2515 rc = do_set_interface(fsg, -1);
2518 /* Enable the interface */
2519 if (new_config != 0) {
2520 fsg->config = new_config;
2521 if ((rc = do_set_interface(fsg, 0)) != 0)
2522 fsg->config = 0; // Reset on errors
2526 switch (fsg->gadget->speed) {
2527 case USB_SPEED_LOW: speed = "low"; break;
2528 case USB_SPEED_FULL: speed = "full"; break;
2529 case USB_SPEED_HIGH: speed = "high"; break;
2530 default: speed = "?"; break;
2532 INFO(fsg, "%s speed config #%d\n", speed, fsg->config);
2539 /*-------------------------------------------------------------------------*/
2541 static void handle_exception(struct fsg_dev *fsg)
2546 struct fsg_buffhd *bh;
2547 enum fsg_state old_state;
2549 struct fsg_lun *curlun;
2550 unsigned int exception_req_tag;
2553 /* Clear the existing signals. Anything but SIGUSR1 is converted
2554 * into a high-priority EXIT exception. */
2556 sig = dequeue_signal_lock(current, ¤t->blocked, &info);
2559 if (sig != SIGUSR1) {
2560 if (fsg->state < FSG_STATE_EXIT)
2561 DBG(fsg, "Main thread exiting on signal\n");
2562 raise_exception(fsg, FSG_STATE_EXIT);
2566 /* Cancel all the pending transfers */
2567 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2568 bh = &fsg->common->buffhds[i];
2570 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2571 if (bh->outreq_busy)
2572 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2575 /* Wait until everything is idle */
2578 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2579 bh = &fsg->common->buffhds[i];
2580 num_active += bh->inreq_busy + bh->outreq_busy;
2582 if (num_active == 0)
2584 if (sleep_thread(fsg))
2588 /* Clear out the controller's fifos */
2589 if (fsg->bulk_in_enabled)
2590 usb_ep_fifo_flush(fsg->bulk_in);
2591 if (fsg->bulk_out_enabled)
2592 usb_ep_fifo_flush(fsg->bulk_out);
2594 /* Reset the I/O buffer states and pointers, the SCSI
2595 * state, and the exception. Then invoke the handler. */
2596 spin_lock_irq(&fsg->lock);
2598 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2599 bh = &fsg->common->buffhds[i];
2600 bh->state = BUF_STATE_EMPTY;
2602 fsg->common->next_buffhd_to_fill = fsg->common->next_buffhd_to_drain =
2603 &fsg->common->buffhds[0];
2605 exception_req_tag = fsg->exception_req_tag;
2606 new_config = fsg->new_config;
2607 old_state = fsg->state;
2609 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2610 fsg->state = FSG_STATE_STATUS_PHASE;
2612 for (i = 0; i < fsg->common->nluns; ++i) {
2613 curlun = &fsg->common->luns[i];
2614 curlun->prevent_medium_removal = 0;
2615 curlun->sense_data = curlun->unit_attention_data =
2617 curlun->sense_data_info = 0;
2618 curlun->info_valid = 0;
2620 fsg->state = FSG_STATE_IDLE;
2622 spin_unlock_irq(&fsg->lock);
2624 /* Carry out any extra actions required for the exception */
2625 switch (old_state) {
2629 case FSG_STATE_ABORT_BULK_OUT:
2631 spin_lock_irq(&fsg->lock);
2632 if (fsg->state == FSG_STATE_STATUS_PHASE)
2633 fsg->state = FSG_STATE_IDLE;
2634 spin_unlock_irq(&fsg->lock);
2637 case FSG_STATE_RESET:
2638 /* In case we were forced against our will to halt a
2639 * bulk endpoint, clear the halt now. (The SuperH UDC
2640 * requires this.) */
2641 if (test_and_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2642 usb_ep_clear_halt(fsg->bulk_in);
2644 if (fsg->ep0_req_tag == exception_req_tag)
2645 ep0_queue(fsg); // Complete the status stage
2647 /* Technically this should go here, but it would only be
2648 * a waste of time. Ditto for the INTERFACE_CHANGE and
2649 * CONFIG_CHANGE cases. */
2650 // for (i = 0; i < fsg->common->nluns; ++i)
2651 // fsg->common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2654 case FSG_STATE_INTERFACE_CHANGE:
2655 rc = do_set_interface(fsg, 0);
2656 if (fsg->ep0_req_tag != exception_req_tag)
2658 if (rc != 0) // STALL on errors
2659 fsg_set_halt(fsg, fsg->ep0);
2660 else // Complete the status stage
2664 case FSG_STATE_CONFIG_CHANGE:
2665 rc = do_set_config(fsg, new_config);
2666 if (fsg->ep0_req_tag != exception_req_tag)
2668 if (rc != 0) // STALL on errors
2669 fsg_set_halt(fsg, fsg->ep0);
2670 else // Complete the status stage
2674 case FSG_STATE_DISCONNECT:
2675 for (i = 0; i < fsg->common->nluns; ++i)
2676 fsg_lun_fsync_sub(&fsg->common->luns[i]);
2677 do_set_config(fsg, 0); // Unconfigured state
2680 case FSG_STATE_EXIT:
2681 case FSG_STATE_TERMINATED:
2682 do_set_config(fsg, 0); // Free resources
2683 spin_lock_irq(&fsg->lock);
2684 fsg->state = FSG_STATE_TERMINATED; // Stop the thread
2685 spin_unlock_irq(&fsg->lock);
2691 /*-------------------------------------------------------------------------*/
2693 static int fsg_main_thread(void *fsg_)
2695 struct fsg_dev *fsg = fsg_;
2697 /* Allow the thread to be killed by a signal, but set the signal mask
2698 * to block everything but INT, TERM, KILL, and USR1. */
2699 allow_signal(SIGINT);
2700 allow_signal(SIGTERM);
2701 allow_signal(SIGKILL);
2702 allow_signal(SIGUSR1);
2704 /* Allow the thread to be frozen */
2707 /* Arrange for userspace references to be interpreted as kernel
2708 * pointers. That way we can pass a kernel pointer to a routine
2709 * that expects a __user pointer and it will work okay. */
2713 while (fsg->state != FSG_STATE_TERMINATED) {
2714 if (exception_in_progress(fsg) || signal_pending(current)) {
2715 handle_exception(fsg);
2719 if (!fsg->running) {
2724 if (get_next_command(fsg))
2727 spin_lock_irq(&fsg->lock);
2728 if (!exception_in_progress(fsg))
2729 fsg->state = FSG_STATE_DATA_PHASE;
2730 spin_unlock_irq(&fsg->lock);
2732 if (do_scsi_command(fsg) || finish_reply(fsg))
2735 spin_lock_irq(&fsg->lock);
2736 if (!exception_in_progress(fsg))
2737 fsg->state = FSG_STATE_STATUS_PHASE;
2738 spin_unlock_irq(&fsg->lock);
2740 if (send_status(fsg))
2743 spin_lock_irq(&fsg->lock);
2744 if (!exception_in_progress(fsg))
2745 fsg->state = FSG_STATE_IDLE;
2746 spin_unlock_irq(&fsg->lock);
2749 spin_lock_irq(&fsg->lock);
2750 fsg->thread_task = NULL;
2751 spin_unlock_irq(&fsg->lock);
2753 /* If we are exiting because of a signal, unregister the
2755 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2756 usb_gadget_unregister_driver(&fsg_driver);
2758 /* Let the unbind and cleanup routines know the thread has exited */
2759 complete_and_exit(&fsg->thread_notifier, 0);
2763 /*************************** DEVICE ATTRIBUTES ***************************/
2766 /* The write permissions and store_xxx pointers are set in fsg_bind() */
2767 static DEVICE_ATTR(ro, 0444, fsg_show_ro, NULL);
2768 static DEVICE_ATTR(file, 0444, fsg_show_file, NULL);
2771 /****************************** FSG COMMON ******************************/
2773 static void fsg_common_release(struct kref *ref);
2775 static void fsg_lun_release(struct device *dev)
2777 /* Nothing needs to be done */
2780 static inline void fsg_common_get(struct fsg_common *common)
2782 kref_get(&common->ref);
2785 static inline void fsg_common_put(struct fsg_common *common)
2787 kref_put(&common->ref, fsg_common_release);
2791 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2792 struct usb_gadget *gadget)
2794 struct fsg_buffhd *bh;
2795 struct fsg_lun *curlun;
2798 /* Find out how many LUNs there should be */
2799 nluns = mod_data.nluns;
2801 nluns = max(mod_data.num_filenames, 1u);
2802 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2803 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2804 return ERR_PTR(-EINVAL);
2809 common = kzalloc(sizeof *common, GFP_KERNEL);
2811 return ERR_PTR(-ENOMEM);
2812 common->free_storage_on_release = 1;
2814 memset(common, 0, sizeof common);
2815 common->free_storage_on_release = 0;
2817 common->gadget = gadget;
2819 /* Create the LUNs, open their backing files, and register the
2820 * LUN devices in sysfs. */
2821 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2824 return ERR_PTR(-ENOMEM);
2826 common->luns = curlun;
2828 init_rwsem(&common->filesem);
2830 for (i = 0; i < nluns; ++i, ++curlun) {
2831 curlun->cdrom = !!mod_data.cdrom;
2832 curlun->ro = mod_data.cdrom || mod_data.ro[i];
2833 curlun->removable = mod_data.removable;
2834 curlun->dev.release = fsg_lun_release;
2835 curlun->dev.parent = &gadget->dev;
2836 curlun->dev.driver = &fsg_driver.driver;
2837 dev_set_drvdata(&curlun->dev, &common->filesem);
2838 dev_set_name(&curlun->dev,"%s-lun%d",
2839 dev_name(&gadget->dev), i);
2841 rc = device_register(&curlun->dev);
2843 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2848 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2851 rc = device_create_file(&curlun->dev, &dev_attr_file);
2855 if (mod_data.file[i] && *mod_data.file[i]) {
2856 rc = fsg_lun_open(curlun, mod_data.file[i]);
2859 } else if (!mod_data.removable) {
2860 ERROR(common, "no file given for LUN%d\n", i);
2865 common->nluns = nluns;
2868 /* Data buffers cyclic list */
2869 /* Buffers in buffhds are static -- no need for additional
2871 bh = common->buffhds;
2872 i = FSG_NUM_BUFFERS - 1;
2875 } while (++bh, --i);
2876 bh->next = common->buffhds;
2880 if (mod_data.release == 0xffff) { // Parameter wasn't set
2883 /* The sa1100 controller is not supported */
2884 if (gadget_is_sa1100(gadget))
2887 gcnum = usb_gadget_controller_number(gadget);
2889 mod_data.release = 0x0300 + gcnum;
2891 WARNING(common, "controller '%s' not recognized\n",
2893 WARNING(common, "controller '%s' not recognized\n",
2895 mod_data.release = 0x0399;
2900 /* Some peripheral controllers are known not to be able to
2901 * halt bulk endpoints correctly. If one of them is present,
2904 if (gadget_is_sh(fsg->gadget) || gadget_is_at91(fsg->gadget))
2905 mod_data.can_stall = 0;
2908 kref_init(&common->ref);
2913 common->nluns = i + 1;
2915 /* Call fsg_common_release() directly, ref is not initialised */
2916 fsg_common_release(&common->ref);
2921 static void fsg_common_release(struct kref *ref)
2923 struct fsg_common *common =
2924 container_of(ref, struct fsg_common, ref);
2925 unsigned i = common->nluns;
2926 struct fsg_lun *lun = common->luns;
2928 /* Beware tempting for -> do-while optimization: when in error
2929 * recovery nluns may be zero. */
2931 for (; i; --i, ++lun) {
2932 device_remove_file(&lun->dev, &dev_attr_ro);
2933 device_remove_file(&lun->dev, &dev_attr_file);
2935 device_unregister(&lun->dev);
2938 kfree(common->luns);
2939 if (common->free_storage_on_release)
2944 /*-------------------------------------------------------------------------*/
2947 static void /* __init_or_exit */ fsg_unbind(struct usb_gadget *gadget)
2949 struct fsg_dev *fsg = get_gadget_data(gadget);
2950 struct usb_request *req = fsg->ep0req;
2952 DBG(fsg, "unbind\n");
2953 clear_bit(REGISTERED, &fsg->atomic_bitflags);
2955 /* If the thread isn't already dead, tell it to exit now */
2956 if (fsg->state != FSG_STATE_TERMINATED) {
2957 raise_exception(fsg, FSG_STATE_EXIT);
2958 wait_for_completion(&fsg->thread_notifier);
2960 /* The cleanup routine waits for this completion also */
2961 complete(&fsg->thread_notifier);
2964 /* Free the request and buffer for endpoint 0 */
2967 usb_ep_free_request(fsg->ep0, req);
2970 fsg_common_put(fsg->common);
2972 set_gadget_data(gadget, NULL);
2976 static int __init fsg_bind(struct usb_gadget *gadget)
2978 struct fsg_dev *fsg;
2981 struct fsg_lun *curlun;
2983 struct usb_request *req;
2987 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
2991 /* Initialise common */
2992 fsg->common = fsg_common_init(0, gadget);
2993 if (IS_ERR(fsg->common))
2994 return PTR_ERR(fsg->common);
2996 /* Basic parameters */
2997 fsg->gadget = gadget;
2998 set_gadget_data(gadget, fsg);
2999 fsg->ep0 = gadget->ep0;
3000 fsg->ep0->driver_data = fsg;
3002 spin_lock_init(&fsg->lock);
3003 init_completion(&fsg->thread_notifier);
3005 /* Enable the store_xxx attributes */
3006 if (mod_data.removable) {
3007 dev_attr_file.attr.mode = 0644;
3008 dev_attr_file.store = fsg_store_file;
3009 if (!mod_data.cdrom) {
3010 dev_attr_ro.attr.mode = 0644;
3011 dev_attr_ro.store = fsg_store_ro;
3015 /* Find all the endpoints we will use */
3016 usb_ep_autoconfig_reset(gadget);
3017 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3020 ep->driver_data = fsg; // claim the endpoint
3023 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3026 ep->driver_data = fsg; // claim the endpoint
3029 /* Fix up the descriptors */
3030 device_desc.bMaxPacketSize0 = fsg->ep0->maxpacket;
3031 device_desc.bcdDevice = cpu_to_le16(mod_data.release);
3033 if (gadget_is_dualspeed(gadget)) {
3034 /* Assume ep0 uses the same maxpacket value for both speeds */
3035 dev_qualifier.bMaxPacketSize0 = fsg->ep0->maxpacket;
3037 /* Assume endpoint addresses are the same for both speeds */
3038 fsg_hs_bulk_in_desc.bEndpointAddress =
3039 fsg_fs_bulk_in_desc.bEndpointAddress;
3040 fsg_hs_bulk_out_desc.bEndpointAddress =
3041 fsg_fs_bulk_out_desc.bEndpointAddress;
3044 if (gadget_is_otg(gadget))
3045 fsg_otg_desc.bmAttributes |= USB_OTG_HNP;
3049 /* Allocate the request and buffer for endpoint 0 */
3050 fsg->ep0req = req = usb_ep_alloc_request(fsg->ep0, GFP_KERNEL);
3053 req->buf = kmalloc(EP0_BUFSIZE, GFP_KERNEL);
3056 req->complete = ep0_complete;
3058 /* This should reflect the actual gadget power source */
3059 usb_gadget_set_selfpowered(gadget);
3061 snprintf(fsg_string_manufacturer, sizeof fsg_string_manufacturer,
3063 init_utsname()->sysname, init_utsname()->release,
3066 /* On a real device, serial[] would be loaded from permanent
3067 * storage. We just encode it from the driver version string. */
3068 for (i = 0; i < sizeof fsg_string_serial - 2; i += 2) {
3069 unsigned char c = DRIVER_VERSION[i / 2];
3073 sprintf(&fsg_string_serial[i], "%02X", c);
3076 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
3077 "file-storage-gadget");
3078 if (IS_ERR(fsg->thread_task)) {
3079 rc = PTR_ERR(fsg->thread_task);
3083 INFO(fsg, DRIVER_DESC ", version: " DRIVER_VERSION "\n");
3084 INFO(fsg, "Number of LUNs=%d\n", fsg->common->nluns);
3086 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3087 for (i = 0; i < fsg->common->nluns; ++i) {
3088 curlun = &fsg->common->luns[i];
3089 if (fsg_lun_is_open(curlun)) {
3092 p = d_path(&curlun->filp->f_path,
3097 LINFO(curlun, "ro=%d, file: %s\n",
3098 curlun->ro, (p ? p : "(error)"));
3103 DBG(fsg, "removable=%d, stall=%d, cdrom=%d, buflen=%u\n",
3104 mod_data.removable, mod_data.can_stall,
3105 mod_data.cdrom, FSG_BUFLEN);
3106 DBG(fsg, "I/O thread pid: %d\n", task_pid_nr(fsg->thread_task));
3108 set_bit(REGISTERED, &fsg->atomic_bitflags);
3110 /* Tell the thread to start working */
3111 wake_up_process(fsg->thread_task);
3117 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3121 fsg->state = FSG_STATE_TERMINATED; // The thread is dead
3123 complete(&fsg->thread_notifier);
3128 /*-------------------------------------------------------------------------*/
3130 static struct usb_gadget_driver fsg_driver = {
3131 #ifdef CONFIG_USB_GADGET_DUALSPEED
3132 .speed = USB_SPEED_HIGH,
3134 .speed = USB_SPEED_FULL,
3136 .function = (char *) fsg_string_product,
3138 .unbind = fsg_unbind,
3139 .disconnect = fsg_disconnect,
3143 .name = DRIVER_NAME,
3144 .owner = THIS_MODULE,
3152 static int __init fsg_init(void)
3154 return usb_gadget_register_driver(&fsg_driver);
3156 module_init(fsg_init);
3159 static void __exit fsg_cleanup(void)
3161 /* Unregister the driver iff the thread hasn't already done so */
3163 test_and_clear_bit(REGISTERED, &the_fsg->atomic_bitflags))
3164 usb_gadget_unregister_driver(&fsg_driver);
3166 module_exit(fsg_cleanup);