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 /* FSF callback functions */
322 struct fsg_operations {
323 /* Callback function to call when thread exits. If no
324 * callback is set or it returns value lower then zero MSF
325 * will force eject all LUNs it operates on (including those
326 * marked as non-removable or with prevent_medium_removal flag
328 int (*thread_exits)(struct fsg_common *common);
330 /* Called prior to ejection. Negative return means error,
331 * zero means to continue with ejection, positive means not to
333 int (*pre_eject)(struct fsg_common *common,
334 struct fsg_lun *lun, int num);
335 /* Called after ejection. Negative return means error, zero
336 * or positive is just a success. */
337 int (*post_eject)(struct fsg_common *common,
338 struct fsg_lun *lun, int num);
342 /* Data shared by all the FSG instances. */
344 struct usb_gadget *gadget;
345 struct fsg_dev *fsg, *new_fsg;
346 wait_queue_head_t fsg_wait;
348 /* filesem protects: backing files in use */
349 struct rw_semaphore filesem;
351 /* lock protects: state, all the req_busy's */
354 struct usb_ep *ep0; /* Copy of gadget->ep0 */
355 struct usb_request *ep0req; /* Copy of cdev->req */
356 unsigned int ep0_req_tag;
358 struct fsg_buffhd *next_buffhd_to_fill;
359 struct fsg_buffhd *next_buffhd_to_drain;
360 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
363 u8 cmnd[MAX_COMMAND_SIZE];
367 struct fsg_lun *luns;
368 struct fsg_lun *curlun;
370 unsigned int bulk_out_maxpacket;
371 enum fsg_state state; /* For exception handling */
372 unsigned int exception_req_tag;
374 enum data_direction data_dir;
376 u32 data_size_from_cmnd;
381 unsigned int can_stall:1;
382 unsigned int free_storage_on_release:1;
383 unsigned int phase_error:1;
384 unsigned int short_packet_received:1;
385 unsigned int bad_lun_okay:1;
386 unsigned int running:1;
388 int thread_wakeup_needed;
389 struct completion thread_notifier;
390 struct task_struct *thread_task;
392 /* Callback functions. */
393 const struct fsg_operations *ops;
394 /* Gadget's private data. */
397 /* Vendor (8 chars), product (16 chars), release (4
398 * hexadecimal digits) and NUL byte */
399 char inquiry_string[8 + 16 + 4 + 1];
407 struct fsg_lun_config {
408 const char *filename;
412 } luns[FSG_MAX_LUNS];
414 const char *lun_name_format;
415 const char *thread_name;
417 /* Callback functions. */
418 const struct fsg_operations *ops;
419 /* Gadget's private data. */
422 const char *vendor_name; /* 8 characters or less */
423 const char *product_name; /* 16 characters or less */
431 struct usb_function function;
432 struct usb_gadget *gadget; /* Copy of cdev->gadget */
433 struct fsg_common *common;
435 u16 interface_number;
437 unsigned int bulk_in_enabled:1;
438 unsigned int bulk_out_enabled:1;
440 unsigned long atomic_bitflags;
441 #define IGNORE_BULK_OUT 0
443 struct usb_ep *bulk_in;
444 struct usb_ep *bulk_out;
448 static inline int __fsg_is_set(struct fsg_common *common,
449 const char *func, unsigned line)
453 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
458 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
461 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
463 return container_of(f, struct fsg_dev, function);
467 typedef void (*fsg_routine_t)(struct fsg_dev *);
469 static int exception_in_progress(struct fsg_common *common)
471 return common->state > FSG_STATE_IDLE;
474 /* Make bulk-out requests be divisible by the maxpacket size */
475 static void set_bulk_out_req_length(struct fsg_common *common,
476 struct fsg_buffhd *bh, unsigned int length)
480 bh->bulk_out_intended_length = length;
481 rem = length % common->bulk_out_maxpacket;
483 length += common->bulk_out_maxpacket - rem;
484 bh->outreq->length = length;
487 /*-------------------------------------------------------------------------*/
489 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
493 if (ep == fsg->bulk_in)
495 else if (ep == fsg->bulk_out)
499 DBG(fsg, "%s set halt\n", name);
500 return usb_ep_set_halt(ep);
504 /*-------------------------------------------------------------------------*/
506 /* These routines may be called in process context or in_irq */
508 /* Caller must hold fsg->lock */
509 static void wakeup_thread(struct fsg_common *common)
511 /* Tell the main thread that something has happened */
512 common->thread_wakeup_needed = 1;
513 if (common->thread_task)
514 wake_up_process(common->thread_task);
518 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
522 /* Do nothing if a higher-priority exception is already in progress.
523 * If a lower-or-equal priority exception is in progress, preempt it
524 * and notify the main thread by sending it a signal. */
525 spin_lock_irqsave(&common->lock, flags);
526 if (common->state <= new_state) {
527 common->exception_req_tag = common->ep0_req_tag;
528 common->state = new_state;
529 if (common->thread_task)
530 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
531 common->thread_task);
533 spin_unlock_irqrestore(&common->lock, flags);
537 /*-------------------------------------------------------------------------*/
539 static int ep0_queue(struct fsg_common *common)
543 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
544 common->ep0->driver_data = common;
545 if (rc != 0 && rc != -ESHUTDOWN) {
546 /* We can't do much more than wait for a reset */
547 WARNING(common, "error in submission: %s --> %d\n",
548 common->ep0->name, rc);
553 /*-------------------------------------------------------------------------*/
555 /* Bulk and interrupt endpoint completion handlers.
556 * These always run in_irq. */
558 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
560 struct fsg_common *common = ep->driver_data;
561 struct fsg_buffhd *bh = req->context;
563 if (req->status || req->actual != req->length)
564 DBG(common, "%s --> %d, %u/%u\n", __func__,
565 req->status, req->actual, req->length);
566 if (req->status == -ECONNRESET) /* Request was cancelled */
567 usb_ep_fifo_flush(ep);
569 /* Hold the lock while we update the request and buffer states */
571 spin_lock(&common->lock);
573 bh->state = BUF_STATE_EMPTY;
574 wakeup_thread(common);
575 spin_unlock(&common->lock);
578 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
580 struct fsg_common *common = ep->driver_data;
581 struct fsg_buffhd *bh = req->context;
583 dump_msg(common, "bulk-out", req->buf, req->actual);
584 if (req->status || req->actual != bh->bulk_out_intended_length)
585 DBG(common, "%s --> %d, %u/%u\n", __func__,
586 req->status, req->actual,
587 bh->bulk_out_intended_length);
588 if (req->status == -ECONNRESET) /* Request was cancelled */
589 usb_ep_fifo_flush(ep);
591 /* Hold the lock while we update the request and buffer states */
593 spin_lock(&common->lock);
595 bh->state = BUF_STATE_FULL;
596 wakeup_thread(common);
597 spin_unlock(&common->lock);
601 /*-------------------------------------------------------------------------*/
603 /* Ep0 class-specific handlers. These always run in_irq. */
605 static int fsg_setup(struct usb_function *f,
606 const struct usb_ctrlrequest *ctrl)
608 struct fsg_dev *fsg = fsg_from_func(f);
609 struct usb_request *req = fsg->common->ep0req;
610 u16 w_index = le16_to_cpu(ctrl->wIndex);
611 u16 w_value = le16_to_cpu(ctrl->wValue);
612 u16 w_length = le16_to_cpu(ctrl->wLength);
614 if (!fsg_is_set(fsg->common))
617 switch (ctrl->bRequest) {
619 case USB_BULK_RESET_REQUEST:
620 if (ctrl->bRequestType !=
621 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
623 if (w_index != fsg->interface_number || w_value != 0)
626 /* Raise an exception to stop the current operation
627 * and reinitialize our state. */
628 DBG(fsg, "bulk reset request\n");
629 raise_exception(fsg->common, FSG_STATE_RESET);
630 return DELAYED_STATUS;
632 case USB_BULK_GET_MAX_LUN_REQUEST:
633 if (ctrl->bRequestType !=
634 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
636 if (w_index != fsg->interface_number || w_value != 0)
638 VDBG(fsg, "get max LUN\n");
639 *(u8 *) req->buf = fsg->common->nluns - 1;
641 /* Respond with data/status */
642 req->length = min((u16)1, w_length);
643 return ep0_queue(fsg->common);
647 "unknown class-specific control req "
648 "%02x.%02x v%04x i%04x l%u\n",
649 ctrl->bRequestType, ctrl->bRequest,
650 le16_to_cpu(ctrl->wValue), w_index, w_length);
655 /*-------------------------------------------------------------------------*/
657 /* All the following routines run in process context */
660 /* Use this for bulk or interrupt transfers, not ep0 */
661 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
662 struct usb_request *req, int *pbusy,
663 enum fsg_buffer_state *state)
667 if (ep == fsg->bulk_in)
668 dump_msg(fsg, "bulk-in", req->buf, req->length);
670 spin_lock_irq(&fsg->common->lock);
672 *state = BUF_STATE_BUSY;
673 spin_unlock_irq(&fsg->common->lock);
674 rc = usb_ep_queue(ep, req, GFP_KERNEL);
677 *state = BUF_STATE_EMPTY;
679 /* We can't do much more than wait for a reset */
681 /* Note: currently the net2280 driver fails zero-length
682 * submissions if DMA is enabled. */
683 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
685 WARNING(fsg, "error in submission: %s --> %d\n",
690 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
691 if (fsg_is_set(common)) \
692 start_transfer((common)->fsg, (common)->fsg->ep_name, \
693 req, pbusy, state); \
696 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
697 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
701 static int sleep_thread(struct fsg_common *common)
705 /* Wait until a signal arrives or we are woken up */
708 set_current_state(TASK_INTERRUPTIBLE);
709 if (signal_pending(current)) {
713 if (common->thread_wakeup_needed)
717 __set_current_state(TASK_RUNNING);
718 common->thread_wakeup_needed = 0;
723 /*-------------------------------------------------------------------------*/
725 static int do_read(struct fsg_common *common)
727 struct fsg_lun *curlun = common->curlun;
729 struct fsg_buffhd *bh;
732 loff_t file_offset, file_offset_tmp;
734 unsigned int partial_page;
737 /* Get the starting Logical Block Address and check that it's
739 if (common->cmnd[0] == SC_READ_6)
740 lba = get_unaligned_be24(&common->cmnd[1]);
742 lba = get_unaligned_be32(&common->cmnd[2]);
744 /* We allow DPO (Disable Page Out = don't save data in the
745 * cache) and FUA (Force Unit Access = don't read from the
746 * cache), but we don't implement them. */
747 if ((common->cmnd[1] & ~0x18) != 0) {
748 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
752 if (lba >= curlun->num_sectors) {
753 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
756 file_offset = ((loff_t) lba) << 9;
758 /* Carry out the file reads */
759 amount_left = common->data_size_from_cmnd;
760 if (unlikely(amount_left == 0))
761 return -EIO; /* No default reply */
765 /* Figure out how much we need to read:
766 * Try to read the remaining amount.
767 * But don't read more than the buffer size.
768 * And don't try to read past the end of the file.
769 * Finally, if we're not at a page boundary, don't read past
771 * If this means reading 0 then we were asked to read past
772 * the end of file. */
773 amount = min(amount_left, FSG_BUFLEN);
774 amount = min((loff_t) amount,
775 curlun->file_length - file_offset);
776 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
777 if (partial_page > 0)
778 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
781 /* Wait for the next buffer to become available */
782 bh = common->next_buffhd_to_fill;
783 while (bh->state != BUF_STATE_EMPTY) {
784 rc = sleep_thread(common);
789 /* If we were asked to read past the end of file,
790 * end with an empty buffer. */
793 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
794 curlun->sense_data_info = file_offset >> 9;
795 curlun->info_valid = 1;
796 bh->inreq->length = 0;
797 bh->state = BUF_STATE_FULL;
801 /* Perform the read */
802 file_offset_tmp = file_offset;
803 nread = vfs_read(curlun->filp,
804 (char __user *) bh->buf,
805 amount, &file_offset_tmp);
806 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
807 (unsigned long long) file_offset,
809 if (signal_pending(current))
813 LDBG(curlun, "error in file read: %d\n",
816 } else if (nread < amount) {
817 LDBG(curlun, "partial file read: %d/%u\n",
818 (int) nread, amount);
819 nread -= (nread & 511); /* Round down to a block */
821 file_offset += nread;
822 amount_left -= nread;
823 common->residue -= nread;
824 bh->inreq->length = nread;
825 bh->state = BUF_STATE_FULL;
827 /* If an error occurred, report it and its position */
828 if (nread < amount) {
829 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
830 curlun->sense_data_info = file_offset >> 9;
831 curlun->info_valid = 1;
835 if (amount_left == 0)
836 break; /* No more left to read */
838 /* Send this buffer and go read some more */
840 START_TRANSFER_OR(common, bulk_in, bh->inreq,
841 &bh->inreq_busy, &bh->state)
842 /* Don't know what to do if
843 * common->fsg is NULL */
845 common->next_buffhd_to_fill = bh->next;
848 return -EIO; /* No default reply */
852 /*-------------------------------------------------------------------------*/
854 static int do_write(struct fsg_common *common)
856 struct fsg_lun *curlun = common->curlun;
858 struct fsg_buffhd *bh;
860 u32 amount_left_to_req, amount_left_to_write;
861 loff_t usb_offset, file_offset, file_offset_tmp;
863 unsigned int partial_page;
868 curlun->sense_data = SS_WRITE_PROTECTED;
871 spin_lock(&curlun->filp->f_lock);
872 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
873 spin_unlock(&curlun->filp->f_lock);
875 /* Get the starting Logical Block Address and check that it's
877 if (common->cmnd[0] == SC_WRITE_6)
878 lba = get_unaligned_be24(&common->cmnd[1]);
880 lba = get_unaligned_be32(&common->cmnd[2]);
882 /* We allow DPO (Disable Page Out = don't save data in the
883 * cache) and FUA (Force Unit Access = write directly to the
884 * medium). We don't implement DPO; we implement FUA by
885 * performing synchronous output. */
886 if (common->cmnd[1] & ~0x18) {
887 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
890 if (common->cmnd[1] & 0x08) { /* FUA */
891 spin_lock(&curlun->filp->f_lock);
892 curlun->filp->f_flags |= O_SYNC;
893 spin_unlock(&curlun->filp->f_lock);
896 if (lba >= curlun->num_sectors) {
897 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
901 /* Carry out the file writes */
903 file_offset = usb_offset = ((loff_t) lba) << 9;
904 amount_left_to_req = common->data_size_from_cmnd;
905 amount_left_to_write = common->data_size_from_cmnd;
907 while (amount_left_to_write > 0) {
909 /* Queue a request for more data from the host */
910 bh = common->next_buffhd_to_fill;
911 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
913 /* Figure out how much we want to get:
914 * Try to get the remaining amount.
915 * But don't get more than the buffer size.
916 * And don't try to go past the end of the file.
917 * If we're not at a page boundary,
918 * don't go past the next page.
919 * If this means getting 0, then we were asked
920 * to write past the end of file.
921 * Finally, round down to a block boundary. */
922 amount = min(amount_left_to_req, FSG_BUFLEN);
923 amount = min((loff_t) amount, curlun->file_length -
925 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
926 if (partial_page > 0)
928 (unsigned int) PAGE_CACHE_SIZE - partial_page);
933 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
934 curlun->sense_data_info = usb_offset >> 9;
935 curlun->info_valid = 1;
938 amount -= (amount & 511);
941 /* Why were we were asked to transfer a
947 /* Get the next buffer */
948 usb_offset += amount;
949 common->usb_amount_left -= amount;
950 amount_left_to_req -= amount;
951 if (amount_left_to_req == 0)
954 /* amount is always divisible by 512, hence by
955 * the bulk-out maxpacket size */
956 bh->outreq->length = amount;
957 bh->bulk_out_intended_length = amount;
958 bh->outreq->short_not_ok = 1;
959 START_TRANSFER_OR(common, bulk_out, bh->outreq,
960 &bh->outreq_busy, &bh->state)
961 /* Don't know what to do if
962 * common->fsg is NULL */
964 common->next_buffhd_to_fill = bh->next;
968 /* Write the received data to the backing file */
969 bh = common->next_buffhd_to_drain;
970 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
971 break; /* We stopped early */
972 if (bh->state == BUF_STATE_FULL) {
974 common->next_buffhd_to_drain = bh->next;
975 bh->state = BUF_STATE_EMPTY;
977 /* Did something go wrong with the transfer? */
978 if (bh->outreq->status != 0) {
979 curlun->sense_data = SS_COMMUNICATION_FAILURE;
980 curlun->sense_data_info = file_offset >> 9;
981 curlun->info_valid = 1;
985 amount = bh->outreq->actual;
986 if (curlun->file_length - file_offset < amount) {
988 "write %u @ %llu beyond end %llu\n",
989 amount, (unsigned long long) file_offset,
990 (unsigned long long) curlun->file_length);
991 amount = curlun->file_length - file_offset;
994 /* Perform the write */
995 file_offset_tmp = file_offset;
996 nwritten = vfs_write(curlun->filp,
997 (char __user *) bh->buf,
998 amount, &file_offset_tmp);
999 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1000 (unsigned long long) file_offset,
1002 if (signal_pending(current))
1003 return -EINTR; /* Interrupted! */
1006 LDBG(curlun, "error in file write: %d\n",
1009 } else if (nwritten < amount) {
1010 LDBG(curlun, "partial file write: %d/%u\n",
1011 (int) nwritten, amount);
1012 nwritten -= (nwritten & 511);
1013 /* Round down to a block */
1015 file_offset += nwritten;
1016 amount_left_to_write -= nwritten;
1017 common->residue -= nwritten;
1019 /* If an error occurred, report it and its position */
1020 if (nwritten < amount) {
1021 curlun->sense_data = SS_WRITE_ERROR;
1022 curlun->sense_data_info = file_offset >> 9;
1023 curlun->info_valid = 1;
1027 /* Did the host decide to stop early? */
1028 if (bh->outreq->actual != bh->outreq->length) {
1029 common->short_packet_received = 1;
1035 /* Wait for something to happen */
1036 rc = sleep_thread(common);
1041 return -EIO; /* No default reply */
1045 /*-------------------------------------------------------------------------*/
1047 static int do_synchronize_cache(struct fsg_common *common)
1049 struct fsg_lun *curlun = common->curlun;
1052 /* We ignore the requested LBA and write out all file's
1053 * dirty data buffers. */
1054 rc = fsg_lun_fsync_sub(curlun);
1056 curlun->sense_data = SS_WRITE_ERROR;
1061 /*-------------------------------------------------------------------------*/
1063 static void invalidate_sub(struct fsg_lun *curlun)
1065 struct file *filp = curlun->filp;
1066 struct inode *inode = filp->f_path.dentry->d_inode;
1069 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1070 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1073 static int do_verify(struct fsg_common *common)
1075 struct fsg_lun *curlun = common->curlun;
1077 u32 verification_length;
1078 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1079 loff_t file_offset, file_offset_tmp;
1081 unsigned int amount;
1084 /* Get the starting Logical Block Address and check that it's
1086 lba = get_unaligned_be32(&common->cmnd[2]);
1087 if (lba >= curlun->num_sectors) {
1088 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1092 /* We allow DPO (Disable Page Out = don't save data in the
1093 * cache) but we don't implement it. */
1094 if (common->cmnd[1] & ~0x10) {
1095 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1099 verification_length = get_unaligned_be16(&common->cmnd[7]);
1100 if (unlikely(verification_length == 0))
1101 return -EIO; /* No default reply */
1103 /* Prepare to carry out the file verify */
1104 amount_left = verification_length << 9;
1105 file_offset = ((loff_t) lba) << 9;
1107 /* Write out all the dirty buffers before invalidating them */
1108 fsg_lun_fsync_sub(curlun);
1109 if (signal_pending(current))
1112 invalidate_sub(curlun);
1113 if (signal_pending(current))
1116 /* Just try to read the requested blocks */
1117 while (amount_left > 0) {
1119 /* Figure out how much we need to read:
1120 * Try to read the remaining amount, but not more than
1122 * And don't try to read past the end of the file.
1123 * If this means reading 0 then we were asked to read
1124 * past the end of file. */
1125 amount = min(amount_left, FSG_BUFLEN);
1126 amount = min((loff_t) amount,
1127 curlun->file_length - file_offset);
1129 curlun->sense_data =
1130 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1131 curlun->sense_data_info = file_offset >> 9;
1132 curlun->info_valid = 1;
1136 /* Perform the read */
1137 file_offset_tmp = file_offset;
1138 nread = vfs_read(curlun->filp,
1139 (char __user *) bh->buf,
1140 amount, &file_offset_tmp);
1141 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1142 (unsigned long long) file_offset,
1144 if (signal_pending(current))
1148 LDBG(curlun, "error in file verify: %d\n",
1151 } else if (nread < amount) {
1152 LDBG(curlun, "partial file verify: %d/%u\n",
1153 (int) nread, amount);
1154 nread -= (nread & 511); /* Round down to a sector */
1157 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1158 curlun->sense_data_info = file_offset >> 9;
1159 curlun->info_valid = 1;
1162 file_offset += nread;
1163 amount_left -= nread;
1169 /*-------------------------------------------------------------------------*/
1171 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1173 struct fsg_lun *curlun = common->curlun;
1174 u8 *buf = (u8 *) bh->buf;
1176 if (!curlun) { /* Unsupported LUNs are okay */
1177 common->bad_lun_okay = 1;
1179 buf[0] = 0x7f; /* Unsupported, no device-type */
1180 buf[4] = 31; /* Additional length */
1184 buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1185 buf[1] = curlun->removable ? 0x80 : 0;
1186 buf[2] = 2; /* ANSI SCSI level 2 */
1187 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1188 buf[4] = 31; /* Additional length */
1189 buf[5] = 0; /* No special options */
1192 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1197 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1199 struct fsg_lun *curlun = common->curlun;
1200 u8 *buf = (u8 *) bh->buf;
1205 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1207 * If a REQUEST SENSE command is received from an initiator
1208 * with a pending unit attention condition (before the target
1209 * generates the contingent allegiance condition), then the
1210 * target shall either:
1211 * a) report any pending sense data and preserve the unit
1212 * attention condition on the logical unit, or,
1213 * b) report the unit attention condition, may discard any
1214 * pending sense data, and clear the unit attention
1215 * condition on the logical unit for that initiator.
1217 * FSG normally uses option a); enable this code to use option b).
1220 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1221 curlun->sense_data = curlun->unit_attention_data;
1222 curlun->unit_attention_data = SS_NO_SENSE;
1226 if (!curlun) { /* Unsupported LUNs are okay */
1227 common->bad_lun_okay = 1;
1228 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1232 sd = curlun->sense_data;
1233 sdinfo = curlun->sense_data_info;
1234 valid = curlun->info_valid << 7;
1235 curlun->sense_data = SS_NO_SENSE;
1236 curlun->sense_data_info = 0;
1237 curlun->info_valid = 0;
1241 buf[0] = valid | 0x70; /* Valid, current error */
1243 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1244 buf[7] = 18 - 8; /* Additional sense length */
1251 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1253 struct fsg_lun *curlun = common->curlun;
1254 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1255 int pmi = common->cmnd[8];
1256 u8 *buf = (u8 *) bh->buf;
1258 /* Check the PMI and LBA fields */
1259 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1260 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1264 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1265 /* Max logical block */
1266 put_unaligned_be32(512, &buf[4]); /* Block length */
1271 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1273 struct fsg_lun *curlun = common->curlun;
1274 int msf = common->cmnd[1] & 0x02;
1275 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1276 u8 *buf = (u8 *) bh->buf;
1278 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1279 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1282 if (lba >= curlun->num_sectors) {
1283 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1288 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1289 store_cdrom_address(&buf[4], msf, lba);
1294 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1296 struct fsg_lun *curlun = common->curlun;
1297 int msf = common->cmnd[1] & 0x02;
1298 int start_track = common->cmnd[6];
1299 u8 *buf = (u8 *) bh->buf;
1301 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1303 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1308 buf[1] = (20-2); /* TOC data length */
1309 buf[2] = 1; /* First track number */
1310 buf[3] = 1; /* Last track number */
1311 buf[5] = 0x16; /* Data track, copying allowed */
1312 buf[6] = 0x01; /* Only track is number 1 */
1313 store_cdrom_address(&buf[8], msf, 0);
1315 buf[13] = 0x16; /* Lead-out track is data */
1316 buf[14] = 0xAA; /* Lead-out track number */
1317 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1322 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1324 struct fsg_lun *curlun = common->curlun;
1325 int mscmnd = common->cmnd[0];
1326 u8 *buf = (u8 *) bh->buf;
1329 int changeable_values, all_pages;
1333 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1334 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1337 pc = common->cmnd[2] >> 6;
1338 page_code = common->cmnd[2] & 0x3f;
1340 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1343 changeable_values = (pc == 1);
1344 all_pages = (page_code == 0x3f);
1346 /* Write the mode parameter header. Fixed values are: default
1347 * medium type, no cache control (DPOFUA), and no block descriptors.
1348 * The only variable value is the WriteProtect bit. We will fill in
1349 * the mode data length later. */
1351 if (mscmnd == SC_MODE_SENSE_6) {
1352 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1355 } else { /* SC_MODE_SENSE_10 */
1356 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1358 limit = 65535; /* Should really be FSG_BUFLEN */
1361 /* No block descriptors */
1363 /* The mode pages, in numerical order. The only page we support
1364 * is the Caching page. */
1365 if (page_code == 0x08 || all_pages) {
1367 buf[0] = 0x08; /* Page code */
1368 buf[1] = 10; /* Page length */
1369 memset(buf+2, 0, 10); /* None of the fields are changeable */
1371 if (!changeable_values) {
1372 buf[2] = 0x04; /* Write cache enable, */
1373 /* Read cache not disabled */
1374 /* No cache retention priorities */
1375 put_unaligned_be16(0xffff, &buf[4]);
1376 /* Don't disable prefetch */
1377 /* Minimum prefetch = 0 */
1378 put_unaligned_be16(0xffff, &buf[8]);
1379 /* Maximum prefetch */
1380 put_unaligned_be16(0xffff, &buf[10]);
1381 /* Maximum prefetch ceiling */
1386 /* Check that a valid page was requested and the mode data length
1387 * isn't too long. */
1389 if (!valid_page || len > limit) {
1390 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1394 /* Store the mode data length */
1395 if (mscmnd == SC_MODE_SENSE_6)
1398 put_unaligned_be16(len - 2, buf0);
1403 static int do_start_stop(struct fsg_common *common)
1405 struct fsg_lun *curlun = common->curlun;
1410 } else if (!curlun->removable) {
1411 curlun->sense_data = SS_INVALID_COMMAND;
1413 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1414 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1415 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1419 loej = common->cmnd[4] & 0x02;
1420 start = common->cmnd[4] & 0x01;
1422 /* Our emulation doesn't support mounting; the medium is
1423 * available for use as soon as it is loaded. */
1425 if (!fsg_lun_is_open(curlun)) {
1426 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1432 /* Are we allowed to unload the media? */
1433 if (curlun->prevent_medium_removal) {
1434 LDBG(curlun, "unload attempt prevented\n");
1435 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1442 /* Simulate an unload/eject */
1443 if (common->ops && common->ops->pre_eject) {
1444 int r = common->ops->pre_eject(common, curlun,
1445 curlun - common->luns);
1446 if (unlikely(r < 0))
1452 up_read(&common->filesem);
1453 down_write(&common->filesem);
1454 fsg_lun_close(curlun);
1455 up_write(&common->filesem);
1456 down_read(&common->filesem);
1458 return common->ops && common->ops->post_eject
1459 ? min(0, common->ops->post_eject(common, curlun,
1460 curlun - common->luns))
1465 static int do_prevent_allow(struct fsg_common *common)
1467 struct fsg_lun *curlun = common->curlun;
1470 if (!common->curlun) {
1472 } else if (!common->curlun->removable) {
1473 common->curlun->sense_data = SS_INVALID_COMMAND;
1477 prevent = common->cmnd[4] & 0x01;
1478 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1479 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1483 if (curlun->prevent_medium_removal && !prevent)
1484 fsg_lun_fsync_sub(curlun);
1485 curlun->prevent_medium_removal = prevent;
1490 static int do_read_format_capacities(struct fsg_common *common,
1491 struct fsg_buffhd *bh)
1493 struct fsg_lun *curlun = common->curlun;
1494 u8 *buf = (u8 *) bh->buf;
1496 buf[0] = buf[1] = buf[2] = 0;
1497 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1500 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1501 /* Number of blocks */
1502 put_unaligned_be32(512, &buf[4]); /* Block length */
1503 buf[4] = 0x02; /* Current capacity */
1508 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1510 struct fsg_lun *curlun = common->curlun;
1512 /* We don't support MODE SELECT */
1514 curlun->sense_data = SS_INVALID_COMMAND;
1519 /*-------------------------------------------------------------------------*/
1521 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1525 rc = fsg_set_halt(fsg, fsg->bulk_in);
1527 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1529 if (rc != -EAGAIN) {
1530 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1535 /* Wait for a short time and then try again */
1536 if (msleep_interruptible(100) != 0)
1538 rc = usb_ep_set_halt(fsg->bulk_in);
1543 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1547 DBG(fsg, "bulk-in set wedge\n");
1548 rc = usb_ep_set_wedge(fsg->bulk_in);
1550 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1552 if (rc != -EAGAIN) {
1553 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1558 /* Wait for a short time and then try again */
1559 if (msleep_interruptible(100) != 0)
1561 rc = usb_ep_set_wedge(fsg->bulk_in);
1566 static int pad_with_zeros(struct fsg_dev *fsg)
1568 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1569 u32 nkeep = bh->inreq->length;
1573 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1574 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1575 while (fsg->common->usb_amount_left > 0) {
1577 /* Wait for the next buffer to be free */
1578 while (bh->state != BUF_STATE_EMPTY) {
1579 rc = sleep_thread(fsg->common);
1584 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1585 memset(bh->buf + nkeep, 0, nsend - nkeep);
1586 bh->inreq->length = nsend;
1587 bh->inreq->zero = 0;
1588 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1589 &bh->inreq_busy, &bh->state);
1590 bh = fsg->common->next_buffhd_to_fill = bh->next;
1591 fsg->common->usb_amount_left -= nsend;
1597 static int throw_away_data(struct fsg_common *common)
1599 struct fsg_buffhd *bh;
1603 for (bh = common->next_buffhd_to_drain;
1604 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1605 bh = common->next_buffhd_to_drain) {
1607 /* Throw away the data in a filled buffer */
1608 if (bh->state == BUF_STATE_FULL) {
1610 bh->state = BUF_STATE_EMPTY;
1611 common->next_buffhd_to_drain = bh->next;
1613 /* A short packet or an error ends everything */
1614 if (bh->outreq->actual != bh->outreq->length ||
1615 bh->outreq->status != 0) {
1616 raise_exception(common,
1617 FSG_STATE_ABORT_BULK_OUT);
1623 /* Try to submit another request if we need one */
1624 bh = common->next_buffhd_to_fill;
1625 if (bh->state == BUF_STATE_EMPTY
1626 && common->usb_amount_left > 0) {
1627 amount = min(common->usb_amount_left, FSG_BUFLEN);
1629 /* amount is always divisible by 512, hence by
1630 * the bulk-out maxpacket size */
1631 bh->outreq->length = amount;
1632 bh->bulk_out_intended_length = amount;
1633 bh->outreq->short_not_ok = 1;
1634 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1635 &bh->outreq_busy, &bh->state)
1636 /* Don't know what to do if
1637 * common->fsg is NULL */
1639 common->next_buffhd_to_fill = bh->next;
1640 common->usb_amount_left -= amount;
1644 /* Otherwise wait for something to happen */
1645 rc = sleep_thread(common);
1653 static int finish_reply(struct fsg_common *common)
1655 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1658 switch (common->data_dir) {
1660 break; /* Nothing to send */
1662 /* If we don't know whether the host wants to read or write,
1663 * this must be CB or CBI with an unknown command. We mustn't
1664 * try to send or receive any data. So stall both bulk pipes
1665 * if we can and wait for a reset. */
1666 case DATA_DIR_UNKNOWN:
1667 if (!common->can_stall) {
1669 } else if (fsg_is_set(common)) {
1670 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1671 rc = halt_bulk_in_endpoint(common->fsg);
1673 /* Don't know what to do if common->fsg is NULL */
1678 /* All but the last buffer of data must have already been sent */
1679 case DATA_DIR_TO_HOST:
1680 if (common->data_size == 0) {
1681 /* Nothing to send */
1683 /* If there's no residue, simply send the last buffer */
1684 } else if (common->residue == 0) {
1685 bh->inreq->zero = 0;
1686 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1687 &bh->inreq_busy, &bh->state)
1689 common->next_buffhd_to_fill = bh->next;
1691 /* For Bulk-only, if we're allowed to stall then send the
1692 * short packet and halt the bulk-in endpoint. If we can't
1693 * stall, pad out the remaining data with 0's. */
1694 } else if (common->can_stall) {
1695 bh->inreq->zero = 1;
1696 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1697 &bh->inreq_busy, &bh->state)
1698 /* Don't know what to do if
1699 * common->fsg is NULL */
1701 common->next_buffhd_to_fill = bh->next;
1703 rc = halt_bulk_in_endpoint(common->fsg);
1704 } else if (fsg_is_set(common)) {
1705 rc = pad_with_zeros(common->fsg);
1707 /* Don't know what to do if common->fsg is NULL */
1712 /* We have processed all we want from the data the host has sent.
1713 * There may still be outstanding bulk-out requests. */
1714 case DATA_DIR_FROM_HOST:
1715 if (common->residue == 0) {
1716 /* Nothing to receive */
1718 /* Did the host stop sending unexpectedly early? */
1719 } else if (common->short_packet_received) {
1720 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1723 /* We haven't processed all the incoming data. Even though
1724 * we may be allowed to stall, doing so would cause a race.
1725 * The controller may already have ACK'ed all the remaining
1726 * bulk-out packets, in which case the host wouldn't see a
1727 * STALL. Not realizing the endpoint was halted, it wouldn't
1728 * clear the halt -- leading to problems later on. */
1730 } else if (common->can_stall) {
1731 if (fsg_is_set(common))
1732 fsg_set_halt(common->fsg,
1733 common->fsg->bulk_out);
1734 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1738 /* We can't stall. Read in the excess data and throw it
1741 rc = throw_away_data(common);
1749 static int send_status(struct fsg_common *common)
1751 struct fsg_lun *curlun = common->curlun;
1752 struct fsg_buffhd *bh;
1753 struct bulk_cs_wrap *csw;
1755 u8 status = USB_STATUS_PASS;
1758 /* Wait for the next buffer to become available */
1759 bh = common->next_buffhd_to_fill;
1760 while (bh->state != BUF_STATE_EMPTY) {
1761 rc = sleep_thread(common);
1767 sd = curlun->sense_data;
1768 sdinfo = curlun->sense_data_info;
1769 } else if (common->bad_lun_okay)
1772 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1774 if (common->phase_error) {
1775 DBG(common, "sending phase-error status\n");
1776 status = USB_STATUS_PHASE_ERROR;
1777 sd = SS_INVALID_COMMAND;
1778 } else if (sd != SS_NO_SENSE) {
1779 DBG(common, "sending command-failure status\n");
1780 status = USB_STATUS_FAIL;
1781 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1783 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1786 /* Store and send the Bulk-only CSW */
1787 csw = (void *)bh->buf;
1789 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1790 csw->Tag = common->tag;
1791 csw->Residue = cpu_to_le32(common->residue);
1792 csw->Status = status;
1794 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1795 bh->inreq->zero = 0;
1796 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1797 &bh->inreq_busy, &bh->state)
1798 /* Don't know what to do if common->fsg is NULL */
1801 common->next_buffhd_to_fill = bh->next;
1806 /*-------------------------------------------------------------------------*/
1808 /* Check whether the command is properly formed and whether its data size
1809 * and direction agree with the values we already have. */
1810 static int check_command(struct fsg_common *common, int cmnd_size,
1811 enum data_direction data_dir, unsigned int mask,
1812 int needs_medium, const char *name)
1815 int lun = common->cmnd[1] >> 5;
1816 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1818 struct fsg_lun *curlun;
1821 if (common->data_dir != DATA_DIR_UNKNOWN)
1822 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1824 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1825 name, cmnd_size, dirletter[(int) data_dir],
1826 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1828 /* We can't reply at all until we know the correct data direction
1830 if (common->data_size_from_cmnd == 0)
1831 data_dir = DATA_DIR_NONE;
1832 if (common->data_size < common->data_size_from_cmnd) {
1833 /* Host data size < Device data size is a phase error.
1834 * Carry out the command, but only transfer as much as
1835 * we are allowed. */
1836 common->data_size_from_cmnd = common->data_size;
1837 common->phase_error = 1;
1839 common->residue = common->data_size;
1840 common->usb_amount_left = common->data_size;
1842 /* Conflicting data directions is a phase error */
1843 if (common->data_dir != data_dir
1844 && common->data_size_from_cmnd > 0) {
1845 common->phase_error = 1;
1849 /* Verify the length of the command itself */
1850 if (cmnd_size != common->cmnd_size) {
1852 /* Special case workaround: There are plenty of buggy SCSI
1853 * implementations. Many have issues with cbw->Length
1854 * field passing a wrong command size. For those cases we
1855 * always try to work around the problem by using the length
1856 * sent by the host side provided it is at least as large
1857 * as the correct command length.
1858 * Examples of such cases would be MS-Windows, which issues
1859 * REQUEST SENSE with cbw->Length == 12 where it should
1860 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1861 * REQUEST SENSE with cbw->Length == 10 where it should
1864 if (cmnd_size <= common->cmnd_size) {
1865 DBG(common, "%s is buggy! Expected length %d "
1866 "but we got %d\n", name,
1867 cmnd_size, common->cmnd_size);
1868 cmnd_size = common->cmnd_size;
1870 common->phase_error = 1;
1875 /* Check that the LUN values are consistent */
1876 if (common->lun != lun)
1877 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1881 if (common->lun >= 0 && common->lun < common->nluns) {
1882 curlun = &common->luns[common->lun];
1883 common->curlun = curlun;
1884 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1885 curlun->sense_data = SS_NO_SENSE;
1886 curlun->sense_data_info = 0;
1887 curlun->info_valid = 0;
1890 common->curlun = NULL;
1892 common->bad_lun_okay = 0;
1894 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1895 * to use unsupported LUNs; all others may not. */
1896 if (common->cmnd[0] != SC_INQUIRY &&
1897 common->cmnd[0] != SC_REQUEST_SENSE) {
1898 DBG(common, "unsupported LUN %d\n", common->lun);
1903 /* If a unit attention condition exists, only INQUIRY and
1904 * REQUEST SENSE commands are allowed; anything else must fail. */
1905 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1906 common->cmnd[0] != SC_INQUIRY &&
1907 common->cmnd[0] != SC_REQUEST_SENSE) {
1908 curlun->sense_data = curlun->unit_attention_data;
1909 curlun->unit_attention_data = SS_NO_SENSE;
1913 /* Check that only command bytes listed in the mask are non-zero */
1914 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1915 for (i = 1; i < cmnd_size; ++i) {
1916 if (common->cmnd[i] && !(mask & (1 << i))) {
1918 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1923 /* If the medium isn't mounted and the command needs to access
1924 * it, return an error. */
1925 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1926 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1934 static int do_scsi_command(struct fsg_common *common)
1936 struct fsg_buffhd *bh;
1938 int reply = -EINVAL;
1940 static char unknown[16];
1944 /* Wait for the next buffer to become available for data or status */
1945 bh = common->next_buffhd_to_fill;
1946 common->next_buffhd_to_drain = bh;
1947 while (bh->state != BUF_STATE_EMPTY) {
1948 rc = sleep_thread(common);
1952 common->phase_error = 0;
1953 common->short_packet_received = 0;
1955 down_read(&common->filesem); /* We're using the backing file */
1956 switch (common->cmnd[0]) {
1959 common->data_size_from_cmnd = common->cmnd[4];
1960 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1964 reply = do_inquiry(common, bh);
1967 case SC_MODE_SELECT_6:
1968 common->data_size_from_cmnd = common->cmnd[4];
1969 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1973 reply = do_mode_select(common, bh);
1976 case SC_MODE_SELECT_10:
1977 common->data_size_from_cmnd =
1978 get_unaligned_be16(&common->cmnd[7]);
1979 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1983 reply = do_mode_select(common, bh);
1986 case SC_MODE_SENSE_6:
1987 common->data_size_from_cmnd = common->cmnd[4];
1988 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1989 (1<<1) | (1<<2) | (1<<4), 0,
1992 reply = do_mode_sense(common, bh);
1995 case SC_MODE_SENSE_10:
1996 common->data_size_from_cmnd =
1997 get_unaligned_be16(&common->cmnd[7]);
1998 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1999 (1<<1) | (1<<2) | (3<<7), 0,
2002 reply = do_mode_sense(common, bh);
2005 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2006 common->data_size_from_cmnd = 0;
2007 reply = check_command(common, 6, DATA_DIR_NONE,
2009 "PREVENT-ALLOW MEDIUM REMOVAL");
2011 reply = do_prevent_allow(common);
2015 i = common->cmnd[4];
2016 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2017 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2021 reply = do_read(common);
2025 common->data_size_from_cmnd =
2026 get_unaligned_be16(&common->cmnd[7]) << 9;
2027 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2028 (1<<1) | (0xf<<2) | (3<<7), 1,
2031 reply = do_read(common);
2035 common->data_size_from_cmnd =
2036 get_unaligned_be32(&common->cmnd[6]) << 9;
2037 reply = check_command(common, 12, DATA_DIR_TO_HOST,
2038 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2041 reply = do_read(common);
2044 case SC_READ_CAPACITY:
2045 common->data_size_from_cmnd = 8;
2046 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2047 (0xf<<2) | (1<<8), 1,
2050 reply = do_read_capacity(common, bh);
2053 case SC_READ_HEADER:
2054 if (!common->curlun || !common->curlun->cdrom)
2056 common->data_size_from_cmnd =
2057 get_unaligned_be16(&common->cmnd[7]);
2058 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2059 (3<<7) | (0x1f<<1), 1,
2062 reply = do_read_header(common, bh);
2066 if (!common->curlun || !common->curlun->cdrom)
2068 common->data_size_from_cmnd =
2069 get_unaligned_be16(&common->cmnd[7]);
2070 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2074 reply = do_read_toc(common, bh);
2077 case SC_READ_FORMAT_CAPACITIES:
2078 common->data_size_from_cmnd =
2079 get_unaligned_be16(&common->cmnd[7]);
2080 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2082 "READ FORMAT CAPACITIES");
2084 reply = do_read_format_capacities(common, bh);
2087 case SC_REQUEST_SENSE:
2088 common->data_size_from_cmnd = common->cmnd[4];
2089 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2093 reply = do_request_sense(common, bh);
2096 case SC_START_STOP_UNIT:
2097 common->data_size_from_cmnd = 0;
2098 reply = check_command(common, 6, DATA_DIR_NONE,
2102 reply = do_start_stop(common);
2105 case SC_SYNCHRONIZE_CACHE:
2106 common->data_size_from_cmnd = 0;
2107 reply = check_command(common, 10, DATA_DIR_NONE,
2108 (0xf<<2) | (3<<7), 1,
2109 "SYNCHRONIZE CACHE");
2111 reply = do_synchronize_cache(common);
2114 case SC_TEST_UNIT_READY:
2115 common->data_size_from_cmnd = 0;
2116 reply = check_command(common, 6, DATA_DIR_NONE,
2121 /* Although optional, this command is used by MS-Windows. We
2122 * support a minimal version: BytChk must be 0. */
2124 common->data_size_from_cmnd = 0;
2125 reply = check_command(common, 10, DATA_DIR_NONE,
2126 (1<<1) | (0xf<<2) | (3<<7), 1,
2129 reply = do_verify(common);
2133 i = common->cmnd[4];
2134 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2135 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2139 reply = do_write(common);
2143 common->data_size_from_cmnd =
2144 get_unaligned_be16(&common->cmnd[7]) << 9;
2145 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2146 (1<<1) | (0xf<<2) | (3<<7), 1,
2149 reply = do_write(common);
2153 common->data_size_from_cmnd =
2154 get_unaligned_be32(&common->cmnd[6]) << 9;
2155 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2156 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2159 reply = do_write(common);
2162 /* Some mandatory commands that we recognize but don't implement.
2163 * They don't mean much in this setting. It's left as an exercise
2164 * for anyone interested to implement RESERVE and RELEASE in terms
2165 * of Posix locks. */
2166 case SC_FORMAT_UNIT:
2169 case SC_SEND_DIAGNOSTIC:
2174 common->data_size_from_cmnd = 0;
2175 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2176 reply = check_command(common, common->cmnd_size,
2177 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2179 common->curlun->sense_data = SS_INVALID_COMMAND;
2184 up_read(&common->filesem);
2186 if (reply == -EINTR || signal_pending(current))
2189 /* Set up the single reply buffer for finish_reply() */
2190 if (reply == -EINVAL)
2191 reply = 0; /* Error reply length */
2192 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2193 reply = min((u32) reply, common->data_size_from_cmnd);
2194 bh->inreq->length = reply;
2195 bh->state = BUF_STATE_FULL;
2196 common->residue -= reply;
2197 } /* Otherwise it's already set */
2203 /*-------------------------------------------------------------------------*/
2205 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2207 struct usb_request *req = bh->outreq;
2208 struct fsg_bulk_cb_wrap *cbw = req->buf;
2209 struct fsg_common *common = fsg->common;
2211 /* Was this a real packet? Should it be ignored? */
2212 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2215 /* Is the CBW valid? */
2216 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2217 cbw->Signature != cpu_to_le32(
2219 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2221 le32_to_cpu(cbw->Signature));
2223 /* The Bulk-only spec says we MUST stall the IN endpoint
2224 * (6.6.1), so it's unavoidable. It also says we must
2225 * retain this state until the next reset, but there's
2226 * no way to tell the controller driver it should ignore
2227 * Clear-Feature(HALT) requests.
2229 * We aren't required to halt the OUT endpoint; instead
2230 * we can simply accept and discard any data received
2231 * until the next reset. */
2232 wedge_bulk_in_endpoint(fsg);
2233 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2237 /* Is the CBW meaningful? */
2238 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2239 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2240 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2242 cbw->Lun, cbw->Flags, cbw->Length);
2244 /* We can do anything we want here, so let's stall the
2245 * bulk pipes if we are allowed to. */
2246 if (common->can_stall) {
2247 fsg_set_halt(fsg, fsg->bulk_out);
2248 halt_bulk_in_endpoint(fsg);
2253 /* Save the command for later */
2254 common->cmnd_size = cbw->Length;
2255 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2256 if (cbw->Flags & USB_BULK_IN_FLAG)
2257 common->data_dir = DATA_DIR_TO_HOST;
2259 common->data_dir = DATA_DIR_FROM_HOST;
2260 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2261 if (common->data_size == 0)
2262 common->data_dir = DATA_DIR_NONE;
2263 common->lun = cbw->Lun;
2264 common->tag = cbw->Tag;
2269 static int get_next_command(struct fsg_common *common)
2271 struct fsg_buffhd *bh;
2274 /* Wait for the next buffer to become available */
2275 bh = common->next_buffhd_to_fill;
2276 while (bh->state != BUF_STATE_EMPTY) {
2277 rc = sleep_thread(common);
2282 /* Queue a request to read a Bulk-only CBW */
2283 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2284 bh->outreq->short_not_ok = 1;
2285 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2286 &bh->outreq_busy, &bh->state)
2287 /* Don't know what to do if common->fsg is NULL */
2290 /* We will drain the buffer in software, which means we
2291 * can reuse it for the next filling. No need to advance
2292 * next_buffhd_to_fill. */
2294 /* Wait for the CBW to arrive */
2295 while (bh->state != BUF_STATE_FULL) {
2296 rc = sleep_thread(common);
2301 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2302 bh->state = BUF_STATE_EMPTY;
2308 /*-------------------------------------------------------------------------*/
2310 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2311 const struct usb_endpoint_descriptor *d)
2315 ep->driver_data = common;
2316 rc = usb_ep_enable(ep, d);
2318 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2322 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2323 struct usb_request **preq)
2325 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2328 ERROR(common, "can't allocate request for %s\n", ep->name);
2332 /* Reset interface setting and re-init endpoint state (toggle etc). */
2333 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2335 const struct usb_endpoint_descriptor *d;
2336 struct fsg_dev *fsg;
2339 if (common->running)
2340 DBG(common, "reset interface\n");
2343 /* Deallocate the requests */
2347 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2348 struct fsg_buffhd *bh = &common->buffhds[i];
2351 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2355 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2360 /* Disable the endpoints */
2361 if (fsg->bulk_in_enabled) {
2362 usb_ep_disable(fsg->bulk_in);
2363 fsg->bulk_in_enabled = 0;
2365 if (fsg->bulk_out_enabled) {
2366 usb_ep_disable(fsg->bulk_out);
2367 fsg->bulk_out_enabled = 0;
2371 wake_up(&common->fsg_wait);
2374 common->running = 0;
2378 common->fsg = new_fsg;
2381 /* Enable the endpoints */
2382 d = fsg_ep_desc(common->gadget,
2383 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2384 rc = enable_endpoint(common, fsg->bulk_in, d);
2387 fsg->bulk_in_enabled = 1;
2389 d = fsg_ep_desc(common->gadget,
2390 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2391 rc = enable_endpoint(common, fsg->bulk_out, d);
2394 fsg->bulk_out_enabled = 1;
2395 common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2396 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2398 /* Allocate the requests */
2399 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2400 struct fsg_buffhd *bh = &common->buffhds[i];
2402 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2405 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2408 bh->inreq->buf = bh->outreq->buf = bh->buf;
2409 bh->inreq->context = bh->outreq->context = bh;
2410 bh->inreq->complete = bulk_in_complete;
2411 bh->outreq->complete = bulk_out_complete;
2414 common->running = 1;
2415 for (i = 0; i < common->nluns; ++i)
2416 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2421 /****************************** ALT CONFIGS ******************************/
2424 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2426 struct fsg_dev *fsg = fsg_from_func(f);
2427 fsg->common->new_fsg = fsg;
2428 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2432 static void fsg_disable(struct usb_function *f)
2434 struct fsg_dev *fsg = fsg_from_func(f);
2435 fsg->common->new_fsg = NULL;
2436 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2440 /*-------------------------------------------------------------------------*/
2442 static void handle_exception(struct fsg_common *common)
2446 struct fsg_buffhd *bh;
2447 enum fsg_state old_state;
2448 struct fsg_lun *curlun;
2449 unsigned int exception_req_tag;
2451 /* Clear the existing signals. Anything but SIGUSR1 is converted
2452 * into a high-priority EXIT exception. */
2455 dequeue_signal_lock(current, ¤t->blocked, &info);
2458 if (sig != SIGUSR1) {
2459 if (common->state < FSG_STATE_EXIT)
2460 DBG(common, "Main thread exiting on signal\n");
2461 raise_exception(common, FSG_STATE_EXIT);
2465 /* Cancel all the pending transfers */
2466 if (likely(common->fsg)) {
2467 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2468 bh = &common->buffhds[i];
2470 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2471 if (bh->outreq_busy)
2472 usb_ep_dequeue(common->fsg->bulk_out,
2476 /* Wait until everything is idle */
2479 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2480 bh = &common->buffhds[i];
2481 num_active += bh->inreq_busy + bh->outreq_busy;
2483 if (num_active == 0)
2485 if (sleep_thread(common))
2489 /* Clear out the controller's fifos */
2490 if (common->fsg->bulk_in_enabled)
2491 usb_ep_fifo_flush(common->fsg->bulk_in);
2492 if (common->fsg->bulk_out_enabled)
2493 usb_ep_fifo_flush(common->fsg->bulk_out);
2496 /* Reset the I/O buffer states and pointers, the SCSI
2497 * state, and the exception. Then invoke the handler. */
2498 spin_lock_irq(&common->lock);
2500 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2501 bh = &common->buffhds[i];
2502 bh->state = BUF_STATE_EMPTY;
2504 common->next_buffhd_to_fill = &common->buffhds[0];
2505 common->next_buffhd_to_drain = &common->buffhds[0];
2506 exception_req_tag = common->exception_req_tag;
2507 old_state = common->state;
2509 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2510 common->state = FSG_STATE_STATUS_PHASE;
2512 for (i = 0; i < common->nluns; ++i) {
2513 curlun = &common->luns[i];
2514 curlun->prevent_medium_removal = 0;
2515 curlun->sense_data = SS_NO_SENSE;
2516 curlun->unit_attention_data = SS_NO_SENSE;
2517 curlun->sense_data_info = 0;
2518 curlun->info_valid = 0;
2520 common->state = FSG_STATE_IDLE;
2522 spin_unlock_irq(&common->lock);
2524 /* Carry out any extra actions required for the exception */
2525 switch (old_state) {
2526 case FSG_STATE_ABORT_BULK_OUT:
2527 send_status(common);
2528 spin_lock_irq(&common->lock);
2529 if (common->state == FSG_STATE_STATUS_PHASE)
2530 common->state = FSG_STATE_IDLE;
2531 spin_unlock_irq(&common->lock);
2534 case FSG_STATE_RESET:
2535 /* In case we were forced against our will to halt a
2536 * bulk endpoint, clear the halt now. (The SuperH UDC
2537 * requires this.) */
2538 if (!fsg_is_set(common))
2540 if (test_and_clear_bit(IGNORE_BULK_OUT,
2541 &common->fsg->atomic_bitflags))
2542 usb_ep_clear_halt(common->fsg->bulk_in);
2544 if (common->ep0_req_tag == exception_req_tag)
2545 ep0_queue(common); /* Complete the status stage */
2547 /* Technically this should go here, but it would only be
2548 * a waste of time. Ditto for the INTERFACE_CHANGE and
2549 * CONFIG_CHANGE cases. */
2550 /* for (i = 0; i < common->nluns; ++i) */
2551 /* common->luns[i].unit_attention_data = */
2552 /* SS_RESET_OCCURRED; */
2555 case FSG_STATE_CONFIG_CHANGE:
2556 do_set_interface(common, common->new_fsg);
2559 case FSG_STATE_EXIT:
2560 case FSG_STATE_TERMINATED:
2561 do_set_interface(common, NULL); /* Free resources */
2562 spin_lock_irq(&common->lock);
2563 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2564 spin_unlock_irq(&common->lock);
2567 case FSG_STATE_INTERFACE_CHANGE:
2568 case FSG_STATE_DISCONNECT:
2569 case FSG_STATE_COMMAND_PHASE:
2570 case FSG_STATE_DATA_PHASE:
2571 case FSG_STATE_STATUS_PHASE:
2572 case FSG_STATE_IDLE:
2578 /*-------------------------------------------------------------------------*/
2580 static int fsg_main_thread(void *common_)
2582 struct fsg_common *common = common_;
2584 /* Allow the thread to be killed by a signal, but set the signal mask
2585 * to block everything but INT, TERM, KILL, and USR1. */
2586 allow_signal(SIGINT);
2587 allow_signal(SIGTERM);
2588 allow_signal(SIGKILL);
2589 allow_signal(SIGUSR1);
2591 /* Allow the thread to be frozen */
2594 /* Arrange for userspace references to be interpreted as kernel
2595 * pointers. That way we can pass a kernel pointer to a routine
2596 * that expects a __user pointer and it will work okay. */
2600 while (common->state != FSG_STATE_TERMINATED) {
2601 if (exception_in_progress(common) || signal_pending(current)) {
2602 handle_exception(common);
2606 if (!common->running) {
2607 sleep_thread(common);
2611 if (get_next_command(common))
2614 spin_lock_irq(&common->lock);
2615 if (!exception_in_progress(common))
2616 common->state = FSG_STATE_DATA_PHASE;
2617 spin_unlock_irq(&common->lock);
2619 if (do_scsi_command(common) || finish_reply(common))
2622 spin_lock_irq(&common->lock);
2623 if (!exception_in_progress(common))
2624 common->state = FSG_STATE_STATUS_PHASE;
2625 spin_unlock_irq(&common->lock);
2627 if (send_status(common))
2630 spin_lock_irq(&common->lock);
2631 if (!exception_in_progress(common))
2632 common->state = FSG_STATE_IDLE;
2633 spin_unlock_irq(&common->lock);
2636 spin_lock_irq(&common->lock);
2637 common->thread_task = NULL;
2638 spin_unlock_irq(&common->lock);
2640 if (!common->ops || !common->ops->thread_exits
2641 || common->ops->thread_exits(common) < 0) {
2642 struct fsg_lun *curlun = common->luns;
2643 unsigned i = common->nluns;
2645 down_write(&common->filesem);
2646 for (; i--; ++curlun) {
2647 if (!fsg_lun_is_open(curlun))
2650 fsg_lun_close(curlun);
2651 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2653 up_write(&common->filesem);
2656 /* Let the unbind and cleanup routines know the thread has exited */
2657 complete_and_exit(&common->thread_notifier, 0);
2661 /*************************** DEVICE ATTRIBUTES ***************************/
2663 /* Write permission is checked per LUN in store_*() functions. */
2664 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2665 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2668 /****************************** FSG COMMON ******************************/
2670 static void fsg_common_release(struct kref *ref);
2672 static void fsg_lun_release(struct device *dev)
2674 /* Nothing needs to be done */
2677 static inline void fsg_common_get(struct fsg_common *common)
2679 kref_get(&common->ref);
2682 static inline void fsg_common_put(struct fsg_common *common)
2684 kref_put(&common->ref, fsg_common_release);
2688 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2689 struct usb_composite_dev *cdev,
2690 struct fsg_config *cfg)
2692 struct usb_gadget *gadget = cdev->gadget;
2693 struct fsg_buffhd *bh;
2694 struct fsg_lun *curlun;
2695 struct fsg_lun_config *lcfg;
2699 /* Find out how many LUNs there should be */
2701 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2702 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2703 return ERR_PTR(-EINVAL);
2708 common = kzalloc(sizeof *common, GFP_KERNEL);
2710 return ERR_PTR(-ENOMEM);
2711 common->free_storage_on_release = 1;
2713 memset(common, 0, sizeof common);
2714 common->free_storage_on_release = 0;
2717 common->ops = cfg->ops;
2718 common->private_data = cfg->private_data;
2720 common->gadget = gadget;
2721 common->ep0 = gadget->ep0;
2722 common->ep0req = cdev->req;
2724 /* Maybe allocate device-global string IDs, and patch descriptors */
2725 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2726 rc = usb_string_id(cdev);
2727 if (unlikely(rc < 0))
2729 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2730 fsg_intf_desc.iInterface = rc;
2733 /* Create the LUNs, open their backing files, and register the
2734 * LUN devices in sysfs. */
2735 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2736 if (unlikely(!curlun)) {
2740 common->luns = curlun;
2742 init_rwsem(&common->filesem);
2744 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2745 curlun->cdrom = !!lcfg->cdrom;
2746 curlun->ro = lcfg->cdrom || lcfg->ro;
2747 curlun->removable = lcfg->removable;
2748 curlun->dev.release = fsg_lun_release;
2749 curlun->dev.parent = &gadget->dev;
2750 /* curlun->dev.driver = &fsg_driver.driver; XXX */
2751 dev_set_drvdata(&curlun->dev, &common->filesem);
2752 dev_set_name(&curlun->dev,
2753 cfg->lun_name_format
2754 ? cfg->lun_name_format
2758 rc = device_register(&curlun->dev);
2760 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2765 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2768 rc = device_create_file(&curlun->dev, &dev_attr_file);
2772 if (lcfg->filename) {
2773 rc = fsg_lun_open(curlun, lcfg->filename);
2776 } else if (!curlun->removable) {
2777 ERROR(common, "no file given for LUN%d\n", i);
2782 common->nluns = nluns;
2785 /* Data buffers cyclic list */
2786 bh = common->buffhds;
2787 i = FSG_NUM_BUFFERS;
2788 goto buffhds_first_it;
2793 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2794 if (unlikely(!bh->buf)) {
2799 bh->next = common->buffhds;
2802 /* Prepare inquiryString */
2803 if (cfg->release != 0xffff) {
2806 i = usb_gadget_controller_number(gadget);
2810 WARNING(common, "controller '%s' not recognized\n",
2815 #define OR(x, y) ((x) ? (x) : (y))
2816 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2818 OR(cfg->vendor_name, "Linux "),
2819 /* Assume product name dependent on the first LUN */
2820 OR(cfg->product_name, common->luns->cdrom
2821 ? "File-Stor Gadget"
2822 : "File-CD Gadget "),
2826 /* Some peripheral controllers are known not to be able to
2827 * halt bulk endpoints correctly. If one of them is present,
2830 common->can_stall = cfg->can_stall &&
2831 !(gadget_is_at91(common->gadget));
2834 spin_lock_init(&common->lock);
2835 kref_init(&common->ref);
2838 /* Tell the thread to start working */
2839 common->thread_task =
2840 kthread_create(fsg_main_thread, common,
2841 OR(cfg->thread_name, "file-storage"));
2842 if (IS_ERR(common->thread_task)) {
2843 rc = PTR_ERR(common->thread_task);
2846 init_completion(&common->thread_notifier);
2847 init_waitqueue_head(&common->fsg_wait);
2852 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2853 INFO(common, "Number of LUNs=%d\n", common->nluns);
2855 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2856 for (i = 0, nluns = common->nluns, curlun = common->luns;
2859 char *p = "(no medium)";
2860 if (fsg_lun_is_open(curlun)) {
2863 p = d_path(&curlun->filp->f_path,
2869 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
2870 curlun->removable ? "removable " : "",
2871 curlun->ro ? "read only " : "",
2872 curlun->cdrom ? "CD-ROM " : "",
2877 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
2879 wake_up_process(common->thread_task);
2885 common->nluns = i + 1;
2887 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2888 /* Call fsg_common_release() directly, ref might be not
2890 fsg_common_release(&common->ref);
2895 static void fsg_common_release(struct kref *ref)
2897 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2899 /* If the thread isn't already dead, tell it to exit now */
2900 if (common->state != FSG_STATE_TERMINATED) {
2901 raise_exception(common, FSG_STATE_EXIT);
2902 wait_for_completion(&common->thread_notifier);
2904 /* The cleanup routine waits for this completion also */
2905 complete(&common->thread_notifier);
2908 if (likely(common->luns)) {
2909 struct fsg_lun *lun = common->luns;
2910 unsigned i = common->nluns;
2912 /* In error recovery common->nluns may be zero. */
2913 for (; i; --i, ++lun) {
2914 device_remove_file(&lun->dev, &dev_attr_ro);
2915 device_remove_file(&lun->dev, &dev_attr_file);
2917 device_unregister(&lun->dev);
2920 kfree(common->luns);
2924 struct fsg_buffhd *bh = common->buffhds;
2925 unsigned i = FSG_NUM_BUFFERS;
2928 } while (++bh, --i);
2931 if (common->free_storage_on_release)
2936 /*-------------------------------------------------------------------------*/
2939 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2941 struct fsg_dev *fsg = fsg_from_func(f);
2942 struct fsg_common *common = fsg->common;
2944 DBG(fsg, "unbind\n");
2945 if (fsg->common->fsg == fsg) {
2946 fsg->common->new_fsg = NULL;
2947 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2948 /* FIXME: make interruptible or killable somehow? */
2949 wait_event(common->fsg_wait, common->fsg != fsg);
2952 fsg_common_put(common);
2953 usb_free_descriptors(fsg->function.descriptors);
2954 usb_free_descriptors(fsg->function.hs_descriptors);
2959 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2961 struct fsg_dev *fsg = fsg_from_func(f);
2962 struct usb_gadget *gadget = c->cdev->gadget;
2966 fsg->gadget = gadget;
2969 i = usb_interface_id(c, f);
2972 fsg_intf_desc.bInterfaceNumber = i;
2973 fsg->interface_number = i;
2975 /* Find all the endpoints we will use */
2976 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2979 ep->driver_data = fsg->common; /* claim the endpoint */
2982 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2985 ep->driver_data = fsg->common; /* claim the endpoint */
2988 /* Copy descriptors */
2989 f->descriptors = usb_copy_descriptors(fsg_fs_function);
2990 if (unlikely(!f->descriptors))
2993 if (gadget_is_dualspeed(gadget)) {
2994 /* Assume endpoint addresses are the same for both speeds */
2995 fsg_hs_bulk_in_desc.bEndpointAddress =
2996 fsg_fs_bulk_in_desc.bEndpointAddress;
2997 fsg_hs_bulk_out_desc.bEndpointAddress =
2998 fsg_fs_bulk_out_desc.bEndpointAddress;
2999 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
3000 if (unlikely(!f->hs_descriptors)) {
3001 usb_free_descriptors(f->descriptors);
3009 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3014 /****************************** ADD FUNCTION ******************************/
3016 static struct usb_gadget_strings *fsg_strings_array[] = {
3021 static int fsg_bind_config(struct usb_composite_dev *cdev,
3022 struct usb_configuration *c,
3023 struct fsg_common *common)
3025 struct fsg_dev *fsg;
3028 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3032 fsg->function.name = FSG_DRIVER_DESC;
3033 fsg->function.strings = fsg_strings_array;
3034 fsg->function.bind = fsg_bind;
3035 fsg->function.unbind = fsg_unbind;
3036 fsg->function.setup = fsg_setup;
3037 fsg->function.set_alt = fsg_set_alt;
3038 fsg->function.disable = fsg_disable;
3040 fsg->common = common;
3041 /* Our caller holds a reference to common structure so we
3042 * don't have to be worry about it being freed until we return
3043 * from this function. So instead of incrementing counter now
3044 * and decrement in error recovery we increment it only when
3045 * call to usb_add_function() was successful. */
3047 rc = usb_add_function(c, &fsg->function);
3051 fsg_common_get(fsg->common);
3055 static inline int __deprecated __maybe_unused
3056 fsg_add(struct usb_composite_dev *cdev,
3057 struct usb_configuration *c,
3058 struct fsg_common *common)
3060 return fsg_bind_config(cdev, c, common);
3064 /************************* Module parameters *************************/
3067 struct fsg_module_parameters {
3068 char *file[FSG_MAX_LUNS];
3069 int ro[FSG_MAX_LUNS];
3070 int removable[FSG_MAX_LUNS];
3071 int cdrom[FSG_MAX_LUNS];
3073 unsigned int file_count, ro_count, removable_count, cdrom_count;
3074 unsigned int luns; /* nluns */
3075 int stall; /* can_stall */
3079 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3080 module_param_array_named(prefix ## name, params.name, type, \
3081 &prefix ## params.name ## _count, \
3083 MODULE_PARM_DESC(prefix ## name, desc)
3085 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3086 module_param_named(prefix ## name, params.name, type, \
3088 MODULE_PARM_DESC(prefix ## name, desc)
3090 #define FSG_MODULE_PARAMETERS(prefix, params) \
3091 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3092 "names of backing files or devices"); \
3093 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3094 "true to force read-only"); \
3095 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3096 "true to simulate removable media"); \
3097 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3098 "true to simulate CD-ROM instead of disk"); \
3099 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3100 "number of LUNs"); \
3101 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3102 "false to prevent bulk stalls")
3106 fsg_config_from_params(struct fsg_config *cfg,
3107 const struct fsg_module_parameters *params)
3109 struct fsg_lun_config *lun;
3112 /* Configure LUNs */
3114 min(params->luns ?: (params->file_count ?: 1u),
3115 (unsigned)FSG_MAX_LUNS);
3116 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3117 lun->ro = !!params->ro[i];
3118 lun->cdrom = !!params->cdrom[i];
3119 lun->removable = /* Removable by default */
3120 params->removable_count <= i || params->removable[i];
3122 params->file_count > i && params->file[i][0]
3127 /* Let MSF use defaults */
3128 cfg->lun_name_format = 0;
3129 cfg->thread_name = 0;
3130 cfg->vendor_name = 0;
3131 cfg->product_name = 0;
3132 cfg->release = 0xffff;
3135 cfg->private_data = NULL;
3138 cfg->can_stall = params->stall;
3141 static inline struct fsg_common *
3142 fsg_common_from_params(struct fsg_common *common,
3143 struct usb_composite_dev *cdev,
3144 const struct fsg_module_parameters *params)
3145 __attribute__((unused));
3146 static inline struct fsg_common *
3147 fsg_common_from_params(struct fsg_common *common,
3148 struct usb_composite_dev *cdev,
3149 const struct fsg_module_parameters *params)
3151 struct fsg_config cfg;
3152 fsg_config_from_params(&cfg, params);
3153 return fsg_common_init(common, cdev, &cfg);