2 * f_mass_storage.c -- Mass Storage USB Composite Function
4 * Copyright (C) 2003-2008 Alan Stern
5 * Copyright (C) 2009 Samsung Electronics
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;
324 struct fsg_dev *fsg, *new_fsg;
325 wait_queue_head_t fsg_wait;
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 enum data_direction data_dir;
356 u32 data_size_from_cmnd;
361 unsigned int can_stall:1;
362 unsigned int free_storage_on_release:1;
363 unsigned int phase_error:1;
364 unsigned int short_packet_received:1;
365 unsigned int bad_lun_okay:1;
366 unsigned int running:1;
368 int thread_wakeup_needed;
369 struct completion thread_notifier;
370 struct task_struct *thread_task;
372 /* Callback function to call when thread exits. */
373 int (*thread_exits)(struct fsg_common *common);
374 /* Gadget's private data. */
377 /* Vendor (8 chars), product (16 chars), release (4
378 * hexadecimal digits) and NUL byte */
379 char inquiry_string[8 + 16 + 4 + 1];
387 struct fsg_lun_config {
388 const char *filename;
392 } luns[FSG_MAX_LUNS];
394 const char *lun_name_format;
395 const char *thread_name;
397 /* Callback function to call when thread exits. If no
398 * callback is set or it returns value lower then zero MSF
399 * will force eject all LUNs it operates on (including those
400 * marked as non-removable or with prevent_medium_removal flag
402 int (*thread_exits)(struct fsg_common *common);
403 /* Gadget's private data. */
406 const char *vendor_name; /* 8 characters or less */
407 const char *product_name; /* 16 characters or less */
415 struct usb_function function;
416 struct usb_gadget *gadget; /* Copy of cdev->gadget */
417 struct fsg_common *common;
419 u16 interface_number;
421 unsigned int bulk_in_enabled:1;
422 unsigned int bulk_out_enabled:1;
424 unsigned long atomic_bitflags;
425 #define IGNORE_BULK_OUT 0
427 struct usb_ep *bulk_in;
428 struct usb_ep *bulk_out;
432 static inline int __fsg_is_set(struct fsg_common *common,
433 const char *func, unsigned line)
437 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
441 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
444 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
446 return container_of(f, struct fsg_dev, function);
450 typedef void (*fsg_routine_t)(struct fsg_dev *);
452 static int exception_in_progress(struct fsg_common *common)
454 return common->state > FSG_STATE_IDLE;
457 /* Make bulk-out requests be divisible by the maxpacket size */
458 static void set_bulk_out_req_length(struct fsg_common *common,
459 struct fsg_buffhd *bh, unsigned int length)
463 bh->bulk_out_intended_length = length;
464 rem = length % common->bulk_out_maxpacket;
466 length += common->bulk_out_maxpacket - rem;
467 bh->outreq->length = length;
470 /*-------------------------------------------------------------------------*/
472 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
476 if (ep == fsg->bulk_in)
478 else if (ep == fsg->bulk_out)
482 DBG(fsg, "%s set halt\n", name);
483 return usb_ep_set_halt(ep);
487 /*-------------------------------------------------------------------------*/
489 /* These routines may be called in process context or in_irq */
491 /* Caller must hold fsg->lock */
492 static void wakeup_thread(struct fsg_common *common)
494 /* Tell the main thread that something has happened */
495 common->thread_wakeup_needed = 1;
496 if (common->thread_task)
497 wake_up_process(common->thread_task);
501 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
505 /* Do nothing if a higher-priority exception is already in progress.
506 * If a lower-or-equal priority exception is in progress, preempt it
507 * and notify the main thread by sending it a signal. */
508 spin_lock_irqsave(&common->lock, flags);
509 if (common->state <= new_state) {
510 common->exception_req_tag = common->ep0_req_tag;
511 common->state = new_state;
512 if (common->thread_task)
513 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
514 common->thread_task);
516 spin_unlock_irqrestore(&common->lock, flags);
520 /*-------------------------------------------------------------------------*/
522 static int ep0_queue(struct fsg_common *common)
526 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
527 common->ep0->driver_data = common;
528 if (rc != 0 && rc != -ESHUTDOWN) {
529 /* We can't do much more than wait for a reset */
530 WARNING(common, "error in submission: %s --> %d\n",
531 common->ep0->name, rc);
536 /*-------------------------------------------------------------------------*/
538 /* Bulk and interrupt endpoint completion handlers.
539 * These always run in_irq. */
541 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
543 struct fsg_common *common = ep->driver_data;
544 struct fsg_buffhd *bh = req->context;
546 if (req->status || req->actual != req->length)
547 DBG(common, "%s --> %d, %u/%u\n", __func__,
548 req->status, req->actual, req->length);
549 if (req->status == -ECONNRESET) /* Request was cancelled */
550 usb_ep_fifo_flush(ep);
552 /* Hold the lock while we update the request and buffer states */
554 spin_lock(&common->lock);
556 bh->state = BUF_STATE_EMPTY;
557 wakeup_thread(common);
558 spin_unlock(&common->lock);
561 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
563 struct fsg_common *common = ep->driver_data;
564 struct fsg_buffhd *bh = req->context;
566 dump_msg(common, "bulk-out", req->buf, req->actual);
567 if (req->status || req->actual != bh->bulk_out_intended_length)
568 DBG(common, "%s --> %d, %u/%u\n", __func__,
569 req->status, req->actual,
570 bh->bulk_out_intended_length);
571 if (req->status == -ECONNRESET) /* Request was cancelled */
572 usb_ep_fifo_flush(ep);
574 /* Hold the lock while we update the request and buffer states */
576 spin_lock(&common->lock);
578 bh->state = BUF_STATE_FULL;
579 wakeup_thread(common);
580 spin_unlock(&common->lock);
584 /*-------------------------------------------------------------------------*/
586 /* Ep0 class-specific handlers. These always run in_irq. */
588 static int fsg_setup(struct usb_function *f,
589 const struct usb_ctrlrequest *ctrl)
591 struct fsg_dev *fsg = fsg_from_func(f);
592 struct usb_request *req = fsg->common->ep0req;
593 u16 w_index = le16_to_cpu(ctrl->wIndex);
594 u16 w_value = le16_to_cpu(ctrl->wValue);
595 u16 w_length = le16_to_cpu(ctrl->wLength);
597 if (!fsg_is_set(fsg->common))
600 switch (ctrl->bRequest) {
602 case USB_BULK_RESET_REQUEST:
603 if (ctrl->bRequestType !=
604 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
606 if (w_index != fsg->interface_number || w_value != 0)
609 /* Raise an exception to stop the current operation
610 * and reinitialize our state. */
611 DBG(fsg, "bulk reset request\n");
612 raise_exception(fsg->common, FSG_STATE_RESET);
613 return DELAYED_STATUS;
615 case USB_BULK_GET_MAX_LUN_REQUEST:
616 if (ctrl->bRequestType !=
617 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
619 if (w_index != fsg->interface_number || w_value != 0)
621 VDBG(fsg, "get max LUN\n");
622 *(u8 *) req->buf = fsg->common->nluns - 1;
624 /* Respond with data/status */
625 req->length = min((u16)1, w_length);
626 fsg->common->ep0req_name =
627 ctrl->bRequestType & USB_DIR_IN ? "ep0-in" : "ep0-out";
628 return ep0_queue(fsg->common);
632 "unknown class-specific control req "
633 "%02x.%02x v%04x i%04x l%u\n",
634 ctrl->bRequestType, ctrl->bRequest,
635 le16_to_cpu(ctrl->wValue), w_index, w_length);
640 /*-------------------------------------------------------------------------*/
642 /* All the following routines run in process context */
645 /* Use this for bulk or interrupt transfers, not ep0 */
646 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
647 struct usb_request *req, int *pbusy,
648 enum fsg_buffer_state *state)
652 if (ep == fsg->bulk_in)
653 dump_msg(fsg, "bulk-in", req->buf, req->length);
655 spin_lock_irq(&fsg->common->lock);
657 *state = BUF_STATE_BUSY;
658 spin_unlock_irq(&fsg->common->lock);
659 rc = usb_ep_queue(ep, req, GFP_KERNEL);
662 *state = BUF_STATE_EMPTY;
664 /* We can't do much more than wait for a reset */
666 /* Note: currently the net2280 driver fails zero-length
667 * submissions if DMA is enabled. */
668 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
670 WARNING(fsg, "error in submission: %s --> %d\n",
675 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
676 if (fsg_is_set(common)) \
677 start_transfer((common)->fsg, (common)->fsg->ep_name, \
678 req, pbusy, state); \
681 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
682 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
686 static int sleep_thread(struct fsg_common *common)
690 /* Wait until a signal arrives or we are woken up */
693 set_current_state(TASK_INTERRUPTIBLE);
694 if (signal_pending(current)) {
698 if (common->thread_wakeup_needed)
702 __set_current_state(TASK_RUNNING);
703 common->thread_wakeup_needed = 0;
708 /*-------------------------------------------------------------------------*/
710 static int do_read(struct fsg_common *common)
712 struct fsg_lun *curlun = common->curlun;
714 struct fsg_buffhd *bh;
717 loff_t file_offset, file_offset_tmp;
719 unsigned int partial_page;
722 /* Get the starting Logical Block Address and check that it's
724 if (common->cmnd[0] == SC_READ_6)
725 lba = get_unaligned_be24(&common->cmnd[1]);
727 lba = get_unaligned_be32(&common->cmnd[2]);
729 /* We allow DPO (Disable Page Out = don't save data in the
730 * cache) and FUA (Force Unit Access = don't read from the
731 * cache), but we don't implement them. */
732 if ((common->cmnd[1] & ~0x18) != 0) {
733 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
737 if (lba >= curlun->num_sectors) {
738 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
741 file_offset = ((loff_t) lba) << 9;
743 /* Carry out the file reads */
744 amount_left = common->data_size_from_cmnd;
745 if (unlikely(amount_left == 0))
746 return -EIO; /* No default reply */
750 /* Figure out how much we need to read:
751 * Try to read the remaining amount.
752 * But don't read more than the buffer size.
753 * And don't try to read past the end of the file.
754 * Finally, if we're not at a page boundary, don't read past
756 * If this means reading 0 then we were asked to read past
757 * the end of file. */
758 amount = min(amount_left, FSG_BUFLEN);
759 amount = min((loff_t) amount,
760 curlun->file_length - file_offset);
761 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
762 if (partial_page > 0)
763 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
766 /* Wait for the next buffer to become available */
767 bh = common->next_buffhd_to_fill;
768 while (bh->state != BUF_STATE_EMPTY) {
769 rc = sleep_thread(common);
774 /* If we were asked to read past the end of file,
775 * end with an empty buffer. */
778 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
779 curlun->sense_data_info = file_offset >> 9;
780 curlun->info_valid = 1;
781 bh->inreq->length = 0;
782 bh->state = BUF_STATE_FULL;
786 /* Perform the read */
787 file_offset_tmp = file_offset;
788 nread = vfs_read(curlun->filp,
789 (char __user *) bh->buf,
790 amount, &file_offset_tmp);
791 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
792 (unsigned long long) file_offset,
794 if (signal_pending(current))
798 LDBG(curlun, "error in file read: %d\n",
801 } else if (nread < amount) {
802 LDBG(curlun, "partial file read: %d/%u\n",
803 (int) nread, amount);
804 nread -= (nread & 511); /* Round down to a block */
806 file_offset += nread;
807 amount_left -= nread;
808 common->residue -= nread;
809 bh->inreq->length = nread;
810 bh->state = BUF_STATE_FULL;
812 /* If an error occurred, report it and its position */
813 if (nread < amount) {
814 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
815 curlun->sense_data_info = file_offset >> 9;
816 curlun->info_valid = 1;
820 if (amount_left == 0)
821 break; /* No more left to read */
823 /* Send this buffer and go read some more */
825 START_TRANSFER_OR(common, bulk_in, bh->inreq,
826 &bh->inreq_busy, &bh->state)
827 /* Don't know what to do if
828 * common->fsg is NULL */
830 common->next_buffhd_to_fill = bh->next;
833 return -EIO; /* No default reply */
837 /*-------------------------------------------------------------------------*/
839 static int do_write(struct fsg_common *common)
841 struct fsg_lun *curlun = common->curlun;
843 struct fsg_buffhd *bh;
845 u32 amount_left_to_req, amount_left_to_write;
846 loff_t usb_offset, file_offset, file_offset_tmp;
848 unsigned int partial_page;
853 curlun->sense_data = SS_WRITE_PROTECTED;
856 spin_lock(&curlun->filp->f_lock);
857 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
858 spin_unlock(&curlun->filp->f_lock);
860 /* Get the starting Logical Block Address and check that it's
862 if (common->cmnd[0] == SC_WRITE_6)
863 lba = get_unaligned_be24(&common->cmnd[1]);
865 lba = get_unaligned_be32(&common->cmnd[2]);
867 /* We allow DPO (Disable Page Out = don't save data in the
868 * cache) and FUA (Force Unit Access = write directly to the
869 * medium). We don't implement DPO; we implement FUA by
870 * performing synchronous output. */
871 if (common->cmnd[1] & ~0x18) {
872 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
875 if (common->cmnd[1] & 0x08) { /* FUA */
876 spin_lock(&curlun->filp->f_lock);
877 curlun->filp->f_flags |= O_SYNC;
878 spin_unlock(&curlun->filp->f_lock);
881 if (lba >= curlun->num_sectors) {
882 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
886 /* Carry out the file writes */
888 file_offset = usb_offset = ((loff_t) lba) << 9;
889 amount_left_to_req = common->data_size_from_cmnd;
890 amount_left_to_write = common->data_size_from_cmnd;
892 while (amount_left_to_write > 0) {
894 /* Queue a request for more data from the host */
895 bh = common->next_buffhd_to_fill;
896 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
898 /* Figure out how much we want to get:
899 * Try to get the remaining amount.
900 * But don't get more than the buffer size.
901 * And don't try to go past the end of the file.
902 * If we're not at a page boundary,
903 * don't go past the next page.
904 * If this means getting 0, then we were asked
905 * to write past the end of file.
906 * Finally, round down to a block boundary. */
907 amount = min(amount_left_to_req, FSG_BUFLEN);
908 amount = min((loff_t) amount, curlun->file_length -
910 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
911 if (partial_page > 0)
913 (unsigned int) PAGE_CACHE_SIZE - partial_page);
918 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
919 curlun->sense_data_info = usb_offset >> 9;
920 curlun->info_valid = 1;
923 amount -= (amount & 511);
926 /* Why were we were asked to transfer a
932 /* Get the next buffer */
933 usb_offset += amount;
934 common->usb_amount_left -= amount;
935 amount_left_to_req -= amount;
936 if (amount_left_to_req == 0)
939 /* amount is always divisible by 512, hence by
940 * the bulk-out maxpacket size */
941 bh->outreq->length = amount;
942 bh->bulk_out_intended_length = amount;
943 bh->outreq->short_not_ok = 1;
944 START_TRANSFER_OR(common, bulk_out, bh->outreq,
945 &bh->outreq_busy, &bh->state)
946 /* Don't know what to do if
947 * common->fsg is NULL */
949 common->next_buffhd_to_fill = bh->next;
953 /* Write the received data to the backing file */
954 bh = common->next_buffhd_to_drain;
955 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
956 break; /* We stopped early */
957 if (bh->state == BUF_STATE_FULL) {
959 common->next_buffhd_to_drain = bh->next;
960 bh->state = BUF_STATE_EMPTY;
962 /* Did something go wrong with the transfer? */
963 if (bh->outreq->status != 0) {
964 curlun->sense_data = SS_COMMUNICATION_FAILURE;
965 curlun->sense_data_info = file_offset >> 9;
966 curlun->info_valid = 1;
970 amount = bh->outreq->actual;
971 if (curlun->file_length - file_offset < amount) {
973 "write %u @ %llu beyond end %llu\n",
974 amount, (unsigned long long) file_offset,
975 (unsigned long long) curlun->file_length);
976 amount = curlun->file_length - file_offset;
979 /* Perform the write */
980 file_offset_tmp = file_offset;
981 nwritten = vfs_write(curlun->filp,
982 (char __user *) bh->buf,
983 amount, &file_offset_tmp);
984 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
985 (unsigned long long) file_offset,
987 if (signal_pending(current))
988 return -EINTR; /* Interrupted! */
991 LDBG(curlun, "error in file write: %d\n",
994 } else if (nwritten < amount) {
995 LDBG(curlun, "partial file write: %d/%u\n",
996 (int) nwritten, amount);
997 nwritten -= (nwritten & 511);
998 /* Round down to a block */
1000 file_offset += nwritten;
1001 amount_left_to_write -= nwritten;
1002 common->residue -= nwritten;
1004 /* If an error occurred, report it and its position */
1005 if (nwritten < amount) {
1006 curlun->sense_data = SS_WRITE_ERROR;
1007 curlun->sense_data_info = file_offset >> 9;
1008 curlun->info_valid = 1;
1012 /* Did the host decide to stop early? */
1013 if (bh->outreq->actual != bh->outreq->length) {
1014 common->short_packet_received = 1;
1020 /* Wait for something to happen */
1021 rc = sleep_thread(common);
1026 return -EIO; /* No default reply */
1030 /*-------------------------------------------------------------------------*/
1032 static int do_synchronize_cache(struct fsg_common *common)
1034 struct fsg_lun *curlun = common->curlun;
1037 /* We ignore the requested LBA and write out all file's
1038 * dirty data buffers. */
1039 rc = fsg_lun_fsync_sub(curlun);
1041 curlun->sense_data = SS_WRITE_ERROR;
1046 /*-------------------------------------------------------------------------*/
1048 static void invalidate_sub(struct fsg_lun *curlun)
1050 struct file *filp = curlun->filp;
1051 struct inode *inode = filp->f_path.dentry->d_inode;
1054 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1055 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1058 static int do_verify(struct fsg_common *common)
1060 struct fsg_lun *curlun = common->curlun;
1062 u32 verification_length;
1063 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1064 loff_t file_offset, file_offset_tmp;
1066 unsigned int amount;
1069 /* Get the starting Logical Block Address and check that it's
1071 lba = get_unaligned_be32(&common->cmnd[2]);
1072 if (lba >= curlun->num_sectors) {
1073 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1077 /* We allow DPO (Disable Page Out = don't save data in the
1078 * cache) but we don't implement it. */
1079 if (common->cmnd[1] & ~0x10) {
1080 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1084 verification_length = get_unaligned_be16(&common->cmnd[7]);
1085 if (unlikely(verification_length == 0))
1086 return -EIO; /* No default reply */
1088 /* Prepare to carry out the file verify */
1089 amount_left = verification_length << 9;
1090 file_offset = ((loff_t) lba) << 9;
1092 /* Write out all the dirty buffers before invalidating them */
1093 fsg_lun_fsync_sub(curlun);
1094 if (signal_pending(current))
1097 invalidate_sub(curlun);
1098 if (signal_pending(current))
1101 /* Just try to read the requested blocks */
1102 while (amount_left > 0) {
1104 /* Figure out how much we need to read:
1105 * Try to read the remaining amount, but not more than
1107 * And don't try to read past the end of the file.
1108 * If this means reading 0 then we were asked to read
1109 * past the end of file. */
1110 amount = min(amount_left, FSG_BUFLEN);
1111 amount = min((loff_t) amount,
1112 curlun->file_length - file_offset);
1114 curlun->sense_data =
1115 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1116 curlun->sense_data_info = file_offset >> 9;
1117 curlun->info_valid = 1;
1121 /* Perform the read */
1122 file_offset_tmp = file_offset;
1123 nread = vfs_read(curlun->filp,
1124 (char __user *) bh->buf,
1125 amount, &file_offset_tmp);
1126 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1127 (unsigned long long) file_offset,
1129 if (signal_pending(current))
1133 LDBG(curlun, "error in file verify: %d\n",
1136 } else if (nread < amount) {
1137 LDBG(curlun, "partial file verify: %d/%u\n",
1138 (int) nread, amount);
1139 nread -= (nread & 511); /* Round down to a sector */
1142 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1143 curlun->sense_data_info = file_offset >> 9;
1144 curlun->info_valid = 1;
1147 file_offset += nread;
1148 amount_left -= nread;
1154 /*-------------------------------------------------------------------------*/
1156 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1158 struct fsg_lun *curlun = common->curlun;
1159 u8 *buf = (u8 *) bh->buf;
1161 if (!curlun) { /* Unsupported LUNs are okay */
1162 common->bad_lun_okay = 1;
1164 buf[0] = 0x7f; /* Unsupported, no device-type */
1165 buf[4] = 31; /* Additional length */
1169 buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1170 buf[1] = curlun->removable ? 0x80 : 0;
1171 buf[2] = 2; /* ANSI SCSI level 2 */
1172 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1173 buf[4] = 31; /* Additional length */
1174 buf[5] = 0; /* No special options */
1177 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1182 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1184 struct fsg_lun *curlun = common->curlun;
1185 u8 *buf = (u8 *) bh->buf;
1190 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1192 * If a REQUEST SENSE command is received from an initiator
1193 * with a pending unit attention condition (before the target
1194 * generates the contingent allegiance condition), then the
1195 * target shall either:
1196 * a) report any pending sense data and preserve the unit
1197 * attention condition on the logical unit, or,
1198 * b) report the unit attention condition, may discard any
1199 * pending sense data, and clear the unit attention
1200 * condition on the logical unit for that initiator.
1202 * FSG normally uses option a); enable this code to use option b).
1205 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1206 curlun->sense_data = curlun->unit_attention_data;
1207 curlun->unit_attention_data = SS_NO_SENSE;
1211 if (!curlun) { /* Unsupported LUNs are okay */
1212 common->bad_lun_okay = 1;
1213 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1217 sd = curlun->sense_data;
1218 sdinfo = curlun->sense_data_info;
1219 valid = curlun->info_valid << 7;
1220 curlun->sense_data = SS_NO_SENSE;
1221 curlun->sense_data_info = 0;
1222 curlun->info_valid = 0;
1226 buf[0] = valid | 0x70; /* Valid, current error */
1228 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1229 buf[7] = 18 - 8; /* Additional sense length */
1236 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1238 struct fsg_lun *curlun = common->curlun;
1239 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1240 int pmi = common->cmnd[8];
1241 u8 *buf = (u8 *) bh->buf;
1243 /* Check the PMI and LBA fields */
1244 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1245 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1249 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1250 /* Max logical block */
1251 put_unaligned_be32(512, &buf[4]); /* Block length */
1256 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1258 struct fsg_lun *curlun = common->curlun;
1259 int msf = common->cmnd[1] & 0x02;
1260 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1261 u8 *buf = (u8 *) bh->buf;
1263 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1264 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1267 if (lba >= curlun->num_sectors) {
1268 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1273 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1274 store_cdrom_address(&buf[4], msf, lba);
1279 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1281 struct fsg_lun *curlun = common->curlun;
1282 int msf = common->cmnd[1] & 0x02;
1283 int start_track = common->cmnd[6];
1284 u8 *buf = (u8 *) bh->buf;
1286 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1288 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1293 buf[1] = (20-2); /* TOC data length */
1294 buf[2] = 1; /* First track number */
1295 buf[3] = 1; /* Last track number */
1296 buf[5] = 0x16; /* Data track, copying allowed */
1297 buf[6] = 0x01; /* Only track is number 1 */
1298 store_cdrom_address(&buf[8], msf, 0);
1300 buf[13] = 0x16; /* Lead-out track is data */
1301 buf[14] = 0xAA; /* Lead-out track number */
1302 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1307 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1309 struct fsg_lun *curlun = common->curlun;
1310 int mscmnd = common->cmnd[0];
1311 u8 *buf = (u8 *) bh->buf;
1314 int changeable_values, all_pages;
1318 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1319 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1322 pc = common->cmnd[2] >> 6;
1323 page_code = common->cmnd[2] & 0x3f;
1325 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1328 changeable_values = (pc == 1);
1329 all_pages = (page_code == 0x3f);
1331 /* Write the mode parameter header. Fixed values are: default
1332 * medium type, no cache control (DPOFUA), and no block descriptors.
1333 * The only variable value is the WriteProtect bit. We will fill in
1334 * the mode data length later. */
1336 if (mscmnd == SC_MODE_SENSE_6) {
1337 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1340 } else { /* SC_MODE_SENSE_10 */
1341 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1343 limit = 65535; /* Should really be FSG_BUFLEN */
1346 /* No block descriptors */
1348 /* The mode pages, in numerical order. The only page we support
1349 * is the Caching page. */
1350 if (page_code == 0x08 || all_pages) {
1352 buf[0] = 0x08; /* Page code */
1353 buf[1] = 10; /* Page length */
1354 memset(buf+2, 0, 10); /* None of the fields are changeable */
1356 if (!changeable_values) {
1357 buf[2] = 0x04; /* Write cache enable, */
1358 /* Read cache not disabled */
1359 /* No cache retention priorities */
1360 put_unaligned_be16(0xffff, &buf[4]);
1361 /* Don't disable prefetch */
1362 /* Minimum prefetch = 0 */
1363 put_unaligned_be16(0xffff, &buf[8]);
1364 /* Maximum prefetch */
1365 put_unaligned_be16(0xffff, &buf[10]);
1366 /* Maximum prefetch ceiling */
1371 /* Check that a valid page was requested and the mode data length
1372 * isn't too long. */
1374 if (!valid_page || len > limit) {
1375 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1379 /* Store the mode data length */
1380 if (mscmnd == SC_MODE_SENSE_6)
1383 put_unaligned_be16(len - 2, buf0);
1388 static int do_start_stop(struct fsg_common *common)
1390 struct fsg_lun *curlun = common->curlun;
1395 } else if (!curlun->removable) {
1396 curlun->sense_data = SS_INVALID_COMMAND;
1400 loej = common->cmnd[4] & 0x02;
1401 start = common->cmnd[4] & 0x01;
1403 /* eject code from file_storage.c:do_start_stop() */
1405 if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1406 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1407 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1412 /* Are we allowed to unload the media? */
1413 if (curlun->prevent_medium_removal) {
1414 LDBG(curlun, "unload attempt prevented\n");
1415 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1418 if (loej) { /* Simulate an unload/eject */
1419 up_read(&common->filesem);
1420 down_write(&common->filesem);
1421 fsg_lun_close(curlun);
1422 up_write(&common->filesem);
1423 down_read(&common->filesem);
1427 /* Our emulation doesn't support mounting; the medium is
1428 * available for use as soon as it is loaded. */
1429 if (!fsg_lun_is_open(curlun)) {
1430 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1438 static int do_prevent_allow(struct fsg_common *common)
1440 struct fsg_lun *curlun = common->curlun;
1443 if (!common->curlun) {
1445 } else if (!common->curlun->removable) {
1446 common->curlun->sense_data = SS_INVALID_COMMAND;
1450 prevent = common->cmnd[4] & 0x01;
1451 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1452 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1456 if (curlun->prevent_medium_removal && !prevent)
1457 fsg_lun_fsync_sub(curlun);
1458 curlun->prevent_medium_removal = prevent;
1463 static int do_read_format_capacities(struct fsg_common *common,
1464 struct fsg_buffhd *bh)
1466 struct fsg_lun *curlun = common->curlun;
1467 u8 *buf = (u8 *) bh->buf;
1469 buf[0] = buf[1] = buf[2] = 0;
1470 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1473 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1474 /* Number of blocks */
1475 put_unaligned_be32(512, &buf[4]); /* Block length */
1476 buf[4] = 0x02; /* Current capacity */
1481 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1483 struct fsg_lun *curlun = common->curlun;
1485 /* We don't support MODE SELECT */
1487 curlun->sense_data = SS_INVALID_COMMAND;
1492 /*-------------------------------------------------------------------------*/
1494 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1498 rc = fsg_set_halt(fsg, fsg->bulk_in);
1500 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1502 if (rc != -EAGAIN) {
1503 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1508 /* Wait for a short time and then try again */
1509 if (msleep_interruptible(100) != 0)
1511 rc = usb_ep_set_halt(fsg->bulk_in);
1516 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1520 DBG(fsg, "bulk-in set wedge\n");
1521 rc = usb_ep_set_wedge(fsg->bulk_in);
1523 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1525 if (rc != -EAGAIN) {
1526 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1531 /* Wait for a short time and then try again */
1532 if (msleep_interruptible(100) != 0)
1534 rc = usb_ep_set_wedge(fsg->bulk_in);
1539 static int pad_with_zeros(struct fsg_dev *fsg)
1541 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1542 u32 nkeep = bh->inreq->length;
1546 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1547 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1548 while (fsg->common->usb_amount_left > 0) {
1550 /* Wait for the next buffer to be free */
1551 while (bh->state != BUF_STATE_EMPTY) {
1552 rc = sleep_thread(fsg->common);
1557 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1558 memset(bh->buf + nkeep, 0, nsend - nkeep);
1559 bh->inreq->length = nsend;
1560 bh->inreq->zero = 0;
1561 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1562 &bh->inreq_busy, &bh->state);
1563 bh = fsg->common->next_buffhd_to_fill = bh->next;
1564 fsg->common->usb_amount_left -= nsend;
1570 static int throw_away_data(struct fsg_common *common)
1572 struct fsg_buffhd *bh;
1576 for (bh = common->next_buffhd_to_drain;
1577 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1578 bh = common->next_buffhd_to_drain) {
1580 /* Throw away the data in a filled buffer */
1581 if (bh->state == BUF_STATE_FULL) {
1583 bh->state = BUF_STATE_EMPTY;
1584 common->next_buffhd_to_drain = bh->next;
1586 /* A short packet or an error ends everything */
1587 if (bh->outreq->actual != bh->outreq->length ||
1588 bh->outreq->status != 0) {
1589 raise_exception(common,
1590 FSG_STATE_ABORT_BULK_OUT);
1596 /* Try to submit another request if we need one */
1597 bh = common->next_buffhd_to_fill;
1598 if (bh->state == BUF_STATE_EMPTY
1599 && common->usb_amount_left > 0) {
1600 amount = min(common->usb_amount_left, FSG_BUFLEN);
1602 /* amount is always divisible by 512, hence by
1603 * the bulk-out maxpacket size */
1604 bh->outreq->length = amount;
1605 bh->bulk_out_intended_length = amount;
1606 bh->outreq->short_not_ok = 1;
1607 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1608 &bh->outreq_busy, &bh->state)
1609 /* Don't know what to do if
1610 * common->fsg is NULL */
1612 common->next_buffhd_to_fill = bh->next;
1613 common->usb_amount_left -= amount;
1617 /* Otherwise wait for something to happen */
1618 rc = sleep_thread(common);
1626 static int finish_reply(struct fsg_common *common)
1628 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1631 switch (common->data_dir) {
1633 break; /* Nothing to send */
1635 /* If we don't know whether the host wants to read or write,
1636 * this must be CB or CBI with an unknown command. We mustn't
1637 * try to send or receive any data. So stall both bulk pipes
1638 * if we can and wait for a reset. */
1639 case DATA_DIR_UNKNOWN:
1640 if (!common->can_stall) {
1642 } else if (fsg_is_set(common)) {
1643 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1644 rc = halt_bulk_in_endpoint(common->fsg);
1646 /* Don't know what to do if common->fsg is NULL */
1651 /* All but the last buffer of data must have already been sent */
1652 case DATA_DIR_TO_HOST:
1653 if (common->data_size == 0) {
1654 /* Nothing to send */
1656 /* If there's no residue, simply send the last buffer */
1657 } else if (common->residue == 0) {
1658 bh->inreq->zero = 0;
1659 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1660 &bh->inreq_busy, &bh->state)
1662 common->next_buffhd_to_fill = bh->next;
1664 /* For Bulk-only, if we're allowed to stall then send the
1665 * short packet and halt the bulk-in endpoint. If we can't
1666 * stall, pad out the remaining data with 0's. */
1667 } else if (common->can_stall) {
1668 bh->inreq->zero = 1;
1669 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1670 &bh->inreq_busy, &bh->state)
1671 /* Don't know what to do if
1672 * common->fsg is NULL */
1674 common->next_buffhd_to_fill = bh->next;
1676 rc = halt_bulk_in_endpoint(common->fsg);
1677 } else if (fsg_is_set(common)) {
1678 rc = pad_with_zeros(common->fsg);
1680 /* Don't know what to do if common->fsg is NULL */
1685 /* We have processed all we want from the data the host has sent.
1686 * There may still be outstanding bulk-out requests. */
1687 case DATA_DIR_FROM_HOST:
1688 if (common->residue == 0) {
1689 /* Nothing to receive */
1691 /* Did the host stop sending unexpectedly early? */
1692 } else if (common->short_packet_received) {
1693 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1696 /* We haven't processed all the incoming data. Even though
1697 * we may be allowed to stall, doing so would cause a race.
1698 * The controller may already have ACK'ed all the remaining
1699 * bulk-out packets, in which case the host wouldn't see a
1700 * STALL. Not realizing the endpoint was halted, it wouldn't
1701 * clear the halt -- leading to problems later on. */
1703 } else if (common->can_stall) {
1704 if (fsg_is_set(common))
1705 fsg_set_halt(common->fsg,
1706 common->fsg->bulk_out);
1707 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1711 /* We can't stall. Read in the excess data and throw it
1714 rc = throw_away_data(common);
1722 static int send_status(struct fsg_common *common)
1724 struct fsg_lun *curlun = common->curlun;
1725 struct fsg_buffhd *bh;
1726 struct bulk_cs_wrap *csw;
1728 u8 status = USB_STATUS_PASS;
1731 /* Wait for the next buffer to become available */
1732 bh = common->next_buffhd_to_fill;
1733 while (bh->state != BUF_STATE_EMPTY) {
1734 rc = sleep_thread(common);
1740 sd = curlun->sense_data;
1741 sdinfo = curlun->sense_data_info;
1742 } else if (common->bad_lun_okay)
1745 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1747 if (common->phase_error) {
1748 DBG(common, "sending phase-error status\n");
1749 status = USB_STATUS_PHASE_ERROR;
1750 sd = SS_INVALID_COMMAND;
1751 } else if (sd != SS_NO_SENSE) {
1752 DBG(common, "sending command-failure status\n");
1753 status = USB_STATUS_FAIL;
1754 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1756 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1759 /* Store and send the Bulk-only CSW */
1760 csw = (void *)bh->buf;
1762 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1763 csw->Tag = common->tag;
1764 csw->Residue = cpu_to_le32(common->residue);
1765 csw->Status = status;
1767 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1768 bh->inreq->zero = 0;
1769 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1770 &bh->inreq_busy, &bh->state)
1771 /* Don't know what to do if common->fsg is NULL */
1774 common->next_buffhd_to_fill = bh->next;
1779 /*-------------------------------------------------------------------------*/
1781 /* Check whether the command is properly formed and whether its data size
1782 * and direction agree with the values we already have. */
1783 static int check_command(struct fsg_common *common, int cmnd_size,
1784 enum data_direction data_dir, unsigned int mask,
1785 int needs_medium, const char *name)
1788 int lun = common->cmnd[1] >> 5;
1789 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1791 struct fsg_lun *curlun;
1794 if (common->data_dir != DATA_DIR_UNKNOWN)
1795 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1797 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1798 name, cmnd_size, dirletter[(int) data_dir],
1799 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1801 /* We can't reply at all until we know the correct data direction
1803 if (common->data_size_from_cmnd == 0)
1804 data_dir = DATA_DIR_NONE;
1805 if (common->data_size < common->data_size_from_cmnd) {
1806 /* Host data size < Device data size is a phase error.
1807 * Carry out the command, but only transfer as much as
1808 * we are allowed. */
1809 common->data_size_from_cmnd = common->data_size;
1810 common->phase_error = 1;
1812 common->residue = common->data_size;
1813 common->usb_amount_left = common->data_size;
1815 /* Conflicting data directions is a phase error */
1816 if (common->data_dir != data_dir
1817 && common->data_size_from_cmnd > 0) {
1818 common->phase_error = 1;
1822 /* Verify the length of the command itself */
1823 if (cmnd_size != common->cmnd_size) {
1825 /* Special case workaround: There are plenty of buggy SCSI
1826 * implementations. Many have issues with cbw->Length
1827 * field passing a wrong command size. For those cases we
1828 * always try to work around the problem by using the length
1829 * sent by the host side provided it is at least as large
1830 * as the correct command length.
1831 * Examples of such cases would be MS-Windows, which issues
1832 * REQUEST SENSE with cbw->Length == 12 where it should
1833 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1834 * REQUEST SENSE with cbw->Length == 10 where it should
1837 if (cmnd_size <= common->cmnd_size) {
1838 DBG(common, "%s is buggy! Expected length %d "
1839 "but we got %d\n", name,
1840 cmnd_size, common->cmnd_size);
1841 cmnd_size = common->cmnd_size;
1843 common->phase_error = 1;
1848 /* Check that the LUN values are consistent */
1849 if (common->lun != lun)
1850 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1854 if (common->lun >= 0 && common->lun < common->nluns) {
1855 curlun = &common->luns[common->lun];
1856 common->curlun = curlun;
1857 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1858 curlun->sense_data = SS_NO_SENSE;
1859 curlun->sense_data_info = 0;
1860 curlun->info_valid = 0;
1863 common->curlun = NULL;
1865 common->bad_lun_okay = 0;
1867 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1868 * to use unsupported LUNs; all others may not. */
1869 if (common->cmnd[0] != SC_INQUIRY &&
1870 common->cmnd[0] != SC_REQUEST_SENSE) {
1871 DBG(common, "unsupported LUN %d\n", common->lun);
1876 /* If a unit attention condition exists, only INQUIRY and
1877 * REQUEST SENSE commands are allowed; anything else must fail. */
1878 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1879 common->cmnd[0] != SC_INQUIRY &&
1880 common->cmnd[0] != SC_REQUEST_SENSE) {
1881 curlun->sense_data = curlun->unit_attention_data;
1882 curlun->unit_attention_data = SS_NO_SENSE;
1886 /* Check that only command bytes listed in the mask are non-zero */
1887 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1888 for (i = 1; i < cmnd_size; ++i) {
1889 if (common->cmnd[i] && !(mask & (1 << i))) {
1891 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1896 /* If the medium isn't mounted and the command needs to access
1897 * it, return an error. */
1898 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1899 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1907 static int do_scsi_command(struct fsg_common *common)
1909 struct fsg_buffhd *bh;
1911 int reply = -EINVAL;
1913 static char unknown[16];
1917 /* Wait for the next buffer to become available for data or status */
1918 bh = common->next_buffhd_to_fill;
1919 common->next_buffhd_to_drain = bh;
1920 while (bh->state != BUF_STATE_EMPTY) {
1921 rc = sleep_thread(common);
1925 common->phase_error = 0;
1926 common->short_packet_received = 0;
1928 down_read(&common->filesem); /* We're using the backing file */
1929 switch (common->cmnd[0]) {
1932 common->data_size_from_cmnd = common->cmnd[4];
1933 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1937 reply = do_inquiry(common, bh);
1940 case SC_MODE_SELECT_6:
1941 common->data_size_from_cmnd = common->cmnd[4];
1942 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1946 reply = do_mode_select(common, bh);
1949 case SC_MODE_SELECT_10:
1950 common->data_size_from_cmnd =
1951 get_unaligned_be16(&common->cmnd[7]);
1952 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1956 reply = do_mode_select(common, bh);
1959 case SC_MODE_SENSE_6:
1960 common->data_size_from_cmnd = common->cmnd[4];
1961 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1962 (1<<1) | (1<<2) | (1<<4), 0,
1965 reply = do_mode_sense(common, bh);
1968 case SC_MODE_SENSE_10:
1969 common->data_size_from_cmnd =
1970 get_unaligned_be16(&common->cmnd[7]);
1971 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1972 (1<<1) | (1<<2) | (3<<7), 0,
1975 reply = do_mode_sense(common, bh);
1978 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1979 common->data_size_from_cmnd = 0;
1980 reply = check_command(common, 6, DATA_DIR_NONE,
1982 "PREVENT-ALLOW MEDIUM REMOVAL");
1984 reply = do_prevent_allow(common);
1988 i = common->cmnd[4];
1989 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1990 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1994 reply = do_read(common);
1998 common->data_size_from_cmnd =
1999 get_unaligned_be16(&common->cmnd[7]) << 9;
2000 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2001 (1<<1) | (0xf<<2) | (3<<7), 1,
2004 reply = do_read(common);
2008 common->data_size_from_cmnd =
2009 get_unaligned_be32(&common->cmnd[6]) << 9;
2010 reply = check_command(common, 12, DATA_DIR_TO_HOST,
2011 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2014 reply = do_read(common);
2017 case SC_READ_CAPACITY:
2018 common->data_size_from_cmnd = 8;
2019 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2020 (0xf<<2) | (1<<8), 1,
2023 reply = do_read_capacity(common, bh);
2026 case SC_READ_HEADER:
2027 if (!common->curlun || !common->curlun->cdrom)
2029 common->data_size_from_cmnd =
2030 get_unaligned_be16(&common->cmnd[7]);
2031 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2032 (3<<7) | (0x1f<<1), 1,
2035 reply = do_read_header(common, bh);
2039 if (!common->curlun || !common->curlun->cdrom)
2041 common->data_size_from_cmnd =
2042 get_unaligned_be16(&common->cmnd[7]);
2043 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2047 reply = do_read_toc(common, bh);
2050 case SC_READ_FORMAT_CAPACITIES:
2051 common->data_size_from_cmnd =
2052 get_unaligned_be16(&common->cmnd[7]);
2053 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2055 "READ FORMAT CAPACITIES");
2057 reply = do_read_format_capacities(common, bh);
2060 case SC_REQUEST_SENSE:
2061 common->data_size_from_cmnd = common->cmnd[4];
2062 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2066 reply = do_request_sense(common, bh);
2069 case SC_START_STOP_UNIT:
2070 common->data_size_from_cmnd = 0;
2071 reply = check_command(common, 6, DATA_DIR_NONE,
2075 reply = do_start_stop(common);
2078 case SC_SYNCHRONIZE_CACHE:
2079 common->data_size_from_cmnd = 0;
2080 reply = check_command(common, 10, DATA_DIR_NONE,
2081 (0xf<<2) | (3<<7), 1,
2082 "SYNCHRONIZE CACHE");
2084 reply = do_synchronize_cache(common);
2087 case SC_TEST_UNIT_READY:
2088 common->data_size_from_cmnd = 0;
2089 reply = check_command(common, 6, DATA_DIR_NONE,
2094 /* Although optional, this command is used by MS-Windows. We
2095 * support a minimal version: BytChk must be 0. */
2097 common->data_size_from_cmnd = 0;
2098 reply = check_command(common, 10, DATA_DIR_NONE,
2099 (1<<1) | (0xf<<2) | (3<<7), 1,
2102 reply = do_verify(common);
2106 i = common->cmnd[4];
2107 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2108 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2112 reply = do_write(common);
2116 common->data_size_from_cmnd =
2117 get_unaligned_be16(&common->cmnd[7]) << 9;
2118 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2119 (1<<1) | (0xf<<2) | (3<<7), 1,
2122 reply = do_write(common);
2126 common->data_size_from_cmnd =
2127 get_unaligned_be32(&common->cmnd[6]) << 9;
2128 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2129 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2132 reply = do_write(common);
2135 /* Some mandatory commands that we recognize but don't implement.
2136 * They don't mean much in this setting. It's left as an exercise
2137 * for anyone interested to implement RESERVE and RELEASE in terms
2138 * of Posix locks. */
2139 case SC_FORMAT_UNIT:
2142 case SC_SEND_DIAGNOSTIC:
2147 common->data_size_from_cmnd = 0;
2148 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2149 reply = check_command(common, common->cmnd_size,
2150 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2152 common->curlun->sense_data = SS_INVALID_COMMAND;
2157 up_read(&common->filesem);
2159 if (reply == -EINTR || signal_pending(current))
2162 /* Set up the single reply buffer for finish_reply() */
2163 if (reply == -EINVAL)
2164 reply = 0; /* Error reply length */
2165 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2166 reply = min((u32) reply, common->data_size_from_cmnd);
2167 bh->inreq->length = reply;
2168 bh->state = BUF_STATE_FULL;
2169 common->residue -= reply;
2170 } /* Otherwise it's already set */
2176 /*-------------------------------------------------------------------------*/
2178 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2180 struct usb_request *req = bh->outreq;
2181 struct fsg_bulk_cb_wrap *cbw = req->buf;
2182 struct fsg_common *common = fsg->common;
2184 /* Was this a real packet? Should it be ignored? */
2185 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2188 /* Is the CBW valid? */
2189 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2190 cbw->Signature != cpu_to_le32(
2192 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2194 le32_to_cpu(cbw->Signature));
2196 /* The Bulk-only spec says we MUST stall the IN endpoint
2197 * (6.6.1), so it's unavoidable. It also says we must
2198 * retain this state until the next reset, but there's
2199 * no way to tell the controller driver it should ignore
2200 * Clear-Feature(HALT) requests.
2202 * We aren't required to halt the OUT endpoint; instead
2203 * we can simply accept and discard any data received
2204 * until the next reset. */
2205 wedge_bulk_in_endpoint(fsg);
2206 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2210 /* Is the CBW meaningful? */
2211 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2212 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2213 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2215 cbw->Lun, cbw->Flags, cbw->Length);
2217 /* We can do anything we want here, so let's stall the
2218 * bulk pipes if we are allowed to. */
2219 if (common->can_stall) {
2220 fsg_set_halt(fsg, fsg->bulk_out);
2221 halt_bulk_in_endpoint(fsg);
2226 /* Save the command for later */
2227 common->cmnd_size = cbw->Length;
2228 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2229 if (cbw->Flags & USB_BULK_IN_FLAG)
2230 common->data_dir = DATA_DIR_TO_HOST;
2232 common->data_dir = DATA_DIR_FROM_HOST;
2233 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2234 if (common->data_size == 0)
2235 common->data_dir = DATA_DIR_NONE;
2236 common->lun = cbw->Lun;
2237 common->tag = cbw->Tag;
2242 static int get_next_command(struct fsg_common *common)
2244 struct fsg_buffhd *bh;
2247 /* Wait for the next buffer to become available */
2248 bh = common->next_buffhd_to_fill;
2249 while (bh->state != BUF_STATE_EMPTY) {
2250 rc = sleep_thread(common);
2255 /* Queue a request to read a Bulk-only CBW */
2256 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2257 bh->outreq->short_not_ok = 1;
2258 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2259 &bh->outreq_busy, &bh->state)
2260 /* Don't know what to do if common->fsg is NULL */
2263 /* We will drain the buffer in software, which means we
2264 * can reuse it for the next filling. No need to advance
2265 * next_buffhd_to_fill. */
2267 /* Wait for the CBW to arrive */
2268 while (bh->state != BUF_STATE_FULL) {
2269 rc = sleep_thread(common);
2274 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2275 bh->state = BUF_STATE_EMPTY;
2281 /*-------------------------------------------------------------------------*/
2283 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2284 const struct usb_endpoint_descriptor *d)
2288 ep->driver_data = common;
2289 rc = usb_ep_enable(ep, d);
2291 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2295 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2296 struct usb_request **preq)
2298 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2301 ERROR(common, "can't allocate request for %s\n", ep->name);
2305 /* Reset interface setting and re-init endpoint state (toggle etc). */
2306 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2308 const struct usb_endpoint_descriptor *d;
2309 struct fsg_dev *fsg;
2312 if (common->running)
2313 DBG(common, "reset interface\n");
2316 /* Deallocate the requests */
2320 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2321 struct fsg_buffhd *bh = &common->buffhds[i];
2324 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2328 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2333 /* Disable the endpoints */
2334 if (fsg->bulk_in_enabled) {
2335 usb_ep_disable(fsg->bulk_in);
2336 fsg->bulk_in_enabled = 0;
2338 if (fsg->bulk_out_enabled) {
2339 usb_ep_disable(fsg->bulk_out);
2340 fsg->bulk_out_enabled = 0;
2344 wake_up(&common->fsg_wait);
2347 common->running = 0;
2351 common->fsg = new_fsg;
2354 /* Enable the endpoints */
2355 d = fsg_ep_desc(common->gadget,
2356 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2357 rc = enable_endpoint(common, fsg->bulk_in, d);
2360 fsg->bulk_in_enabled = 1;
2362 d = fsg_ep_desc(common->gadget,
2363 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2364 rc = enable_endpoint(common, fsg->bulk_out, d);
2367 fsg->bulk_out_enabled = 1;
2368 common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2369 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2371 /* Allocate the requests */
2372 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2373 struct fsg_buffhd *bh = &common->buffhds[i];
2375 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2378 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2381 bh->inreq->buf = bh->outreq->buf = bh->buf;
2382 bh->inreq->context = bh->outreq->context = bh;
2383 bh->inreq->complete = bulk_in_complete;
2384 bh->outreq->complete = bulk_out_complete;
2387 common->running = 1;
2388 for (i = 0; i < common->nluns; ++i)
2389 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2394 /****************************** ALT CONFIGS ******************************/
2397 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2399 struct fsg_dev *fsg = fsg_from_func(f);
2400 fsg->common->new_fsg = fsg;
2401 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2405 static void fsg_disable(struct usb_function *f)
2407 struct fsg_dev *fsg = fsg_from_func(f);
2408 fsg->common->new_fsg = NULL;
2409 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2413 /*-------------------------------------------------------------------------*/
2415 static void handle_exception(struct fsg_common *common)
2419 struct fsg_buffhd *bh;
2420 enum fsg_state old_state;
2421 struct fsg_lun *curlun;
2422 unsigned int exception_req_tag;
2424 /* Clear the existing signals. Anything but SIGUSR1 is converted
2425 * into a high-priority EXIT exception. */
2428 dequeue_signal_lock(current, ¤t->blocked, &info);
2431 if (sig != SIGUSR1) {
2432 if (common->state < FSG_STATE_EXIT)
2433 DBG(common, "Main thread exiting on signal\n");
2434 raise_exception(common, FSG_STATE_EXIT);
2438 /* Cancel all the pending transfers */
2439 if (likely(common->fsg)) {
2440 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2441 bh = &common->buffhds[i];
2443 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2444 if (bh->outreq_busy)
2445 usb_ep_dequeue(common->fsg->bulk_out,
2449 /* Wait until everything is idle */
2452 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2453 bh = &common->buffhds[i];
2454 num_active += bh->inreq_busy + bh->outreq_busy;
2456 if (num_active == 0)
2458 if (sleep_thread(common))
2462 /* Clear out the controller's fifos */
2463 if (common->fsg->bulk_in_enabled)
2464 usb_ep_fifo_flush(common->fsg->bulk_in);
2465 if (common->fsg->bulk_out_enabled)
2466 usb_ep_fifo_flush(common->fsg->bulk_out);
2469 /* Reset the I/O buffer states and pointers, the SCSI
2470 * state, and the exception. Then invoke the handler. */
2471 spin_lock_irq(&common->lock);
2473 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2474 bh = &common->buffhds[i];
2475 bh->state = BUF_STATE_EMPTY;
2477 common->next_buffhd_to_fill = &common->buffhds[0];
2478 common->next_buffhd_to_drain = &common->buffhds[0];
2479 exception_req_tag = common->exception_req_tag;
2480 old_state = common->state;
2482 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2483 common->state = FSG_STATE_STATUS_PHASE;
2485 for (i = 0; i < common->nluns; ++i) {
2486 curlun = &common->luns[i];
2487 curlun->prevent_medium_removal = 0;
2488 curlun->sense_data = SS_NO_SENSE;
2489 curlun->unit_attention_data = SS_NO_SENSE;
2490 curlun->sense_data_info = 0;
2491 curlun->info_valid = 0;
2493 common->state = FSG_STATE_IDLE;
2495 spin_unlock_irq(&common->lock);
2497 /* Carry out any extra actions required for the exception */
2498 switch (old_state) {
2499 case FSG_STATE_ABORT_BULK_OUT:
2500 send_status(common);
2501 spin_lock_irq(&common->lock);
2502 if (common->state == FSG_STATE_STATUS_PHASE)
2503 common->state = FSG_STATE_IDLE;
2504 spin_unlock_irq(&common->lock);
2507 case FSG_STATE_RESET:
2508 /* In case we were forced against our will to halt a
2509 * bulk endpoint, clear the halt now. (The SuperH UDC
2510 * requires this.) */
2511 if (!fsg_is_set(common))
2513 if (test_and_clear_bit(IGNORE_BULK_OUT,
2514 &common->fsg->atomic_bitflags))
2515 usb_ep_clear_halt(common->fsg->bulk_in);
2517 if (common->ep0_req_tag == exception_req_tag)
2518 ep0_queue(common); /* Complete the status stage */
2520 /* Technically this should go here, but it would only be
2521 * a waste of time. Ditto for the INTERFACE_CHANGE and
2522 * CONFIG_CHANGE cases. */
2523 /* for (i = 0; i < common->nluns; ++i) */
2524 /* common->luns[i].unit_attention_data = */
2525 /* SS_RESET_OCCURRED; */
2528 case FSG_STATE_CONFIG_CHANGE:
2529 do_set_interface(common, common->new_fsg);
2532 case FSG_STATE_EXIT:
2533 case FSG_STATE_TERMINATED:
2534 do_set_interface(common, NULL); /* Free resources */
2535 spin_lock_irq(&common->lock);
2536 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2537 spin_unlock_irq(&common->lock);
2540 case FSG_STATE_INTERFACE_CHANGE:
2541 case FSG_STATE_DISCONNECT:
2542 case FSG_STATE_COMMAND_PHASE:
2543 case FSG_STATE_DATA_PHASE:
2544 case FSG_STATE_STATUS_PHASE:
2545 case FSG_STATE_IDLE:
2551 /*-------------------------------------------------------------------------*/
2553 static int fsg_main_thread(void *common_)
2555 struct fsg_common *common = common_;
2557 /* Allow the thread to be killed by a signal, but set the signal mask
2558 * to block everything but INT, TERM, KILL, and USR1. */
2559 allow_signal(SIGINT);
2560 allow_signal(SIGTERM);
2561 allow_signal(SIGKILL);
2562 allow_signal(SIGUSR1);
2564 /* Allow the thread to be frozen */
2567 /* Arrange for userspace references to be interpreted as kernel
2568 * pointers. That way we can pass a kernel pointer to a routine
2569 * that expects a __user pointer and it will work okay. */
2573 while (common->state != FSG_STATE_TERMINATED) {
2574 if (exception_in_progress(common) || signal_pending(current)) {
2575 handle_exception(common);
2579 if (!common->running) {
2580 sleep_thread(common);
2584 if (get_next_command(common))
2587 spin_lock_irq(&common->lock);
2588 if (!exception_in_progress(common))
2589 common->state = FSG_STATE_DATA_PHASE;
2590 spin_unlock_irq(&common->lock);
2592 if (do_scsi_command(common) || finish_reply(common))
2595 spin_lock_irq(&common->lock);
2596 if (!exception_in_progress(common))
2597 common->state = FSG_STATE_STATUS_PHASE;
2598 spin_unlock_irq(&common->lock);
2600 if (send_status(common))
2603 spin_lock_irq(&common->lock);
2604 if (!exception_in_progress(common))
2605 common->state = FSG_STATE_IDLE;
2606 spin_unlock_irq(&common->lock);
2609 spin_lock_irq(&common->lock);
2610 common->thread_task = NULL;
2611 spin_unlock_irq(&common->lock);
2613 if (!common->thread_exits || common->thread_exits(common) < 0) {
2614 struct fsg_lun *curlun = common->luns;
2615 unsigned i = common->nluns;
2617 down_write(&common->filesem);
2618 for (; i--; ++curlun) {
2619 if (!fsg_lun_is_open(curlun))
2622 fsg_lun_close(curlun);
2623 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2625 up_write(&common->filesem);
2628 /* Let the unbind and cleanup routines know the thread has exited */
2629 complete_and_exit(&common->thread_notifier, 0);
2633 /*************************** DEVICE ATTRIBUTES ***************************/
2635 /* Write permission is checked per LUN in store_*() functions. */
2636 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2637 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2640 /****************************** FSG COMMON ******************************/
2642 static void fsg_common_release(struct kref *ref);
2644 static void fsg_lun_release(struct device *dev)
2646 /* Nothing needs to be done */
2649 static inline void fsg_common_get(struct fsg_common *common)
2651 kref_get(&common->ref);
2654 static inline void fsg_common_put(struct fsg_common *common)
2656 kref_put(&common->ref, fsg_common_release);
2660 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2661 struct usb_composite_dev *cdev,
2662 struct fsg_config *cfg)
2664 struct usb_gadget *gadget = cdev->gadget;
2665 struct fsg_buffhd *bh;
2666 struct fsg_lun *curlun;
2667 struct fsg_lun_config *lcfg;
2671 /* Find out how many LUNs there should be */
2673 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2674 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2675 return ERR_PTR(-EINVAL);
2680 common = kzalloc(sizeof *common, GFP_KERNEL);
2682 return ERR_PTR(-ENOMEM);
2683 common->free_storage_on_release = 1;
2685 memset(common, 0, sizeof common);
2686 common->free_storage_on_release = 0;
2689 common->private_data = cfg->private_data;
2691 common->gadget = gadget;
2692 common->ep0 = gadget->ep0;
2693 common->ep0req = cdev->req;
2695 /* Maybe allocate device-global string IDs, and patch descriptors */
2696 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2697 rc = usb_string_id(cdev);
2698 if (unlikely(rc < 0))
2700 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2701 fsg_intf_desc.iInterface = rc;
2704 /* Create the LUNs, open their backing files, and register the
2705 * LUN devices in sysfs. */
2706 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2707 if (unlikely(!curlun)) {
2711 common->luns = curlun;
2713 init_rwsem(&common->filesem);
2715 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2716 curlun->cdrom = !!lcfg->cdrom;
2717 curlun->ro = lcfg->cdrom || lcfg->ro;
2718 curlun->removable = lcfg->removable;
2719 curlun->dev.release = fsg_lun_release;
2720 curlun->dev.parent = &gadget->dev;
2721 /* curlun->dev.driver = &fsg_driver.driver; XXX */
2722 dev_set_drvdata(&curlun->dev, &common->filesem);
2723 dev_set_name(&curlun->dev,
2724 cfg->lun_name_format
2725 ? cfg->lun_name_format
2729 rc = device_register(&curlun->dev);
2731 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2736 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2739 rc = device_create_file(&curlun->dev, &dev_attr_file);
2743 if (lcfg->filename) {
2744 rc = fsg_lun_open(curlun, lcfg->filename);
2747 } else if (!curlun->removable) {
2748 ERROR(common, "no file given for LUN%d\n", i);
2753 common->nluns = nluns;
2756 /* Data buffers cyclic list */
2757 bh = common->buffhds;
2758 i = FSG_NUM_BUFFERS;
2759 goto buffhds_first_it;
2764 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2765 if (unlikely(!bh->buf)) {
2770 bh->next = common->buffhds;
2773 /* Prepare inquiryString */
2774 if (cfg->release != 0xffff) {
2777 i = usb_gadget_controller_number(gadget);
2781 WARNING(common, "controller '%s' not recognized\n",
2786 #define OR(x, y) ((x) ? (x) : (y))
2787 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2789 OR(cfg->vendor_name, "Linux "),
2790 /* Assume product name dependent on the first LUN */
2791 OR(cfg->product_name, common->luns->cdrom
2792 ? "File-Stor Gadget"
2793 : "File-CD Gadget "),
2797 /* Some peripheral controllers are known not to be able to
2798 * halt bulk endpoints correctly. If one of them is present,
2801 common->can_stall = cfg->can_stall &&
2802 !(gadget_is_at91(common->gadget));
2805 spin_lock_init(&common->lock);
2806 kref_init(&common->ref);
2809 /* Tell the thread to start working */
2810 common->thread_exits = cfg->thread_exits;
2811 common->thread_task =
2812 kthread_create(fsg_main_thread, common,
2813 OR(cfg->thread_name, "file-storage"));
2814 if (IS_ERR(common->thread_task)) {
2815 rc = PTR_ERR(common->thread_task);
2818 init_completion(&common->thread_notifier);
2819 init_waitqueue_head(&common->fsg_wait);
2824 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2825 INFO(common, "Number of LUNs=%d\n", common->nluns);
2827 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2828 for (i = 0, nluns = common->nluns, curlun = common->luns;
2831 char *p = "(no medium)";
2832 if (fsg_lun_is_open(curlun)) {
2835 p = d_path(&curlun->filp->f_path,
2841 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
2842 curlun->removable ? "removable " : "",
2843 curlun->ro ? "read only " : "",
2844 curlun->cdrom ? "CD-ROM " : "",
2849 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
2851 wake_up_process(common->thread_task);
2857 common->nluns = i + 1;
2859 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2860 /* Call fsg_common_release() directly, ref might be not
2862 fsg_common_release(&common->ref);
2867 static void fsg_common_release(struct kref *ref)
2869 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2871 /* If the thread isn't already dead, tell it to exit now */
2872 if (common->state != FSG_STATE_TERMINATED) {
2873 raise_exception(common, FSG_STATE_EXIT);
2874 wait_for_completion(&common->thread_notifier);
2876 /* The cleanup routine waits for this completion also */
2877 complete(&common->thread_notifier);
2880 if (likely(common->luns)) {
2881 struct fsg_lun *lun = common->luns;
2882 unsigned i = common->nluns;
2884 /* In error recovery common->nluns may be zero. */
2885 for (; i; --i, ++lun) {
2886 device_remove_file(&lun->dev, &dev_attr_ro);
2887 device_remove_file(&lun->dev, &dev_attr_file);
2889 device_unregister(&lun->dev);
2892 kfree(common->luns);
2896 struct fsg_buffhd *bh = common->buffhds;
2897 unsigned i = FSG_NUM_BUFFERS;
2900 } while (++bh, --i);
2903 if (common->free_storage_on_release)
2908 /*-------------------------------------------------------------------------*/
2911 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2913 struct fsg_dev *fsg = fsg_from_func(f);
2914 struct fsg_common *common = fsg->common;
2916 DBG(fsg, "unbind\n");
2917 if (fsg->common->fsg == fsg) {
2918 fsg->common->new_fsg = NULL;
2919 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2920 /* FIXME: make interruptible or killable somehow? */
2921 wait_event(common->fsg_wait, common->fsg != fsg);
2924 fsg_common_put(common);
2925 usb_free_descriptors(fsg->function.descriptors);
2926 usb_free_descriptors(fsg->function.hs_descriptors);
2931 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2933 struct fsg_dev *fsg = fsg_from_func(f);
2934 struct usb_gadget *gadget = c->cdev->gadget;
2938 fsg->gadget = gadget;
2941 i = usb_interface_id(c, f);
2944 fsg_intf_desc.bInterfaceNumber = i;
2945 fsg->interface_number = i;
2947 /* Find all the endpoints we will use */
2948 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2951 ep->driver_data = fsg->common; /* claim the endpoint */
2954 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2957 ep->driver_data = fsg->common; /* claim the endpoint */
2960 /* Copy descriptors */
2961 f->descriptors = usb_copy_descriptors(fsg_fs_function);
2962 if (unlikely(!f->descriptors))
2965 if (gadget_is_dualspeed(gadget)) {
2966 /* Assume endpoint addresses are the same for both speeds */
2967 fsg_hs_bulk_in_desc.bEndpointAddress =
2968 fsg_fs_bulk_in_desc.bEndpointAddress;
2969 fsg_hs_bulk_out_desc.bEndpointAddress =
2970 fsg_fs_bulk_out_desc.bEndpointAddress;
2971 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
2972 if (unlikely(!f->hs_descriptors)) {
2973 usb_free_descriptors(f->descriptors);
2981 ERROR(fsg, "unable to autoconfigure all endpoints\n");
2986 /****************************** ADD FUNCTION ******************************/
2988 static struct usb_gadget_strings *fsg_strings_array[] = {
2993 static int fsg_add(struct usb_composite_dev *cdev,
2994 struct usb_configuration *c,
2995 struct fsg_common *common)
2997 struct fsg_dev *fsg;
3000 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3004 fsg->function.name = FSG_DRIVER_DESC;
3005 fsg->function.strings = fsg_strings_array;
3006 fsg->function.bind = fsg_bind;
3007 fsg->function.unbind = fsg_unbind;
3008 fsg->function.setup = fsg_setup;
3009 fsg->function.set_alt = fsg_set_alt;
3010 fsg->function.disable = fsg_disable;
3012 fsg->common = common;
3013 /* Our caller holds a reference to common structure so we
3014 * don't have to be worry about it being freed until we return
3015 * from this function. So instead of incrementing counter now
3016 * and decrement in error recovery we increment it only when
3017 * call to usb_add_function() was successful. */
3019 rc = usb_add_function(c, &fsg->function);
3023 fsg_common_get(fsg->common);
3029 /************************* Module parameters *************************/
3032 struct fsg_module_parameters {
3033 char *file[FSG_MAX_LUNS];
3034 int ro[FSG_MAX_LUNS];
3035 int removable[FSG_MAX_LUNS];
3036 int cdrom[FSG_MAX_LUNS];
3038 unsigned int file_count, ro_count, removable_count, cdrom_count;
3039 unsigned int luns; /* nluns */
3040 int stall; /* can_stall */
3044 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3045 module_param_array_named(prefix ## name, params.name, type, \
3046 &prefix ## params.name ## _count, \
3048 MODULE_PARM_DESC(prefix ## name, desc)
3050 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3051 module_param_named(prefix ## name, params.name, type, \
3053 MODULE_PARM_DESC(prefix ## name, desc)
3055 #define FSG_MODULE_PARAMETERS(prefix, params) \
3056 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3057 "names of backing files or devices"); \
3058 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3059 "true to force read-only"); \
3060 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3061 "true to simulate removable media"); \
3062 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3063 "true to simulate CD-ROM instead of disk"); \
3064 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3065 "number of LUNs"); \
3066 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3067 "false to prevent bulk stalls")
3071 fsg_config_from_params(struct fsg_config *cfg,
3072 const struct fsg_module_parameters *params)
3074 struct fsg_lun_config *lun;
3077 /* Configure LUNs */
3079 min(params->luns ?: (params->file_count ?: 1u),
3080 (unsigned)FSG_MAX_LUNS);
3081 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3082 lun->ro = !!params->ro[i];
3083 lun->cdrom = !!params->cdrom[i];
3084 lun->removable = /* Removable by default */
3085 params->removable_count <= i || params->removable[i];
3087 params->file_count > i && params->file[i][0]
3092 /* Let MSF use defaults */
3093 cfg->lun_name_format = 0;
3094 cfg->thread_name = 0;
3095 cfg->vendor_name = 0;
3096 cfg->product_name = 0;
3097 cfg->release = 0xffff;
3099 cfg->thread_exits = 0;
3100 cfg->private_data = 0;
3103 cfg->can_stall = params->stall;
3106 static inline struct fsg_common *
3107 fsg_common_from_params(struct fsg_common *common,
3108 struct usb_composite_dev *cdev,
3109 const struct fsg_module_parameters *params)
3110 __attribute__((unused));
3111 static inline struct fsg_common *
3112 fsg_common_from_params(struct fsg_common *common,
3113 struct usb_composite_dev *cdev,
3114 const struct fsg_module_parameters *params)
3116 struct fsg_config cfg;
3117 fsg_config_from_params(&cfg, params);
3118 return fsg_common_init(common, cdev, &cfg);