2 * f_mass_storage.c -- Mass Storage USB Composite Function
4 * Copyright (C) 2003-2008 Alan Stern
5 * Copyright (C) 2009 Samsung Electronics
6 * Author: Michal Nazarewicz <m.nazarewicz@samsung.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions, and the following disclaimer,
14 * without modification.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. The names of the above-listed copyright holders may not be used
19 * to endorse or promote products derived from this software without
20 * specific prior written permission.
22 * ALTERNATIVELY, this software may be distributed under the terms of the
23 * GNU General Public License ("GPL") as published by the Free Software
24 * Foundation, either version 2 of that License or (at your option) any
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
28 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
31 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
33 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
34 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
35 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
36 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
37 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 * The Mass Storage Function acts as a USB Mass Storage device,
43 * appearing to the host as a disk drive or as a CD-ROM drive. In
44 * addition to providing an example of a genuinely useful composite
45 * function for a USB device, it also illustrates a technique of
46 * double-buffering for increased throughput.
48 * Function supports multiple logical units (LUNs). Backing storage
49 * for each LUN is provided by a regular file or a block device.
50 * Access for each LUN can be limited to read-only. Moreover, the
51 * function can indicate that LUN is removable and/or CD-ROM. (The
52 * later implies read-only access.)
54 * MSF is configured by specifying a fsg_config structure. It has the
57 * nluns Number of LUNs function have (anywhere from 1
58 * to FSG_MAX_LUNS which is 8).
59 * luns An array of LUN configuration values. This
60 * should be filled for each LUN that
61 * function will include (ie. for "nluns"
62 * LUNs). Each element of the array has
63 * the following fields:
64 * ->filename The path to the backing file for the LUN.
65 * Required if LUN is not marked as
67 * ->ro Flag specifying access to the LUN shall be
68 * read-only. This is implied if CD-ROM
69 * emulation is enabled as well as when
70 * it was impossible to open "filename"
72 * ->removable Flag specifying that LUN shall be indicated as
74 * ->cdrom Flag specifying that LUN shall be reported as
77 * lun_name_format A printf-like format for names of the LUN
78 * devices. This determines how the
79 * directory in sysfs will be named.
80 * Unless you are using several MSFs in
81 * a single gadget (as opposed to single
82 * MSF in many configurations) you may
83 * leave it as NULL (in which case
84 * "lun%d" will be used). In the format
85 * you can use "%d" to index LUNs for
86 * MSF's with more than one LUN. (Beware
87 * that there is only one integer given
88 * as an argument for the format and
89 * specifying invalid format may cause
90 * unspecified behaviour.)
91 * thread_name Name of the kernel thread process used by the
92 * MSF. You can safely set it to NULL
93 * (in which case default "file-storage"
98 * release Information used as a reply to INQUIRY
99 * request. To use default set to NULL,
100 * NULL, 0xffff respectively. The first
101 * field should be 8 and the second 16
102 * characters or less.
104 * can_stall Set to permit function to halt bulk endpoints.
105 * Disabled on some USB devices known not
106 * to work correctly. You should set it
109 * If "removable" is not set for a LUN then a backing file must be
110 * specified. If it is set, then NULL filename means the LUN's medium
111 * is not loaded (an empty string as "filename" in the fsg_config
112 * structure causes error). The CD-ROM emulation includes a single
113 * data track and no audio tracks; hence there need be only one
114 * backing file per LUN. Note also that the CD-ROM block length is
115 * set to 512 rather than the more common value 2048.
118 * MSF includes support for module parameters. If gadget using it
119 * decides to use it, the following module parameters will be
122 * file=filename[,filename...]
123 * Names of the files or block devices used for
125 * ro=b[,b...] Default false, boolean for read-only access.
127 * Default true, boolean for removable media.
128 * cdrom=b[,b...] Default false, boolean for whether to emulate
130 * luns=N Default N = number of filenames, number of
132 * stall Default determined according to the type of
133 * USB device controller (usually true),
134 * boolean to permit the driver to halt
137 * The module parameters may be prefixed with some string. You need
138 * to consult gadget's documentation or source to verify whether it is
139 * using those module parameters and if it does what are the prefixes
140 * (look for FSG_MODULE_PARAMETERS() macro usage, what's inside it is
144 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
145 * needed. The memory requirement amounts to two 16K buffers, size
146 * configurable by a parameter. Support is included for both
147 * full-speed and high-speed operation.
149 * Note that the driver is slightly non-portable in that it assumes a
150 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
151 * interrupt-in endpoints. With most device controllers this isn't an
152 * issue, but there may be some with hardware restrictions that prevent
153 * a buffer from being used by more than one endpoint.
156 * The pathnames of the backing files and the ro settings are
157 * available in the attribute files "file" and "ro" in the lun<n> (or
158 * to be more precise in a directory which name comes from
159 * "lun_name_format" option!) subdirectory of the gadget's sysfs
160 * directory. If the "removable" option is set, writing to these
161 * files will simulate ejecting/loading the medium (writing an empty
162 * line means eject) and adjusting a write-enable tab. Changes to the
163 * ro setting are not allowed when the medium is loaded or if CD-ROM
164 * emulation is being used.
166 * When a LUN receive an "eject" SCSI request (Start/Stop Unit),
167 * if the LUN is removable, the backing file is released to simulate
171 * This function is heavily based on "File-backed Storage Gadget" by
172 * Alan Stern which in turn is heavily based on "Gadget Zero" by David
173 * Brownell. The driver's SCSI command interface was based on the
174 * "Information technology - Small Computer System Interface - 2"
175 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
176 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
177 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
178 * was based on the "Universal Serial Bus Mass Storage Class UFI
179 * Command Specification" document, Revision 1.0, December 14, 1998,
181 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
188 * The MSF is fairly straightforward. There is a main kernel
189 * thread that handles most of the work. Interrupt routines field
190 * callbacks from the controller driver: bulk- and interrupt-request
191 * completion notifications, endpoint-0 events, and disconnect events.
192 * Completion events are passed to the main thread by wakeup calls. Many
193 * ep0 requests are handled at interrupt time, but SetInterface,
194 * SetConfiguration, and device reset requests are forwarded to the
195 * thread in the form of "exceptions" using SIGUSR1 signals (since they
196 * should interrupt any ongoing file I/O operations).
198 * The thread's main routine implements the standard command/data/status
199 * parts of a SCSI interaction. It and its subroutines are full of tests
200 * for pending signals/exceptions -- all this polling is necessary since
201 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
202 * indication that the driver really wants to be running in userspace.)
203 * An important point is that so long as the thread is alive it keeps an
204 * open reference to the backing file. This will prevent unmounting
205 * the backing file's underlying filesystem and could cause problems
206 * during system shutdown, for example. To prevent such problems, the
207 * thread catches INT, TERM, and KILL signals and converts them into
210 * In normal operation the main thread is started during the gadget's
211 * fsg_bind() callback and stopped during fsg_unbind(). But it can
212 * also exit when it receives a signal, and there's no point leaving
213 * the gadget running when the thread is dead. At of this moment, MSF
214 * provides no way to deregister the gadget when thread dies -- maybe
215 * a callback functions is needed.
217 * To provide maximum throughput, the driver uses a circular pipeline of
218 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
219 * arbitrarily long; in practice the benefits don't justify having more
220 * than 2 stages (i.e., double buffering). But it helps to think of the
221 * pipeline as being a long one. Each buffer head contains a bulk-in and
222 * a bulk-out request pointer (since the buffer can be used for both
223 * output and input -- directions always are given from the host's
224 * point of view) as well as a pointer to the buffer and various state
227 * Use of the pipeline follows a simple protocol. There is a variable
228 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
229 * At any time that buffer head may still be in use from an earlier
230 * request, so each buffer head has a state variable indicating whether
231 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
232 * buffer head to be EMPTY, filling the buffer either by file I/O or by
233 * USB I/O (during which the buffer head is BUSY), and marking the buffer
234 * head FULL when the I/O is complete. Then the buffer will be emptied
235 * (again possibly by USB I/O, during which it is marked BUSY) and
236 * finally marked EMPTY again (possibly by a completion routine).
238 * A module parameter tells the driver to avoid stalling the bulk
239 * endpoints wherever the transport specification allows. This is
240 * necessary for some UDCs like the SuperH, which cannot reliably clear a
241 * halt on a bulk endpoint. However, under certain circumstances the
242 * Bulk-only specification requires a stall. In such cases the driver
243 * will halt the endpoint and set a flag indicating that it should clear
244 * the halt in software during the next device reset. Hopefully this
245 * will permit everything to work correctly. Furthermore, although the
246 * specification allows the bulk-out endpoint to halt when the host sends
247 * too much data, implementing this would cause an unavoidable race.
248 * The driver will always use the "no-stall" approach for OUT transfers.
250 * One subtle point concerns sending status-stage responses for ep0
251 * requests. Some of these requests, such as device reset, can involve
252 * interrupting an ongoing file I/O operation, which might take an
253 * arbitrarily long time. During that delay the host might give up on
254 * the original ep0 request and issue a new one. When that happens the
255 * driver should not notify the host about completion of the original
256 * request, as the host will no longer be waiting for it. So the driver
257 * assigns to each ep0 request a unique tag, and it keeps track of the
258 * tag value of the request associated with a long-running exception
259 * (device-reset, interface-change, or configuration-change). When the
260 * exception handler is finished, the status-stage response is submitted
261 * only if the current ep0 request tag is equal to the exception request
262 * tag. Thus only the most recently received ep0 request will get a
263 * status-stage response.
265 * Warning: This driver source file is too long. It ought to be split up
266 * into a header file plus about 3 separate .c files, to handle the details
267 * of the Gadget, USB Mass Storage, and SCSI protocols.
271 /* #define VERBOSE_DEBUG */
272 /* #define DUMP_MSGS */
275 #include <linux/blkdev.h>
276 #include <linux/completion.h>
277 #include <linux/dcache.h>
278 #include <linux/delay.h>
279 #include <linux/device.h>
280 #include <linux/fcntl.h>
281 #include <linux/file.h>
282 #include <linux/fs.h>
283 #include <linux/kref.h>
284 #include <linux/kthread.h>
285 #include <linux/limits.h>
286 #include <linux/rwsem.h>
287 #include <linux/slab.h>
288 #include <linux/spinlock.h>
289 #include <linux/string.h>
290 #include <linux/freezer.h>
291 #include <linux/utsname.h>
293 #include <linux/usb/ch9.h>
294 #include <linux/usb/gadget.h>
296 #include "gadget_chips.h"
300 /*------------------------------------------------------------------------*/
302 #define FSG_DRIVER_DESC "Mass Storage Function"
303 #define FSG_DRIVER_VERSION "2009/09/11"
305 static const char fsg_string_interface[] = "Mass Storage";
308 #define FSG_NO_INTR_EP 1
309 #define FSG_NO_DEVICE_STRINGS 1
311 #define FSG_NO_INTR_EP 1
313 #include "storage_common.c"
316 /*-------------------------------------------------------------------------*/
321 /* Data shared by all the FSG instances. */
323 struct usb_gadget *gadget;
325 struct fsg_dev *prev_fsg;
327 /* filesem protects: backing files in use */
328 struct rw_semaphore filesem;
330 /* lock protects: state, all the req_busy's */
333 struct usb_ep *ep0; /* Copy of gadget->ep0 */
334 struct usb_request *ep0req; /* Copy of cdev->req */
335 unsigned int ep0_req_tag;
336 const char *ep0req_name;
338 struct fsg_buffhd *next_buffhd_to_fill;
339 struct fsg_buffhd *next_buffhd_to_drain;
340 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
343 u8 cmnd[MAX_COMMAND_SIZE];
347 struct fsg_lun *luns;
348 struct fsg_lun *curlun;
350 unsigned int bulk_out_maxpacket;
351 enum fsg_state state; /* For exception handling */
352 unsigned int exception_req_tag;
354 u8 config, new_config;
355 enum data_direction data_dir;
357 u32 data_size_from_cmnd;
362 unsigned int can_stall:1;
363 unsigned int free_storage_on_release:1;
364 unsigned int phase_error:1;
365 unsigned int short_packet_received:1;
366 unsigned int bad_lun_okay:1;
367 unsigned int running:1;
369 int thread_wakeup_needed;
370 struct completion thread_notifier;
371 struct task_struct *thread_task;
373 /* Callback function to call when thread exits. */
374 int (*thread_exits)(struct fsg_common *common);
375 /* Gadget's private data. */
378 /* Vendor (8 chars), product (16 chars), release (4
379 * hexadecimal digits) and NUL byte */
380 char inquiry_string[8 + 16 + 4 + 1];
388 struct fsg_lun_config {
389 const char *filename;
393 } luns[FSG_MAX_LUNS];
395 const char *lun_name_format;
396 const char *thread_name;
398 /* Callback function to call when thread exits. If no
399 * callback is set or it returns value lower then zero MSF
400 * will force eject all LUNs it operates on (including those
401 * marked as non-removable or with prevent_medium_removal flag
403 int (*thread_exits)(struct fsg_common *common);
404 /* Gadget's private data. */
407 const char *vendor_name; /* 8 characters or less */
408 const char *product_name; /* 16 characters or less */
416 struct usb_function function;
417 struct usb_gadget *gadget; /* Copy of cdev->gadget */
418 struct fsg_common *common;
420 u16 interface_number;
422 unsigned int bulk_in_enabled:1;
423 unsigned int bulk_out_enabled:1;
425 unsigned long atomic_bitflags;
426 #define IGNORE_BULK_OUT 0
428 struct usb_ep *bulk_in;
429 struct usb_ep *bulk_out;
433 static inline int __fsg_is_set(struct fsg_common *common,
434 const char *func, unsigned line)
438 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
442 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
445 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
447 return container_of(f, struct fsg_dev, function);
451 typedef void (*fsg_routine_t)(struct fsg_dev *);
453 static int exception_in_progress(struct fsg_common *common)
455 return common->state > FSG_STATE_IDLE;
458 /* Make bulk-out requests be divisible by the maxpacket size */
459 static void set_bulk_out_req_length(struct fsg_common *common,
460 struct fsg_buffhd *bh, unsigned int length)
464 bh->bulk_out_intended_length = length;
465 rem = length % common->bulk_out_maxpacket;
467 length += common->bulk_out_maxpacket - rem;
468 bh->outreq->length = length;
471 /*-------------------------------------------------------------------------*/
473 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
477 if (ep == fsg->bulk_in)
479 else if (ep == fsg->bulk_out)
483 DBG(fsg, "%s set halt\n", name);
484 return usb_ep_set_halt(ep);
488 /*-------------------------------------------------------------------------*/
490 /* These routines may be called in process context or in_irq */
492 /* Caller must hold fsg->lock */
493 static void wakeup_thread(struct fsg_common *common)
495 /* Tell the main thread that something has happened */
496 common->thread_wakeup_needed = 1;
497 if (common->thread_task)
498 wake_up_process(common->thread_task);
502 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
506 /* Do nothing if a higher-priority exception is already in progress.
507 * If a lower-or-equal priority exception is in progress, preempt it
508 * and notify the main thread by sending it a signal. */
509 spin_lock_irqsave(&common->lock, flags);
510 if (common->state <= new_state) {
511 common->exception_req_tag = common->ep0_req_tag;
512 common->state = new_state;
513 if (common->thread_task)
514 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
515 common->thread_task);
517 spin_unlock_irqrestore(&common->lock, flags);
521 /*-------------------------------------------------------------------------*/
523 static int ep0_queue(struct fsg_common *common)
527 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
528 common->ep0->driver_data = common;
529 if (rc != 0 && rc != -ESHUTDOWN) {
530 /* We can't do much more than wait for a reset */
531 WARNING(common, "error in submission: %s --> %d\n",
532 common->ep0->name, rc);
537 /*-------------------------------------------------------------------------*/
539 /* Bulk and interrupt endpoint completion handlers.
540 * These always run in_irq. */
542 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
544 struct fsg_common *common = ep->driver_data;
545 struct fsg_buffhd *bh = req->context;
547 if (req->status || req->actual != req->length)
548 DBG(common, "%s --> %d, %u/%u\n", __func__,
549 req->status, req->actual, req->length);
550 if (req->status == -ECONNRESET) /* Request was cancelled */
551 usb_ep_fifo_flush(ep);
553 /* Hold the lock while we update the request and buffer states */
555 spin_lock(&common->lock);
557 bh->state = BUF_STATE_EMPTY;
558 wakeup_thread(common);
559 spin_unlock(&common->lock);
562 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
564 struct fsg_common *common = ep->driver_data;
565 struct fsg_buffhd *bh = req->context;
567 dump_msg(common, "bulk-out", req->buf, req->actual);
568 if (req->status || req->actual != bh->bulk_out_intended_length)
569 DBG(common, "%s --> %d, %u/%u\n", __func__,
570 req->status, req->actual,
571 bh->bulk_out_intended_length);
572 if (req->status == -ECONNRESET) /* Request was cancelled */
573 usb_ep_fifo_flush(ep);
575 /* Hold the lock while we update the request and buffer states */
577 spin_lock(&common->lock);
579 bh->state = BUF_STATE_FULL;
580 wakeup_thread(common);
581 spin_unlock(&common->lock);
585 /*-------------------------------------------------------------------------*/
587 /* Ep0 class-specific handlers. These always run in_irq. */
589 static int fsg_setup(struct usb_function *f,
590 const struct usb_ctrlrequest *ctrl)
592 struct fsg_dev *fsg = fsg_from_func(f);
593 struct usb_request *req = fsg->common->ep0req;
594 u16 w_index = le16_to_cpu(ctrl->wIndex);
595 u16 w_value = le16_to_cpu(ctrl->wValue);
596 u16 w_length = le16_to_cpu(ctrl->wLength);
598 if (!fsg->common->config)
601 switch (ctrl->bRequest) {
603 case USB_BULK_RESET_REQUEST:
604 if (ctrl->bRequestType !=
605 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
607 if (w_index != fsg->interface_number || w_value != 0)
610 /* Raise an exception to stop the current operation
611 * and reinitialize our state. */
612 DBG(fsg, "bulk reset request\n");
613 raise_exception(fsg->common, FSG_STATE_RESET);
614 return DELAYED_STATUS;
616 case USB_BULK_GET_MAX_LUN_REQUEST:
617 if (ctrl->bRequestType !=
618 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
620 if (w_index != fsg->interface_number || w_value != 0)
622 VDBG(fsg, "get max LUN\n");
623 *(u8 *) req->buf = fsg->common->nluns - 1;
625 /* Respond with data/status */
626 req->length = min((u16)1, w_length);
627 fsg->common->ep0req_name =
628 ctrl->bRequestType & USB_DIR_IN ? "ep0-in" : "ep0-out";
629 return ep0_queue(fsg->common);
633 "unknown class-specific control req "
634 "%02x.%02x v%04x i%04x l%u\n",
635 ctrl->bRequestType, ctrl->bRequest,
636 le16_to_cpu(ctrl->wValue), w_index, w_length);
641 /*-------------------------------------------------------------------------*/
643 /* All the following routines run in process context */
646 /* Use this for bulk or interrupt transfers, not ep0 */
647 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
648 struct usb_request *req, int *pbusy,
649 enum fsg_buffer_state *state)
653 if (ep == fsg->bulk_in)
654 dump_msg(fsg, "bulk-in", req->buf, req->length);
656 spin_lock_irq(&fsg->common->lock);
658 *state = BUF_STATE_BUSY;
659 spin_unlock_irq(&fsg->common->lock);
660 rc = usb_ep_queue(ep, req, GFP_KERNEL);
663 *state = BUF_STATE_EMPTY;
665 /* We can't do much more than wait for a reset */
667 /* Note: currently the net2280 driver fails zero-length
668 * submissions if DMA is enabled. */
669 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
671 WARNING(fsg, "error in submission: %s --> %d\n",
676 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
677 if (fsg_is_set(common)) \
678 start_transfer((common)->fsg, (common)->fsg->ep_name, \
679 req, pbusy, state); \
682 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
683 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
687 static int sleep_thread(struct fsg_common *common)
691 /* Wait until a signal arrives or we are woken up */
694 set_current_state(TASK_INTERRUPTIBLE);
695 if (signal_pending(current)) {
699 if (common->thread_wakeup_needed)
703 __set_current_state(TASK_RUNNING);
704 common->thread_wakeup_needed = 0;
709 /*-------------------------------------------------------------------------*/
711 static int do_read(struct fsg_common *common)
713 struct fsg_lun *curlun = common->curlun;
715 struct fsg_buffhd *bh;
718 loff_t file_offset, file_offset_tmp;
720 unsigned int partial_page;
723 /* Get the starting Logical Block Address and check that it's
725 if (common->cmnd[0] == SC_READ_6)
726 lba = get_unaligned_be24(&common->cmnd[1]);
728 lba = get_unaligned_be32(&common->cmnd[2]);
730 /* We allow DPO (Disable Page Out = don't save data in the
731 * cache) and FUA (Force Unit Access = don't read from the
732 * cache), but we don't implement them. */
733 if ((common->cmnd[1] & ~0x18) != 0) {
734 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
738 if (lba >= curlun->num_sectors) {
739 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
742 file_offset = ((loff_t) lba) << 9;
744 /* Carry out the file reads */
745 amount_left = common->data_size_from_cmnd;
746 if (unlikely(amount_left == 0))
747 return -EIO; /* No default reply */
751 /* Figure out how much we need to read:
752 * Try to read the remaining amount.
753 * But don't read more than the buffer size.
754 * And don't try to read past the end of the file.
755 * Finally, if we're not at a page boundary, don't read past
757 * If this means reading 0 then we were asked to read past
758 * the end of file. */
759 amount = min(amount_left, FSG_BUFLEN);
760 amount = min((loff_t) amount,
761 curlun->file_length - file_offset);
762 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
763 if (partial_page > 0)
764 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
767 /* Wait for the next buffer to become available */
768 bh = common->next_buffhd_to_fill;
769 while (bh->state != BUF_STATE_EMPTY) {
770 rc = sleep_thread(common);
775 /* If we were asked to read past the end of file,
776 * end with an empty buffer. */
779 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
780 curlun->sense_data_info = file_offset >> 9;
781 curlun->info_valid = 1;
782 bh->inreq->length = 0;
783 bh->state = BUF_STATE_FULL;
787 /* Perform the read */
788 file_offset_tmp = file_offset;
789 nread = vfs_read(curlun->filp,
790 (char __user *) bh->buf,
791 amount, &file_offset_tmp);
792 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
793 (unsigned long long) file_offset,
795 if (signal_pending(current))
799 LDBG(curlun, "error in file read: %d\n",
802 } else if (nread < amount) {
803 LDBG(curlun, "partial file read: %d/%u\n",
804 (int) nread, amount);
805 nread -= (nread & 511); /* Round down to a block */
807 file_offset += nread;
808 amount_left -= nread;
809 common->residue -= nread;
810 bh->inreq->length = nread;
811 bh->state = BUF_STATE_FULL;
813 /* If an error occurred, report it and its position */
814 if (nread < amount) {
815 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
816 curlun->sense_data_info = file_offset >> 9;
817 curlun->info_valid = 1;
821 if (amount_left == 0)
822 break; /* No more left to read */
824 /* Send this buffer and go read some more */
826 START_TRANSFER_OR(common, bulk_in, bh->inreq,
827 &bh->inreq_busy, &bh->state)
828 /* Don't know what to do if
829 * common->fsg is NULL */
831 common->next_buffhd_to_fill = bh->next;
834 return -EIO; /* No default reply */
838 /*-------------------------------------------------------------------------*/
840 static int do_write(struct fsg_common *common)
842 struct fsg_lun *curlun = common->curlun;
844 struct fsg_buffhd *bh;
846 u32 amount_left_to_req, amount_left_to_write;
847 loff_t usb_offset, file_offset, file_offset_tmp;
849 unsigned int partial_page;
854 curlun->sense_data = SS_WRITE_PROTECTED;
857 spin_lock(&curlun->filp->f_lock);
858 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
859 spin_unlock(&curlun->filp->f_lock);
861 /* Get the starting Logical Block Address and check that it's
863 if (common->cmnd[0] == SC_WRITE_6)
864 lba = get_unaligned_be24(&common->cmnd[1]);
866 lba = get_unaligned_be32(&common->cmnd[2]);
868 /* We allow DPO (Disable Page Out = don't save data in the
869 * cache) and FUA (Force Unit Access = write directly to the
870 * medium). We don't implement DPO; we implement FUA by
871 * performing synchronous output. */
872 if (common->cmnd[1] & ~0x18) {
873 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
876 if (common->cmnd[1] & 0x08) { /* FUA */
877 spin_lock(&curlun->filp->f_lock);
878 curlun->filp->f_flags |= O_SYNC;
879 spin_unlock(&curlun->filp->f_lock);
882 if (lba >= curlun->num_sectors) {
883 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
887 /* Carry out the file writes */
889 file_offset = usb_offset = ((loff_t) lba) << 9;
890 amount_left_to_req = common->data_size_from_cmnd;
891 amount_left_to_write = common->data_size_from_cmnd;
893 while (amount_left_to_write > 0) {
895 /* Queue a request for more data from the host */
896 bh = common->next_buffhd_to_fill;
897 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
899 /* Figure out how much we want to get:
900 * Try to get the remaining amount.
901 * But don't get more than the buffer size.
902 * And don't try to go past the end of the file.
903 * If we're not at a page boundary,
904 * don't go past the next page.
905 * If this means getting 0, then we were asked
906 * to write past the end of file.
907 * Finally, round down to a block boundary. */
908 amount = min(amount_left_to_req, FSG_BUFLEN);
909 amount = min((loff_t) amount, curlun->file_length -
911 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
912 if (partial_page > 0)
914 (unsigned int) PAGE_CACHE_SIZE - partial_page);
919 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
920 curlun->sense_data_info = usb_offset >> 9;
921 curlun->info_valid = 1;
924 amount -= (amount & 511);
927 /* Why were we were asked to transfer a
933 /* Get the next buffer */
934 usb_offset += amount;
935 common->usb_amount_left -= amount;
936 amount_left_to_req -= amount;
937 if (amount_left_to_req == 0)
940 /* amount is always divisible by 512, hence by
941 * the bulk-out maxpacket size */
942 bh->outreq->length = amount;
943 bh->bulk_out_intended_length = amount;
944 bh->outreq->short_not_ok = 1;
945 START_TRANSFER_OR(common, bulk_out, bh->outreq,
946 &bh->outreq_busy, &bh->state)
947 /* Don't know what to do if
948 * common->fsg is NULL */
950 common->next_buffhd_to_fill = bh->next;
954 /* Write the received data to the backing file */
955 bh = common->next_buffhd_to_drain;
956 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
957 break; /* We stopped early */
958 if (bh->state == BUF_STATE_FULL) {
960 common->next_buffhd_to_drain = bh->next;
961 bh->state = BUF_STATE_EMPTY;
963 /* Did something go wrong with the transfer? */
964 if (bh->outreq->status != 0) {
965 curlun->sense_data = SS_COMMUNICATION_FAILURE;
966 curlun->sense_data_info = file_offset >> 9;
967 curlun->info_valid = 1;
971 amount = bh->outreq->actual;
972 if (curlun->file_length - file_offset < amount) {
974 "write %u @ %llu beyond end %llu\n",
975 amount, (unsigned long long) file_offset,
976 (unsigned long long) curlun->file_length);
977 amount = curlun->file_length - file_offset;
980 /* Perform the write */
981 file_offset_tmp = file_offset;
982 nwritten = vfs_write(curlun->filp,
983 (char __user *) bh->buf,
984 amount, &file_offset_tmp);
985 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
986 (unsigned long long) file_offset,
988 if (signal_pending(current))
989 return -EINTR; /* Interrupted! */
992 LDBG(curlun, "error in file write: %d\n",
995 } else if (nwritten < amount) {
996 LDBG(curlun, "partial file write: %d/%u\n",
997 (int) nwritten, amount);
998 nwritten -= (nwritten & 511);
999 /* Round down to a block */
1001 file_offset += nwritten;
1002 amount_left_to_write -= nwritten;
1003 common->residue -= nwritten;
1005 /* If an error occurred, report it and its position */
1006 if (nwritten < amount) {
1007 curlun->sense_data = SS_WRITE_ERROR;
1008 curlun->sense_data_info = file_offset >> 9;
1009 curlun->info_valid = 1;
1013 /* Did the host decide to stop early? */
1014 if (bh->outreq->actual != bh->outreq->length) {
1015 common->short_packet_received = 1;
1021 /* Wait for something to happen */
1022 rc = sleep_thread(common);
1027 return -EIO; /* No default reply */
1031 /*-------------------------------------------------------------------------*/
1033 static int do_synchronize_cache(struct fsg_common *common)
1035 struct fsg_lun *curlun = common->curlun;
1038 /* We ignore the requested LBA and write out all file's
1039 * dirty data buffers. */
1040 rc = fsg_lun_fsync_sub(curlun);
1042 curlun->sense_data = SS_WRITE_ERROR;
1047 /*-------------------------------------------------------------------------*/
1049 static void invalidate_sub(struct fsg_lun *curlun)
1051 struct file *filp = curlun->filp;
1052 struct inode *inode = filp->f_path.dentry->d_inode;
1055 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1056 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1059 static int do_verify(struct fsg_common *common)
1061 struct fsg_lun *curlun = common->curlun;
1063 u32 verification_length;
1064 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1065 loff_t file_offset, file_offset_tmp;
1067 unsigned int amount;
1070 /* Get the starting Logical Block Address and check that it's
1072 lba = get_unaligned_be32(&common->cmnd[2]);
1073 if (lba >= curlun->num_sectors) {
1074 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1078 /* We allow DPO (Disable Page Out = don't save data in the
1079 * cache) but we don't implement it. */
1080 if (common->cmnd[1] & ~0x10) {
1081 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1085 verification_length = get_unaligned_be16(&common->cmnd[7]);
1086 if (unlikely(verification_length == 0))
1087 return -EIO; /* No default reply */
1089 /* Prepare to carry out the file verify */
1090 amount_left = verification_length << 9;
1091 file_offset = ((loff_t) lba) << 9;
1093 /* Write out all the dirty buffers before invalidating them */
1094 fsg_lun_fsync_sub(curlun);
1095 if (signal_pending(current))
1098 invalidate_sub(curlun);
1099 if (signal_pending(current))
1102 /* Just try to read the requested blocks */
1103 while (amount_left > 0) {
1105 /* Figure out how much we need to read:
1106 * Try to read the remaining amount, but not more than
1108 * And don't try to read past the end of the file.
1109 * If this means reading 0 then we were asked to read
1110 * past the end of file. */
1111 amount = min(amount_left, FSG_BUFLEN);
1112 amount = min((loff_t) amount,
1113 curlun->file_length - file_offset);
1115 curlun->sense_data =
1116 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1117 curlun->sense_data_info = file_offset >> 9;
1118 curlun->info_valid = 1;
1122 /* Perform the read */
1123 file_offset_tmp = file_offset;
1124 nread = vfs_read(curlun->filp,
1125 (char __user *) bh->buf,
1126 amount, &file_offset_tmp);
1127 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1128 (unsigned long long) file_offset,
1130 if (signal_pending(current))
1134 LDBG(curlun, "error in file verify: %d\n",
1137 } else if (nread < amount) {
1138 LDBG(curlun, "partial file verify: %d/%u\n",
1139 (int) nread, amount);
1140 nread -= (nread & 511); /* Round down to a sector */
1143 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1144 curlun->sense_data_info = file_offset >> 9;
1145 curlun->info_valid = 1;
1148 file_offset += nread;
1149 amount_left -= nread;
1155 /*-------------------------------------------------------------------------*/
1157 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1159 struct fsg_lun *curlun = common->curlun;
1160 u8 *buf = (u8 *) bh->buf;
1162 if (!curlun) { /* Unsupported LUNs are okay */
1163 common->bad_lun_okay = 1;
1165 buf[0] = 0x7f; /* Unsupported, no device-type */
1166 buf[4] = 31; /* Additional length */
1170 buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1171 buf[1] = curlun->removable ? 0x80 : 0;
1172 buf[2] = 2; /* ANSI SCSI level 2 */
1173 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1174 buf[4] = 31; /* Additional length */
1175 buf[5] = 0; /* No special options */
1178 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1183 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1185 struct fsg_lun *curlun = common->curlun;
1186 u8 *buf = (u8 *) bh->buf;
1191 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1193 * If a REQUEST SENSE command is received from an initiator
1194 * with a pending unit attention condition (before the target
1195 * generates the contingent allegiance condition), then the
1196 * target shall either:
1197 * a) report any pending sense data and preserve the unit
1198 * attention condition on the logical unit, or,
1199 * b) report the unit attention condition, may discard any
1200 * pending sense data, and clear the unit attention
1201 * condition on the logical unit for that initiator.
1203 * FSG normally uses option a); enable this code to use option b).
1206 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1207 curlun->sense_data = curlun->unit_attention_data;
1208 curlun->unit_attention_data = SS_NO_SENSE;
1212 if (!curlun) { /* Unsupported LUNs are okay */
1213 common->bad_lun_okay = 1;
1214 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1218 sd = curlun->sense_data;
1219 sdinfo = curlun->sense_data_info;
1220 valid = curlun->info_valid << 7;
1221 curlun->sense_data = SS_NO_SENSE;
1222 curlun->sense_data_info = 0;
1223 curlun->info_valid = 0;
1227 buf[0] = valid | 0x70; /* Valid, current error */
1229 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1230 buf[7] = 18 - 8; /* Additional sense length */
1237 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1239 struct fsg_lun *curlun = common->curlun;
1240 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1241 int pmi = common->cmnd[8];
1242 u8 *buf = (u8 *) bh->buf;
1244 /* Check the PMI and LBA fields */
1245 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1246 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1250 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1251 /* Max logical block */
1252 put_unaligned_be32(512, &buf[4]); /* Block length */
1257 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1259 struct fsg_lun *curlun = common->curlun;
1260 int msf = common->cmnd[1] & 0x02;
1261 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1262 u8 *buf = (u8 *) bh->buf;
1264 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1265 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1268 if (lba >= curlun->num_sectors) {
1269 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1274 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1275 store_cdrom_address(&buf[4], msf, lba);
1280 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1282 struct fsg_lun *curlun = common->curlun;
1283 int msf = common->cmnd[1] & 0x02;
1284 int start_track = common->cmnd[6];
1285 u8 *buf = (u8 *) bh->buf;
1287 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1289 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1294 buf[1] = (20-2); /* TOC data length */
1295 buf[2] = 1; /* First track number */
1296 buf[3] = 1; /* Last track number */
1297 buf[5] = 0x16; /* Data track, copying allowed */
1298 buf[6] = 0x01; /* Only track is number 1 */
1299 store_cdrom_address(&buf[8], msf, 0);
1301 buf[13] = 0x16; /* Lead-out track is data */
1302 buf[14] = 0xAA; /* Lead-out track number */
1303 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1308 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1310 struct fsg_lun *curlun = common->curlun;
1311 int mscmnd = common->cmnd[0];
1312 u8 *buf = (u8 *) bh->buf;
1315 int changeable_values, all_pages;
1319 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1320 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1323 pc = common->cmnd[2] >> 6;
1324 page_code = common->cmnd[2] & 0x3f;
1326 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1329 changeable_values = (pc == 1);
1330 all_pages = (page_code == 0x3f);
1332 /* Write the mode parameter header. Fixed values are: default
1333 * medium type, no cache control (DPOFUA), and no block descriptors.
1334 * The only variable value is the WriteProtect bit. We will fill in
1335 * the mode data length later. */
1337 if (mscmnd == SC_MODE_SENSE_6) {
1338 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1341 } else { /* SC_MODE_SENSE_10 */
1342 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1344 limit = 65535; /* Should really be FSG_BUFLEN */
1347 /* No block descriptors */
1349 /* The mode pages, in numerical order. The only page we support
1350 * is the Caching page. */
1351 if (page_code == 0x08 || all_pages) {
1353 buf[0] = 0x08; /* Page code */
1354 buf[1] = 10; /* Page length */
1355 memset(buf+2, 0, 10); /* None of the fields are changeable */
1357 if (!changeable_values) {
1358 buf[2] = 0x04; /* Write cache enable, */
1359 /* Read cache not disabled */
1360 /* No cache retention priorities */
1361 put_unaligned_be16(0xffff, &buf[4]);
1362 /* Don't disable prefetch */
1363 /* Minimum prefetch = 0 */
1364 put_unaligned_be16(0xffff, &buf[8]);
1365 /* Maximum prefetch */
1366 put_unaligned_be16(0xffff, &buf[10]);
1367 /* Maximum prefetch ceiling */
1372 /* Check that a valid page was requested and the mode data length
1373 * isn't too long. */
1375 if (!valid_page || len > limit) {
1376 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1380 /* Store the mode data length */
1381 if (mscmnd == SC_MODE_SENSE_6)
1384 put_unaligned_be16(len - 2, buf0);
1389 static int do_start_stop(struct fsg_common *common)
1391 struct fsg_lun *curlun = common->curlun;
1396 } else if (!curlun->removable) {
1397 curlun->sense_data = SS_INVALID_COMMAND;
1401 loej = common->cmnd[4] & 0x02;
1402 start = common->cmnd[4] & 0x01;
1404 /* eject code from file_storage.c:do_start_stop() */
1406 if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1407 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1408 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1413 /* Are we allowed to unload the media? */
1414 if (curlun->prevent_medium_removal) {
1415 LDBG(curlun, "unload attempt prevented\n");
1416 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1419 if (loej) { /* Simulate an unload/eject */
1420 up_read(&common->filesem);
1421 down_write(&common->filesem);
1422 fsg_lun_close(curlun);
1423 up_write(&common->filesem);
1424 down_read(&common->filesem);
1428 /* Our emulation doesn't support mounting; the medium is
1429 * available for use as soon as it is loaded. */
1430 if (!fsg_lun_is_open(curlun)) {
1431 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1439 static int do_prevent_allow(struct fsg_common *common)
1441 struct fsg_lun *curlun = common->curlun;
1444 if (!common->curlun) {
1446 } else if (!common->curlun->removable) {
1447 common->curlun->sense_data = SS_INVALID_COMMAND;
1451 prevent = common->cmnd[4] & 0x01;
1452 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1453 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1457 if (curlun->prevent_medium_removal && !prevent)
1458 fsg_lun_fsync_sub(curlun);
1459 curlun->prevent_medium_removal = prevent;
1464 static int do_read_format_capacities(struct fsg_common *common,
1465 struct fsg_buffhd *bh)
1467 struct fsg_lun *curlun = common->curlun;
1468 u8 *buf = (u8 *) bh->buf;
1470 buf[0] = buf[1] = buf[2] = 0;
1471 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1474 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1475 /* Number of blocks */
1476 put_unaligned_be32(512, &buf[4]); /* Block length */
1477 buf[4] = 0x02; /* Current capacity */
1482 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1484 struct fsg_lun *curlun = common->curlun;
1486 /* We don't support MODE SELECT */
1488 curlun->sense_data = SS_INVALID_COMMAND;
1493 /*-------------------------------------------------------------------------*/
1495 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1499 rc = fsg_set_halt(fsg, fsg->bulk_in);
1501 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1503 if (rc != -EAGAIN) {
1504 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1509 /* Wait for a short time and then try again */
1510 if (msleep_interruptible(100) != 0)
1512 rc = usb_ep_set_halt(fsg->bulk_in);
1517 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1521 DBG(fsg, "bulk-in set wedge\n");
1522 rc = usb_ep_set_wedge(fsg->bulk_in);
1524 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1526 if (rc != -EAGAIN) {
1527 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1532 /* Wait for a short time and then try again */
1533 if (msleep_interruptible(100) != 0)
1535 rc = usb_ep_set_wedge(fsg->bulk_in);
1540 static int pad_with_zeros(struct fsg_dev *fsg)
1542 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1543 u32 nkeep = bh->inreq->length;
1547 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1548 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1549 while (fsg->common->usb_amount_left > 0) {
1551 /* Wait for the next buffer to be free */
1552 while (bh->state != BUF_STATE_EMPTY) {
1553 rc = sleep_thread(fsg->common);
1558 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1559 memset(bh->buf + nkeep, 0, nsend - nkeep);
1560 bh->inreq->length = nsend;
1561 bh->inreq->zero = 0;
1562 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1563 &bh->inreq_busy, &bh->state);
1564 bh = fsg->common->next_buffhd_to_fill = bh->next;
1565 fsg->common->usb_amount_left -= nsend;
1571 static int throw_away_data(struct fsg_common *common)
1573 struct fsg_buffhd *bh;
1577 for (bh = common->next_buffhd_to_drain;
1578 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1579 bh = common->next_buffhd_to_drain) {
1581 /* Throw away the data in a filled buffer */
1582 if (bh->state == BUF_STATE_FULL) {
1584 bh->state = BUF_STATE_EMPTY;
1585 common->next_buffhd_to_drain = bh->next;
1587 /* A short packet or an error ends everything */
1588 if (bh->outreq->actual != bh->outreq->length ||
1589 bh->outreq->status != 0) {
1590 raise_exception(common,
1591 FSG_STATE_ABORT_BULK_OUT);
1597 /* Try to submit another request if we need one */
1598 bh = common->next_buffhd_to_fill;
1599 if (bh->state == BUF_STATE_EMPTY
1600 && common->usb_amount_left > 0) {
1601 amount = min(common->usb_amount_left, FSG_BUFLEN);
1603 /* amount is always divisible by 512, hence by
1604 * the bulk-out maxpacket size */
1605 bh->outreq->length = amount;
1606 bh->bulk_out_intended_length = amount;
1607 bh->outreq->short_not_ok = 1;
1608 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1609 &bh->outreq_busy, &bh->state)
1610 /* Don't know what to do if
1611 * common->fsg is NULL */
1613 common->next_buffhd_to_fill = bh->next;
1614 common->usb_amount_left -= amount;
1618 /* Otherwise wait for something to happen */
1619 rc = sleep_thread(common);
1627 static int finish_reply(struct fsg_common *common)
1629 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1632 switch (common->data_dir) {
1634 break; /* Nothing to send */
1636 /* If we don't know whether the host wants to read or write,
1637 * this must be CB or CBI with an unknown command. We mustn't
1638 * try to send or receive any data. So stall both bulk pipes
1639 * if we can and wait for a reset. */
1640 case DATA_DIR_UNKNOWN:
1641 if (!common->can_stall) {
1643 } else if (fsg_is_set(common)) {
1644 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1645 rc = halt_bulk_in_endpoint(common->fsg);
1647 /* Don't know what to do if common->fsg is NULL */
1652 /* All but the last buffer of data must have already been sent */
1653 case DATA_DIR_TO_HOST:
1654 if (common->data_size == 0) {
1655 /* Nothing to send */
1657 /* If there's no residue, simply send the last buffer */
1658 } else if (common->residue == 0) {
1659 bh->inreq->zero = 0;
1660 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1661 &bh->inreq_busy, &bh->state)
1663 common->next_buffhd_to_fill = bh->next;
1665 /* For Bulk-only, if we're allowed to stall then send the
1666 * short packet and halt the bulk-in endpoint. If we can't
1667 * stall, pad out the remaining data with 0's. */
1668 } else if (common->can_stall) {
1669 bh->inreq->zero = 1;
1670 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1671 &bh->inreq_busy, &bh->state)
1672 /* Don't know what to do if
1673 * common->fsg is NULL */
1675 common->next_buffhd_to_fill = bh->next;
1677 rc = halt_bulk_in_endpoint(common->fsg);
1678 } else if (fsg_is_set(common)) {
1679 rc = pad_with_zeros(common->fsg);
1681 /* Don't know what to do if common->fsg is NULL */
1686 /* We have processed all we want from the data the host has sent.
1687 * There may still be outstanding bulk-out requests. */
1688 case DATA_DIR_FROM_HOST:
1689 if (common->residue == 0) {
1690 /* Nothing to receive */
1692 /* Did the host stop sending unexpectedly early? */
1693 } else if (common->short_packet_received) {
1694 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1697 /* We haven't processed all the incoming data. Even though
1698 * we may be allowed to stall, doing so would cause a race.
1699 * The controller may already have ACK'ed all the remaining
1700 * bulk-out packets, in which case the host wouldn't see a
1701 * STALL. Not realizing the endpoint was halted, it wouldn't
1702 * clear the halt -- leading to problems later on. */
1704 } else if (common->can_stall) {
1705 if (fsg_is_set(common))
1706 fsg_set_halt(common->fsg,
1707 common->fsg->bulk_out);
1708 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1712 /* We can't stall. Read in the excess data and throw it
1715 rc = throw_away_data(common);
1723 static int send_status(struct fsg_common *common)
1725 struct fsg_lun *curlun = common->curlun;
1726 struct fsg_buffhd *bh;
1727 struct bulk_cs_wrap *csw;
1729 u8 status = USB_STATUS_PASS;
1732 /* Wait for the next buffer to become available */
1733 bh = common->next_buffhd_to_fill;
1734 while (bh->state != BUF_STATE_EMPTY) {
1735 rc = sleep_thread(common);
1741 sd = curlun->sense_data;
1742 sdinfo = curlun->sense_data_info;
1743 } else if (common->bad_lun_okay)
1746 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1748 if (common->phase_error) {
1749 DBG(common, "sending phase-error status\n");
1750 status = USB_STATUS_PHASE_ERROR;
1751 sd = SS_INVALID_COMMAND;
1752 } else if (sd != SS_NO_SENSE) {
1753 DBG(common, "sending command-failure status\n");
1754 status = USB_STATUS_FAIL;
1755 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1757 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1760 /* Store and send the Bulk-only CSW */
1761 csw = (void *)bh->buf;
1763 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1764 csw->Tag = common->tag;
1765 csw->Residue = cpu_to_le32(common->residue);
1766 csw->Status = status;
1768 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1769 bh->inreq->zero = 0;
1770 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1771 &bh->inreq_busy, &bh->state)
1772 /* Don't know what to do if common->fsg is NULL */
1775 common->next_buffhd_to_fill = bh->next;
1780 /*-------------------------------------------------------------------------*/
1782 /* Check whether the command is properly formed and whether its data size
1783 * and direction agree with the values we already have. */
1784 static int check_command(struct fsg_common *common, int cmnd_size,
1785 enum data_direction data_dir, unsigned int mask,
1786 int needs_medium, const char *name)
1789 int lun = common->cmnd[1] >> 5;
1790 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1792 struct fsg_lun *curlun;
1795 if (common->data_dir != DATA_DIR_UNKNOWN)
1796 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1798 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1799 name, cmnd_size, dirletter[(int) data_dir],
1800 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1802 /* We can't reply at all until we know the correct data direction
1804 if (common->data_size_from_cmnd == 0)
1805 data_dir = DATA_DIR_NONE;
1806 if (common->data_size < common->data_size_from_cmnd) {
1807 /* Host data size < Device data size is a phase error.
1808 * Carry out the command, but only transfer as much as
1809 * we are allowed. */
1810 common->data_size_from_cmnd = common->data_size;
1811 common->phase_error = 1;
1813 common->residue = common->data_size;
1814 common->usb_amount_left = common->data_size;
1816 /* Conflicting data directions is a phase error */
1817 if (common->data_dir != data_dir
1818 && common->data_size_from_cmnd > 0) {
1819 common->phase_error = 1;
1823 /* Verify the length of the command itself */
1824 if (cmnd_size != common->cmnd_size) {
1826 /* Special case workaround: There are plenty of buggy SCSI
1827 * implementations. Many have issues with cbw->Length
1828 * field passing a wrong command size. For those cases we
1829 * always try to work around the problem by using the length
1830 * sent by the host side provided it is at least as large
1831 * as the correct command length.
1832 * Examples of such cases would be MS-Windows, which issues
1833 * REQUEST SENSE with cbw->Length == 12 where it should
1834 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1835 * REQUEST SENSE with cbw->Length == 10 where it should
1838 if (cmnd_size <= common->cmnd_size) {
1839 DBG(common, "%s is buggy! Expected length %d "
1840 "but we got %d\n", name,
1841 cmnd_size, common->cmnd_size);
1842 cmnd_size = common->cmnd_size;
1844 common->phase_error = 1;
1849 /* Check that the LUN values are consistent */
1850 if (common->lun != lun)
1851 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1855 if (common->lun >= 0 && common->lun < common->nluns) {
1856 curlun = &common->luns[common->lun];
1857 common->curlun = curlun;
1858 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1859 curlun->sense_data = SS_NO_SENSE;
1860 curlun->sense_data_info = 0;
1861 curlun->info_valid = 0;
1864 common->curlun = NULL;
1866 common->bad_lun_okay = 0;
1868 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1869 * to use unsupported LUNs; all others may not. */
1870 if (common->cmnd[0] != SC_INQUIRY &&
1871 common->cmnd[0] != SC_REQUEST_SENSE) {
1872 DBG(common, "unsupported LUN %d\n", common->lun);
1877 /* If a unit attention condition exists, only INQUIRY and
1878 * REQUEST SENSE commands are allowed; anything else must fail. */
1879 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1880 common->cmnd[0] != SC_INQUIRY &&
1881 common->cmnd[0] != SC_REQUEST_SENSE) {
1882 curlun->sense_data = curlun->unit_attention_data;
1883 curlun->unit_attention_data = SS_NO_SENSE;
1887 /* Check that only command bytes listed in the mask are non-zero */
1888 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1889 for (i = 1; i < cmnd_size; ++i) {
1890 if (common->cmnd[i] && !(mask & (1 << i))) {
1892 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1897 /* If the medium isn't mounted and the command needs to access
1898 * it, return an error. */
1899 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1900 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1908 static int do_scsi_command(struct fsg_common *common)
1910 struct fsg_buffhd *bh;
1912 int reply = -EINVAL;
1914 static char unknown[16];
1918 /* Wait for the next buffer to become available for data or status */
1919 bh = common->next_buffhd_to_fill;
1920 common->next_buffhd_to_drain = bh;
1921 while (bh->state != BUF_STATE_EMPTY) {
1922 rc = sleep_thread(common);
1926 common->phase_error = 0;
1927 common->short_packet_received = 0;
1929 down_read(&common->filesem); /* We're using the backing file */
1930 switch (common->cmnd[0]) {
1933 common->data_size_from_cmnd = common->cmnd[4];
1934 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1938 reply = do_inquiry(common, bh);
1941 case SC_MODE_SELECT_6:
1942 common->data_size_from_cmnd = common->cmnd[4];
1943 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1947 reply = do_mode_select(common, bh);
1950 case SC_MODE_SELECT_10:
1951 common->data_size_from_cmnd =
1952 get_unaligned_be16(&common->cmnd[7]);
1953 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1957 reply = do_mode_select(common, bh);
1960 case SC_MODE_SENSE_6:
1961 common->data_size_from_cmnd = common->cmnd[4];
1962 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1963 (1<<1) | (1<<2) | (1<<4), 0,
1966 reply = do_mode_sense(common, bh);
1969 case SC_MODE_SENSE_10:
1970 common->data_size_from_cmnd =
1971 get_unaligned_be16(&common->cmnd[7]);
1972 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1973 (1<<1) | (1<<2) | (3<<7), 0,
1976 reply = do_mode_sense(common, bh);
1979 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1980 common->data_size_from_cmnd = 0;
1981 reply = check_command(common, 6, DATA_DIR_NONE,
1983 "PREVENT-ALLOW MEDIUM REMOVAL");
1985 reply = do_prevent_allow(common);
1989 i = common->cmnd[4];
1990 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1991 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1995 reply = do_read(common);
1999 common->data_size_from_cmnd =
2000 get_unaligned_be16(&common->cmnd[7]) << 9;
2001 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2002 (1<<1) | (0xf<<2) | (3<<7), 1,
2005 reply = do_read(common);
2009 common->data_size_from_cmnd =
2010 get_unaligned_be32(&common->cmnd[6]) << 9;
2011 reply = check_command(common, 12, DATA_DIR_TO_HOST,
2012 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2015 reply = do_read(common);
2018 case SC_READ_CAPACITY:
2019 common->data_size_from_cmnd = 8;
2020 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2021 (0xf<<2) | (1<<8), 1,
2024 reply = do_read_capacity(common, bh);
2027 case SC_READ_HEADER:
2028 if (!common->curlun || !common->curlun->cdrom)
2030 common->data_size_from_cmnd =
2031 get_unaligned_be16(&common->cmnd[7]);
2032 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2033 (3<<7) | (0x1f<<1), 1,
2036 reply = do_read_header(common, bh);
2040 if (!common->curlun || !common->curlun->cdrom)
2042 common->data_size_from_cmnd =
2043 get_unaligned_be16(&common->cmnd[7]);
2044 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2048 reply = do_read_toc(common, bh);
2051 case SC_READ_FORMAT_CAPACITIES:
2052 common->data_size_from_cmnd =
2053 get_unaligned_be16(&common->cmnd[7]);
2054 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2056 "READ FORMAT CAPACITIES");
2058 reply = do_read_format_capacities(common, bh);
2061 case SC_REQUEST_SENSE:
2062 common->data_size_from_cmnd = common->cmnd[4];
2063 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2067 reply = do_request_sense(common, bh);
2070 case SC_START_STOP_UNIT:
2071 common->data_size_from_cmnd = 0;
2072 reply = check_command(common, 6, DATA_DIR_NONE,
2076 reply = do_start_stop(common);
2079 case SC_SYNCHRONIZE_CACHE:
2080 common->data_size_from_cmnd = 0;
2081 reply = check_command(common, 10, DATA_DIR_NONE,
2082 (0xf<<2) | (3<<7), 1,
2083 "SYNCHRONIZE CACHE");
2085 reply = do_synchronize_cache(common);
2088 case SC_TEST_UNIT_READY:
2089 common->data_size_from_cmnd = 0;
2090 reply = check_command(common, 6, DATA_DIR_NONE,
2095 /* Although optional, this command is used by MS-Windows. We
2096 * support a minimal version: BytChk must be 0. */
2098 common->data_size_from_cmnd = 0;
2099 reply = check_command(common, 10, DATA_DIR_NONE,
2100 (1<<1) | (0xf<<2) | (3<<7), 1,
2103 reply = do_verify(common);
2107 i = common->cmnd[4];
2108 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2109 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2113 reply = do_write(common);
2117 common->data_size_from_cmnd =
2118 get_unaligned_be16(&common->cmnd[7]) << 9;
2119 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2120 (1<<1) | (0xf<<2) | (3<<7), 1,
2123 reply = do_write(common);
2127 common->data_size_from_cmnd =
2128 get_unaligned_be32(&common->cmnd[6]) << 9;
2129 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2130 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2133 reply = do_write(common);
2136 /* Some mandatory commands that we recognize but don't implement.
2137 * They don't mean much in this setting. It's left as an exercise
2138 * for anyone interested to implement RESERVE and RELEASE in terms
2139 * of Posix locks. */
2140 case SC_FORMAT_UNIT:
2143 case SC_SEND_DIAGNOSTIC:
2148 common->data_size_from_cmnd = 0;
2149 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2150 reply = check_command(common, common->cmnd_size,
2151 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2153 common->curlun->sense_data = SS_INVALID_COMMAND;
2158 up_read(&common->filesem);
2160 if (reply == -EINTR || signal_pending(current))
2163 /* Set up the single reply buffer for finish_reply() */
2164 if (reply == -EINVAL)
2165 reply = 0; /* Error reply length */
2166 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2167 reply = min((u32) reply, common->data_size_from_cmnd);
2168 bh->inreq->length = reply;
2169 bh->state = BUF_STATE_FULL;
2170 common->residue -= reply;
2171 } /* Otherwise it's already set */
2177 /*-------------------------------------------------------------------------*/
2179 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2181 struct usb_request *req = bh->outreq;
2182 struct fsg_bulk_cb_wrap *cbw = req->buf;
2183 struct fsg_common *common = fsg->common;
2185 /* Was this a real packet? Should it be ignored? */
2186 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2189 /* Is the CBW valid? */
2190 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2191 cbw->Signature != cpu_to_le32(
2193 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2195 le32_to_cpu(cbw->Signature));
2197 /* The Bulk-only spec says we MUST stall the IN endpoint
2198 * (6.6.1), so it's unavoidable. It also says we must
2199 * retain this state until the next reset, but there's
2200 * no way to tell the controller driver it should ignore
2201 * Clear-Feature(HALT) requests.
2203 * We aren't required to halt the OUT endpoint; instead
2204 * we can simply accept and discard any data received
2205 * until the next reset. */
2206 wedge_bulk_in_endpoint(fsg);
2207 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2211 /* Is the CBW meaningful? */
2212 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2213 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2214 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2216 cbw->Lun, cbw->Flags, cbw->Length);
2218 /* We can do anything we want here, so let's stall the
2219 * bulk pipes if we are allowed to. */
2220 if (common->can_stall) {
2221 fsg_set_halt(fsg, fsg->bulk_out);
2222 halt_bulk_in_endpoint(fsg);
2227 /* Save the command for later */
2228 common->cmnd_size = cbw->Length;
2229 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2230 if (cbw->Flags & USB_BULK_IN_FLAG)
2231 common->data_dir = DATA_DIR_TO_HOST;
2233 common->data_dir = DATA_DIR_FROM_HOST;
2234 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2235 if (common->data_size == 0)
2236 common->data_dir = DATA_DIR_NONE;
2237 common->lun = cbw->Lun;
2238 common->tag = cbw->Tag;
2243 static int get_next_command(struct fsg_common *common)
2245 struct fsg_buffhd *bh;
2248 /* Wait for the next buffer to become available */
2249 bh = common->next_buffhd_to_fill;
2250 while (bh->state != BUF_STATE_EMPTY) {
2251 rc = sleep_thread(common);
2256 /* Queue a request to read a Bulk-only CBW */
2257 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2258 bh->outreq->short_not_ok = 1;
2259 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2260 &bh->outreq_busy, &bh->state)
2261 /* Don't know what to do if common->fsg is NULL */
2264 /* We will drain the buffer in software, which means we
2265 * can reuse it for the next filling. No need to advance
2266 * next_buffhd_to_fill. */
2268 /* Wait for the CBW to arrive */
2269 while (bh->state != BUF_STATE_FULL) {
2270 rc = sleep_thread(common);
2275 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2276 bh->state = BUF_STATE_EMPTY;
2282 /*-------------------------------------------------------------------------*/
2284 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2285 const struct usb_endpoint_descriptor *d)
2289 ep->driver_data = common;
2290 rc = usb_ep_enable(ep, d);
2292 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2296 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2297 struct usb_request **preq)
2299 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2302 ERROR(common, "can't allocate request for %s\n", ep->name);
2307 * Reset interface setting and re-init endpoint state (toggle etc).
2308 * Call with altsetting < 0 to disable the interface. The only other
2309 * available altsetting is 0, which enables the interface.
2311 static int do_set_interface(struct fsg_common *common, int altsetting)
2315 const struct usb_endpoint_descriptor *d;
2317 if (common->running)
2318 DBG(common, "reset interface\n");
2321 /* Deallocate the requests */
2322 if (common->prev_fsg) {
2323 struct fsg_dev *fsg = common->prev_fsg;
2325 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2326 struct fsg_buffhd *bh = &common->buffhds[i];
2329 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2333 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2338 /* Disable the endpoints */
2339 if (fsg->bulk_in_enabled) {
2340 usb_ep_disable(fsg->bulk_in);
2341 fsg->bulk_in_enabled = 0;
2343 if (fsg->bulk_out_enabled) {
2344 usb_ep_disable(fsg->bulk_out);
2345 fsg->bulk_out_enabled = 0;
2348 common->prev_fsg = 0;
2351 common->running = 0;
2352 if (altsetting < 0 || rc != 0)
2355 DBG(common, "set interface %d\n", altsetting);
2357 if (fsg_is_set(common)) {
2358 struct fsg_dev *fsg = common->fsg;
2359 common->prev_fsg = common->fsg;
2361 /* Enable the endpoints */
2362 d = fsg_ep_desc(common->gadget,
2363 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2364 rc = enable_endpoint(common, fsg->bulk_in, d);
2367 fsg->bulk_in_enabled = 1;
2369 d = fsg_ep_desc(common->gadget,
2370 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2371 rc = enable_endpoint(common, fsg->bulk_out, d);
2374 fsg->bulk_out_enabled = 1;
2375 common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2376 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2378 /* Allocate the requests */
2379 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2380 struct fsg_buffhd *bh = &common->buffhds[i];
2382 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2385 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2388 bh->inreq->buf = bh->outreq->buf = bh->buf;
2389 bh->inreq->context = bh->outreq->context = bh;
2390 bh->inreq->complete = bulk_in_complete;
2391 bh->outreq->complete = bulk_out_complete;
2394 common->running = 1;
2395 for (i = 0; i < common->nluns; ++i)
2396 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2405 * Change our operational configuration. This code must agree with the code
2406 * that returns config descriptors, and with interface altsetting code.
2408 * It's also responsible for power management interactions. Some
2409 * configurations might not work with our current power sources.
2410 * For now we just assume the gadget is always self-powered.
2412 static int do_set_config(struct fsg_common *common, u8 new_config)
2416 /* Disable the single interface */
2417 if (common->config != 0) {
2418 DBG(common, "reset config\n");
2420 rc = do_set_interface(common, -1);
2423 /* Enable the interface */
2424 if (new_config != 0) {
2425 common->config = new_config;
2426 rc = do_set_interface(common, 0);
2428 common->config = 0; /* Reset on errors */
2434 /****************************** ALT CONFIGS ******************************/
2437 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2439 struct fsg_dev *fsg = fsg_from_func(f);
2440 fsg->common->prev_fsg = fsg->common->fsg;
2441 fsg->common->fsg = fsg;
2442 fsg->common->new_config = 1;
2443 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2447 static void fsg_disable(struct usb_function *f)
2449 struct fsg_dev *fsg = fsg_from_func(f);
2450 fsg->common->prev_fsg = fsg->common->fsg;
2451 fsg->common->fsg = fsg;
2452 fsg->common->new_config = 0;
2453 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2457 /*-------------------------------------------------------------------------*/
2459 static void handle_exception(struct fsg_common *common)
2464 struct fsg_buffhd *bh;
2465 enum fsg_state old_state;
2467 struct fsg_lun *curlun;
2468 unsigned int exception_req_tag;
2471 /* Clear the existing signals. Anything but SIGUSR1 is converted
2472 * into a high-priority EXIT exception. */
2474 sig = dequeue_signal_lock(current, ¤t->blocked, &info);
2477 if (sig != SIGUSR1) {
2478 if (common->state < FSG_STATE_EXIT)
2479 DBG(common, "Main thread exiting on signal\n");
2480 raise_exception(common, FSG_STATE_EXIT);
2484 /* Cancel all the pending transfers */
2485 if (fsg_is_set(common)) {
2486 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2487 bh = &common->buffhds[i];
2489 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2490 if (bh->outreq_busy)
2491 usb_ep_dequeue(common->fsg->bulk_out,
2495 /* Wait until everything is idle */
2498 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2499 bh = &common->buffhds[i];
2500 num_active += bh->inreq_busy + bh->outreq_busy;
2502 if (num_active == 0)
2504 if (sleep_thread(common))
2508 /* Clear out the controller's fifos */
2509 if (common->fsg->bulk_in_enabled)
2510 usb_ep_fifo_flush(common->fsg->bulk_in);
2511 if (common->fsg->bulk_out_enabled)
2512 usb_ep_fifo_flush(common->fsg->bulk_out);
2515 /* Reset the I/O buffer states and pointers, the SCSI
2516 * state, and the exception. Then invoke the handler. */
2517 spin_lock_irq(&common->lock);
2519 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2520 bh = &common->buffhds[i];
2521 bh->state = BUF_STATE_EMPTY;
2523 common->next_buffhd_to_fill = &common->buffhds[0];
2524 common->next_buffhd_to_drain = &common->buffhds[0];
2525 exception_req_tag = common->exception_req_tag;
2526 new_config = common->new_config;
2527 old_state = common->state;
2529 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2530 common->state = FSG_STATE_STATUS_PHASE;
2532 for (i = 0; i < common->nluns; ++i) {
2533 curlun = &common->luns[i];
2534 curlun->prevent_medium_removal = 0;
2535 curlun->sense_data = SS_NO_SENSE;
2536 curlun->unit_attention_data = SS_NO_SENSE;
2537 curlun->sense_data_info = 0;
2538 curlun->info_valid = 0;
2540 common->state = FSG_STATE_IDLE;
2542 spin_unlock_irq(&common->lock);
2544 /* Carry out any extra actions required for the exception */
2545 switch (old_state) {
2546 case FSG_STATE_ABORT_BULK_OUT:
2547 send_status(common);
2548 spin_lock_irq(&common->lock);
2549 if (common->state == FSG_STATE_STATUS_PHASE)
2550 common->state = FSG_STATE_IDLE;
2551 spin_unlock_irq(&common->lock);
2554 case FSG_STATE_RESET:
2555 /* In case we were forced against our will to halt a
2556 * bulk endpoint, clear the halt now. (The SuperH UDC
2557 * requires this.) */
2558 if (!fsg_is_set(common))
2560 if (test_and_clear_bit(IGNORE_BULK_OUT,
2561 &common->fsg->atomic_bitflags))
2562 usb_ep_clear_halt(common->fsg->bulk_in);
2564 if (common->ep0_req_tag == exception_req_tag)
2565 ep0_queue(common); /* Complete the status stage */
2567 /* Technically this should go here, but it would only be
2568 * a waste of time. Ditto for the INTERFACE_CHANGE and
2569 * CONFIG_CHANGE cases. */
2570 /* for (i = 0; i < common->nluns; ++i) */
2571 /* common->luns[i].unit_attention_data = */
2572 /* SS_RESET_OCCURRED; */
2575 case FSG_STATE_CONFIG_CHANGE:
2576 rc = do_set_config(common, new_config);
2579 case FSG_STATE_EXIT:
2580 case FSG_STATE_TERMINATED:
2581 do_set_config(common, 0); /* Free resources */
2582 spin_lock_irq(&common->lock);
2583 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2584 spin_unlock_irq(&common->lock);
2587 case FSG_STATE_INTERFACE_CHANGE:
2588 case FSG_STATE_DISCONNECT:
2589 case FSG_STATE_COMMAND_PHASE:
2590 case FSG_STATE_DATA_PHASE:
2591 case FSG_STATE_STATUS_PHASE:
2592 case FSG_STATE_IDLE:
2598 /*-------------------------------------------------------------------------*/
2600 static int fsg_main_thread(void *common_)
2602 struct fsg_common *common = common_;
2604 /* Allow the thread to be killed by a signal, but set the signal mask
2605 * to block everything but INT, TERM, KILL, and USR1. */
2606 allow_signal(SIGINT);
2607 allow_signal(SIGTERM);
2608 allow_signal(SIGKILL);
2609 allow_signal(SIGUSR1);
2611 /* Allow the thread to be frozen */
2614 /* Arrange for userspace references to be interpreted as kernel
2615 * pointers. That way we can pass a kernel pointer to a routine
2616 * that expects a __user pointer and it will work okay. */
2620 while (common->state != FSG_STATE_TERMINATED) {
2621 if (exception_in_progress(common) || signal_pending(current)) {
2622 handle_exception(common);
2626 if (!common->running) {
2627 sleep_thread(common);
2631 if (get_next_command(common))
2634 spin_lock_irq(&common->lock);
2635 if (!exception_in_progress(common))
2636 common->state = FSG_STATE_DATA_PHASE;
2637 spin_unlock_irq(&common->lock);
2639 if (do_scsi_command(common) || finish_reply(common))
2642 spin_lock_irq(&common->lock);
2643 if (!exception_in_progress(common))
2644 common->state = FSG_STATE_STATUS_PHASE;
2645 spin_unlock_irq(&common->lock);
2647 if (send_status(common))
2650 spin_lock_irq(&common->lock);
2651 if (!exception_in_progress(common))
2652 common->state = FSG_STATE_IDLE;
2653 spin_unlock_irq(&common->lock);
2656 spin_lock_irq(&common->lock);
2657 common->thread_task = NULL;
2658 spin_unlock_irq(&common->lock);
2660 if (!common->thread_exits || common->thread_exits(common) < 0) {
2661 struct fsg_lun *curlun = common->luns;
2662 unsigned i = common->nluns;
2664 down_write(&common->filesem);
2665 for (; i--; ++curlun) {
2666 if (!fsg_lun_is_open(curlun))
2669 fsg_lun_close(curlun);
2670 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2672 up_write(&common->filesem);
2675 /* Let the unbind and cleanup routines know the thread has exited */
2676 complete_and_exit(&common->thread_notifier, 0);
2680 /*************************** DEVICE ATTRIBUTES ***************************/
2682 /* Write permission is checked per LUN in store_*() functions. */
2683 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2684 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2687 /****************************** FSG COMMON ******************************/
2689 static void fsg_common_release(struct kref *ref);
2691 static void fsg_lun_release(struct device *dev)
2693 /* Nothing needs to be done */
2696 static inline void fsg_common_get(struct fsg_common *common)
2698 kref_get(&common->ref);
2701 static inline void fsg_common_put(struct fsg_common *common)
2703 kref_put(&common->ref, fsg_common_release);
2707 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2708 struct usb_composite_dev *cdev,
2709 struct fsg_config *cfg)
2711 struct usb_gadget *gadget = cdev->gadget;
2712 struct fsg_buffhd *bh;
2713 struct fsg_lun *curlun;
2714 struct fsg_lun_config *lcfg;
2718 /* Find out how many LUNs there should be */
2720 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2721 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2722 return ERR_PTR(-EINVAL);
2727 common = kzalloc(sizeof *common, GFP_KERNEL);
2729 return ERR_PTR(-ENOMEM);
2730 common->free_storage_on_release = 1;
2732 memset(common, 0, sizeof common);
2733 common->free_storage_on_release = 0;
2736 common->private_data = cfg->private_data;
2738 common->gadget = gadget;
2739 common->ep0 = gadget->ep0;
2740 common->ep0req = cdev->req;
2742 /* Maybe allocate device-global string IDs, and patch descriptors */
2743 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2744 rc = usb_string_id(cdev);
2749 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2750 fsg_intf_desc.iInterface = rc;
2753 /* Create the LUNs, open their backing files, and register the
2754 * LUN devices in sysfs. */
2755 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2758 return ERR_PTR(-ENOMEM);
2760 common->luns = curlun;
2762 init_rwsem(&common->filesem);
2764 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2765 curlun->cdrom = !!lcfg->cdrom;
2766 curlun->ro = lcfg->cdrom || lcfg->ro;
2767 curlun->removable = lcfg->removable;
2768 curlun->dev.release = fsg_lun_release;
2769 curlun->dev.parent = &gadget->dev;
2770 /* curlun->dev.driver = &fsg_driver.driver; XXX */
2771 dev_set_drvdata(&curlun->dev, &common->filesem);
2772 dev_set_name(&curlun->dev,
2773 cfg->lun_name_format
2774 ? cfg->lun_name_format
2778 rc = device_register(&curlun->dev);
2780 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2785 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2788 rc = device_create_file(&curlun->dev, &dev_attr_file);
2792 if (lcfg->filename) {
2793 rc = fsg_lun_open(curlun, lcfg->filename);
2796 } else if (!curlun->removable) {
2797 ERROR(common, "no file given for LUN%d\n", i);
2802 common->nluns = nluns;
2805 /* Data buffers cyclic list */
2806 bh = common->buffhds;
2807 i = FSG_NUM_BUFFERS;
2808 goto buffhds_first_it;
2813 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2814 if (unlikely(!bh->buf)) {
2819 bh->next = common->buffhds;
2822 /* Prepare inquiryString */
2823 if (cfg->release != 0xffff) {
2826 i = usb_gadget_controller_number(gadget);
2830 WARNING(common, "controller '%s' not recognized\n",
2835 #define OR(x, y) ((x) ? (x) : (y))
2836 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2838 OR(cfg->vendor_name, "Linux "),
2839 /* Assume product name dependent on the first LUN */
2840 OR(cfg->product_name, common->luns->cdrom
2841 ? "File-Stor Gadget"
2842 : "File-CD Gadget "),
2846 /* Some peripheral controllers are known not to be able to
2847 * halt bulk endpoints correctly. If one of them is present,
2850 common->can_stall = cfg->can_stall &&
2851 !(gadget_is_at91(common->gadget));
2854 spin_lock_init(&common->lock);
2855 kref_init(&common->ref);
2858 /* Tell the thread to start working */
2859 common->thread_exits = cfg->thread_exits;
2860 common->thread_task =
2861 kthread_create(fsg_main_thread, common,
2862 OR(cfg->thread_name, "file-storage"));
2863 if (IS_ERR(common->thread_task)) {
2864 rc = PTR_ERR(common->thread_task);
2867 init_completion(&common->thread_notifier);
2872 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2873 INFO(common, "Number of LUNs=%d\n", common->nluns);
2875 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2876 for (i = 0, nluns = common->nluns, curlun = common->luns;
2879 char *p = "(no medium)";
2880 if (fsg_lun_is_open(curlun)) {
2883 p = d_path(&curlun->filp->f_path,
2889 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
2890 curlun->removable ? "removable " : "",
2891 curlun->ro ? "read only " : "",
2892 curlun->cdrom ? "CD-ROM " : "",
2897 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
2899 wake_up_process(common->thread_task);
2905 common->nluns = i + 1;
2907 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2908 /* Call fsg_common_release() directly, ref might be not
2910 fsg_common_release(&common->ref);
2915 static void fsg_common_release(struct kref *ref)
2917 struct fsg_common *common =
2918 container_of(ref, struct fsg_common, ref);
2919 unsigned i = common->nluns;
2920 struct fsg_lun *lun = common->luns;
2921 struct fsg_buffhd *bh;
2923 /* If the thread isn't already dead, tell it to exit now */
2924 if (common->state != FSG_STATE_TERMINATED) {
2925 raise_exception(common, FSG_STATE_EXIT);
2926 wait_for_completion(&common->thread_notifier);
2928 /* The cleanup routine waits for this completion also */
2929 complete(&common->thread_notifier);
2932 /* Beware tempting for -> do-while optimization: when in error
2933 * recovery nluns may be zero. */
2935 for (; i; --i, ++lun) {
2936 device_remove_file(&lun->dev, &dev_attr_ro);
2937 device_remove_file(&lun->dev, &dev_attr_file);
2939 device_unregister(&lun->dev);
2942 kfree(common->luns);
2944 i = FSG_NUM_BUFFERS;
2945 bh = common->buffhds;
2948 } while (++bh, --i);
2950 if (common->free_storage_on_release)
2955 /*-------------------------------------------------------------------------*/
2958 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2960 struct fsg_dev *fsg = fsg_from_func(f);
2962 DBG(fsg, "unbind\n");
2963 fsg_common_put(fsg->common);
2964 usb_free_descriptors(fsg->function.descriptors);
2965 usb_free_descriptors(fsg->function.hs_descriptors);
2970 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2972 struct fsg_dev *fsg = fsg_from_func(f);
2973 struct usb_gadget *gadget = c->cdev->gadget;
2978 fsg->gadget = gadget;
2981 i = usb_interface_id(c, f);
2984 fsg_intf_desc.bInterfaceNumber = i;
2985 fsg->interface_number = i;
2987 /* Find all the endpoints we will use */
2988 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2991 ep->driver_data = fsg->common; /* claim the endpoint */
2994 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2997 ep->driver_data = fsg->common; /* claim the endpoint */
3000 if (gadget_is_dualspeed(gadget)) {
3001 /* Assume endpoint addresses are the same for both speeds */
3002 fsg_hs_bulk_in_desc.bEndpointAddress =
3003 fsg_fs_bulk_in_desc.bEndpointAddress;
3004 fsg_hs_bulk_out_desc.bEndpointAddress =
3005 fsg_fs_bulk_out_desc.bEndpointAddress;
3006 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
3007 if (unlikely(!f->hs_descriptors))
3014 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3020 /****************************** ADD FUNCTION ******************************/
3022 static struct usb_gadget_strings *fsg_strings_array[] = {
3027 static int fsg_add(struct usb_composite_dev *cdev,
3028 struct usb_configuration *c,
3029 struct fsg_common *common)
3031 struct fsg_dev *fsg;
3034 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3038 fsg->function.name = FSG_DRIVER_DESC;
3039 fsg->function.strings = fsg_strings_array;
3040 fsg->function.descriptors = usb_copy_descriptors(fsg_fs_function);
3041 if (unlikely(!fsg->function.descriptors)) {
3043 goto error_free_fsg;
3045 fsg->function.bind = fsg_bind;
3046 fsg->function.unbind = fsg_unbind;
3047 fsg->function.setup = fsg_setup;
3048 fsg->function.set_alt = fsg_set_alt;
3049 fsg->function.disable = fsg_disable;
3051 fsg->common = common;
3052 /* Our caller holds a reference to common structure so we
3053 * don't have to be worry about it being freed until we return
3054 * from this function. So instead of incrementing counter now
3055 * and decrement in error recovery we increment it only when
3056 * call to usb_add_function() was successful. */
3058 rc = usb_add_function(c, &fsg->function);
3060 goto error_free_all;
3062 fsg_common_get(fsg->common);
3066 usb_free_descriptors(fsg->function.descriptors);
3067 /* fsg_bind() might have copied those; or maybe not? who cares
3068 * -- free it just in case. */
3069 usb_free_descriptors(fsg->function.hs_descriptors);
3078 /************************* Module parameters *************************/
3081 struct fsg_module_parameters {
3082 char *file[FSG_MAX_LUNS];
3083 int ro[FSG_MAX_LUNS];
3084 int removable[FSG_MAX_LUNS];
3085 int cdrom[FSG_MAX_LUNS];
3087 unsigned int file_count, ro_count, removable_count, cdrom_count;
3088 unsigned int luns; /* nluns */
3089 int stall; /* can_stall */
3093 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3094 module_param_array_named(prefix ## name, params.name, type, \
3095 &prefix ## params.name ## _count, \
3097 MODULE_PARM_DESC(prefix ## name, desc)
3099 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3100 module_param_named(prefix ## name, params.name, type, \
3102 MODULE_PARM_DESC(prefix ## name, desc)
3104 #define FSG_MODULE_PARAMETERS(prefix, params) \
3105 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3106 "names of backing files or devices"); \
3107 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3108 "true to force read-only"); \
3109 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3110 "true to simulate removable media"); \
3111 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3112 "true to simulate CD-ROM instead of disk"); \
3113 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3114 "number of LUNs"); \
3115 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3116 "false to prevent bulk stalls")
3120 fsg_config_from_params(struct fsg_config *cfg,
3121 const struct fsg_module_parameters *params)
3123 struct fsg_lun_config *lun;
3126 /* Configure LUNs */
3128 min(params->luns ?: (params->file_count ?: 1u),
3129 (unsigned)FSG_MAX_LUNS);
3130 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3131 lun->ro = !!params->ro[i];
3132 lun->cdrom = !!params->cdrom[i];
3133 lun->removable = /* Removable by default */
3134 params->removable_count <= i || params->removable[i];
3136 params->file_count > i && params->file[i][0]
3141 /* Let MSF use defaults */
3142 cfg->lun_name_format = 0;
3143 cfg->thread_name = 0;
3144 cfg->vendor_name = 0;
3145 cfg->product_name = 0;
3146 cfg->release = 0xffff;
3148 cfg->thread_exits = 0;
3149 cfg->private_data = 0;
3152 cfg->can_stall = params->stall;
3155 static inline struct fsg_common *
3156 fsg_common_from_params(struct fsg_common *common,
3157 struct usb_composite_dev *cdev,
3158 const struct fsg_module_parameters *params)
3159 __attribute__((unused));
3160 static inline struct fsg_common *
3161 fsg_common_from_params(struct fsg_common *common,
3162 struct usb_composite_dev *cdev,
3163 const struct fsg_module_parameters *params)
3165 struct fsg_config cfg;
3166 fsg_config_from_params(&cfg, params);
3167 return fsg_common_init(common, cdev, &cfg);