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 <mina86@mina86.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.
41 * The Mass Storage Function acts as a USB Mass Storage device,
42 * appearing to the host as a disk drive or as a CD-ROM drive. In
43 * addition to providing an example of a genuinely useful composite
44 * function for a USB device, it also illustrates a technique of
45 * double-buffering for increased throughput.
47 * For more information about MSF and in particular its module
48 * parameters and sysfs interface read the
49 * <Documentation/usb/mass-storage.txt> file.
53 * MSF is configured by specifying a fsg_config structure. It has the
56 * nluns Number of LUNs function have (anywhere from 1
57 * to FSG_MAX_LUNS which is 8).
58 * luns An array of LUN configuration values. This
59 * should be filled for each LUN that
60 * function will include (ie. for "nluns"
61 * LUNs). Each element of the array has
62 * the following fields:
63 * ->filename The path to the backing file for the LUN.
64 * Required if LUN is not marked as
66 * ->ro Flag specifying access to the LUN shall be
67 * read-only. This is implied if CD-ROM
68 * emulation is enabled as well as when
69 * it was impossible to open "filename"
71 * ->removable Flag specifying that LUN shall be indicated as
73 * ->cdrom Flag specifying that LUN shall be reported as
75 * ->nofua Flag specifying that FUA flag in SCSI WRITE(10,12)
76 * commands for this LUN shall be ignored.
80 * release Information used as a reply to INQUIRY
81 * request. To use default set to NULL,
82 * NULL, 0xffff respectively. The first
83 * field should be 8 and the second 16
86 * can_stall Set to permit function to halt bulk endpoints.
87 * Disabled on some USB devices known not
88 * to work correctly. You should set it
91 * If "removable" is not set for a LUN then a backing file must be
92 * specified. If it is set, then NULL filename means the LUN's medium
93 * is not loaded (an empty string as "filename" in the fsg_config
94 * structure causes error). The CD-ROM emulation includes a single
95 * data track and no audio tracks; hence there need be only one
96 * backing file per LUN.
98 * This function is heavily based on "File-backed Storage Gadget" by
99 * Alan Stern which in turn is heavily based on "Gadget Zero" by David
100 * Brownell. The driver's SCSI command interface was based on the
101 * "Information technology - Small Computer System Interface - 2"
102 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
103 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
104 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
105 * was based on the "Universal Serial Bus Mass Storage Class UFI
106 * Command Specification" document, Revision 1.0, December 14, 1998,
108 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
114 * The MSF is fairly straightforward. There is a main kernel
115 * thread that handles most of the work. Interrupt routines field
116 * callbacks from the controller driver: bulk- and interrupt-request
117 * completion notifications, endpoint-0 events, and disconnect events.
118 * Completion events are passed to the main thread by wakeup calls. Many
119 * ep0 requests are handled at interrupt time, but SetInterface,
120 * SetConfiguration, and device reset requests are forwarded to the
121 * thread in the form of "exceptions" using SIGUSR1 signals (since they
122 * should interrupt any ongoing file I/O operations).
124 * The thread's main routine implements the standard command/data/status
125 * parts of a SCSI interaction. It and its subroutines are full of tests
126 * for pending signals/exceptions -- all this polling is necessary since
127 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
128 * indication that the driver really wants to be running in userspace.)
129 * An important point is that so long as the thread is alive it keeps an
130 * open reference to the backing file. This will prevent unmounting
131 * the backing file's underlying filesystem and could cause problems
132 * during system shutdown, for example. To prevent such problems, the
133 * thread catches INT, TERM, and KILL signals and converts them into
136 * In normal operation the main thread is started during the gadget's
137 * fsg_bind() callback and stopped during fsg_unbind(). But it can
138 * also exit when it receives a signal, and there's no point leaving
139 * the gadget running when the thread is dead. As of this moment, MSF
140 * provides no way to deregister the gadget when thread dies -- maybe
141 * a callback functions is needed.
143 * To provide maximum throughput, the driver uses a circular pipeline of
144 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
145 * arbitrarily long; in practice the benefits don't justify having more
146 * than 2 stages (i.e., double buffering). But it helps to think of the
147 * pipeline as being a long one. Each buffer head contains a bulk-in and
148 * a bulk-out request pointer (since the buffer can be used for both
149 * output and input -- directions always are given from the host's
150 * point of view) as well as a pointer to the buffer and various state
153 * Use of the pipeline follows a simple protocol. There is a variable
154 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
155 * At any time that buffer head may still be in use from an earlier
156 * request, so each buffer head has a state variable indicating whether
157 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
158 * buffer head to be EMPTY, filling the buffer either by file I/O or by
159 * USB I/O (during which the buffer head is BUSY), and marking the buffer
160 * head FULL when the I/O is complete. Then the buffer will be emptied
161 * (again possibly by USB I/O, during which it is marked BUSY) and
162 * finally marked EMPTY again (possibly by a completion routine).
164 * A module parameter tells the driver to avoid stalling the bulk
165 * endpoints wherever the transport specification allows. This is
166 * necessary for some UDCs like the SuperH, which cannot reliably clear a
167 * halt on a bulk endpoint. However, under certain circumstances the
168 * Bulk-only specification requires a stall. In such cases the driver
169 * will halt the endpoint and set a flag indicating that it should clear
170 * the halt in software during the next device reset. Hopefully this
171 * will permit everything to work correctly. Furthermore, although the
172 * specification allows the bulk-out endpoint to halt when the host sends
173 * too much data, implementing this would cause an unavoidable race.
174 * The driver will always use the "no-stall" approach for OUT transfers.
176 * One subtle point concerns sending status-stage responses for ep0
177 * requests. Some of these requests, such as device reset, can involve
178 * interrupting an ongoing file I/O operation, which might take an
179 * arbitrarily long time. During that delay the host might give up on
180 * the original ep0 request and issue a new one. When that happens the
181 * driver should not notify the host about completion of the original
182 * request, as the host will no longer be waiting for it. So the driver
183 * assigns to each ep0 request a unique tag, and it keeps track of the
184 * tag value of the request associated with a long-running exception
185 * (device-reset, interface-change, or configuration-change). When the
186 * exception handler is finished, the status-stage response is submitted
187 * only if the current ep0 request tag is equal to the exception request
188 * tag. Thus only the most recently received ep0 request will get a
189 * status-stage response.
191 * Warning: This driver source file is too long. It ought to be split up
192 * into a header file plus about 3 separate .c files, to handle the details
193 * of the Gadget, USB Mass Storage, and SCSI protocols.
196 /* #define VERBOSE_DEBUG */
197 /* #define DUMP_MSGS */
199 #include <linux/blkdev.h>
200 #include <linux/completion.h>
201 #include <linux/dcache.h>
202 #include <linux/delay.h>
203 #include <linux/device.h>
204 #include <linux/fcntl.h>
205 #include <linux/file.h>
206 #include <linux/fs.h>
207 #include <linux/kref.h>
208 #include <linux/kthread.h>
209 #include <linux/limits.h>
210 #include <linux/rwsem.h>
211 #include <linux/slab.h>
212 #include <linux/spinlock.h>
213 #include <linux/string.h>
214 #include <linux/freezer.h>
216 #include <linux/usb/ch9.h>
217 #include <linux/usb/gadget.h>
218 #include <linux/usb/composite.h>
220 #include "gadget_chips.h"
222 #ifdef CONFIG_ARCH_ROCKCHIP
223 #include <linux/power_supply.h>
224 #include <linux/reboot.h>
225 #include <linux/syscalls.h>
227 /*------------------------------------------------------------------------*/
229 #define FSG_DRIVER_DESC "Mass Storage Function"
230 #define FSG_DRIVER_VERSION "2009/09/11"
232 static const char fsg_string_interface[] = "Mass Storage";
234 #include "storage_common.c"
236 #ifdef CONFIG_USB_CSW_HACK
237 static int write_error_after_csw_sent;
238 static int csw_hack_sent;
240 /*-------------------------------------------------------------------------*/
245 /* FSF callback functions */
246 struct fsg_operations {
248 * Callback function to call when thread exits. If no
249 * callback is set or it returns value lower then zero MSF
250 * will force eject all LUNs it operates on (including those
251 * marked as non-removable or with prevent_medium_removal flag
254 int (*thread_exits) (struct fsg_common *common);
256 * Called prior to ejection. Negative return means error,
257 * zero means to continue with ejection, positive means not to
260 int (*pre_eject) (struct fsg_common *common,
261 struct fsg_lun *lun, int num);
263 * Called after ejection. Negative return means error, zero
264 * or positive is just a success.
266 int (*post_eject) (struct fsg_common *common,
267 struct fsg_lun *lun, int num);
270 /* Data shared by all the FSG instances. */
272 struct usb_gadget *gadget;
273 struct usb_composite_dev *cdev;
274 struct fsg_dev *fsg, *new_fsg;
275 wait_queue_head_t fsg_wait;
277 /* filesem protects: backing files in use */
278 struct rw_semaphore filesem;
280 /* lock protects: state, all the req_busy's */
283 struct usb_ep *ep0; /* Copy of gadget->ep0 */
284 struct usb_request *ep0req; /* Copy of cdev->req */
285 unsigned int ep0_req_tag;
287 struct fsg_buffhd *next_buffhd_to_fill;
288 struct fsg_buffhd *next_buffhd_to_drain;
289 struct fsg_buffhd *buffhds;
292 u8 cmnd[MAX_COMMAND_SIZE];
296 struct fsg_lun *luns;
297 struct fsg_lun *curlun;
299 unsigned int bulk_out_maxpacket;
300 enum fsg_state state; /* For exception handling */
301 unsigned int exception_req_tag;
303 enum data_direction data_dir;
305 u32 data_size_from_cmnd;
310 unsigned int can_stall:1;
311 unsigned int free_storage_on_release:1;
312 unsigned int phase_error:1;
313 unsigned int short_packet_received:1;
314 unsigned int bad_lun_okay:1;
315 unsigned int running:1;
317 int thread_wakeup_needed;
318 struct completion thread_notifier;
319 struct task_struct *thread_task;
321 /* Callback functions. */
322 const struct fsg_operations *ops;
323 /* Gadget's private data. */
327 * Vendor (8 chars), product (16 chars), release (4
328 * hexadecimal digits) and NUL byte
330 char inquiry_string[8 + 16 + 4 + 1];
337 struct fsg_lun_config {
338 const char *filename;
343 } luns[FSG_MAX_LUNS];
345 /* Callback functions. */
346 const struct fsg_operations *ops;
347 /* Gadget's private data. */
350 const char *vendor_name; /* 8 characters or less */
351 const char *product_name; /* 16 characters or less */
357 struct usb_function function;
358 struct usb_gadget *gadget; /* Copy of cdev->gadget */
359 struct fsg_common *common;
361 u16 interface_number;
363 unsigned int bulk_in_enabled:1;
364 unsigned int bulk_out_enabled:1;
366 unsigned long atomic_bitflags;
367 #define IGNORE_BULK_OUT 0
369 struct usb_ep *bulk_in;
370 struct usb_ep *bulk_out;
373 static inline int __fsg_is_set(struct fsg_common *common,
374 const char *func, unsigned line)
378 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
383 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
385 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
387 return container_of(f, struct fsg_dev, function);
390 typedef void (*fsg_routine_t) (struct fsg_dev *);
391 static int send_status(struct fsg_common *common);
393 static int exception_in_progress(struct fsg_common *common)
395 return common->state > FSG_STATE_IDLE;
398 /* Make bulk-out requests be divisible by the maxpacket size */
399 static void set_bulk_out_req_length(struct fsg_common *common,
400 struct fsg_buffhd *bh, unsigned int length)
404 bh->bulk_out_intended_length = length;
405 rem = length % common->bulk_out_maxpacket;
407 length += common->bulk_out_maxpacket - rem;
408 bh->outreq->length = length;
411 /*-------------------------------------------------------------------------*/
413 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
417 if (ep == fsg->bulk_in)
419 else if (ep == fsg->bulk_out)
423 DBG(fsg, "%s set halt\n", name);
424 return usb_ep_set_halt(ep);
427 /*-------------------------------------------------------------------------*/
429 /* These routines may be called in process context or in_irq */
431 /* Caller must hold fsg->lock */
432 static void wakeup_thread(struct fsg_common *common)
434 smp_wmb(); /* ensure the write of bh->state is complete */
435 /* Tell the main thread that something has happened */
436 common->thread_wakeup_needed = 1;
437 if (common->thread_task)
438 wake_up_process(common->thread_task);
441 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
446 * Do nothing if a higher-priority exception is already in progress.
447 * If a lower-or-equal priority exception is in progress, preempt it
448 * and notify the main thread by sending it a signal.
450 spin_lock_irqsave(&common->lock, flags);
451 if (common->state <= new_state) {
452 common->exception_req_tag = common->ep0_req_tag;
453 common->state = new_state;
454 if (common->thread_task)
455 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
456 common->thread_task);
458 spin_unlock_irqrestore(&common->lock, flags);
461 /*-------------------------------------------------------------------------*/
463 static int ep0_queue(struct fsg_common *common)
467 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
468 common->ep0->driver_data = common;
469 if (rc != 0 && rc != -ESHUTDOWN) {
470 /* We can't do much more than wait for a reset */
471 WARNING(common, "error in submission: %s --> %d\n",
472 common->ep0->name, rc);
477 /*-------------------------------------------------------------------------*/
479 /* Completion handlers. These always run in_irq. */
481 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
483 struct fsg_common *common = ep->driver_data;
484 struct fsg_buffhd *bh = req->context;
486 if (req->status || req->actual != req->length)
487 DBG(common, "%s --> %d, %u/%u\n", __func__,
488 req->status, req->actual, req->length);
489 if (req->status == -ECONNRESET) /* Request was cancelled */
490 usb_ep_fifo_flush(ep);
492 /* Hold the lock while we update the request and buffer states */
494 spin_lock(&common->lock);
496 bh->state = BUF_STATE_EMPTY;
497 wakeup_thread(common);
498 spin_unlock(&common->lock);
501 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
503 struct fsg_common *common = ep->driver_data;
504 struct fsg_buffhd *bh = req->context;
506 dump_msg(common, "bulk-out", req->buf, req->actual);
507 if (req->status || req->actual != bh->bulk_out_intended_length)
508 DBG(common, "%s --> %d, %u/%u\n", __func__,
509 req->status, req->actual, bh->bulk_out_intended_length);
510 if (req->status == -ECONNRESET) /* Request was cancelled */
511 usb_ep_fifo_flush(ep);
513 /* Hold the lock while we update the request and buffer states */
515 spin_lock(&common->lock);
517 bh->state = BUF_STATE_FULL;
518 wakeup_thread(common);
519 spin_unlock(&common->lock);
522 static int fsg_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
524 struct fsg_dev *fsg = fsg_from_func(f);
525 struct usb_request *req = fsg->common->ep0req;
526 u16 w_index = le16_to_cpu(ctrl->wIndex);
527 u16 w_value = le16_to_cpu(ctrl->wValue);
528 u16 w_length = le16_to_cpu(ctrl->wLength);
530 if (!fsg_is_set(fsg->common))
533 ++fsg->common->ep0_req_tag; /* Record arrival of a new request */
536 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
538 switch (ctrl->bRequest) {
540 case US_BULK_RESET_REQUEST:
541 if (ctrl->bRequestType !=
542 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
544 if (w_index != fsg->interface_number || w_value != 0 ||
549 * Raise an exception to stop the current operation
550 * and reinitialize our state.
552 DBG(fsg, "bulk reset request\n");
553 raise_exception(fsg->common, FSG_STATE_RESET);
554 return DELAYED_STATUS;
556 case US_BULK_GET_MAX_LUN:
557 if (ctrl->bRequestType !=
558 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
560 if (w_index != fsg->interface_number || w_value != 0 ||
563 VDBG(fsg, "get max LUN\n");
564 *(u8 *) req->buf = fsg->common->nluns - 1;
566 /* Respond with data/status */
567 req->length = min((u16) 1, w_length);
568 return ep0_queue(fsg->common);
572 "unknown class-specific control req %02x.%02x v%04x i%04x l%u\n",
573 ctrl->bRequestType, ctrl->bRequest,
574 le16_to_cpu(ctrl->wValue), w_index, w_length);
578 /*-------------------------------------------------------------------------*/
580 /* All the following routines run in process context */
582 /* Use this for bulk or interrupt transfers, not ep0 */
583 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
584 struct usb_request *req, int *pbusy,
585 enum fsg_buffer_state *state)
589 if (ep == fsg->bulk_in)
590 dump_msg(fsg, "bulk-in", req->buf, req->length);
592 spin_lock_irq(&fsg->common->lock);
594 *state = BUF_STATE_BUSY;
595 spin_unlock_irq(&fsg->common->lock);
596 rc = usb_ep_queue(ep, req, GFP_KERNEL);
599 *state = BUF_STATE_EMPTY;
601 /* We can't do much more than wait for a reset */
604 * Note: currently the net2280 driver fails zero-length
605 * submissions if DMA is enabled.
607 if (rc != -ESHUTDOWN &&
608 !(rc == -EOPNOTSUPP && req->length == 0))
609 WARNING(fsg, "error in submission: %s --> %d\n",
614 static bool start_in_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
616 if (!fsg_is_set(common))
618 start_transfer(common->fsg, common->fsg->bulk_in,
619 bh->inreq, &bh->inreq_busy, &bh->state);
623 static bool start_out_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
625 if (!fsg_is_set(common))
627 start_transfer(common->fsg, common->fsg->bulk_out,
628 bh->outreq, &bh->outreq_busy, &bh->state);
632 static int sleep_thread(struct fsg_common *common)
636 /* Wait until a signal arrives or we are woken up */
639 set_current_state(TASK_INTERRUPTIBLE);
640 if (signal_pending(current)) {
644 if (common->thread_wakeup_needed)
648 __set_current_state(TASK_RUNNING);
649 common->thread_wakeup_needed = 0;
650 smp_rmb(); /* ensure the latest bh->state is visible */
654 /*-------------------------------------------------------------------------*/
656 static int do_read(struct fsg_common *common)
658 struct fsg_lun *curlun = common->curlun;
660 struct fsg_buffhd *bh;
663 loff_t file_offset, file_offset_tmp;
666 #ifdef CONFIG_USB_MSC_PROFILING
671 * Get the starting Logical Block Address and check that it's
674 if (common->cmnd[0] == READ_6)
675 lba = get_unaligned_be24(&common->cmnd[1]);
677 lba = get_unaligned_be32(&common->cmnd[2]);
680 * We allow DPO (Disable Page Out = don't save data in the
681 * cache) and FUA (Force Unit Access = don't read from the
682 * cache), but we don't implement them.
684 if ((common->cmnd[1] & ~0x18) != 0) {
685 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
689 if (lba >= curlun->num_sectors) {
690 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
693 file_offset = ((loff_t) lba) << curlun->blkbits;
695 /* Carry out the file reads */
696 amount_left = common->data_size_from_cmnd;
697 if (unlikely(amount_left == 0))
698 return -EIO; /* No default reply */
702 * Figure out how much we need to read:
703 * Try to read the remaining amount.
704 * But don't read more than the buffer size.
705 * And don't try to read past the end of the file.
707 amount = min(amount_left, FSG_BUFLEN);
708 amount = min((loff_t) amount,
709 curlun->file_length - file_offset);
711 * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
712 * because of the DOEPTSIZ.PKTCNT has only 10 bits
714 if ((common->gadget->speed != USB_SPEED_HIGH)
715 && (amount > 0x8000))
718 /* Wait for the next buffer to become available */
719 bh = common->next_buffhd_to_fill;
720 while (bh->state != BUF_STATE_EMPTY) {
721 rc = sleep_thread(common);
727 * If we were asked to read past the end of file,
728 * end with an empty buffer.
732 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
733 curlun->sense_data_info =
734 file_offset >> curlun->blkbits;
735 curlun->info_valid = 1;
736 bh->inreq->length = 0;
737 bh->state = BUF_STATE_FULL;
741 /* Perform the read */
742 file_offset_tmp = file_offset;
744 #ifdef CONFIG_USB_MSC_PROFILING
747 nread = vfs_read(curlun->filp,
748 (char __user *)bh->buf,
749 amount, &file_offset_tmp);
750 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
751 (unsigned long long)file_offset, (int)nread);
752 #ifdef CONFIG_USB_MSC_PROFILING
753 diff = ktime_sub(ktime_get(), start);
754 curlun->perf.rbytes += nread;
755 curlun->perf.rtime = ktime_add(curlun->perf.rtime, diff);
757 if (signal_pending(current))
761 LDBG(curlun, "error in file read: %d\n", (int)nread);
763 } else if (nread < amount) {
764 LDBG(curlun, "partial file read: %d/%u\n",
766 nread = round_down(nread, curlun->blksize);
768 file_offset += nread;
769 amount_left -= nread;
770 common->residue -= nread;
773 * Except at the end of the transfer, nread will be
774 * equal to the buffer size, which is divisible by the
775 * bulk-in maxpacket size.
777 bh->inreq->length = nread;
778 bh->state = BUF_STATE_FULL;
780 /* If an error occurred, report it and its position */
781 if (nread < amount) {
782 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
783 curlun->sense_data_info =
784 file_offset >> curlun->blkbits;
785 curlun->info_valid = 1;
789 if (amount_left == 0)
790 break; /* No more left to read */
792 /* Send this buffer and go read some more */
794 if (!start_in_transfer(common, bh))
795 /* Don't know what to do if common->fsg is NULL */
797 common->next_buffhd_to_fill = bh->next;
800 return -EIO; /* No default reply */
803 /*-------------------------------------------------------------------------*/
805 static int do_write(struct fsg_common *common)
807 struct fsg_lun *curlun = common->curlun;
809 struct fsg_buffhd *bh;
811 u32 amount_left_to_req, amount_left_to_write;
812 loff_t usb_offset, file_offset, file_offset_tmp;
817 #ifdef CONFIG_USB_CSW_HACK
821 #ifdef CONFIG_USB_MSC_PROFILING
825 curlun->sense_data = SS_WRITE_PROTECTED;
828 spin_lock(&curlun->filp->f_lock);
829 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
830 spin_unlock(&curlun->filp->f_lock);
833 * Get the starting Logical Block Address and check that it's
836 if (common->cmnd[0] == WRITE_6)
837 lba = get_unaligned_be24(&common->cmnd[1]);
839 lba = get_unaligned_be32(&common->cmnd[2]);
842 * We allow DPO (Disable Page Out = don't save data in the
843 * cache) and FUA (Force Unit Access = write directly to the
844 * medium). We don't implement DPO; we implement FUA by
845 * performing synchronous output.
847 if (common->cmnd[1] & ~0x18) {
848 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
851 if (!curlun->nofua && (common->cmnd[1] & 0x08)) { /* FUA */
852 spin_lock(&curlun->filp->f_lock);
853 curlun->filp->f_flags |= O_SYNC;
854 spin_unlock(&curlun->filp->f_lock);
857 if (lba >= curlun->num_sectors) {
858 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
862 /* Carry out the file writes */
864 file_offset = usb_offset = ((loff_t) lba) << curlun->blkbits;
865 amount_left_to_req = common->data_size_from_cmnd;
866 amount_left_to_write = common->data_size_from_cmnd;
868 while (amount_left_to_write > 0) {
870 /* Queue a request for more data from the host */
871 bh = common->next_buffhd_to_fill;
872 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
875 * Figure out how much we want to get:
876 * Try to get the remaining amount,
877 * but not more than the buffer size.
879 amount = min(amount_left_to_req, FSG_BUFLEN);
881 /* Beyond the end of the backing file? */
882 if (usb_offset >= curlun->file_length) {
885 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
886 curlun->sense_data_info =
887 usb_offset >> curlun->blkbits;
888 curlun->info_valid = 1;
892 /* Get the next buffer */
893 usb_offset += amount;
894 common->usb_amount_left -= amount;
895 amount_left_to_req -= amount;
896 if (amount_left_to_req == 0)
900 * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
901 * because of the DOEPTSIZ.PKTCNT has only 10 bits
903 if ((common->gadget->speed != USB_SPEED_HIGH)
904 && (amount > 0x8000))
908 * Except at the end of the transfer, amount will be
909 * equal to the buffer size, which is divisible by
910 * the bulk-out maxpacket size.
912 set_bulk_out_req_length(common, bh, amount);
913 if (!start_out_transfer(common, bh))
914 /* Dunno what to do if common->fsg is NULL */
916 common->next_buffhd_to_fill = bh->next;
920 /* Write the received data to the backing file */
921 bh = common->next_buffhd_to_drain;
922 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
923 break; /* We stopped early */
924 #ifdef CONFIG_USB_CSW_HACK
926 * If the csw packet is already submmitted to the hardware,
927 * by marking the state of buffer as full, then by checking
928 * the residue, we make sure that this csw packet is not
929 * written on to the storage media.
931 if (bh->state == BUF_STATE_FULL && common->residue) {
933 if (bh->state == BUF_STATE_FULL) {
936 common->next_buffhd_to_drain = bh->next;
937 bh->state = BUF_STATE_EMPTY;
939 /* Did something go wrong with the transfer? */
940 if (bh->outreq->status != 0) {
941 curlun->sense_data = SS_COMMUNICATION_FAILURE;
942 curlun->sense_data_info =
943 file_offset >> curlun->blkbits;
944 curlun->info_valid = 1;
948 amount = bh->outreq->actual;
949 if (curlun->file_length - file_offset < amount) {
951 "write %u @ %llu beyond end %llu\n",
952 amount, (unsigned long long)file_offset,
953 (unsigned long long)curlun->file_length);
954 amount = curlun->file_length - file_offset;
957 /* Don't accept excess data. The spec doesn't say
958 * what to do in this case. We'll ignore the error.
960 amount = min(amount, bh->bulk_out_intended_length);
962 /* Don't write a partial block */
963 amount = round_down(amount, curlun->blksize);
967 /* Perform the write */
968 file_offset_tmp = file_offset;
969 #ifdef CONFIG_USB_MSC_PROFILING
972 nwritten = vfs_write(curlun->filp,
973 (char __user *)bh->buf,
974 amount, &file_offset_tmp);
975 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
976 (unsigned long long)file_offset, (int)nwritten);
977 #ifdef CONFIG_USB_MSC_PROFILING
978 diff = ktime_sub(ktime_get(), start);
979 curlun->perf.wbytes += nwritten;
981 ktime_add(curlun->perf.wtime, diff);
983 if (signal_pending(current))
984 return -EINTR; /* Interrupted! */
987 LDBG(curlun, "error in file write: %d\n",
990 } else if (nwritten < amount) {
991 LDBG(curlun, "partial file write: %d/%u\n",
992 (int)nwritten, amount);
994 round_down(nwritten, curlun->blksize);
996 file_offset += nwritten;
997 amount_left_to_write -= nwritten;
998 common->residue -= nwritten;
1000 /* If an error occurred, report it and its position */
1001 if (nwritten < amount) {
1002 curlun->sense_data = SS_WRITE_ERROR;
1003 curlun->sense_data_info =
1004 file_offset >> curlun->blkbits;
1005 curlun->info_valid = 1;
1006 #ifdef CONFIG_USB_CSW_HACK
1007 write_error_after_csw_sent = 1;
1012 #ifdef CONFIG_USB_CSW_HACK
1014 if ((nwritten == amount) && !csw_hack_sent) {
1015 if (write_error_after_csw_sent)
1018 * Check if any of the buffer is in the
1019 * busy state, if any buffer is in busy state,
1020 * means the complete data is not received
1021 * yet from the host. So there is no point in
1022 * csw right away without the complete data.
1024 for (i = 0; i < fsg_num_buffers; i++) {
1025 if (common->buffhds[i].state ==
1029 if (!amount_left_to_req && i == fsg_num_buffers) {
1031 send_status(common);
1037 /* Did the host decide to stop early? */
1038 if (bh->outreq->actual < bh->bulk_out_intended_length) {
1039 common->short_packet_received = 1;
1045 /* Wait for something to happen */
1046 rc = sleep_thread(common);
1051 return -EIO; /* No default reply */
1054 /*-------------------------------------------------------------------------*/
1056 static int do_synchronize_cache(struct fsg_common *common)
1058 struct fsg_lun *curlun = common->curlun;
1061 /* We ignore the requested LBA and write out all file's
1062 * dirty data buffers. */
1063 rc = fsg_lun_fsync_sub(curlun);
1065 curlun->sense_data = SS_WRITE_ERROR;
1069 /*-------------------------------------------------------------------------*/
1070 #ifndef CONFIG_ARCH_ROCKCHIP
1071 static void invalidate_sub(struct fsg_lun *curlun)
1073 struct file *filp = curlun->filp;
1074 struct inode *inode = file_inode(filp);
1077 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1078 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1081 static int do_verify(struct fsg_common *common)
1083 struct fsg_lun *curlun = common->curlun;
1085 u32 verification_length;
1086 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1087 loff_t file_offset, file_offset_tmp;
1089 unsigned int amount;
1093 * Get the starting Logical Block Address and check that it's
1096 lba = get_unaligned_be32(&common->cmnd[2]);
1097 if (lba >= curlun->num_sectors) {
1098 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1103 * We allow DPO (Disable Page Out = don't save data in the
1104 * cache) but we don't implement it.
1106 if (common->cmnd[1] & ~0x10) {
1107 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1111 verification_length = get_unaligned_be16(&common->cmnd[7]);
1112 if (unlikely(verification_length == 0))
1113 return -EIO; /* No default reply */
1115 /* Prepare to carry out the file verify */
1116 amount_left = verification_length << curlun->blkbits;
1117 file_offset = ((loff_t) lba) << curlun->blkbits;
1119 /* Write out all the dirty buffers before invalidating them */
1120 fsg_lun_fsync_sub(curlun);
1121 if (signal_pending(current))
1124 invalidate_sub(curlun);
1125 if (signal_pending(current))
1128 /* Just try to read the requested blocks */
1129 while (amount_left > 0) {
1131 * Figure out how much we need to read:
1132 * Try to read the remaining amount, but not more than
1134 * And don't try to read past the end of the file.
1136 amount = min(amount_left, FSG_BUFLEN);
1137 amount = min((loff_t) amount,
1138 curlun->file_length - file_offset);
1140 curlun->sense_data =
1141 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1142 curlun->sense_data_info =
1143 file_offset >> curlun->blkbits;
1144 curlun->info_valid = 1;
1148 /* Perform the read */
1149 file_offset_tmp = file_offset;
1150 nread = vfs_read(curlun->filp,
1151 (char __user *)bh->buf,
1152 amount, &file_offset_tmp);
1153 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1154 (unsigned long long)file_offset, (int)nread);
1155 if (signal_pending(current))
1159 LDBG(curlun, "error in file verify: %d\n", (int)nread);
1161 } else if (nread < amount) {
1162 LDBG(curlun, "partial file verify: %d/%u\n",
1163 (int)nread, amount);
1164 nread = round_down(nread, curlun->blksize);
1167 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1168 curlun->sense_data_info =
1169 file_offset >> curlun->blkbits;
1170 curlun->info_valid = 1;
1173 file_offset += nread;
1174 amount_left -= nread;
1180 /*-------------------------------------------------------------------------*/
1182 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1184 struct fsg_lun *curlun = common->curlun;
1185 u8 *buf = (u8 *) bh->buf;
1187 if (!curlun) { /* Unsupported LUNs are okay */
1188 common->bad_lun_okay = 1;
1190 buf[0] = 0x7f; /* Unsupported, no device-type */
1191 buf[4] = 31; /* Additional length */
1195 buf[0] = curlun->cdrom ? TYPE_ROM : TYPE_DISK;
1196 buf[1] = curlun->removable ? 0x80 : 0;
1197 buf[2] = 2; /* ANSI SCSI level 2 */
1198 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1199 buf[4] = 31; /* Additional length */
1200 buf[5] = 0; /* No special options */
1203 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1207 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1209 struct fsg_lun *curlun = common->curlun;
1210 u8 *buf = (u8 *) bh->buf;
1215 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1217 * If a REQUEST SENSE command is received from an initiator
1218 * with a pending unit attention condition (before the target
1219 * generates the contingent allegiance condition), then the
1220 * target shall either:
1221 * a) report any pending sense data and preserve the unit
1222 * attention condition on the logical unit, or,
1223 * b) report the unit attention condition, may discard any
1224 * pending sense data, and clear the unit attention
1225 * condition on the logical unit for that initiator.
1227 * FSG normally uses option a); enable this code to use option b).
1230 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1231 curlun->sense_data = curlun->unit_attention_data;
1232 curlun->unit_attention_data = SS_NO_SENSE;
1236 if (!curlun) { /* Unsupported LUNs are okay */
1237 common->bad_lun_okay = 1;
1238 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1242 sd = curlun->sense_data;
1243 sdinfo = curlun->sense_data_info;
1244 valid = curlun->info_valid << 7;
1245 curlun->sense_data = SS_NO_SENSE;
1246 curlun->sense_data_info = 0;
1247 curlun->info_valid = 0;
1251 buf[0] = valid | 0x70; /* Valid, current error */
1253 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1254 buf[7] = 18 - 8; /* Additional sense length */
1260 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1262 struct fsg_lun *curlun = common->curlun;
1263 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1264 int pmi = common->cmnd[8];
1265 u8 *buf = (u8 *) bh->buf;
1267 /* Check the PMI and LBA fields */
1268 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1269 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1273 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1274 /* Max logical block */
1275 put_unaligned_be32(curlun->blksize, &buf[4]); /* Block length */
1279 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1281 struct fsg_lun *curlun = common->curlun;
1282 int msf = common->cmnd[1] & 0x02;
1283 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1284 u8 *buf = (u8 *) bh->buf;
1286 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1287 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1290 if (lba >= curlun->num_sectors) {
1291 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1296 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1297 store_cdrom_address(&buf[4], msf, lba);
1301 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1303 struct fsg_lun *curlun = common->curlun;
1304 int msf = common->cmnd[1] & 0x02;
1305 int start_track = common->cmnd[6];
1306 u8 *buf = (u8 *) bh->buf;
1308 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1310 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1315 buf[1] = (20 - 2); /* TOC data length */
1316 buf[2] = 1; /* First track number */
1317 buf[3] = 1; /* Last track number */
1318 buf[5] = 0x16; /* Data track, copying allowed */
1319 buf[6] = 0x01; /* Only track is number 1 */
1320 store_cdrom_address(&buf[8], msf, 0);
1322 buf[13] = 0x16; /* Lead-out track is data */
1323 buf[14] = 0xAA; /* Lead-out track number */
1324 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1328 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1330 struct fsg_lun *curlun = common->curlun;
1331 int mscmnd = common->cmnd[0];
1332 u8 *buf = (u8 *) bh->buf;
1335 int changeable_values, all_pages;
1339 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1340 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1343 pc = common->cmnd[2] >> 6;
1344 page_code = common->cmnd[2] & 0x3f;
1346 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1349 changeable_values = (pc == 1);
1350 all_pages = (page_code == 0x3f);
1353 * Write the mode parameter header. Fixed values are: default
1354 * medium type, no cache control (DPOFUA), and no block descriptors.
1355 * The only variable value is the WriteProtect bit. We will fill in
1356 * the mode data length later.
1359 if (mscmnd == MODE_SENSE) {
1360 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1363 } else { /* MODE_SENSE_10 */
1364 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1366 limit = 65535; /* Should really be FSG_BUFLEN */
1369 /* No block descriptors */
1372 * The mode pages, in numerical order. The only page we support
1373 * is the Caching page.
1375 if (page_code == 0x08 || all_pages) {
1377 buf[0] = 0x08; /* Page code */
1378 buf[1] = 10; /* Page length */
1379 memset(buf + 2, 0, 10); /* None of the fields are changeable */
1381 if (!changeable_values) {
1382 buf[2] = 0x04; /* Write cache enable, */
1383 /* Read cache not disabled */
1384 /* No cache retention priorities */
1385 put_unaligned_be16(0xffff, &buf[4]);
1386 /* Don't disable prefetch */
1387 /* Minimum prefetch = 0 */
1388 put_unaligned_be16(0xffff, &buf[8]);
1389 /* Maximum prefetch */
1390 put_unaligned_be16(0xffff, &buf[10]);
1391 /* Maximum prefetch ceiling */
1397 * Check that a valid page was requested and the mode data length
1401 if (!valid_page || len > limit) {
1402 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1406 /* Store the mode data length */
1407 if (mscmnd == MODE_SENSE)
1410 put_unaligned_be16(len - 2, buf0);
1414 static int do_start_stop(struct fsg_common *common)
1416 struct fsg_lun *curlun = common->curlun;
1421 } else if (!curlun->removable) {
1422 curlun->sense_data = SS_INVALID_COMMAND;
1424 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1425 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1426 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1430 loej = common->cmnd[4] & 0x02;
1431 start = common->cmnd[4] & 0x01;
1434 * Our emulation doesn't support mounting; the medium is
1435 * available for use as soon as it is loaded.
1438 if (!fsg_lun_is_open(curlun)) {
1439 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1445 /* Are we allowed to unload the media? */
1446 if (curlun->prevent_medium_removal) {
1447 LDBG(curlun, "unload attempt prevented\n");
1448 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1455 /* Simulate an unload/eject */
1456 if (common->ops && common->ops->pre_eject) {
1457 int r = common->ops->pre_eject(common, curlun,
1458 curlun - common->luns);
1459 if (unlikely(r < 0))
1465 up_read(&common->filesem);
1466 down_write(&common->filesem);
1467 fsg_lun_close(curlun);
1468 up_write(&common->filesem);
1469 down_read(&common->filesem);
1471 return common->ops && common->ops->post_eject
1472 ? min(0, common->ops->post_eject(common, curlun,
1473 curlun - common->luns))
1477 static int do_prevent_allow(struct fsg_common *common)
1479 struct fsg_lun *curlun = common->curlun;
1482 if (!common->curlun) {
1484 } else if (!common->curlun->removable) {
1485 common->curlun->sense_data = SS_INVALID_COMMAND;
1489 prevent = common->cmnd[4] & 0x01;
1490 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1491 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1495 if (!curlun->nofua && curlun->prevent_medium_removal && !prevent)
1496 fsg_lun_fsync_sub(curlun);
1497 curlun->prevent_medium_removal = prevent;
1501 static int do_read_format_capacities(struct fsg_common *common,
1502 struct fsg_buffhd *bh)
1504 struct fsg_lun *curlun = common->curlun;
1505 u8 *buf = (u8 *) bh->buf;
1507 buf[0] = buf[1] = buf[2] = 0;
1508 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1511 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1512 /* Number of blocks */
1513 put_unaligned_be32(curlun->blksize, &buf[4]); /* Block length */
1514 buf[4] = 0x02; /* Current capacity */
1518 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1520 struct fsg_lun *curlun = common->curlun;
1522 /* We don't support MODE SELECT */
1524 curlun->sense_data = SS_INVALID_COMMAND;
1528 /*-------------------------------------------------------------------------*/
1530 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1534 rc = fsg_set_halt(fsg, fsg->bulk_in);
1536 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1538 if (rc != -EAGAIN) {
1539 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1544 /* Wait for a short time and then try again */
1545 if (msleep_interruptible(100) != 0)
1547 rc = usb_ep_set_halt(fsg->bulk_in);
1552 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1556 DBG(fsg, "bulk-in set wedge\n");
1557 rc = usb_ep_set_wedge(fsg->bulk_in);
1559 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1561 if (rc != -EAGAIN) {
1562 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1567 /* Wait for a short time and then try again */
1568 if (msleep_interruptible(100) != 0)
1570 rc = usb_ep_set_wedge(fsg->bulk_in);
1575 static int throw_away_data(struct fsg_common *common)
1577 struct fsg_buffhd *bh;
1581 for (bh = common->next_buffhd_to_drain;
1582 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1583 bh = common->next_buffhd_to_drain) {
1585 /* Throw away the data in a filled buffer */
1586 if (bh->state == BUF_STATE_FULL) {
1588 bh->state = BUF_STATE_EMPTY;
1589 common->next_buffhd_to_drain = bh->next;
1591 /* A short packet or an error ends everything */
1592 if (bh->outreq->actual < bh->bulk_out_intended_length ||
1593 bh->outreq->status != 0) {
1594 raise_exception(common,
1595 FSG_STATE_ABORT_BULK_OUT);
1601 /* Try to submit another request if we need one */
1602 bh = common->next_buffhd_to_fill;
1603 if (bh->state == BUF_STATE_EMPTY && common->usb_amount_left > 0) {
1604 amount = min(common->usb_amount_left, FSG_BUFLEN);
1607 * Except at the end of the transfer, amount will be
1608 * equal to the buffer size, which is divisible by
1609 * the bulk-out maxpacket size.
1611 set_bulk_out_req_length(common, bh, amount);
1612 if (!start_out_transfer(common, bh))
1613 /* Dunno what to do if common->fsg is NULL */
1615 common->next_buffhd_to_fill = bh->next;
1616 common->usb_amount_left -= amount;
1620 /* Otherwise wait for something to happen */
1621 rc = sleep_thread(common);
1628 static int finish_reply(struct fsg_common *common)
1630 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1633 switch (common->data_dir) {
1635 break; /* Nothing to send */
1638 * If we don't know whether the host wants to read or write,
1639 * this must be CB or CBI with an unknown command. We mustn't
1640 * try to send or receive any data. So stall both bulk pipes
1641 * if we can and wait for a reset.
1643 case DATA_DIR_UNKNOWN:
1644 if (!common->can_stall) {
1646 } else if (fsg_is_set(common)) {
1647 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1648 rc = halt_bulk_in_endpoint(common->fsg);
1650 /* Don't know what to do if common->fsg is NULL */
1655 /* All but the last buffer of data must have already been sent */
1656 case DATA_DIR_TO_HOST:
1657 if (common->data_size == 0) {
1658 /* Nothing to send */
1660 /* Don't know what to do if common->fsg is NULL */
1661 } else if (!fsg_is_set(common)) {
1664 /* If there's no residue, simply send the last buffer */
1665 } else if (common->residue == 0) {
1666 bh->inreq->zero = 0;
1667 if (!start_in_transfer(common, bh))
1669 common->next_buffhd_to_fill = bh->next;
1672 * For Bulk-only, mark the end of the data with a short
1673 * packet. If we are allowed to stall, halt the bulk-in
1674 * endpoint. (Note: This violates the Bulk-Only Transport
1675 * specification, which requires us to pad the data if we
1676 * don't halt the endpoint. Presumably nobody will mind.)
1679 bh->inreq->zero = 1;
1680 if (!start_in_transfer(common, bh))
1682 common->next_buffhd_to_fill = bh->next;
1683 if (common->can_stall)
1684 rc = halt_bulk_in_endpoint(common->fsg);
1689 * We have processed all we want from the data the host has sent.
1690 * There may still be outstanding bulk-out requests.
1692 case DATA_DIR_FROM_HOST:
1693 if (common->residue == 0) {
1694 /* Nothing to receive */
1696 /* Did the host stop sending unexpectedly early? */
1697 } else if (common->short_packet_received) {
1698 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1702 * We haven't processed all the incoming data. Even though
1703 * we may be allowed to stall, doing so would cause a race.
1704 * The controller may already have ACK'ed all the remaining
1705 * bulk-out packets, in which case the host wouldn't see a
1706 * STALL. Not realizing the endpoint was halted, it wouldn't
1707 * clear the halt -- leading to problems later on.
1710 } else if (common->can_stall) {
1711 if (fsg_is_set(common))
1712 fsg_set_halt(common->fsg,
1713 common->fsg->bulk_out);
1714 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1719 * We can't stall. Read in the excess data and throw it
1723 rc = throw_away_data(common);
1730 static int send_status(struct fsg_common *common)
1732 struct fsg_lun *curlun = common->curlun;
1733 struct fsg_buffhd *bh;
1734 struct bulk_cs_wrap *csw;
1736 u8 status = US_BULK_STAT_OK;
1739 /* Wait for the next buffer to become available */
1740 bh = common->next_buffhd_to_fill;
1741 while (bh->state != BUF_STATE_EMPTY) {
1742 rc = sleep_thread(common);
1748 sd = curlun->sense_data;
1749 sdinfo = curlun->sense_data_info;
1750 } else if (common->bad_lun_okay)
1753 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1755 if (common->phase_error) {
1756 DBG(common, "sending phase-error status\n");
1757 status = US_BULK_STAT_PHASE;
1758 sd = SS_INVALID_COMMAND;
1759 } else if (sd != SS_NO_SENSE) {
1760 DBG(common, "sending command-failure status\n");
1761 status = US_BULK_STAT_FAIL;
1762 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1763 " info x%x\n", SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1766 /* Store and send the Bulk-only CSW */
1767 csw = (void *)bh->buf;
1769 csw->Signature = cpu_to_le32(US_BULK_CS_SIGN);
1770 csw->Tag = common->tag;
1771 csw->Residue = cpu_to_le32(common->residue);
1772 #ifdef CONFIG_USB_CSW_HACK
1773 /* Since csw is being sent early, before
1774 * writing on to storage media, need to set
1775 * residue to zero,assuming that write will succeed.
1777 if (write_error_after_csw_sent) {
1778 write_error_after_csw_sent = 0;
1779 csw->Residue = cpu_to_le32(common->residue);
1783 csw->Residue = cpu_to_le32(common->residue);
1785 csw->Status = status;
1787 bh->inreq->length = US_BULK_CS_WRAP_LEN;
1788 bh->inreq->zero = 0;
1789 if (!start_in_transfer(common, bh))
1790 /* Don't know what to do if common->fsg is NULL */
1793 common->next_buffhd_to_fill = bh->next;
1797 /*-------------------------------------------------------------------------*/
1800 * Check whether the command is properly formed and whether its data size
1801 * and direction agree with the values we already have.
1803 static int check_command(struct fsg_common *common, int cmnd_size,
1804 enum data_direction data_dir, unsigned int mask,
1805 int needs_medium, const char *name)
1808 unsigned int lun = common->cmnd[1] >> 5;
1809 static const char dirletter[4] = { 'u', 'o', 'i', 'n' };
1811 struct fsg_lun *curlun;
1814 if (common->data_dir != DATA_DIR_UNKNOWN)
1815 sprintf(hdlen, ", H%c=%u", dirletter[(int)common->data_dir],
1817 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1818 name, cmnd_size, dirletter[(int)data_dir],
1819 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1822 * We can't reply at all until we know the correct data direction
1825 if (common->data_size_from_cmnd == 0)
1826 data_dir = DATA_DIR_NONE;
1827 if (common->data_size < common->data_size_from_cmnd) {
1829 * Host data size < Device data size is a phase error.
1830 * Carry out the command, but only transfer as much as
1833 common->data_size_from_cmnd = common->data_size;
1834 common->phase_error = 1;
1836 common->residue = common->data_size;
1837 common->usb_amount_left = common->data_size;
1839 /* Conflicting data directions is a phase error */
1840 if (common->data_dir != data_dir && common->data_size_from_cmnd > 0) {
1841 common->phase_error = 1;
1845 /* Verify the length of the command itself */
1846 if (cmnd_size != common->cmnd_size) {
1849 * Special case workaround: There are plenty of buggy SCSI
1850 * implementations. Many have issues with cbw->Length
1851 * field passing a wrong command size. For those cases we
1852 * always try to work around the problem by using the length
1853 * sent by the host side provided it is at least as large
1854 * as the correct command length.
1855 * Examples of such cases would be MS-Windows, which issues
1856 * REQUEST SENSE with cbw->Length == 12 where it should
1857 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1858 * REQUEST SENSE with cbw->Length == 10 where it should
1861 if (cmnd_size <= common->cmnd_size) {
1862 DBG(common, "%s is buggy! Expected length %d "
1863 "but we got %d\n", name,
1864 cmnd_size, common->cmnd_size);
1865 cmnd_size = common->cmnd_size;
1867 common->phase_error = 1;
1872 /* Check that the LUN values are consistent */
1873 if (common->lun != lun)
1874 DBG(common, "using LUN %u from CBW, not LUN %u from CDB\n",
1878 curlun = common->curlun;
1880 if (common->cmnd[0] != REQUEST_SENSE) {
1881 curlun->sense_data = SS_NO_SENSE;
1882 curlun->sense_data_info = 0;
1883 curlun->info_valid = 0;
1886 common->bad_lun_okay = 0;
1889 * INQUIRY and REQUEST SENSE commands are explicitly allowed
1890 * to use unsupported LUNs; all others may not.
1892 if (common->cmnd[0] != INQUIRY &&
1893 common->cmnd[0] != REQUEST_SENSE) {
1894 DBG(common, "unsupported LUN %u\n", common->lun);
1900 * If a unit attention condition exists, only INQUIRY and
1901 * REQUEST SENSE commands are allowed; anything else must fail.
1903 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1904 common->cmnd[0] != INQUIRY && common->cmnd[0] != REQUEST_SENSE) {
1905 curlun->sense_data = curlun->unit_attention_data;
1906 curlun->unit_attention_data = SS_NO_SENSE;
1910 /* Check that only command bytes listed in the mask are non-zero */
1911 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1912 for (i = 1; i < cmnd_size; ++i) {
1913 if (common->cmnd[i] && !(mask & (1 << i))) {
1915 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1920 /* If the medium isn't mounted and the command needs to access
1921 * it, return an error. */
1922 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1923 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1930 /* wrapper of check_command for data size in blocks handling */
1931 static int check_command_size_in_blocks(struct fsg_common *common,
1933 enum data_direction data_dir,
1934 unsigned int mask, int needs_medium,
1938 common->data_size_from_cmnd <<= common->curlun->blkbits;
1939 return check_command(common, cmnd_size, data_dir,
1940 mask, needs_medium, name);
1943 #ifdef CONFIG_ARCH_ROCKCHIP
1944 static void deferred_restart(struct work_struct *dummy)
1947 kernel_restart("loader");
1950 static DECLARE_WORK(restart_work, deferred_restart);
1952 typedef struct tagLoaderParam {
1958 #define PARM_TAG 0x4D524150
1959 #define MSC_EXT_DBG 1
1960 extern int GetParamterInfo(char *pbuf, int len);
1962 /* the buf is bh->buf,it is large enough. */
1963 static char *get_param_tag(char *buf, const char *tag)
1967 char *pp = buf + 256;
1969 i = GetParamterInfo(pp, 1024);
1970 pi = (PARM_INFO *) pp;
1971 if (pi->tag != PARM_TAG) {
1973 printk("paramter error,tag=0x%x\n", pi->tag);
1976 if (pi->length + sizeof(PARM_INFO) > i) {
1977 GetParamterInfo(pp, pi->length + sizeof(PARM_INFO) + 511);
1979 pp = strstr(pi->parameter, tag);
1982 pp += strlen(tag); /* sizeof "MACHINE_MODEL:" */
1983 while (*pp == ' ' || *pp == '\t') {
1984 if (pp - pi->parameter >= pi->length)
1989 while (*pp != 0x0d && *pp != 0x0a) {
1990 if (pp - pi->parameter >= pi->length)
2000 static int do_get_product_name(int ret, char *buf)
2002 char *tag = "MACHINE_MODEL:";
2009 memset(buf, 0, ret);
2010 pname = get_param_tag(buf, tag);
2015 printk("%s%s\n", tag, buf);
2020 static int do_get_versions(int ret, char *buf)
2022 /* get boot version and fireware version from cmdline
2023 * bootver=2010-07-08#4.02 firmware_ver=1.0.0 // Firmware Ver:16.01.0000
2024 * return format: 0x02 0x04 0x00 0x00 0x00 0x01
2025 * RK29: bootver=2011-07-18#2.05 firmware_ver=0.2.3 (==00.02.0003)
2026 * for the old loader,the firmware_ver may be empty,so get the fw ver from paramter.
2028 #define ASC_BCD0(c) (((c-'0'))&0xf)
2029 #define ASC_BCD1(c) (((c-'0')<<4)&0xf0)
2033 char *l_tag = "bootver=";
2034 char *fw_tag = "FIRMWARE_VER:";
2042 memset(ver, 0x00, ret);
2043 p_l = strstr(saved_command_line, l_tag);
2047 p_l += strlen(l_tag);
2048 p_l = strchr(p_l, '#');
2051 if (p_l[1] == '.') {
2052 ver[1] = ASC_BCD0(p_l[0]);
2055 ver[1] = ASC_BCD1(p_l[0]) | ASC_BCD0(p_l[1]);
2058 ver[0] = ASC_BCD1(p_l[0]) | ASC_BCD0(p_l[1]);
2061 p_f = get_param_tag(ver, fw_tag);
2065 if (p_f[1] == '.') {
2066 ver[5] = ASC_BCD0(p_f[0]);
2069 ver[5] = ASC_BCD1(p_f[0]) | ASC_BCD0(p_f[1]);
2072 if (p_f[1] == '.') {
2073 ver[4] = ASC_BCD0(p_f[0]);
2076 ver[4] = ASC_BCD1(p_f[0]) | ASC_BCD0(p_f[1]);
2079 ver[2] = ASC_BCD0(p_f[0]);
2081 if (p_f[0] != ' ') {
2082 ver[2] |= ASC_BCD1(p_f[0]);
2085 /* only support 2 byte version. */
2089 printk("VERSION:%02x %02x %02x %02x %02x %02x\n",
2090 ver[0], ver[1], ver[2], ver[3], ver[4], ver[5]);
2097 static int do_scsi_command(struct fsg_common *common)
2099 struct fsg_buffhd *bh;
2101 int reply = -EINVAL;
2103 static char unknown[16];
2104 #ifdef CONFIG_ARCH_ROCKCHIP
2105 struct fsg_common *fsg = common;
2110 /* Wait for the next buffer to become available for data or status */
2111 bh = common->next_buffhd_to_fill;
2112 common->next_buffhd_to_drain = bh;
2113 while (bh->state != BUF_STATE_EMPTY) {
2114 rc = sleep_thread(common);
2118 common->phase_error = 0;
2119 common->short_packet_received = 0;
2121 down_read(&common->filesem); /* We're using the backing file */
2122 switch (common->cmnd[0]) {
2125 common->data_size_from_cmnd = common->cmnd[4];
2126 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2127 (1 << 4), 0, "INQUIRY");
2129 reply = do_inquiry(common, bh);
2133 common->data_size_from_cmnd = common->cmnd[4];
2134 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2135 (1 << 1) | (1 << 4), 0, "MODE SELECT(6)");
2137 reply = do_mode_select(common, bh);
2140 case MODE_SELECT_10:
2141 common->data_size_from_cmnd =
2142 get_unaligned_be16(&common->cmnd[7]);
2143 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2144 (1 << 1) | (3 << 7), 0,
2147 reply = do_mode_select(common, bh);
2151 common->data_size_from_cmnd = common->cmnd[4];
2152 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2153 (1 << 1) | (1 << 2) | (1 << 4), 0,
2156 reply = do_mode_sense(common, bh);
2160 common->data_size_from_cmnd =
2161 get_unaligned_be16(&common->cmnd[7]);
2162 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2163 (1 << 1) | (1 << 2) | (3 << 7), 0,
2166 reply = do_mode_sense(common, bh);
2169 case ALLOW_MEDIUM_REMOVAL:
2170 common->data_size_from_cmnd = 0;
2171 reply = check_command(common, 6, DATA_DIR_NONE,
2173 "PREVENT-ALLOW MEDIUM REMOVAL");
2175 reply = do_prevent_allow(common);
2179 i = common->cmnd[4];
2180 common->data_size_from_cmnd = (i == 0) ? 256 : i;
2181 reply = check_command_size_in_blocks(common, 6,
2183 (7 << 1) | (1 << 4), 1,
2186 reply = do_read(common);
2190 common->data_size_from_cmnd =
2191 get_unaligned_be16(&common->cmnd[7]);
2192 reply = check_command_size_in_blocks(common, 10,
2194 (1 << 1) | (0xf << 2) | (3
2199 reply = do_read(common);
2203 common->data_size_from_cmnd =
2204 get_unaligned_be32(&common->cmnd[6]);
2205 reply = check_command_size_in_blocks(common, 12,
2207 (1 << 1) | (0xf << 2) |
2208 (0xf << 6), 1, "READ(12)");
2210 reply = do_read(common);
2214 common->data_size_from_cmnd = 8;
2215 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2216 (0xf << 2) | (1 << 8), 1,
2219 reply = do_read_capacity(common, bh);
2223 if (!common->curlun || !common->curlun->cdrom)
2225 common->data_size_from_cmnd =
2226 get_unaligned_be16(&common->cmnd[7]);
2227 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2228 (3 << 7) | (0x1f << 1), 1, "READ HEADER");
2230 reply = do_read_header(common, bh);
2234 if (!common->curlun || !common->curlun->cdrom)
2236 common->data_size_from_cmnd =
2237 get_unaligned_be16(&common->cmnd[7]);
2238 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2239 (7 << 6) | (1 << 1), 1, "READ TOC");
2241 reply = do_read_toc(common, bh);
2244 case READ_FORMAT_CAPACITIES:
2245 common->data_size_from_cmnd =
2246 get_unaligned_be16(&common->cmnd[7]);
2247 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2248 (3 << 7), 1, "READ FORMAT CAPACITIES");
2250 reply = do_read_format_capacities(common, bh);
2254 common->data_size_from_cmnd = common->cmnd[4];
2255 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2256 (1 << 4), 0, "REQUEST SENSE");
2258 reply = do_request_sense(common, bh);
2262 common->data_size_from_cmnd = 0;
2263 reply = check_command(common, 6, DATA_DIR_NONE,
2264 (1 << 1) | (1 << 4), 0,
2267 reply = do_start_stop(common);
2270 case SYNCHRONIZE_CACHE:
2271 common->data_size_from_cmnd = 0;
2272 reply = check_command(common, 10, DATA_DIR_NONE,
2273 (0xf << 2) | (3 << 7), 1,
2274 "SYNCHRONIZE CACHE");
2276 reply = do_synchronize_cache(common);
2279 case TEST_UNIT_READY:
2280 common->data_size_from_cmnd = 0;
2281 reply = check_command(common, 6, DATA_DIR_NONE,
2282 0, 1, "TEST UNIT READY");
2286 * Although optional, this command is used by MS-Windows. We
2287 * support a minimal version: BytChk must be 0.
2290 common->data_size_from_cmnd = 0;
2291 reply = check_command(common, 10, DATA_DIR_NONE,
2292 (1 << 1) | (0xf << 2) | (3 << 7), 1,
2295 #ifdef CONFIG_ARCH_ROCKCHIP
2296 reply = 0; /* zyf 20100302 */
2298 reply = do_verify(common);
2303 i = common->cmnd[4];
2304 common->data_size_from_cmnd = (i == 0) ? 256 : i;
2305 reply = check_command_size_in_blocks(common, 6,
2307 (7 << 1) | (1 << 4), 1,
2310 reply = do_write(common);
2314 common->data_size_from_cmnd =
2315 get_unaligned_be16(&common->cmnd[7]);
2316 reply = check_command_size_in_blocks(common, 10,
2318 (1 << 1) | (0xf << 2) | (3
2323 reply = do_write(common);
2327 common->data_size_from_cmnd =
2328 get_unaligned_be32(&common->cmnd[6]);
2329 reply = check_command_size_in_blocks(common, 12,
2331 (1 << 1) | (0xf << 2) |
2335 reply = do_write(common);
2339 * Some mandatory commands that we recognize but don't implement.
2340 * They don't mean much in this setting. It's left as an exercise
2341 * for anyone interested to implement RESERVE and RELEASE in terms
2347 case SEND_DIAGNOSTIC:
2352 common->data_size_from_cmnd = 0;
2353 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2354 reply = check_command(common, common->cmnd_size,
2355 DATA_DIR_UNKNOWN, ~0, 0, unknown);
2357 common->curlun->sense_data = SS_INVALID_COMMAND;
2361 #ifdef CONFIG_ARCH_ROCKCHIP
2363 if (fsg->cmnd[1] != 0xe0 ||
2364 fsg->cmnd[2] != 0xff || fsg->cmnd[3] != 0xff ||
2365 fsg->cmnd[4] != 0xff)
2367 if (fsg->cmnd_size >= 6 && fsg->cmnd[5] == 0xfe) {
2368 schedule_work(&restart_work);
2369 } else if (fsg->cmnd[5] == 0xf3) {
2370 fsg->data_size_from_cmnd = fsg->data_size;
2371 /* get product name from parameter section */
2372 reply = do_get_product_name(fsg->data_size, bh->buf);
2373 } else if (fsg->cmnd[5] == 0xff) {
2374 fsg->data_size_from_cmnd = fsg->data_size;
2375 reply = do_get_versions(fsg->data_size, bh->buf);
2380 up_read(&common->filesem);
2382 if (reply == -EINTR || signal_pending(current))
2385 /* Set up the single reply buffer for finish_reply() */
2386 if (reply == -EINVAL)
2387 reply = 0; /* Error reply length */
2388 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2389 reply = min((u32) reply, common->data_size_from_cmnd);
2390 bh->inreq->length = reply;
2391 bh->state = BUF_STATE_FULL;
2392 common->residue -= reply;
2394 /* Otherwise it's already set */
2398 /*-------------------------------------------------------------------------*/
2400 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2402 struct usb_request *req = bh->outreq;
2403 struct bulk_cb_wrap *cbw = req->buf;
2404 struct fsg_common *common = fsg->common;
2406 /* Was this a real packet? Should it be ignored? */
2407 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2410 /* Is the CBW valid? */
2411 if (req->actual != US_BULK_CB_WRAP_LEN ||
2412 cbw->Signature != cpu_to_le32(US_BULK_CB_SIGN)) {
2413 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2414 req->actual, le32_to_cpu(cbw->Signature));
2417 * The Bulk-only spec says we MUST stall the IN endpoint
2418 * (6.6.1), so it's unavoidable. It also says we must
2419 * retain this state until the next reset, but there's
2420 * no way to tell the controller driver it should ignore
2421 * Clear-Feature(HALT) requests.
2423 * We aren't required to halt the OUT endpoint; instead
2424 * we can simply accept and discard any data received
2425 * until the next reset.
2427 wedge_bulk_in_endpoint(fsg);
2428 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2432 /* Is the CBW meaningful? */
2433 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~US_BULK_FLAG_IN ||
2434 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2435 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2436 "cmdlen %u\n", cbw->Lun, cbw->Flags, cbw->Length);
2439 * We can do anything we want here, so let's stall the
2440 * bulk pipes if we are allowed to.
2442 if (common->can_stall) {
2443 fsg_set_halt(fsg, fsg->bulk_out);
2444 halt_bulk_in_endpoint(fsg);
2449 /* Save the command for later */
2450 common->cmnd_size = cbw->Length;
2451 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2452 if (cbw->Flags & US_BULK_FLAG_IN)
2453 common->data_dir = DATA_DIR_TO_HOST;
2455 common->data_dir = DATA_DIR_FROM_HOST;
2456 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2457 if (common->data_size == 0)
2458 common->data_dir = DATA_DIR_NONE;
2459 common->lun = cbw->Lun;
2460 if (common->lun >= 0 && common->lun < common->nluns)
2461 common->curlun = &common->luns[common->lun];
2463 common->curlun = NULL;
2464 common->tag = cbw->Tag;
2468 static int get_next_command(struct fsg_common *common)
2470 struct fsg_buffhd *bh;
2473 /* Wait for the next buffer to become available */
2474 bh = common->next_buffhd_to_fill;
2475 while (bh->state != BUF_STATE_EMPTY) {
2476 rc = sleep_thread(common);
2481 /* Queue a request to read a Bulk-only CBW */
2482 set_bulk_out_req_length(common, bh, US_BULK_CB_WRAP_LEN);
2483 if (!start_out_transfer(common, bh))
2484 /* Don't know what to do if common->fsg is NULL */
2488 * We will drain the buffer in software, which means we
2489 * can reuse it for the next filling. No need to advance
2490 * next_buffhd_to_fill.
2493 /* Wait for the CBW to arrive */
2494 while (bh->state != BUF_STATE_FULL) {
2495 rc = sleep_thread(common);
2500 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2501 bh->state = BUF_STATE_EMPTY;
2506 /*-------------------------------------------------------------------------*/
2508 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2509 struct usb_request **preq)
2511 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2514 ERROR(common, "can't allocate request for %s\n", ep->name);
2518 /* Reset interface setting and re-init endpoint state (toggle etc). */
2519 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2521 struct fsg_dev *fsg;
2524 if (common->running)
2525 DBG(common, "reset interface\n");
2528 /* Deallocate the requests */
2532 for (i = 0; i < fsg_num_buffers; ++i) {
2533 struct fsg_buffhd *bh = &common->buffhds[i];
2536 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2540 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2545 /* Disable the endpoints */
2546 if (fsg->bulk_in_enabled) {
2547 usb_ep_disable(fsg->bulk_in);
2548 fsg->bulk_in_enabled = 0;
2550 if (fsg->bulk_out_enabled) {
2551 usb_ep_disable(fsg->bulk_out);
2552 fsg->bulk_out_enabled = 0;
2556 wake_up(&common->fsg_wait);
2559 common->running = 0;
2563 common->fsg = new_fsg;
2566 /* Enable the endpoints */
2567 rc = config_ep_by_speed(common->gadget, &(fsg->function), fsg->bulk_in);
2570 rc = usb_ep_enable(fsg->bulk_in);
2573 fsg->bulk_in->driver_data = common;
2574 fsg->bulk_in_enabled = 1;
2576 rc = config_ep_by_speed(common->gadget, &(fsg->function),
2580 rc = usb_ep_enable(fsg->bulk_out);
2583 fsg->bulk_out->driver_data = common;
2584 fsg->bulk_out_enabled = 1;
2585 common->bulk_out_maxpacket = usb_endpoint_maxp(fsg->bulk_out->desc);
2586 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2588 /* Allocate the requests */
2589 for (i = 0; i < fsg_num_buffers; ++i) {
2590 struct fsg_buffhd *bh = &common->buffhds[i];
2592 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2595 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2598 bh->inreq->buf = bh->outreq->buf = bh->buf;
2599 bh->inreq->context = bh->outreq->context = bh;
2600 bh->inreq->complete = bulk_in_complete;
2601 bh->outreq->complete = bulk_out_complete;
2604 common->running = 1;
2605 for (i = 0; i < common->nluns; ++i)
2606 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2610 /****************************** ALT CONFIGS ******************************/
2612 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2614 struct fsg_dev *fsg = fsg_from_func(f);
2615 fsg->common->new_fsg = fsg;
2616 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2617 return USB_GADGET_DELAYED_STATUS;
2620 static void fsg_disable(struct usb_function *f)
2622 struct fsg_dev *fsg = fsg_from_func(f);
2623 fsg->common->new_fsg = NULL;
2624 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2627 /*-------------------------------------------------------------------------*/
2629 static void handle_exception(struct fsg_common *common)
2633 struct fsg_buffhd *bh;
2634 enum fsg_state old_state;
2635 struct fsg_lun *curlun;
2636 unsigned int exception_req_tag;
2639 * Clear the existing signals. Anything but SIGUSR1 is converted
2640 * into a high-priority EXIT exception.
2644 dequeue_signal_lock(current, ¤t->blocked, &info);
2647 if (sig != SIGUSR1) {
2648 if (common->state < FSG_STATE_EXIT)
2649 DBG(common, "Main thread exiting on signal\n");
2650 raise_exception(common, FSG_STATE_EXIT);
2654 /* Cancel all the pending transfers */
2655 if (likely(common->fsg)) {
2656 for (i = 0; i < fsg_num_buffers; ++i) {
2657 bh = &common->buffhds[i];
2659 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2660 if (bh->outreq_busy)
2661 usb_ep_dequeue(common->fsg->bulk_out,
2665 /* Wait until everything is idle */
2668 for (i = 0; i < fsg_num_buffers; ++i) {
2669 bh = &common->buffhds[i];
2670 num_active += bh->inreq_busy + bh->outreq_busy;
2672 if (num_active == 0)
2674 if (sleep_thread(common))
2678 /* Clear out the controller's fifos */
2679 if (common->fsg->bulk_in_enabled)
2680 usb_ep_fifo_flush(common->fsg->bulk_in);
2681 if (common->fsg->bulk_out_enabled)
2682 usb_ep_fifo_flush(common->fsg->bulk_out);
2686 * Reset the I/O buffer states and pointers, the SCSI
2687 * state, and the exception. Then invoke the handler.
2689 spin_lock_irq(&common->lock);
2691 for (i = 0; i < fsg_num_buffers; ++i) {
2692 bh = &common->buffhds[i];
2693 bh->state = BUF_STATE_EMPTY;
2695 common->next_buffhd_to_fill = &common->buffhds[0];
2696 common->next_buffhd_to_drain = &common->buffhds[0];
2697 exception_req_tag = common->exception_req_tag;
2698 old_state = common->state;
2700 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2701 common->state = FSG_STATE_STATUS_PHASE;
2703 for (i = 0; i < common->nluns; ++i) {
2704 curlun = &common->luns[i];
2705 curlun->prevent_medium_removal = 0;
2706 curlun->sense_data = SS_NO_SENSE;
2707 curlun->unit_attention_data = SS_NO_SENSE;
2708 curlun->sense_data_info = 0;
2709 curlun->info_valid = 0;
2711 common->state = FSG_STATE_IDLE;
2713 spin_unlock_irq(&common->lock);
2715 /* Carry out any extra actions required for the exception */
2716 switch (old_state) {
2717 case FSG_STATE_ABORT_BULK_OUT:
2718 send_status(common);
2719 spin_lock_irq(&common->lock);
2720 if (common->state == FSG_STATE_STATUS_PHASE)
2721 common->state = FSG_STATE_IDLE;
2722 spin_unlock_irq(&common->lock);
2725 case FSG_STATE_RESET:
2727 * In case we were forced against our will to halt a
2728 * bulk endpoint, clear the halt now. (The SuperH UDC
2731 if (!fsg_is_set(common))
2733 if (test_and_clear_bit(IGNORE_BULK_OUT,
2734 &common->fsg->atomic_bitflags))
2735 usb_ep_clear_halt(common->fsg->bulk_in);
2737 if (common->ep0_req_tag == exception_req_tag)
2738 ep0_queue(common); /* Complete the status stage */
2741 * Technically this should go here, but it would only be
2742 * a waste of time. Ditto for the INTERFACE_CHANGE and
2743 * CONFIG_CHANGE cases.
2745 /* for (i = 0; i < common->nluns; ++i) */
2746 /* common->luns[i].unit_attention_data = */
2747 /* SS_RESET_OCCURRED; */
2750 case FSG_STATE_CONFIG_CHANGE:
2751 do_set_interface(common, common->new_fsg);
2752 if (common->new_fsg)
2753 usb_composite_setup_continue(common->cdev);
2756 case FSG_STATE_EXIT:
2757 case FSG_STATE_TERMINATED:
2758 do_set_interface(common, NULL); /* Free resources */
2759 spin_lock_irq(&common->lock);
2760 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2761 spin_unlock_irq(&common->lock);
2764 case FSG_STATE_INTERFACE_CHANGE:
2765 case FSG_STATE_DISCONNECT:
2766 case FSG_STATE_COMMAND_PHASE:
2767 case FSG_STATE_DATA_PHASE:
2768 case FSG_STATE_STATUS_PHASE:
2769 case FSG_STATE_IDLE:
2774 /*-------------------------------------------------------------------------*/
2776 static int fsg_main_thread(void *common_)
2778 struct fsg_common *common = common_;
2781 * Allow the thread to be killed by a signal, but set the signal mask
2782 * to block everything but INT, TERM, KILL, and USR1.
2784 allow_signal(SIGINT);
2785 allow_signal(SIGTERM);
2786 allow_signal(SIGKILL);
2787 allow_signal(SIGUSR1);
2789 /* Allow the thread to be frozen */
2793 * Arrange for userspace references to be interpreted as kernel
2794 * pointers. That way we can pass a kernel pointer to a routine
2795 * that expects a __user pointer and it will work okay.
2800 while (common->state != FSG_STATE_TERMINATED) {
2801 if (exception_in_progress(common) || signal_pending(current)) {
2802 handle_exception(common);
2806 if (!common->running) {
2807 sleep_thread(common);
2811 if (get_next_command(common))
2814 spin_lock_irq(&common->lock);
2815 if (!exception_in_progress(common))
2816 common->state = FSG_STATE_DATA_PHASE;
2817 spin_unlock_irq(&common->lock);
2819 if (do_scsi_command(common) || finish_reply(common))
2822 spin_lock_irq(&common->lock);
2823 if (!exception_in_progress(common))
2824 common->state = FSG_STATE_STATUS_PHASE;
2825 spin_unlock_irq(&common->lock);
2827 #ifdef CONFIG_USB_CSW_HACK
2828 /* Since status is already sent for write scsi command,
2829 * need to skip sending status once again if it is a
2830 * write scsi command.
2832 if (csw_hack_sent) {
2837 if (send_status(common))
2840 spin_lock_irq(&common->lock);
2841 if (!exception_in_progress(common))
2842 common->state = FSG_STATE_IDLE;
2843 spin_unlock_irq(&common->lock);
2846 spin_lock_irq(&common->lock);
2847 common->thread_task = NULL;
2848 spin_unlock_irq(&common->lock);
2850 if (!common->ops || !common->ops->thread_exits
2851 || common->ops->thread_exits(common) < 0) {
2852 struct fsg_lun *curlun = common->luns;
2853 unsigned i = common->nluns;
2855 down_write(&common->filesem);
2856 for (; i--; ++curlun) {
2857 if (!fsg_lun_is_open(curlun))
2860 fsg_lun_close(curlun);
2861 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2863 up_write(&common->filesem);
2866 /* Let fsg_unbind() know the thread has exited */
2867 complete_and_exit(&common->thread_notifier, 0);
2870 /*************************** DEVICE ATTRIBUTES ***************************/
2872 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2873 static DEVICE_ATTR(nofua, 0644, fsg_show_nofua, fsg_store_nofua);
2874 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2875 #ifdef CONFIG_USB_MSC_PROFILING
2876 static DEVICE_ATTR(perf, 0644, fsg_show_perf, fsg_store_perf);
2879 static struct device_attribute dev_attr_ro_cdrom =
2880 __ATTR(ro, 0444, fsg_show_ro, NULL);
2881 static struct device_attribute dev_attr_file_nonremovable =
2882 __ATTR(file, 0444, fsg_show_file, NULL);
2884 /****************************** FSG COMMON ******************************/
2886 static void fsg_common_release(struct kref *ref);
2888 static void fsg_lun_release(struct device *dev)
2890 /* Nothing needs to be done */
2893 static inline void fsg_common_get(struct fsg_common *common)
2895 kref_get(&common->ref);
2898 static inline void fsg_common_put(struct fsg_common *common)
2900 kref_put(&common->ref, fsg_common_release);
2903 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2904 struct usb_composite_dev *cdev,
2905 struct fsg_config *cfg)
2907 struct usb_gadget *gadget = cdev->gadget;
2908 struct fsg_buffhd *bh;
2909 struct fsg_lun *curlun;
2910 struct fsg_lun_config *lcfg;
2914 rc = fsg_num_buffers_validate();
2918 /* Find out how many LUNs there should be */
2920 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2921 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2922 return ERR_PTR(-EINVAL);
2927 common = kzalloc(sizeof *common, GFP_KERNEL);
2929 return ERR_PTR(-ENOMEM);
2930 common->free_storage_on_release = 1;
2932 memset(common, 0, sizeof *common);
2933 common->free_storage_on_release = 0;
2936 common->buffhds = kcalloc(fsg_num_buffers,
2937 sizeof *(common->buffhds), GFP_KERNEL);
2938 if (!common->buffhds) {
2939 if (common->free_storage_on_release)
2941 return ERR_PTR(-ENOMEM);
2944 common->ops = cfg->ops;
2945 common->private_data = cfg->private_data;
2947 common->gadget = gadget;
2948 common->ep0 = gadget->ep0;
2949 common->ep0req = cdev->req;
2950 common->cdev = cdev;
2952 /* Maybe allocate device-global string IDs, and patch descriptors */
2953 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2954 rc = usb_string_id(cdev);
2955 if (unlikely(rc < 0))
2957 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2958 fsg_intf_desc.iInterface = rc;
2962 * Create the LUNs, open their backing files, and register the
2963 * LUN devices in sysfs.
2965 curlun = kcalloc(nluns, sizeof(*curlun), GFP_KERNEL);
2966 if (unlikely(!curlun)) {
2970 common->luns = curlun;
2972 init_rwsem(&common->filesem);
2974 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2975 curlun->cdrom = !!lcfg->cdrom;
2976 curlun->ro = lcfg->cdrom || lcfg->ro;
2977 curlun->initially_ro = curlun->ro;
2978 curlun->removable = lcfg->removable;
2979 curlun->nofua = lcfg->nofua;
2980 curlun->dev.release = fsg_lun_release;
2981 curlun->dev.parent = &gadget->dev;
2982 /* curlun->dev.driver = &fsg_driver.driver; XXX */
2983 dev_set_drvdata(&curlun->dev, &common->filesem);
2984 dev_set_name(&curlun->dev, "lun%d", i);
2986 rc = device_register(&curlun->dev);
2988 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2990 put_device(&curlun->dev);
2994 rc = device_create_file(&curlun->dev,
2996 ? &dev_attr_ro_cdrom : &dev_attr_ro);
2999 rc = device_create_file(&curlun->dev,
3002 : &dev_attr_file_nonremovable);
3005 rc = device_create_file(&curlun->dev, &dev_attr_nofua);
3008 #ifdef CONFIG_USB_MSC_PROFILING
3009 rc = device_create_file(&curlun->dev, &dev_attr_perf);
3011 dev_err(&gadget->dev, "failed to create sysfs entry:"
3012 "(dev_attr_perf) error: %d\n", rc);
3014 if (lcfg->filename) {
3015 rc = fsg_lun_open(curlun, lcfg->filename);
3018 } else if (!curlun->removable) {
3019 ERROR(common, "no file given for LUN%d\n", i);
3024 common->nluns = nluns;
3026 /* Data buffers cyclic list */
3027 bh = common->buffhds;
3028 i = fsg_num_buffers;
3029 goto buffhds_first_it;
3034 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
3035 if (unlikely(!bh->buf)) {
3040 bh->next = common->buffhds;
3042 /* Prepare inquiryString */
3043 i = get_default_bcdDevice();
3044 snprintf(common->inquiry_string, sizeof common->inquiry_string,
3045 "%-8s%-16s%04x", cfg->vendor_name ? : "Linux",
3046 /* Assume product name dependent on the first LUN */
3047 cfg->product_name ? : (common->luns->cdrom
3048 ? "File-Stor Gadget"
3049 : "File-CD Gadget"), i);
3052 * Some peripheral controllers are known not to be able to
3053 * halt bulk endpoints correctly. If one of them is present,
3056 common->can_stall = cfg->can_stall && !(gadget_is_at91(common->gadget));
3058 spin_lock_init(&common->lock);
3059 kref_init(&common->ref);
3061 /* Tell the thread to start working */
3062 common->thread_task =
3063 kthread_create(fsg_main_thread, common, "file-storage");
3064 if (IS_ERR(common->thread_task)) {
3065 rc = PTR_ERR(common->thread_task);
3068 init_completion(&common->thread_notifier);
3069 init_waitqueue_head(&common->fsg_wait);
3072 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
3073 INFO(common, "Number of LUNs=%d\n", common->nluns);
3075 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3076 for (i = 0, nluns = common->nluns, curlun = common->luns;
3077 i < nluns; ++curlun, ++i) {
3078 char *p = "(no medium)";
3079 if (fsg_lun_is_open(curlun)) {
3082 p = d_path(&curlun->filp->f_path,
3088 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
3089 curlun->removable ? "removable " : "",
3090 curlun->ro ? "read only " : "",
3091 curlun->cdrom ? "CD-ROM " : "", p);
3095 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
3097 wake_up_process(common->thread_task);
3102 common->nluns = i + 1;
3104 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
3105 /* Call fsg_common_release() directly, ref might be not initialised. */
3106 fsg_common_release(&common->ref);
3110 static void fsg_common_release(struct kref *ref)
3112 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
3114 /* If the thread isn't already dead, tell it to exit now */
3115 if (common->state != FSG_STATE_TERMINATED) {
3116 raise_exception(common, FSG_STATE_EXIT);
3117 wait_for_completion(&common->thread_notifier);
3120 if (likely(common->luns)) {
3121 struct fsg_lun *lun = common->luns;
3122 unsigned i = common->nluns;
3124 /* In error recovery common->nluns may be zero. */
3125 for (; i; --i, ++lun) {
3126 #ifdef CONFIG_USB_MSC_PROFILING
3127 device_remove_file(&lun->dev, &dev_attr_perf);
3129 device_remove_file(&lun->dev, &dev_attr_nofua);
3130 device_remove_file(&lun->dev,
3132 ? &dev_attr_ro_cdrom : &dev_attr_ro);
3133 device_remove_file(&lun->dev,
3136 : &dev_attr_file_nonremovable);
3138 device_unregister(&lun->dev);
3141 kfree(common->luns);
3145 struct fsg_buffhd *bh = common->buffhds;
3146 unsigned i = fsg_num_buffers;
3149 } while (++bh, --i);
3152 kfree(common->buffhds);
3153 if (common->free_storage_on_release)
3157 /*-------------------------------------------------------------------------*/
3159 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
3161 struct fsg_dev *fsg = fsg_from_func(f);
3162 struct fsg_common *common = fsg->common;
3164 DBG(fsg, "unbind\n");
3165 if (fsg->common->fsg == fsg) {
3166 fsg->common->new_fsg = NULL;
3167 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
3168 /* FIXME: make interruptible or killable somehow? */
3169 wait_event(common->fsg_wait, common->fsg != fsg);
3172 fsg_common_put(common);
3173 usb_free_all_descriptors(&fsg->function);
3177 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
3179 struct fsg_dev *fsg = fsg_from_func(f);
3180 struct usb_gadget *gadget = c->cdev->gadget;
3186 fsg->gadget = gadget;
3189 i = usb_interface_id(c, f);
3192 fsg_intf_desc.bInterfaceNumber = i;
3193 fsg->interface_number = i;
3195 /* Find all the endpoints we will use */
3196 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3199 ep->driver_data = fsg->common; /* claim the endpoint */
3202 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3205 ep->driver_data = fsg->common; /* claim the endpoint */
3208 /* Assume endpoint addresses are the same for both speeds */
3209 fsg_hs_bulk_in_desc.bEndpointAddress =
3210 fsg_fs_bulk_in_desc.bEndpointAddress;
3211 fsg_hs_bulk_out_desc.bEndpointAddress =
3212 fsg_fs_bulk_out_desc.bEndpointAddress;
3214 /* Calculate bMaxBurst, we know packet size is 1024 */
3215 max_burst = min_t(unsigned, FSG_BUFLEN / 1024, 15);
3217 fsg_ss_bulk_in_desc.bEndpointAddress =
3218 fsg_fs_bulk_in_desc.bEndpointAddress;
3219 fsg_ss_bulk_in_comp_desc.bMaxBurst = max_burst;
3221 fsg_ss_bulk_out_desc.bEndpointAddress =
3222 fsg_fs_bulk_out_desc.bEndpointAddress;
3223 fsg_ss_bulk_out_comp_desc.bMaxBurst = max_burst;
3225 ret = usb_assign_descriptors(f, fsg_fs_function, fsg_hs_function,
3233 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3237 /****************************** ADD FUNCTION ******************************/
3239 static struct usb_gadget_strings *fsg_strings_array[] = {
3244 static int fsg_bind_config(struct usb_composite_dev *cdev,
3245 struct usb_configuration *c,
3246 struct fsg_common *common)
3248 struct fsg_dev *fsg;
3251 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3255 fsg->function.name = FSG_DRIVER_DESC;
3256 fsg->function.strings = fsg_strings_array;
3257 fsg->function.bind = fsg_bind;
3258 fsg->function.unbind = fsg_unbind;
3259 fsg->function.setup = fsg_setup;
3260 fsg->function.set_alt = fsg_set_alt;
3261 fsg->function.disable = fsg_disable;
3263 fsg->common = common;
3265 * Our caller holds a reference to common structure so we
3266 * don't have to be worry about it being freed until we return
3267 * from this function. So instead of incrementing counter now
3268 * and decrement in error recovery we increment it only when
3269 * call to usb_add_function() was successful.
3272 rc = usb_add_function(c, &fsg->function);
3276 fsg_common_get(fsg->common);
3280 /************************* Module parameters *************************/
3282 struct fsg_module_parameters {
3283 char *file[FSG_MAX_LUNS];
3284 bool ro[FSG_MAX_LUNS];
3285 bool removable[FSG_MAX_LUNS];
3286 bool cdrom[FSG_MAX_LUNS];
3287 bool nofua[FSG_MAX_LUNS];
3289 unsigned int file_count, ro_count, removable_count, cdrom_count;
3290 unsigned int nofua_count;
3291 unsigned int luns; /* nluns */
3292 bool stall; /* can_stall */
3295 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3296 module_param_array_named(prefix ## name, params.name, type, \
3297 &prefix ## params.name ## _count, \
3299 MODULE_PARM_DESC(prefix ## name, desc)
3301 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3302 module_param_named(prefix ## name, params.name, type, \
3304 MODULE_PARM_DESC(prefix ## name, desc)
3306 #define FSG_MODULE_PARAMETERS(prefix, params) \
3307 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3308 "names of backing files or devices"); \
3309 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3310 "true to force read-only"); \
3311 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3312 "true to simulate removable media"); \
3313 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3314 "true to simulate CD-ROM instead of disk"); \
3315 _FSG_MODULE_PARAM_ARRAY(prefix, params, nofua, bool, \
3316 "true to ignore SCSI WRITE(10,12) FUA bit"); \
3317 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3318 "number of LUNs"); \
3319 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3320 "false to prevent bulk stalls")
3323 fsg_config_from_params(struct fsg_config *cfg,
3324 const struct fsg_module_parameters *params)
3326 struct fsg_lun_config *lun;
3329 /* Configure LUNs */
3331 min(params->luns ? : (params->file_count ? : 1u),
3332 (unsigned)FSG_MAX_LUNS);
3333 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3334 lun->ro = !!params->ro[i];
3335 lun->cdrom = !!params->cdrom[i];
3336 lun->removable = !!params->removable[i];
3337 lun->filename = params->file_count > i && params->file[i][0]
3342 /* Let MSF use defaults */
3343 cfg->vendor_name = 0;
3344 cfg->product_name = 0;
3347 cfg->private_data = NULL;
3350 cfg->can_stall = params->stall;
3353 static inline struct fsg_common *fsg_common_from_params(struct fsg_common
3355 struct usb_composite_dev
3358 fsg_module_parameters
3360 __attribute__ ((unused));
3361 static inline struct fsg_common *fsg_common_from_params(struct fsg_common
3363 struct usb_composite_dev
3366 fsg_module_parameters
3369 struct fsg_config cfg;
3370 fsg_config_from_params(&cfg, params);
3371 return fsg_common_init(common, cdev, &cfg);