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"
298 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
299 #include <linux/usb/android_composite.h>
300 #include <linux/platform_device.h>
302 #define FUNCTION_NAME "usb_mass_storage"
305 #ifdef CONFIG_ARCH_RK29
306 #include <linux/power_supply.h>
307 #include <linux/reboot.h>
308 #include <linux/syscalls.h>
310 static int usb_msc_connected; /*usb charge status*/
312 static void set_msc_connect_flag( int connected )
314 printk("%s status = %d 20101216\n" , __func__, connected);
315 if( usb_msc_connected == connected )
317 usb_msc_connected = connected;//usb mass storage is ok
320 int get_msc_connect_flag( void )
322 return usb_msc_connected;
324 EXPORT_SYMBOL(get_msc_connect_flag);
327 /*------------------------------------------------------------------------*/
329 #define FSG_DRIVER_DESC "Mass Storage Function"
330 #define FSG_DRIVER_VERSION "2009/09/11"
332 static const char fsg_string_interface[] = "Mass Storage";
335 #define FSG_NO_INTR_EP 1
336 #define FSG_NO_DEVICE_STRINGS 1
338 #define FSG_NO_INTR_EP 1
340 #include "storage_common.c"
343 /*-------------------------------------------------------------------------*/
348 /* FSF callback functions */
349 struct fsg_operations {
350 /* Callback function to call when thread exits. If no
351 * callback is set or it returns value lower then zero MSF
352 * will force eject all LUNs it operates on (including those
353 * marked as non-removable or with prevent_medium_removal flag
355 int (*thread_exits)(struct fsg_common *common);
357 /* Called prior to ejection. Negative return means error,
358 * zero means to continue with ejection, positive means not to
360 int (*pre_eject)(struct fsg_common *common,
361 struct fsg_lun *lun, int num);
362 /* Called after ejection. Negative return means error, zero
363 * or positive is just a success. */
364 int (*post_eject)(struct fsg_common *common,
365 struct fsg_lun *lun, int num);
369 /* Data shared by all the FSG instances. */
371 struct usb_gadget *gadget;
372 struct fsg_dev *fsg, *new_fsg;
373 wait_queue_head_t fsg_wait;
375 /* filesem protects: backing files in use */
376 struct rw_semaphore filesem;
378 /* lock protects: state, all the req_busy's */
381 struct usb_ep *ep0; /* Copy of gadget->ep0 */
382 struct usb_request *ep0req; /* Copy of cdev->req */
383 unsigned int ep0_req_tag;
385 struct fsg_buffhd *next_buffhd_to_fill;
386 struct fsg_buffhd *next_buffhd_to_drain;
387 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
390 u8 cmnd[MAX_COMMAND_SIZE];
394 struct fsg_lun *luns;
395 struct fsg_lun *curlun;
397 unsigned int bulk_out_maxpacket;
398 enum fsg_state state; /* For exception handling */
399 unsigned int exception_req_tag;
401 enum data_direction data_dir;
403 u32 data_size_from_cmnd;
408 unsigned int can_stall:1;
409 unsigned int free_storage_on_release:1;
410 unsigned int phase_error:1;
411 unsigned int short_packet_received:1;
412 unsigned int bad_lun_okay:1;
413 unsigned int running:1;
415 int thread_wakeup_needed;
416 struct completion thread_notifier;
417 struct task_struct *thread_task;
419 /* Callback functions. */
420 const struct fsg_operations *ops;
421 /* Gadget's private data. */
424 /* Vendor (8 chars), product (16 chars), release (4
425 * hexadecimal digits) and NUL byte */
426 char inquiry_string[8 + 16 + 4 + 1];
434 struct fsg_lun_config {
435 const char *filename;
439 } luns[FSG_MAX_LUNS];
441 const char *lun_name_format;
442 const char *thread_name;
444 /* Callback functions. */
445 const struct fsg_operations *ops;
446 /* Gadget's private data. */
449 const char *vendor_name; /* 8 characters or less */
450 const char *product_name; /* 16 characters or less */
455 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
456 struct platform_device *pdev;
462 struct usb_function function;
463 struct usb_gadget *gadget; /* Copy of cdev->gadget */
464 struct fsg_common *common;
466 u16 interface_number;
468 unsigned int bulk_in_enabled:1;
469 unsigned int bulk_out_enabled:1;
471 unsigned long atomic_bitflags;
472 #define IGNORE_BULK_OUT 0
474 struct usb_ep *bulk_in;
475 struct usb_ep *bulk_out;
479 static inline int __fsg_is_set(struct fsg_common *common,
480 const char *func, unsigned line)
484 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
489 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
492 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
494 return container_of(f, struct fsg_dev, function);
498 typedef void (*fsg_routine_t)(struct fsg_dev *);
500 static int exception_in_progress(struct fsg_common *common)
502 return common->state > FSG_STATE_IDLE;
505 /* Make bulk-out requests be divisible by the maxpacket size */
506 static void set_bulk_out_req_length(struct fsg_common *common,
507 struct fsg_buffhd *bh, unsigned int length)
511 bh->bulk_out_intended_length = length;
512 rem = length % common->bulk_out_maxpacket;
514 length += common->bulk_out_maxpacket - rem;
515 bh->outreq->length = length;
518 /*-------------------------------------------------------------------------*/
520 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
524 if (ep == fsg->bulk_in)
526 else if (ep == fsg->bulk_out)
530 DBG(fsg, "%s set halt\n", name);
531 return usb_ep_set_halt(ep);
535 /*-------------------------------------------------------------------------*/
537 /* These routines may be called in process context or in_irq */
539 /* Caller must hold fsg->lock */
540 static void wakeup_thread(struct fsg_common *common)
542 /* Tell the main thread that something has happened */
543 common->thread_wakeup_needed = 1;
544 if (common->thread_task)
545 wake_up_process(common->thread_task);
549 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
553 /* Do nothing if a higher-priority exception is already in progress.
554 * If a lower-or-equal priority exception is in progress, preempt it
555 * and notify the main thread by sending it a signal. */
556 spin_lock_irqsave(&common->lock, flags);
557 if (common->state <= new_state) {
558 common->exception_req_tag = common->ep0_req_tag;
559 common->state = new_state;
560 if (common->thread_task)
561 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
562 common->thread_task);
564 spin_unlock_irqrestore(&common->lock, flags);
568 /*-------------------------------------------------------------------------*/
570 static int ep0_queue(struct fsg_common *common)
574 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
575 common->ep0->driver_data = common;
576 if (rc != 0 && rc != -ESHUTDOWN) {
577 /* We can't do much more than wait for a reset */
578 WARNING(common, "error in submission: %s --> %d\n",
579 common->ep0->name, rc);
584 /*-------------------------------------------------------------------------*/
586 /* Bulk and interrupt endpoint completion handlers.
587 * These always run in_irq. */
589 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
591 struct fsg_common *common = ep->driver_data;
592 struct fsg_buffhd *bh = req->context;
594 if (req->status || req->actual != req->length)
595 DBG(common, "%s --> %d, %u/%u\n", __func__,
596 req->status, req->actual, req->length);
597 if (req->status == -ECONNRESET) /* Request was cancelled */
598 usb_ep_fifo_flush(ep);
600 /* Hold the lock while we update the request and buffer states */
602 spin_lock(&common->lock);
604 bh->state = BUF_STATE_EMPTY;
605 wakeup_thread(common);
606 spin_unlock(&common->lock);
609 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
611 struct fsg_common *common = ep->driver_data;
612 struct fsg_buffhd *bh = req->context;
614 dump_msg(common, "bulk-out", req->buf, req->actual);
615 if (req->status || req->actual != bh->bulk_out_intended_length)
616 DBG(common, "%s --> %d, %u/%u\n", __func__,
617 req->status, req->actual,
618 bh->bulk_out_intended_length);
619 if (req->status == -ECONNRESET) /* Request was cancelled */
620 usb_ep_fifo_flush(ep);
622 /* Hold the lock while we update the request and buffer states */
624 spin_lock(&common->lock);
626 bh->state = BUF_STATE_FULL;
627 wakeup_thread(common);
628 spin_unlock(&common->lock);
632 /*-------------------------------------------------------------------------*/
634 /* Ep0 class-specific handlers. These always run in_irq. */
636 static int fsg_setup(struct usb_function *f,
637 const struct usb_ctrlrequest *ctrl)
639 struct fsg_dev *fsg = fsg_from_func(f);
640 struct usb_request *req = fsg->common->ep0req;
641 u16 w_index = le16_to_cpu(ctrl->wIndex);
642 u16 w_value = le16_to_cpu(ctrl->wValue);
643 u16 w_length = le16_to_cpu(ctrl->wLength);
645 if (!fsg_is_set(fsg->common))
648 switch (ctrl->bRequest) {
650 case USB_BULK_RESET_REQUEST:
651 if (ctrl->bRequestType !=
652 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
654 if (w_index != fsg->interface_number || w_value != 0)
657 /* Raise an exception to stop the current operation
658 * and reinitialize our state. */
659 DBG(fsg, "bulk reset request\n");
660 raise_exception(fsg->common, FSG_STATE_RESET);
661 return DELAYED_STATUS;
663 case USB_BULK_GET_MAX_LUN_REQUEST:
664 if (ctrl->bRequestType !=
665 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
667 if (w_index != fsg->interface_number || w_value != 0)
669 VDBG(fsg, "get max LUN\n");
670 *(u8 *) req->buf = fsg->common->nluns - 1;
672 /* Respond with data/status */
673 req->length = min((u16)1, w_length);
674 return ep0_queue(fsg->common);
678 "unknown class-specific control req "
679 "%02x.%02x v%04x i%04x l%u\n",
680 ctrl->bRequestType, ctrl->bRequest,
681 le16_to_cpu(ctrl->wValue), w_index, w_length);
686 /*-------------------------------------------------------------------------*/
688 /* All the following routines run in process context */
691 /* Use this for bulk or interrupt transfers, not ep0 */
692 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
693 struct usb_request *req, int *pbusy,
694 enum fsg_buffer_state *state)
698 if (ep == fsg->bulk_in)
699 dump_msg(fsg, "bulk-in", req->buf, req->length);
701 spin_lock_irq(&fsg->common->lock);
703 *state = BUF_STATE_BUSY;
704 spin_unlock_irq(&fsg->common->lock);
705 rc = usb_ep_queue(ep, req, GFP_KERNEL);
708 *state = BUF_STATE_EMPTY;
710 /* We can't do much more than wait for a reset */
712 /* Note: currently the net2280 driver fails zero-length
713 * submissions if DMA is enabled. */
714 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
716 WARNING(fsg, "error in submission: %s --> %d\n",
721 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
722 if (fsg_is_set(common)) \
723 start_transfer((common)->fsg, (common)->fsg->ep_name, \
724 req, pbusy, state); \
727 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
728 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
732 static int sleep_thread(struct fsg_common *common)
736 /* Wait until a signal arrives or we are woken up */
739 set_current_state(TASK_INTERRUPTIBLE);
740 if (signal_pending(current)) {
744 if (common->thread_wakeup_needed)
748 __set_current_state(TASK_RUNNING);
749 common->thread_wakeup_needed = 0;
754 /*-------------------------------------------------------------------------*/
756 static int do_read(struct fsg_common *common)
758 struct fsg_lun *curlun = common->curlun;
760 struct fsg_buffhd *bh;
763 loff_t file_offset, file_offset_tmp;
765 unsigned int partial_page;
768 /* Get the starting Logical Block Address and check that it's
770 if (common->cmnd[0] == SC_READ_6)
771 lba = get_unaligned_be24(&common->cmnd[1]);
773 lba = get_unaligned_be32(&common->cmnd[2]);
775 /* We allow DPO (Disable Page Out = don't save data in the
776 * cache) and FUA (Force Unit Access = don't read from the
777 * cache), but we don't implement them. */
778 if ((common->cmnd[1] & ~0x18) != 0) {
779 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
783 if (lba >= curlun->num_sectors) {
784 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
787 file_offset = ((loff_t) lba) << 9;
789 /* Carry out the file reads */
790 amount_left = common->data_size_from_cmnd;
791 if (unlikely(amount_left == 0))
792 return -EIO; /* No default reply */
796 /* Figure out how much we need to read:
797 * Try to read the remaining amount.
798 * But don't read more than the buffer size.
799 * And don't try to read past the end of the file.
800 * Finally, if we're not at a page boundary, don't read past
802 * If this means reading 0 then we were asked to read past
803 * the end of file. */
804 amount = min(amount_left, FSG_BUFLEN);
805 amount = min((loff_t) amount,
806 curlun->file_length - file_offset);
807 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
808 if (partial_page > 0)
809 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
813 * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
814 * because of the DOEPTSIZ.PKTCNT has only 10 bits
816 if((common->gadget->speed != USB_SPEED_HIGH)&&(amount >0x8000))
819 /* Wait for the next buffer to become available */
820 bh = common->next_buffhd_to_fill;
821 while (bh->state != BUF_STATE_EMPTY) {
822 rc = sleep_thread(common);
827 /* If we were asked to read past the end of file,
828 * end with an empty buffer. */
831 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
832 curlun->sense_data_info = file_offset >> 9;
833 curlun->info_valid = 1;
834 bh->inreq->length = 0;
835 bh->state = BUF_STATE_FULL;
839 /* Perform the read */
840 file_offset_tmp = file_offset;
841 nread = vfs_read(curlun->filp,
842 (char __user *) bh->buf,
843 amount, &file_offset_tmp);
844 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
845 (unsigned long long) file_offset,
847 if (signal_pending(current))
851 LDBG(curlun, "error in file read: %d\n",
854 } else if (nread < amount) {
855 LDBG(curlun, "partial file read: %d/%u\n",
856 (int) nread, amount);
857 nread -= (nread & 511); /* Round down to a block */
859 file_offset += nread;
860 amount_left -= nread;
861 common->residue -= nread;
862 bh->inreq->length = nread;
863 bh->state = BUF_STATE_FULL;
865 /* If an error occurred, report it and its position */
866 if (nread < amount) {
867 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
868 curlun->sense_data_info = file_offset >> 9;
869 curlun->info_valid = 1;
873 if (amount_left == 0)
874 break; /* No more left to read */
876 /* Send this buffer and go read some more */
878 START_TRANSFER_OR(common, bulk_in, bh->inreq,
879 &bh->inreq_busy, &bh->state)
880 /* Don't know what to do if
881 * common->fsg is NULL */
883 common->next_buffhd_to_fill = bh->next;
886 return -EIO; /* No default reply */
890 /*-------------------------------------------------------------------------*/
892 static int do_write(struct fsg_common *common)
894 struct fsg_lun *curlun = common->curlun;
896 struct fsg_buffhd *bh;
898 u32 amount_left_to_req, amount_left_to_write;
899 loff_t usb_offset, file_offset, file_offset_tmp;
901 unsigned int partial_page;
906 curlun->sense_data = SS_WRITE_PROTECTED;
909 spin_lock(&curlun->filp->f_lock);
910 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
911 spin_unlock(&curlun->filp->f_lock);
913 /* Get the starting Logical Block Address and check that it's
915 if (common->cmnd[0] == SC_WRITE_6)
916 lba = get_unaligned_be24(&common->cmnd[1]);
918 lba = get_unaligned_be32(&common->cmnd[2]);
920 /* We allow DPO (Disable Page Out = don't save data in the
921 * cache) and FUA (Force Unit Access = write directly to the
922 * medium). We don't implement DPO; we implement FUA by
923 * performing synchronous output. */
924 if (common->cmnd[1] & ~0x18) {
925 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
928 if (common->cmnd[1] & 0x08) { /* FUA */
929 spin_lock(&curlun->filp->f_lock);
930 curlun->filp->f_flags |= O_SYNC;
931 spin_unlock(&curlun->filp->f_lock);
934 if (lba >= curlun->num_sectors) {
935 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
939 /* Carry out the file writes */
941 file_offset = usb_offset = ((loff_t) lba) << 9;
942 amount_left_to_req = common->data_size_from_cmnd;
943 amount_left_to_write = common->data_size_from_cmnd;
945 while (amount_left_to_write > 0) {
947 /* Queue a request for more data from the host */
948 bh = common->next_buffhd_to_fill;
949 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
951 /* Figure out how much we want to get:
952 * Try to get the remaining amount.
953 * But don't get more than the buffer size.
954 * And don't try to go past the end of the file.
955 * If we're not at a page boundary,
956 * don't go past the next page.
957 * If this means getting 0, then we were asked
958 * to write past the end of file.
959 * Finally, round down to a block boundary. */
960 amount = min(amount_left_to_req, FSG_BUFLEN);
961 amount = min((loff_t) amount, curlun->file_length -
963 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
964 if (partial_page > 0)
966 (unsigned int) PAGE_CACHE_SIZE - partial_page);
971 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
972 curlun->sense_data_info = usb_offset >> 9;
973 curlun->info_valid = 1;
976 amount -= (amount & 511);
979 /* Why were we were asked to transfer a
985 /* Get the next buffer */
986 usb_offset += amount;
987 common->usb_amount_left -= amount;
988 amount_left_to_req -= amount;
989 if (amount_left_to_req == 0)
993 * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
994 * because of the DOEPTSIZ.PKTCNT has only 10 bits
996 if((common->gadget->speed != USB_SPEED_HIGH)&&(amount >0x8000))
999 /* amount is always divisible by 512, hence by
1000 * the bulk-out maxpacket size */
1001 bh->outreq->length = amount;
1002 bh->bulk_out_intended_length = amount;
1003 bh->outreq->short_not_ok = 1;
1004 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1005 &bh->outreq_busy, &bh->state)
1006 /* Don't know what to do if
1007 * common->fsg is NULL */
1009 common->next_buffhd_to_fill = bh->next;
1013 /* Write the received data to the backing file */
1014 bh = common->next_buffhd_to_drain;
1015 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1016 break; /* We stopped early */
1017 if (bh->state == BUF_STATE_FULL) {
1019 common->next_buffhd_to_drain = bh->next;
1020 bh->state = BUF_STATE_EMPTY;
1022 /* Did something go wrong with the transfer? */
1023 if (bh->outreq->status != 0) {
1024 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1025 curlun->sense_data_info = file_offset >> 9;
1026 curlun->info_valid = 1;
1030 amount = bh->outreq->actual;
1031 if (curlun->file_length - file_offset < amount) {
1033 "write %u @ %llu beyond end %llu\n",
1034 amount, (unsigned long long) file_offset,
1035 (unsigned long long) curlun->file_length);
1036 amount = curlun->file_length - file_offset;
1039 /* Perform the write */
1040 file_offset_tmp = file_offset;
1041 nwritten = vfs_write(curlun->filp,
1042 (char __user *) bh->buf,
1043 amount, &file_offset_tmp);
1044 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1045 (unsigned long long) file_offset,
1047 if (signal_pending(current))
1048 return -EINTR; /* Interrupted! */
1051 LDBG(curlun, "error in file write: %d\n",
1054 } else if (nwritten < amount) {
1055 LDBG(curlun, "partial file write: %d/%u\n",
1056 (int) nwritten, amount);
1057 nwritten -= (nwritten & 511);
1058 /* Round down to a block */
1060 file_offset += nwritten;
1061 amount_left_to_write -= nwritten;
1062 common->residue -= nwritten;
1064 /* If an error occurred, report it and its position */
1065 if (nwritten < amount) {
1066 curlun->sense_data = SS_WRITE_ERROR;
1067 curlun->sense_data_info = file_offset >> 9;
1068 curlun->info_valid = 1;
1072 /* Did the host decide to stop early? */
1073 if (bh->outreq->actual != bh->outreq->length) {
1074 common->short_packet_received = 1;
1080 /* Wait for something to happen */
1081 rc = sleep_thread(common);
1086 return -EIO; /* No default reply */
1090 /*-------------------------------------------------------------------------*/
1092 static int do_synchronize_cache(struct fsg_common *common)
1094 struct fsg_lun *curlun = common->curlun;
1097 /* We ignore the requested LBA and write out all file's
1098 * dirty data buffers. */
1099 rc = fsg_lun_fsync_sub(curlun);
1101 curlun->sense_data = SS_WRITE_ERROR;
1106 /*-------------------------------------------------------------------------*/
1108 static void invalidate_sub(struct fsg_lun *curlun)
1110 struct file *filp = curlun->filp;
1111 struct inode *inode = filp->f_path.dentry->d_inode;
1114 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1115 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1118 static int do_verify(struct fsg_common *common)
1120 struct fsg_lun *curlun = common->curlun;
1122 u32 verification_length;
1123 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1124 loff_t file_offset, file_offset_tmp;
1126 unsigned int amount;
1129 /* Get the starting Logical Block Address and check that it's
1131 lba = get_unaligned_be32(&common->cmnd[2]);
1132 if (lba >= curlun->num_sectors) {
1133 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1137 /* We allow DPO (Disable Page Out = don't save data in the
1138 * cache) but we don't implement it. */
1139 if (common->cmnd[1] & ~0x10) {
1140 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1144 verification_length = get_unaligned_be16(&common->cmnd[7]);
1145 if (unlikely(verification_length == 0))
1146 return -EIO; /* No default reply */
1148 /* Prepare to carry out the file verify */
1149 amount_left = verification_length << 9;
1150 file_offset = ((loff_t) lba) << 9;
1152 /* Write out all the dirty buffers before invalidating them */
1153 fsg_lun_fsync_sub(curlun);
1154 if (signal_pending(current))
1157 invalidate_sub(curlun);
1158 if (signal_pending(current))
1161 /* Just try to read the requested blocks */
1162 while (amount_left > 0) {
1164 /* Figure out how much we need to read:
1165 * Try to read the remaining amount, but not more than
1167 * And don't try to read past the end of the file.
1168 * If this means reading 0 then we were asked to read
1169 * past the end of file. */
1170 amount = min(amount_left, FSG_BUFLEN);
1171 amount = min((loff_t) amount,
1172 curlun->file_length - file_offset);
1174 curlun->sense_data =
1175 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1176 curlun->sense_data_info = file_offset >> 9;
1177 curlun->info_valid = 1;
1181 /* Perform the read */
1182 file_offset_tmp = file_offset;
1183 nread = vfs_read(curlun->filp,
1184 (char __user *) bh->buf,
1185 amount, &file_offset_tmp);
1186 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1187 (unsigned long long) file_offset,
1189 if (signal_pending(current))
1193 LDBG(curlun, "error in file verify: %d\n",
1196 } else if (nread < amount) {
1197 LDBG(curlun, "partial file verify: %d/%u\n",
1198 (int) nread, amount);
1199 nread -= (nread & 511); /* Round down to a sector */
1202 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1203 curlun->sense_data_info = file_offset >> 9;
1204 curlun->info_valid = 1;
1207 file_offset += nread;
1208 amount_left -= nread;
1214 /*-------------------------------------------------------------------------*/
1216 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1218 struct fsg_lun *curlun = common->curlun;
1219 u8 *buf = (u8 *) bh->buf;
1221 if (!curlun) { /* Unsupported LUNs are okay */
1222 common->bad_lun_okay = 1;
1224 buf[0] = 0x7f; /* Unsupported, no device-type */
1225 buf[4] = 31; /* Additional length */
1229 buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1230 buf[1] = curlun->removable ? 0x80 : 0;
1231 buf[2] = 2; /* ANSI SCSI level 2 */
1232 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1233 buf[4] = 31; /* Additional length */
1234 buf[5] = 0; /* No special options */
1237 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1242 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1244 struct fsg_lun *curlun = common->curlun;
1245 u8 *buf = (u8 *) bh->buf;
1250 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1252 * If a REQUEST SENSE command is received from an initiator
1253 * with a pending unit attention condition (before the target
1254 * generates the contingent allegiance condition), then the
1255 * target shall either:
1256 * a) report any pending sense data and preserve the unit
1257 * attention condition on the logical unit, or,
1258 * b) report the unit attention condition, may discard any
1259 * pending sense data, and clear the unit attention
1260 * condition on the logical unit for that initiator.
1262 * FSG normally uses option a); enable this code to use option b).
1265 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1266 curlun->sense_data = curlun->unit_attention_data;
1267 curlun->unit_attention_data = SS_NO_SENSE;
1271 if (!curlun) { /* Unsupported LUNs are okay */
1272 common->bad_lun_okay = 1;
1273 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1277 sd = curlun->sense_data;
1278 sdinfo = curlun->sense_data_info;
1279 valid = curlun->info_valid << 7;
1280 curlun->sense_data = SS_NO_SENSE;
1281 curlun->sense_data_info = 0;
1282 curlun->info_valid = 0;
1286 buf[0] = valid | 0x70; /* Valid, current error */
1288 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1289 buf[7] = 18 - 8; /* Additional sense length */
1296 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1298 struct fsg_lun *curlun = common->curlun;
1299 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1300 int pmi = common->cmnd[8];
1301 u8 *buf = (u8 *) bh->buf;
1303 /* Check the PMI and LBA fields */
1304 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1305 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1309 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1310 /* Max logical block */
1311 put_unaligned_be32(512, &buf[4]); /* Block length */
1316 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1318 struct fsg_lun *curlun = common->curlun;
1319 int msf = common->cmnd[1] & 0x02;
1320 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1321 u8 *buf = (u8 *) bh->buf;
1323 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1324 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1327 if (lba >= curlun->num_sectors) {
1328 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1333 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1334 store_cdrom_address(&buf[4], msf, lba);
1339 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1341 struct fsg_lun *curlun = common->curlun;
1342 int msf = common->cmnd[1] & 0x02;
1343 int start_track = common->cmnd[6];
1344 u8 *buf = (u8 *) bh->buf;
1346 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1348 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1353 buf[1] = (20-2); /* TOC data length */
1354 buf[2] = 1; /* First track number */
1355 buf[3] = 1; /* Last track number */
1356 buf[5] = 0x16; /* Data track, copying allowed */
1357 buf[6] = 0x01; /* Only track is number 1 */
1358 store_cdrom_address(&buf[8], msf, 0);
1360 buf[13] = 0x16; /* Lead-out track is data */
1361 buf[14] = 0xAA; /* Lead-out track number */
1362 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1367 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1369 struct fsg_lun *curlun = common->curlun;
1370 int mscmnd = common->cmnd[0];
1371 u8 *buf = (u8 *) bh->buf;
1374 int changeable_values, all_pages;
1378 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1379 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1382 pc = common->cmnd[2] >> 6;
1383 page_code = common->cmnd[2] & 0x3f;
1385 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1388 changeable_values = (pc == 1);
1389 all_pages = (page_code == 0x3f);
1391 /* Write the mode parameter header. Fixed values are: default
1392 * medium type, no cache control (DPOFUA), and no block descriptors.
1393 * The only variable value is the WriteProtect bit. We will fill in
1394 * the mode data length later. */
1396 if (mscmnd == SC_MODE_SENSE_6) {
1397 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1400 } else { /* SC_MODE_SENSE_10 */
1401 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1403 limit = 65535; /* Should really be FSG_BUFLEN */
1406 /* No block descriptors */
1408 /* The mode pages, in numerical order. The only page we support
1409 * is the Caching page. */
1410 if (page_code == 0x08 || all_pages) {
1412 buf[0] = 0x08; /* Page code */
1413 buf[1] = 10; /* Page length */
1414 memset(buf+2, 0, 10); /* None of the fields are changeable */
1416 if (!changeable_values) {
1417 buf[2] = 0x04; /* Write cache enable, */
1418 /* Read cache not disabled */
1419 /* No cache retention priorities */
1420 put_unaligned_be16(0xffff, &buf[4]);
1421 /* Don't disable prefetch */
1422 /* Minimum prefetch = 0 */
1423 put_unaligned_be16(0xffff, &buf[8]);
1424 /* Maximum prefetch */
1425 put_unaligned_be16(0xffff, &buf[10]);
1426 /* Maximum prefetch ceiling */
1431 /* Check that a valid page was requested and the mode data length
1432 * isn't too long. */
1434 if (!valid_page || len > limit) {
1435 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1439 /* Store the mode data length */
1440 if (mscmnd == SC_MODE_SENSE_6)
1443 put_unaligned_be16(len - 2, buf0);
1448 static int do_start_stop(struct fsg_common *common)
1450 struct fsg_lun *curlun = common->curlun;
1455 } else if (!curlun->removable) {
1456 curlun->sense_data = SS_INVALID_COMMAND;
1458 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1459 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1460 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1464 loej = common->cmnd[4] & 0x02;
1465 start = common->cmnd[4] & 0x01;
1467 /* Our emulation doesn't support mounting; the medium is
1468 * available for use as soon as it is loaded. */
1470 if (!fsg_lun_is_open(curlun)) {
1471 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1477 /* Are we allowed to unload the media? */
1478 if (curlun->prevent_medium_removal) {
1479 LDBG(curlun, "unload attempt prevented\n");
1480 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1487 /* Simulate an unload/eject */
1488 if (common->ops && common->ops->pre_eject) {
1489 int r = common->ops->pre_eject(common, curlun,
1490 curlun - common->luns);
1491 if (unlikely(r < 0))
1497 up_read(&common->filesem);
1498 down_write(&common->filesem);
1499 fsg_lun_close(curlun);
1500 up_write(&common->filesem);
1501 down_read(&common->filesem);
1503 return common->ops && common->ops->post_eject
1504 ? min(0, common->ops->post_eject(common, curlun,
1505 curlun - common->luns))
1510 static int do_prevent_allow(struct fsg_common *common)
1512 struct fsg_lun *curlun = common->curlun;
1515 if (!common->curlun) {
1517 } else if (!common->curlun->removable) {
1518 common->curlun->sense_data = SS_INVALID_COMMAND;
1522 prevent = common->cmnd[4] & 0x01;
1523 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1524 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1528 if (curlun->prevent_medium_removal && !prevent)
1529 fsg_lun_fsync_sub(curlun);
1530 curlun->prevent_medium_removal = prevent;
1535 static int do_read_format_capacities(struct fsg_common *common,
1536 struct fsg_buffhd *bh)
1538 struct fsg_lun *curlun = common->curlun;
1539 u8 *buf = (u8 *) bh->buf;
1541 buf[0] = buf[1] = buf[2] = 0;
1542 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1545 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1546 /* Number of blocks */
1547 put_unaligned_be32(512, &buf[4]); /* Block length */
1548 buf[4] = 0x02; /* Current capacity */
1553 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1555 struct fsg_lun *curlun = common->curlun;
1557 /* We don't support MODE SELECT */
1559 curlun->sense_data = SS_INVALID_COMMAND;
1564 /*-------------------------------------------------------------------------*/
1566 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1570 rc = fsg_set_halt(fsg, fsg->bulk_in);
1572 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1574 if (rc != -EAGAIN) {
1575 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1580 /* Wait for a short time and then try again */
1581 if (msleep_interruptible(100) != 0)
1583 rc = usb_ep_set_halt(fsg->bulk_in);
1588 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1592 DBG(fsg, "bulk-in set wedge\n");
1593 rc = usb_ep_set_wedge(fsg->bulk_in);
1595 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1597 if (rc != -EAGAIN) {
1598 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1603 /* Wait for a short time and then try again */
1604 if (msleep_interruptible(100) != 0)
1606 rc = usb_ep_set_wedge(fsg->bulk_in);
1611 static int pad_with_zeros(struct fsg_dev *fsg)
1613 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1614 u32 nkeep = bh->inreq->length;
1618 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1619 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1620 while (fsg->common->usb_amount_left > 0) {
1622 /* Wait for the next buffer to be free */
1623 while (bh->state != BUF_STATE_EMPTY) {
1624 rc = sleep_thread(fsg->common);
1629 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1630 memset(bh->buf + nkeep, 0, nsend - nkeep);
1631 bh->inreq->length = nsend;
1632 bh->inreq->zero = 0;
1633 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1634 &bh->inreq_busy, &bh->state);
1635 bh = fsg->common->next_buffhd_to_fill = bh->next;
1636 fsg->common->usb_amount_left -= nsend;
1642 static int throw_away_data(struct fsg_common *common)
1644 struct fsg_buffhd *bh;
1648 for (bh = common->next_buffhd_to_drain;
1649 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1650 bh = common->next_buffhd_to_drain) {
1652 /* Throw away the data in a filled buffer */
1653 if (bh->state == BUF_STATE_FULL) {
1655 bh->state = BUF_STATE_EMPTY;
1656 common->next_buffhd_to_drain = bh->next;
1658 /* A short packet or an error ends everything */
1659 if (bh->outreq->actual != bh->outreq->length ||
1660 bh->outreq->status != 0) {
1661 raise_exception(common,
1662 FSG_STATE_ABORT_BULK_OUT);
1668 /* Try to submit another request if we need one */
1669 bh = common->next_buffhd_to_fill;
1670 if (bh->state == BUF_STATE_EMPTY
1671 && common->usb_amount_left > 0) {
1672 amount = min(common->usb_amount_left, FSG_BUFLEN);
1674 /* amount is always divisible by 512, hence by
1675 * the bulk-out maxpacket size */
1676 bh->outreq->length = amount;
1677 bh->bulk_out_intended_length = amount;
1678 bh->outreq->short_not_ok = 1;
1679 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1680 &bh->outreq_busy, &bh->state)
1681 /* Don't know what to do if
1682 * common->fsg is NULL */
1684 common->next_buffhd_to_fill = bh->next;
1685 common->usb_amount_left -= amount;
1689 /* Otherwise wait for something to happen */
1690 rc = sleep_thread(common);
1698 static int finish_reply(struct fsg_common *common)
1700 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1703 switch (common->data_dir) {
1705 break; /* Nothing to send */
1707 /* If we don't know whether the host wants to read or write,
1708 * this must be CB or CBI with an unknown command. We mustn't
1709 * try to send or receive any data. So stall both bulk pipes
1710 * if we can and wait for a reset. */
1711 case DATA_DIR_UNKNOWN:
1712 if (!common->can_stall) {
1714 } else if (fsg_is_set(common)) {
1715 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1716 rc = halt_bulk_in_endpoint(common->fsg);
1718 /* Don't know what to do if common->fsg is NULL */
1723 /* All but the last buffer of data must have already been sent */
1724 case DATA_DIR_TO_HOST:
1725 if (common->data_size == 0) {
1726 /* Nothing to send */
1728 /* If there's no residue, simply send the last buffer */
1729 } else if (common->residue == 0) {
1730 bh->inreq->zero = 0;
1731 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1732 &bh->inreq_busy, &bh->state)
1734 common->next_buffhd_to_fill = bh->next;
1736 /* For Bulk-only, if we're allowed to stall then send the
1737 * short packet and halt the bulk-in endpoint. If we can't
1738 * stall, pad out the remaining data with 0's. */
1739 } else if (common->can_stall) {
1740 bh->inreq->zero = 1;
1741 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1742 &bh->inreq_busy, &bh->state)
1743 /* Don't know what to do if
1744 * common->fsg is NULL */
1746 common->next_buffhd_to_fill = bh->next;
1748 rc = halt_bulk_in_endpoint(common->fsg);
1749 } else if (fsg_is_set(common)) {
1750 rc = pad_with_zeros(common->fsg);
1752 /* Don't know what to do if common->fsg is NULL */
1757 /* We have processed all we want from the data the host has sent.
1758 * There may still be outstanding bulk-out requests. */
1759 case DATA_DIR_FROM_HOST:
1760 if (common->residue == 0) {
1761 /* Nothing to receive */
1763 /* Did the host stop sending unexpectedly early? */
1764 } else if (common->short_packet_received) {
1765 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1768 /* We haven't processed all the incoming data. Even though
1769 * we may be allowed to stall, doing so would cause a race.
1770 * The controller may already have ACK'ed all the remaining
1771 * bulk-out packets, in which case the host wouldn't see a
1772 * STALL. Not realizing the endpoint was halted, it wouldn't
1773 * clear the halt -- leading to problems later on. */
1775 } else if (common->can_stall) {
1776 if (fsg_is_set(common))
1777 fsg_set_halt(common->fsg,
1778 common->fsg->bulk_out);
1779 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1783 /* We can't stall. Read in the excess data and throw it
1786 rc = throw_away_data(common);
1794 static int send_status(struct fsg_common *common)
1796 struct fsg_lun *curlun = common->curlun;
1797 struct fsg_buffhd *bh;
1798 struct bulk_cs_wrap *csw;
1800 u8 status = USB_STATUS_PASS;
1803 /* Wait for the next buffer to become available */
1804 bh = common->next_buffhd_to_fill;
1805 while (bh->state != BUF_STATE_EMPTY) {
1806 rc = sleep_thread(common);
1812 sd = curlun->sense_data;
1813 sdinfo = curlun->sense_data_info;
1814 } else if (common->bad_lun_okay)
1817 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1819 if (common->phase_error) {
1820 DBG(common, "sending phase-error status\n");
1821 status = USB_STATUS_PHASE_ERROR;
1822 sd = SS_INVALID_COMMAND;
1823 } else if (sd != SS_NO_SENSE) {
1824 DBG(common, "sending command-failure status\n");
1825 status = USB_STATUS_FAIL;
1826 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1828 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1831 /* Store and send the Bulk-only CSW */
1832 csw = (void *)bh->buf;
1834 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1835 csw->Tag = common->tag;
1836 csw->Residue = cpu_to_le32(common->residue);
1837 csw->Status = status;
1839 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1840 bh->inreq->zero = 0;
1841 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1842 &bh->inreq_busy, &bh->state)
1843 /* Don't know what to do if common->fsg is NULL */
1846 common->next_buffhd_to_fill = bh->next;
1851 /*-------------------------------------------------------------------------*/
1853 /* Check whether the command is properly formed and whether its data size
1854 * and direction agree with the values we already have. */
1855 static int check_command(struct fsg_common *common, int cmnd_size,
1856 enum data_direction data_dir, unsigned int mask,
1857 int needs_medium, const char *name)
1860 int lun = common->cmnd[1] >> 5;
1861 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1863 struct fsg_lun *curlun;
1866 if (common->data_dir != DATA_DIR_UNKNOWN)
1867 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1869 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1870 name, cmnd_size, dirletter[(int) data_dir],
1871 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1873 /* We can't reply at all until we know the correct data direction
1875 if (common->data_size_from_cmnd == 0)
1876 data_dir = DATA_DIR_NONE;
1877 if (common->data_size < common->data_size_from_cmnd) {
1878 /* Host data size < Device data size is a phase error.
1879 * Carry out the command, but only transfer as much as
1880 * we are allowed. */
1881 common->data_size_from_cmnd = common->data_size;
1882 common->phase_error = 1;
1884 common->residue = common->data_size;
1885 common->usb_amount_left = common->data_size;
1887 /* Conflicting data directions is a phase error */
1888 if (common->data_dir != data_dir
1889 && common->data_size_from_cmnd > 0) {
1890 common->phase_error = 1;
1894 /* Verify the length of the command itself */
1895 if (cmnd_size != common->cmnd_size) {
1897 /* Special case workaround: There are plenty of buggy SCSI
1898 * implementations. Many have issues with cbw->Length
1899 * field passing a wrong command size. For those cases we
1900 * always try to work around the problem by using the length
1901 * sent by the host side provided it is at least as large
1902 * as the correct command length.
1903 * Examples of such cases would be MS-Windows, which issues
1904 * REQUEST SENSE with cbw->Length == 12 where it should
1905 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1906 * REQUEST SENSE with cbw->Length == 10 where it should
1909 if (cmnd_size <= common->cmnd_size) {
1910 DBG(common, "%s is buggy! Expected length %d "
1911 "but we got %d\n", name,
1912 cmnd_size, common->cmnd_size);
1913 cmnd_size = common->cmnd_size;
1915 common->phase_error = 1;
1920 /* Check that the LUN values are consistent */
1921 if (common->lun != lun)
1922 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1926 if (common->lun >= 0 && common->lun < common->nluns) {
1927 curlun = &common->luns[common->lun];
1928 common->curlun = curlun;
1929 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1930 curlun->sense_data = SS_NO_SENSE;
1931 curlun->sense_data_info = 0;
1932 curlun->info_valid = 0;
1935 common->curlun = NULL;
1937 common->bad_lun_okay = 0;
1939 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1940 * to use unsupported LUNs; all others may not. */
1941 if (common->cmnd[0] != SC_INQUIRY &&
1942 common->cmnd[0] != SC_REQUEST_SENSE) {
1943 DBG(common, "unsupported LUN %d\n", common->lun);
1948 /* If a unit attention condition exists, only INQUIRY and
1949 * REQUEST SENSE commands are allowed; anything else must fail. */
1950 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1951 common->cmnd[0] != SC_INQUIRY &&
1952 common->cmnd[0] != SC_REQUEST_SENSE) {
1953 curlun->sense_data = curlun->unit_attention_data;
1954 curlun->unit_attention_data = SS_NO_SENSE;
1958 /* Check that only command bytes listed in the mask are non-zero */
1959 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1960 for (i = 1; i < cmnd_size; ++i) {
1961 if (common->cmnd[i] && !(mask & (1 << i))) {
1963 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1968 /* If the medium isn't mounted and the command needs to access
1969 * it, return an error. */
1970 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1971 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1979 #ifdef CONFIG_ARCH_RK29
1980 static void deferred_restart(struct work_struct *dummy)
1983 kernel_restart("loader");
1985 static DECLARE_WORK(restart_work, deferred_restart);
1987 typedef struct tagLoaderParam
1994 #define PARM_TAG 0x4D524150
1995 #define MSC_EXT_DBG 1
1996 extern int GetParamterInfo(char * pbuf , int len);
1998 /* the buf is bh->buf,it is large enough. */
1999 static char * get_param_tag( char* buf , const char* tag )
2005 i = GetParamterInfo( pp , 1024 );
2006 pi = (PARM_INFO*)pp;
2007 if( pi->tag != PARM_TAG ){
2009 printk("paramter error,tag=0x%x\n" , pi->tag );
2012 if( pi->length+sizeof(PARM_INFO) > i ) {
2013 GetParamterInfo( pp , pi->length+sizeof(PARM_INFO) + 511 );
2015 pp = strstr( pi->parameter , tag );
2016 if( !pp ) goto error_out;
2017 pp += strlen(tag); // sizeof "MACHINE_MODEL:"
2018 while( *pp == ' ' || *pp == '\t' ) {
2019 if(pp - pi->parameter >= pi->length)
2024 while( *pp != 0x0d && *pp != 0x0a ) {
2025 if(pp - pi->parameter >= pi->length)
2030 if( spp == pp ) return NULL;
2034 static int do_get_product_name(int ret ,char *buf)
2036 char *tag = "MACHINE_MODEL:";
2040 if( buf == NULL ) buf = tbuf;
2042 memset( buf , 0 , ret );
2043 pname = get_param_tag( buf , tag );
2045 strcpy( buf , pname);
2048 printk("%s%s\n" , tag , buf );
2053 static int do_get_versions( int ret ,char* buf )
2055 /* get boot version and fireware version from cmdline
2056 * bootver=2010-07-08#4.02 firmware_ver=1.0.0 // Firmware Ver:16.01.0000
2057 * return format: 0x02 0x04 0x00 0x00 0x00 0x01
2058 * RK29: bootver=2011-07-18#2.05 firmware_ver=0.2.3 (==00.02.0003)
2059 * for the old loader,the firmware_ver may be empty,so get the fw ver from paramter.
2061 #define ASC_BCD0( c ) (((c-'0'))&0xf)
2062 #define ASC_BCD1( c ) (((c-'0')<<4)&0xf0)
2066 char *l_tag = "bootver=";
2067 char *fw_tag = "FIRMWARE_VER:";
2071 if( ver == NULL ) ver = tbuf;
2074 memset( ver , 0x00 , ret );
2075 p_l = strstr( saved_command_line , l_tag );
2079 p_l+=strlen( l_tag );
2080 if( (p_l = strchr( p_l,'#')) ) {
2082 if( p_l[1] == '.' ) {
2083 ver[1] = ASC_BCD0(p_l[0]);
2086 ver[1] = ASC_BCD1(p_l[0])|ASC_BCD0(p_l[1]);
2089 ver[0] = ASC_BCD1(p_l[0])|ASC_BCD0(p_l[1]);
2092 p_f = get_param_tag( ver , fw_tag );
2093 if( !p_f ) return ret;
2095 if( p_f[1] == '.' ) {
2096 ver[5] = ASC_BCD0(p_f[0]);
2099 ver[5] = ASC_BCD1(p_f[0])|ASC_BCD0(p_f[1]);
2102 if( p_f[1] == '.' ) {
2103 ver[4] = ASC_BCD0(p_f[0]);
2106 ver[4] = ASC_BCD1(p_f[0])|ASC_BCD0(p_f[1]);
2109 ver[2] = ASC_BCD0(p_f[0]);
2111 if( p_f[0] != ' ' ){
2112 ver[2] |= ASC_BCD1(p_f[0]);
2115 // only support 2 byte version.
2119 printk("VERSION:%02x %02x %02x %02x %02x %02x\n" ,
2120 ver[0],ver[1],ver[2],ver[3],ver[4],ver[5]);
2126 static int do_scsi_command(struct fsg_common *common)
2128 struct fsg_buffhd *bh;
2130 int reply = -EINVAL;
2132 static char unknown[16];
2133 #ifdef CONFIG_ARCH_RK29
2134 struct fsg_common *fsg = common;
2139 /* Wait for the next buffer to become available for data or status */
2140 bh = common->next_buffhd_to_fill;
2141 common->next_buffhd_to_drain = bh;
2142 while (bh->state != BUF_STATE_EMPTY) {
2143 rc = sleep_thread(common);
2147 common->phase_error = 0;
2148 common->short_packet_received = 0;
2150 down_read(&common->filesem); /* We're using the backing file */
2151 switch (common->cmnd[0]) {
2154 common->data_size_from_cmnd = common->cmnd[4];
2155 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2159 reply = do_inquiry(common, bh);
2162 case SC_MODE_SELECT_6:
2163 common->data_size_from_cmnd = common->cmnd[4];
2164 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2168 reply = do_mode_select(common, bh);
2171 case SC_MODE_SELECT_10:
2172 common->data_size_from_cmnd =
2173 get_unaligned_be16(&common->cmnd[7]);
2174 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2178 reply = do_mode_select(common, bh);
2181 case SC_MODE_SENSE_6:
2182 common->data_size_from_cmnd = common->cmnd[4];
2183 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2184 (1<<1) | (1<<2) | (1<<4), 0,
2187 reply = do_mode_sense(common, bh);
2190 case SC_MODE_SENSE_10:
2191 common->data_size_from_cmnd =
2192 get_unaligned_be16(&common->cmnd[7]);
2193 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2194 (1<<1) | (1<<2) | (3<<7), 0,
2197 reply = do_mode_sense(common, bh);
2200 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2201 common->data_size_from_cmnd = 0;
2202 reply = check_command(common, 6, DATA_DIR_NONE,
2204 "PREVENT-ALLOW MEDIUM REMOVAL");
2206 reply = do_prevent_allow(common);
2210 i = common->cmnd[4];
2211 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2212 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2216 reply = do_read(common);
2220 common->data_size_from_cmnd =
2221 get_unaligned_be16(&common->cmnd[7]) << 9;
2222 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2223 (1<<1) | (0xf<<2) | (3<<7), 1,
2226 reply = do_read(common);
2230 common->data_size_from_cmnd =
2231 get_unaligned_be32(&common->cmnd[6]) << 9;
2232 reply = check_command(common, 12, DATA_DIR_TO_HOST,
2233 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2236 reply = do_read(common);
2239 case SC_READ_CAPACITY:
2240 common->data_size_from_cmnd = 8;
2241 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2242 (0xf<<2) | (1<<8), 1,
2245 reply = do_read_capacity(common, bh);
2248 case SC_READ_HEADER:
2249 if (!common->curlun || !common->curlun->cdrom)
2251 common->data_size_from_cmnd =
2252 get_unaligned_be16(&common->cmnd[7]);
2253 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2254 (3<<7) | (0x1f<<1), 1,
2257 reply = do_read_header(common, bh);
2261 if (!common->curlun || !common->curlun->cdrom)
2263 common->data_size_from_cmnd =
2264 get_unaligned_be16(&common->cmnd[7]);
2265 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2269 reply = do_read_toc(common, bh);
2272 case SC_READ_FORMAT_CAPACITIES:
2273 common->data_size_from_cmnd =
2274 get_unaligned_be16(&common->cmnd[7]);
2275 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2277 "READ FORMAT CAPACITIES");
2279 reply = do_read_format_capacities(common, bh);
2282 case SC_REQUEST_SENSE:
2283 common->data_size_from_cmnd = common->cmnd[4];
2284 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2288 reply = do_request_sense(common, bh);
2291 case SC_START_STOP_UNIT:
2292 common->data_size_from_cmnd = 0;
2293 reply = check_command(common, 6, DATA_DIR_NONE,
2297 reply = do_start_stop(common);
2300 case SC_SYNCHRONIZE_CACHE:
2301 common->data_size_from_cmnd = 0;
2302 reply = check_command(common, 10, DATA_DIR_NONE,
2303 (0xf<<2) | (3<<7), 1,
2304 "SYNCHRONIZE CACHE");
2306 reply = do_synchronize_cache(common);
2309 case SC_TEST_UNIT_READY:
2310 common->data_size_from_cmnd = 0;
2311 reply = check_command(common, 6, DATA_DIR_NONE,
2316 /* Although optional, this command is used by MS-Windows. We
2317 * support a minimal version: BytChk must be 0. */
2319 common->data_size_from_cmnd = 0;
2320 reply = check_command(common, 10, DATA_DIR_NONE,
2321 (1<<1) | (0xf<<2) | (3<<7), 1,
2324 #ifdef CONFIG_ARCH_RK29
2325 reply = 0; //zyf 20100302
2327 reply = do_verify(common);
2332 i = common->cmnd[4];
2333 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2334 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2338 reply = do_write(common);
2342 common->data_size_from_cmnd =
2343 get_unaligned_be16(&common->cmnd[7]) << 9;
2344 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2345 (1<<1) | (0xf<<2) | (3<<7), 1,
2348 reply = do_write(common);
2352 common->data_size_from_cmnd =
2353 get_unaligned_be32(&common->cmnd[6]) << 9;
2354 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2355 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2358 reply = do_write(common);
2361 /* Some mandatory commands that we recognize but don't implement.
2362 * They don't mean much in this setting. It's left as an exercise
2363 * for anyone interested to implement RESERVE and RELEASE in terms
2364 * of Posix locks. */
2365 case SC_FORMAT_UNIT:
2368 case SC_SEND_DIAGNOSTIC:
2373 common->data_size_from_cmnd = 0;
2374 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2375 reply = check_command(common, common->cmnd_size,
2376 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2378 common->curlun->sense_data = SS_INVALID_COMMAND;
2382 #ifdef CONFIG_ARCH_RK29
2384 if( fsg->cmnd[1] != 0xe0 ||
2385 fsg->cmnd[2] != 0xff || fsg->cmnd[3] != 0xff ||
2386 fsg->cmnd[4] != 0xff )
2388 if (fsg->cmnd_size >= 6 && fsg->cmnd[5] == 0xfe) {
2389 schedule_work(&restart_work);
2391 else if ( fsg->cmnd[5] == 0xf3 ) {
2392 fsg->data_size_from_cmnd = fsg->data_size;
2393 /* get product name from parameter section */
2394 reply = do_get_product_name( fsg->data_size,bh->buf );
2396 else if ( fsg->cmnd[5] == 0xff ){
2397 fsg->data_size_from_cmnd = fsg->data_size;
2398 reply = do_get_versions( fsg->data_size,bh->buf );
2403 up_read(&common->filesem);
2405 if (reply == -EINTR || signal_pending(current))
2408 /* Set up the single reply buffer for finish_reply() */
2409 if (reply == -EINVAL)
2410 reply = 0; /* Error reply length */
2411 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2412 reply = min((u32) reply, common->data_size_from_cmnd);
2413 bh->inreq->length = reply;
2414 bh->state = BUF_STATE_FULL;
2415 common->residue -= reply;
2416 } /* Otherwise it's already set */
2422 /*-------------------------------------------------------------------------*/
2424 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2426 struct usb_request *req = bh->outreq;
2427 struct fsg_bulk_cb_wrap *cbw = req->buf;
2428 struct fsg_common *common = fsg->common;
2430 /* Was this a real packet? Should it be ignored? */
2431 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2434 /* Is the CBW valid? */
2435 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2436 cbw->Signature != cpu_to_le32(
2438 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2440 le32_to_cpu(cbw->Signature));
2442 /* The Bulk-only spec says we MUST stall the IN endpoint
2443 * (6.6.1), so it's unavoidable. It also says we must
2444 * retain this state until the next reset, but there's
2445 * no way to tell the controller driver it should ignore
2446 * Clear-Feature(HALT) requests.
2448 * We aren't required to halt the OUT endpoint; instead
2449 * we can simply accept and discard any data received
2450 * until the next reset. */
2451 wedge_bulk_in_endpoint(fsg);
2452 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2456 /* Is the CBW meaningful? */
2457 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2458 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2459 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2461 cbw->Lun, cbw->Flags, cbw->Length);
2463 /* We can do anything we want here, so let's stall the
2464 * bulk pipes if we are allowed to. */
2465 if (common->can_stall) {
2466 fsg_set_halt(fsg, fsg->bulk_out);
2467 halt_bulk_in_endpoint(fsg);
2472 /* Save the command for later */
2473 common->cmnd_size = cbw->Length;
2474 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2475 if (cbw->Flags & USB_BULK_IN_FLAG)
2476 common->data_dir = DATA_DIR_TO_HOST;
2478 common->data_dir = DATA_DIR_FROM_HOST;
2479 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2480 if (common->data_size == 0)
2481 common->data_dir = DATA_DIR_NONE;
2482 common->lun = cbw->Lun;
2483 common->tag = cbw->Tag;
2488 static int get_next_command(struct fsg_common *common)
2490 struct fsg_buffhd *bh;
2493 /* Wait for the next buffer to become available */
2494 bh = common->next_buffhd_to_fill;
2495 while (bh->state != BUF_STATE_EMPTY) {
2496 rc = sleep_thread(common);
2501 /* Queue a request to read a Bulk-only CBW */
2502 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2503 bh->outreq->short_not_ok = 1;
2504 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2505 &bh->outreq_busy, &bh->state)
2506 /* Don't know what to do if common->fsg is NULL */
2509 /* We will drain the buffer in software, which means we
2510 * can reuse it for the next filling. No need to advance
2511 * next_buffhd_to_fill. */
2513 /* Wait for the CBW to arrive */
2514 while (bh->state != BUF_STATE_FULL) {
2515 rc = sleep_thread(common);
2520 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2521 bh->state = BUF_STATE_EMPTY;
2527 /*-------------------------------------------------------------------------*/
2529 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2530 const struct usb_endpoint_descriptor *d)
2534 ep->driver_data = common;
2535 rc = usb_ep_enable(ep, d);
2537 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2541 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2542 struct usb_request **preq)
2544 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2547 ERROR(common, "can't allocate request for %s\n", ep->name);
2551 /* Reset interface setting and re-init endpoint state (toggle etc). */
2552 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2554 const struct usb_endpoint_descriptor *d;
2555 struct fsg_dev *fsg;
2558 if (common->running)
2559 DBG(common, "reset interface\n");
2562 /* Deallocate the requests */
2566 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2567 struct fsg_buffhd *bh = &common->buffhds[i];
2570 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2574 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2579 /* Disable the endpoints */
2580 if (fsg->bulk_in_enabled) {
2581 usb_ep_disable(fsg->bulk_in);
2582 fsg->bulk_in_enabled = 0;
2584 if (fsg->bulk_out_enabled) {
2585 usb_ep_disable(fsg->bulk_out);
2586 fsg->bulk_out_enabled = 0;
2590 wake_up(&common->fsg_wait);
2593 common->running = 0;
2597 common->fsg = new_fsg;
2600 /* Enable the endpoints */
2601 d = fsg_ep_desc(common->gadget,
2602 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2603 rc = enable_endpoint(common, fsg->bulk_in, d);
2606 fsg->bulk_in_enabled = 1;
2608 d = fsg_ep_desc(common->gadget,
2609 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2610 rc = enable_endpoint(common, fsg->bulk_out, d);
2613 fsg->bulk_out_enabled = 1;
2614 common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2615 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2617 /* Allocate the requests */
2618 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2619 struct fsg_buffhd *bh = &common->buffhds[i];
2621 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2624 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2627 bh->inreq->buf = bh->outreq->buf = bh->buf;
2628 bh->inreq->context = bh->outreq->context = bh;
2629 bh->inreq->complete = bulk_in_complete;
2630 bh->outreq->complete = bulk_out_complete;
2633 common->running = 1;
2634 for (i = 0; i < common->nluns; ++i)
2635 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2640 /****************************** ALT CONFIGS ******************************/
2643 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2645 struct fsg_dev *fsg = fsg_from_func(f);
2646 fsg->common->new_fsg = fsg;
2647 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2651 static void fsg_disable(struct usb_function *f)
2653 struct fsg_dev *fsg = fsg_from_func(f);
2654 fsg->common->new_fsg = NULL;
2655 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2657 set_msc_connect_flag(0);
2661 /*-------------------------------------------------------------------------*/
2663 static void handle_exception(struct fsg_common *common)
2667 struct fsg_buffhd *bh;
2668 enum fsg_state old_state;
2669 struct fsg_lun *curlun;
2670 unsigned int exception_req_tag;
2672 /* Clear the existing signals. Anything but SIGUSR1 is converted
2673 * into a high-priority EXIT exception. */
2676 dequeue_signal_lock(current, ¤t->blocked, &info);
2679 if (sig != SIGUSR1) {
2680 if (common->state < FSG_STATE_EXIT)
2681 DBG(common, "Main thread exiting on signal\n");
2682 raise_exception(common, FSG_STATE_EXIT);
2686 /* Cancel all the pending transfers */
2687 if (likely(common->fsg)) {
2688 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2689 bh = &common->buffhds[i];
2691 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2692 if (bh->outreq_busy)
2693 usb_ep_dequeue(common->fsg->bulk_out,
2697 /* Wait until everything is idle */
2700 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2701 bh = &common->buffhds[i];
2702 num_active += bh->inreq_busy + bh->outreq_busy;
2704 if (num_active == 0)
2706 if (sleep_thread(common))
2710 /* Clear out the controller's fifos */
2711 if (common->fsg->bulk_in_enabled)
2712 usb_ep_fifo_flush(common->fsg->bulk_in);
2713 if (common->fsg->bulk_out_enabled)
2714 usb_ep_fifo_flush(common->fsg->bulk_out);
2717 /* Reset the I/O buffer states and pointers, the SCSI
2718 * state, and the exception. Then invoke the handler. */
2719 spin_lock_irq(&common->lock);
2721 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2722 bh = &common->buffhds[i];
2723 bh->state = BUF_STATE_EMPTY;
2725 common->next_buffhd_to_fill = &common->buffhds[0];
2726 common->next_buffhd_to_drain = &common->buffhds[0];
2727 exception_req_tag = common->exception_req_tag;
2728 old_state = common->state;
2730 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2731 common->state = FSG_STATE_STATUS_PHASE;
2733 for (i = 0; i < common->nluns; ++i) {
2734 curlun = &common->luns[i];
2735 curlun->prevent_medium_removal = 0;
2736 curlun->sense_data = SS_NO_SENSE;
2737 curlun->unit_attention_data = SS_NO_SENSE;
2738 curlun->sense_data_info = 0;
2739 curlun->info_valid = 0;
2741 common->state = FSG_STATE_IDLE;
2743 spin_unlock_irq(&common->lock);
2745 /* Carry out any extra actions required for the exception */
2746 switch (old_state) {
2747 case FSG_STATE_ABORT_BULK_OUT:
2748 send_status(common);
2749 spin_lock_irq(&common->lock);
2750 if (common->state == FSG_STATE_STATUS_PHASE)
2751 common->state = FSG_STATE_IDLE;
2752 spin_unlock_irq(&common->lock);
2755 case FSG_STATE_RESET:
2756 /* In case we were forced against our will to halt a
2757 * bulk endpoint, clear the halt now. (The SuperH UDC
2758 * requires this.) */
2759 if (!fsg_is_set(common))
2761 if (test_and_clear_bit(IGNORE_BULK_OUT,
2762 &common->fsg->atomic_bitflags))
2763 usb_ep_clear_halt(common->fsg->bulk_in);
2765 if (common->ep0_req_tag == exception_req_tag)
2766 ep0_queue(common); /* Complete the status stage */
2768 /* Technically this should go here, but it would only be
2769 * a waste of time. Ditto for the INTERFACE_CHANGE and
2770 * CONFIG_CHANGE cases. */
2771 /* for (i = 0; i < common->nluns; ++i) */
2772 /* common->luns[i].unit_attention_data = */
2773 /* SS_RESET_OCCURRED; */
2776 case FSG_STATE_CONFIG_CHANGE:
2777 do_set_interface(common, common->new_fsg);
2780 case FSG_STATE_EXIT:
2781 case FSG_STATE_TERMINATED:
2782 do_set_interface(common, NULL); /* Free resources */
2783 spin_lock_irq(&common->lock);
2784 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2785 spin_unlock_irq(&common->lock);
2788 case FSG_STATE_INTERFACE_CHANGE:
2789 case FSG_STATE_DISCONNECT:
2790 case FSG_STATE_COMMAND_PHASE:
2791 case FSG_STATE_DATA_PHASE:
2792 case FSG_STATE_STATUS_PHASE:
2793 case FSG_STATE_IDLE:
2799 /*-------------------------------------------------------------------------*/
2801 static int fsg_main_thread(void *common_)
2803 struct fsg_common *common = common_;
2805 /* Allow the thread to be killed by a signal, but set the signal mask
2806 * to block everything but INT, TERM, KILL, and USR1. */
2807 allow_signal(SIGINT);
2808 allow_signal(SIGTERM);
2809 allow_signal(SIGKILL);
2810 allow_signal(SIGUSR1);
2812 /* Allow the thread to be frozen */
2815 /* Arrange for userspace references to be interpreted as kernel
2816 * pointers. That way we can pass a kernel pointer to a routine
2817 * that expects a __user pointer and it will work okay. */
2821 while (common->state != FSG_STATE_TERMINATED) {
2822 if (exception_in_progress(common) || signal_pending(current)) {
2823 handle_exception(common);
2827 if (!common->running) {
2828 sleep_thread(common);
2832 if (get_next_command(common))
2835 spin_lock_irq(&common->lock);
2836 if (!exception_in_progress(common))
2837 common->state = FSG_STATE_DATA_PHASE;
2838 spin_unlock_irq(&common->lock);
2840 if (do_scsi_command(common) || finish_reply(common))
2843 spin_lock_irq(&common->lock);
2844 if (!exception_in_progress(common))
2845 common->state = FSG_STATE_STATUS_PHASE;
2846 spin_unlock_irq(&common->lock);
2848 if (send_status(common))
2851 spin_lock_irq(&common->lock);
2852 if (!exception_in_progress(common))
2853 common->state = FSG_STATE_IDLE;
2854 spin_unlock_irq(&common->lock);
2857 spin_lock_irq(&common->lock);
2858 common->thread_task = NULL;
2859 spin_unlock_irq(&common->lock);
2861 if (!common->ops || !common->ops->thread_exits
2862 || common->ops->thread_exits(common) < 0) {
2863 struct fsg_lun *curlun = common->luns;
2864 unsigned i = common->nluns;
2866 down_write(&common->filesem);
2867 for (; i--; ++curlun) {
2868 if (!fsg_lun_is_open(curlun))
2871 fsg_lun_close(curlun);
2872 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2874 up_write(&common->filesem);
2877 /* Let the unbind and cleanup routines know the thread has exited */
2878 complete_and_exit(&common->thread_notifier, 0);
2882 /*************************** DEVICE ATTRIBUTES ***************************/
2884 /* Write permission is checked per LUN in store_*() functions. */
2885 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2886 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2889 /****************************** FSG COMMON ******************************/
2891 static void fsg_common_release(struct kref *ref);
2893 static void fsg_lun_release(struct device *dev)
2895 /* Nothing needs to be done */
2898 static inline void fsg_common_get(struct fsg_common *common)
2900 kref_get(&common->ref);
2903 static inline void fsg_common_put(struct fsg_common *common)
2905 kref_put(&common->ref, fsg_common_release);
2909 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2910 struct usb_composite_dev *cdev,
2911 struct fsg_config *cfg)
2913 struct usb_gadget *gadget = cdev->gadget;
2914 struct fsg_buffhd *bh;
2915 struct fsg_lun *curlun;
2916 struct fsg_lun_config *lcfg;
2920 /* Find out how many LUNs there should be */
2922 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2923 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2924 return ERR_PTR(-EINVAL);
2929 common = kzalloc(sizeof *common, GFP_KERNEL);
2931 return ERR_PTR(-ENOMEM);
2932 common->free_storage_on_release = 1;
2934 memset(common, 0, sizeof common);
2935 common->free_storage_on_release = 0;
2938 common->ops = cfg->ops;
2939 common->private_data = cfg->private_data;
2941 common->gadget = gadget;
2942 common->ep0 = gadget->ep0;
2943 common->ep0req = cdev->req;
2945 /* Maybe allocate device-global string IDs, and patch descriptors */
2946 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2947 rc = usb_string_id(cdev);
2948 if (unlikely(rc < 0))
2950 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2951 fsg_intf_desc.iInterface = rc;
2954 /* Create the LUNs, open their backing files, and register the
2955 * LUN devices in sysfs. */
2956 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2957 if (unlikely(!curlun)) {
2961 common->luns = curlun;
2963 init_rwsem(&common->filesem);
2965 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2966 curlun->cdrom = !!lcfg->cdrom;
2967 curlun->ro = lcfg->cdrom || lcfg->ro;
2968 curlun->removable = lcfg->removable;
2969 curlun->dev.release = fsg_lun_release;
2971 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
2972 /* use "usb_mass_storage" platform device as parent */
2973 curlun->dev.parent = &cfg->pdev->dev;
2975 curlun->dev.parent = &gadget->dev;
2977 /* curlun->dev.driver = &fsg_driver.driver; XXX */
2978 dev_set_drvdata(&curlun->dev, &common->filesem);
2979 dev_set_name(&curlun->dev,
2980 cfg->lun_name_format
2981 ? cfg->lun_name_format
2985 rc = device_register(&curlun->dev);
2987 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2992 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2995 rc = device_create_file(&curlun->dev, &dev_attr_file);
2999 if (lcfg->filename) {
3000 rc = fsg_lun_open(curlun, lcfg->filename);
3003 } else if (!curlun->removable) {
3004 ERROR(common, "no file given for LUN%d\n", i);
3009 common->nluns = nluns;
3012 /* Data buffers cyclic list */
3013 bh = common->buffhds;
3014 i = FSG_NUM_BUFFERS;
3015 goto buffhds_first_it;
3020 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
3021 if (unlikely(!bh->buf)) {
3026 bh->next = common->buffhds;
3029 /* Prepare inquiryString */
3030 if (cfg->release != 0xffff) {
3033 i = usb_gadget_controller_number(gadget);
3037 WARNING(common, "controller '%s' not recognized\n",
3042 #define OR(x, y) ((x) ? (x) : (y))
3043 snprintf(common->inquiry_string, sizeof common->inquiry_string,
3045 OR(cfg->vendor_name, "Linux "),
3046 /* Assume product name dependent on the first LUN */
3047 OR(cfg->product_name, common->luns->cdrom
3048 ? "File-Stor Gadget"
3049 : "File-CD Gadget "),
3053 /* Some peripheral controllers are known not to be able to
3054 * halt bulk endpoints correctly. If one of them is present,
3057 common->can_stall = cfg->can_stall &&
3058 !(gadget_is_at91(common->gadget));
3061 spin_lock_init(&common->lock);
3062 kref_init(&common->ref);
3065 /* Tell the thread to start working */
3066 common->thread_task =
3067 kthread_create(fsg_main_thread, common,
3068 OR(cfg->thread_name, "file-storage"));
3069 if (IS_ERR(common->thread_task)) {
3070 rc = PTR_ERR(common->thread_task);
3073 init_completion(&common->thread_notifier);
3074 init_waitqueue_head(&common->fsg_wait);
3079 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
3080 INFO(common, "Number of LUNs=%d\n", common->nluns);
3082 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
3083 for (i = 0, nluns = common->nluns, curlun = common->luns;
3086 char *p = "(no medium)";
3087 if (fsg_lun_is_open(curlun)) {
3090 p = d_path(&curlun->filp->f_path,
3096 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
3097 curlun->removable ? "removable " : "",
3098 curlun->ro ? "read only " : "",
3099 curlun->cdrom ? "CD-ROM " : "",
3104 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
3106 wake_up_process(common->thread_task);
3112 common->nluns = i + 1;
3114 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
3115 /* Call fsg_common_release() directly, ref might be not
3117 fsg_common_release(&common->ref);
3122 static void fsg_common_release(struct kref *ref)
3124 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
3126 /* If the thread isn't already dead, tell it to exit now */
3127 if (common->state != FSG_STATE_TERMINATED) {
3128 raise_exception(common, FSG_STATE_EXIT);
3129 wait_for_completion(&common->thread_notifier);
3131 /* The cleanup routine waits for this completion also */
3132 complete(&common->thread_notifier);
3135 if (likely(common->luns)) {
3136 struct fsg_lun *lun = common->luns;
3137 unsigned i = common->nluns;
3139 /* In error recovery common->nluns may be zero. */
3140 for (; i; --i, ++lun) {
3141 device_remove_file(&lun->dev, &dev_attr_ro);
3142 device_remove_file(&lun->dev, &dev_attr_file);
3144 device_unregister(&lun->dev);
3147 kfree(common->luns);
3151 struct fsg_buffhd *bh = common->buffhds;
3152 unsigned i = FSG_NUM_BUFFERS;
3155 } while (++bh, --i);
3158 if (common->free_storage_on_release)
3163 /*-------------------------------------------------------------------------*/
3166 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
3168 struct fsg_dev *fsg = fsg_from_func(f);
3169 struct fsg_common *common = fsg->common;
3171 DBG(fsg, "unbind\n");
3172 if (fsg->common->fsg == fsg) {
3173 fsg->common->new_fsg = NULL;
3174 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
3175 /* FIXME: make interruptible or killable somehow? */
3176 wait_event(common->fsg_wait, common->fsg != fsg);
3179 fsg_common_put(common);
3180 usb_free_descriptors(fsg->function.descriptors);
3181 usb_free_descriptors(fsg->function.hs_descriptors);
3186 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
3188 struct fsg_dev *fsg = fsg_from_func(f);
3189 struct usb_gadget *gadget = c->cdev->gadget;
3193 fsg->gadget = gadget;
3196 i = usb_interface_id(c, f);
3199 fsg_intf_desc.bInterfaceNumber = i;
3200 fsg->interface_number = i;
3202 /* Find all the endpoints we will use */
3203 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3206 ep->driver_data = fsg->common; /* claim the endpoint */
3209 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3212 ep->driver_data = fsg->common; /* claim the endpoint */
3215 /* Copy descriptors */
3216 f->descriptors = usb_copy_descriptors(fsg_fs_function);
3217 if (unlikely(!f->descriptors))
3220 if (gadget_is_dualspeed(gadget)) {
3221 /* Assume endpoint addresses are the same for both speeds */
3222 fsg_hs_bulk_in_desc.bEndpointAddress =
3223 fsg_fs_bulk_in_desc.bEndpointAddress;
3224 fsg_hs_bulk_out_desc.bEndpointAddress =
3225 fsg_fs_bulk_out_desc.bEndpointAddress;
3226 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
3227 if (unlikely(!f->hs_descriptors)) {
3228 usb_free_descriptors(f->descriptors);
3236 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3241 /****************************** ADD FUNCTION ******************************/
3243 static struct usb_gadget_strings *fsg_strings_array[] = {
3248 static int fsg_bind_config(struct usb_composite_dev *cdev,
3249 struct usb_configuration *c,
3250 struct fsg_common *common)
3252 struct fsg_dev *fsg;
3255 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3259 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
3260 fsg->function.name = FUNCTION_NAME;
3262 fsg->function.name = FSG_DRIVER_DESC;
3264 fsg->function.strings = fsg_strings_array;
3265 fsg->function.bind = fsg_bind;
3266 fsg->function.unbind = fsg_unbind;
3267 fsg->function.setup = fsg_setup;
3268 fsg->function.set_alt = fsg_set_alt;
3269 fsg->function.disable = fsg_disable;
3271 fsg->common = common;
3272 /* Our caller holds a reference to common structure so we
3273 * don't have to be worry about it being freed until we return
3274 * from this function. So instead of incrementing counter now
3275 * and decrement in error recovery we increment it only when
3276 * call to usb_add_function() was successful. */
3278 rc = usb_add_function(c, &fsg->function);
3282 fsg_common_get(fsg->common);
3286 static inline int __deprecated __maybe_unused
3287 fsg_add(struct usb_composite_dev *cdev,
3288 struct usb_configuration *c,
3289 struct fsg_common *common)
3291 return fsg_bind_config(cdev, c, common);
3295 /************************* Module parameters *************************/
3298 struct fsg_module_parameters {
3299 char *file[FSG_MAX_LUNS];
3300 int ro[FSG_MAX_LUNS];
3301 int removable[FSG_MAX_LUNS];
3302 int cdrom[FSG_MAX_LUNS];
3304 unsigned int file_count, ro_count, removable_count, cdrom_count;
3305 unsigned int luns; /* nluns */
3306 int stall; /* can_stall */
3310 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3311 module_param_array_named(prefix ## name, params.name, type, \
3312 &prefix ## params.name ## _count, \
3314 MODULE_PARM_DESC(prefix ## name, desc)
3316 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3317 module_param_named(prefix ## name, params.name, type, \
3319 MODULE_PARM_DESC(prefix ## name, desc)
3321 #define FSG_MODULE_PARAMETERS(prefix, params) \
3322 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3323 "names of backing files or devices"); \
3324 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3325 "true to force read-only"); \
3326 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3327 "true to simulate removable media"); \
3328 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3329 "true to simulate CD-ROM instead of disk"); \
3330 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3331 "number of LUNs"); \
3332 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3333 "false to prevent bulk stalls")
3337 fsg_config_from_params(struct fsg_config *cfg,
3338 const struct fsg_module_parameters *params)
3340 struct fsg_lun_config *lun;
3343 /* Configure LUNs */
3345 min(params->luns ?: (params->file_count ?: 1u),
3346 (unsigned)FSG_MAX_LUNS);
3347 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3348 lun->ro = !!params->ro[i];
3349 lun->cdrom = !!params->cdrom[i];
3350 lun->removable = /* Removable by default */
3351 params->removable_count <= i || params->removable[i];
3353 params->file_count > i && params->file[i][0]
3358 /* Let MSF use defaults */
3359 cfg->lun_name_format = 0;
3360 cfg->thread_name = 0;
3361 cfg->vendor_name = 0;
3362 cfg->product_name = 0;
3363 cfg->release = 0xffff;
3366 cfg->private_data = NULL;
3369 cfg->can_stall = params->stall;
3372 static inline struct fsg_common *
3373 fsg_common_from_params(struct fsg_common *common,
3374 struct usb_composite_dev *cdev,
3375 const struct fsg_module_parameters *params)
3376 __attribute__((unused));
3377 static inline struct fsg_common *
3378 fsg_common_from_params(struct fsg_common *common,
3379 struct usb_composite_dev *cdev,
3380 const struct fsg_module_parameters *params)
3382 struct fsg_config cfg;
3383 fsg_config_from_params(&cfg, params);
3384 return fsg_common_init(common, cdev, &cfg);
3387 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
3389 #ifdef CONFIG_ARCH_RK29
3390 static enum power_supply_property usb_props[] = {
3391 // POWER_SUPPLY_PROP_STATUS,
3392 POWER_SUPPLY_PROP_ONLINE,
3395 static int usb_get_property(struct power_supply *psy,
3396 enum power_supply_property psp,
3397 union power_supply_propval *val)
3402 case POWER_SUPPLY_PROP_ONLINE:
3403 #ifndef CONFIG_DWC_OTG_HOST_ONLY
3404 val->intval = get_msc_connect_flag();
3416 static int usb_power_supply_register(struct device* parent)
3418 struct power_supply *ps;
3421 ps = kzalloc(sizeof(*ps), GFP_KERNEL);
3423 dev_err(parent, "failed to allocate power supply data\n");
3428 ps->type = POWER_SUPPLY_TYPE_USB;
3429 ps->properties = usb_props;
3430 ps->num_properties = ARRAY_SIZE(usb_props);
3431 ps->get_property = usb_get_property;
3432 ps->external_power_changed = NULL;
3433 retval = power_supply_register(parent, ps);
3435 dev_err(parent, "failed to register battery\n");
3443 static struct fsg_config fsg_cfg;
3445 static int fsg_probe(struct platform_device *pdev)
3447 struct usb_mass_storage_platform_data *pdata = pdev->dev.platform_data;
3450 printk(KERN_INFO "fsg_probe pdev: %p, pdata: %p\n", pdev, pdata);
3454 nluns = pdata->nluns;
3455 if (nluns > FSG_MAX_LUNS)
3456 nluns = FSG_MAX_LUNS;
3457 fsg_cfg.nluns = nluns;
3458 for (i = 0; i < nluns; i++)
3459 fsg_cfg.luns[i].removable = 1;
3461 fsg_cfg.vendor_name = pdata->vendor;
3462 fsg_cfg.product_name = pdata->product;
3463 fsg_cfg.release = pdata->release;
3464 fsg_cfg.can_stall = 0;
3465 fsg_cfg.pdev = pdev;
3467 #ifdef CONFIG_ARCH_RK29
3470 * Initialize usb power supply
3472 int retval = usb_power_supply_register(&pdev->dev);
3474 dev_err(&pdev->dev, "usb_power_supply_register failed\n");
3484 static struct platform_driver fsg_platform_driver = {
3485 .driver = { .name = FUNCTION_NAME, },
3489 int mass_storage_bind_config(struct usb_configuration *c)
3491 struct fsg_common *common = fsg_common_init(NULL, c->cdev, &fsg_cfg);
3494 return fsg_add(c->cdev, c, common);
3497 static struct android_usb_function mass_storage_function = {
3498 .name = FUNCTION_NAME,
3499 .bind_config = mass_storage_bind_config,
3502 static int __init init(void)
3505 printk(KERN_INFO "f_mass_storage init\n");
3506 rc = platform_driver_register(&fsg_platform_driver);
3509 android_register_function(&mass_storage_function);
3513 #endif /* CONFIG_USB_ANDROID_MASS_STORAGE */