2 * drivers/usb/gadget/f_mass_storage.c
4 * Function Driver for USB Mass Storage
6 * Copyright (C) 2008 Google, Inc.
7 * Author: Mike Lockwood <lockwood@android.com>
9 * Based heavily on the file_storage gadget driver in
10 * drivers/usb/gadget/file_storage.c and licensed under the same terms:
12 * Copyright (C) 2003-2007 Alan Stern
13 * All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions, and the following disclaimer,
20 * without modification.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. The names of the above-listed copyright holders may not be used
25 * to endorse or promote products derived from this software without
26 * specific prior written permission.
28 * ALTERNATIVELY, this software may be distributed under the terms of the
29 * GNU General Public License ("GPL") as published by the Free Software
30 * Foundation, either version 2 of that License or (at your option) any
33 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
34 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
35 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
36 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
38 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
39 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
40 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 /* #define VERBOSE_DEBUG */
48 /* #define DUMP_MSGS */
51 #include <linux/blkdev.h>
52 #include <linux/completion.h>
53 #include <linux/dcache.h>
54 #include <linux/delay.h>
55 #include <linux/device.h>
56 #include <linux/fcntl.h>
57 #include <linux/file.h>
59 #include <linux/kref.h>
60 #include <linux/kthread.h>
61 #include <linux/limits.h>
62 #include <linux/rwsem.h>
63 #include <linux/slab.h>
64 #include <linux/spinlock.h>
65 #include <linux/string.h>
66 #include <linux/switch.h>
67 #include <linux/freezer.h>
68 #include <linux/utsname.h>
69 #include <linux/wakelock.h>
70 #include <linux/platform_device.h>
71 #include <linux/power_supply.h>
72 #ifdef CONFIG_ARCH_RK29
73 #include <linux/reboot.h>
74 #include <linux/syscalls.h>
77 #include <linux/usb.h>
78 #include <linux/usb_usual.h>
79 #include <linux/usb/ch9.h>
80 #include <linux/usb/android_composite.h>
82 #include "gadget_chips.h"
84 #define BULK_BUFFER_SIZE 16384 * 4//4096
86 /* flush after every 4 meg of writes to avoid excessive block level caching */
87 #define MAX_UNFLUSHED_BYTES (512 * 1024)// (4 * 1024 * 1024) //original value is 4MB,Modifyed by xbw at 2011-08-18
89 /*-------------------------------------------------------------------------*/
91 #define DRIVER_NAME "usb_mass_storage"
94 static const char shortname[] = DRIVER_NAME;
97 #define LDBG(lun, fmt, args...) \
98 dev_dbg(&(lun)->dev , fmt , ## args)
99 #define MDBG(fmt,args...) \
100 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
102 #define LDBG(lun, fmt, args...) \
104 #define MDBG(fmt,args...) \
113 #define VLDBG(lun, fmt, args...) \
115 #endif /* VERBOSE_DEBUG */
117 #define LERROR(lun, fmt, args...) \
118 dev_err(&(lun)->dev , fmt , ## args)
119 #define LWARN(lun, fmt, args...) \
120 dev_warn(&(lun)->dev , fmt , ## args)
121 #define LINFO(lun, fmt, args...) \
122 dev_info(&(lun)->dev , fmt , ## args)
124 #define MINFO(fmt,args...) \
125 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
132 #define DBG(d, fmt, args...) \
133 dev_dbg(&(d)->cdev->gadget->dev , fmt , ## args)
134 #define VDBG(d, fmt, args...) \
135 dev_vdbg(&(d)->cdev->gadget->dev , fmt , ## args)
136 #define ERROR(d, fmt, args...) \
137 dev_err(&(d)->cdev->gadget->dev , fmt , ## args)
138 #define WARNING(d, fmt, args...) \
139 dev_warn(&(d)->cdev->gadget->dev , fmt , ## args)
140 #define INFO(d, fmt, args...) \
141 dev_info(&(d)->cdev->gadget->dev , fmt , ## args)
144 /*-------------------------------------------------------------------------*/
146 /* Bulk-only data structures */
148 /* Command Block Wrapper */
149 struct bulk_cb_wrap {
150 __le32 Signature; /* Contains 'USBC' */
151 u32 Tag; /* Unique per command id */
152 __le32 DataTransferLength; /* Size of the data */
153 u8 Flags; /* Direction in bit 7 */
154 u8 Lun; /* LUN (normally 0) */
155 u8 Length; /* Of the CDB, <= MAX_COMMAND_SIZE */
156 u8 CDB[16]; /* Command Data Block */
159 #define USB_BULK_CB_WRAP_LEN 31
160 #define USB_BULK_CB_SIG 0x43425355 /* Spells out USBC */
161 #define USB_BULK_IN_FLAG 0x80
163 /* Command Status Wrapper */
164 struct bulk_cs_wrap {
165 __le32 Signature; /* Should = 'USBS' */
166 u32 Tag; /* Same as original command */
167 __le32 Residue; /* Amount not transferred */
168 u8 Status; /* See below */
171 #define USB_BULK_CS_WRAP_LEN 13
172 #define USB_BULK_CS_SIG 0x53425355 /* Spells out 'USBS' */
173 #define USB_STATUS_PASS 0
174 #define USB_STATUS_FAIL 1
175 #define USB_STATUS_PHASE_ERROR 2
177 /* Bulk-only class specific requests */
178 #define USB_BULK_RESET_REQUEST 0xff
179 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
181 /* Length of a SCSI Command Data Block */
182 #define MAX_COMMAND_SIZE 16
184 /* SCSI commands that we recognize */
185 #define SC_FORMAT_UNIT 0x04
186 #define SC_INQUIRY 0x12
187 #define SC_MODE_SELECT_6 0x15
188 #define SC_MODE_SELECT_10 0x55
189 #define SC_MODE_SENSE_6 0x1a
190 #define SC_MODE_SENSE_10 0x5a
191 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
192 #define SC_READ_6 0x08
193 #define SC_READ_10 0x28
194 #define SC_READ_12 0xa8
195 #define SC_READ_CAPACITY 0x25
196 #define SC_READ_FORMAT_CAPACITIES 0x23
197 #define SC_RELEASE 0x17
198 #define SC_REQUEST_SENSE 0x03
199 #define SC_RESERVE 0x16
200 #define SC_SEND_DIAGNOSTIC 0x1d
201 #define SC_START_STOP_UNIT 0x1b
202 #define SC_SYNCHRONIZE_CACHE 0x35
203 #define SC_TEST_UNIT_READY 0x00
204 #define SC_VERIFY 0x2f
205 #define SC_WRITE_6 0x0a
206 #define SC_WRITE_10 0x2a
207 #define SC_WRITE_12 0xaa
209 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
210 #define SS_NO_SENSE 0
211 #define SS_COMMUNICATION_FAILURE 0x040800
212 #define SS_INVALID_COMMAND 0x052000
213 #define SS_INVALID_FIELD_IN_CDB 0x052400
214 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
215 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
216 #define SS_MEDIUM_NOT_PRESENT 0x023a00
217 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
218 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
219 #define SS_RESET_OCCURRED 0x062900
220 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
221 #define SS_UNRECOVERED_READ_ERROR 0x031100
222 #define SS_WRITE_ERROR 0x030c02
223 #define SS_WRITE_PROTECTED 0x072700
225 #define SK(x) ((u8) ((x) >> 16)) /* Sense Key byte, etc. */
226 #define ASC(x) ((u8) ((x) >> 8))
227 #define ASCQ(x) ((u8) (x))
229 static int usb_msc_connected; /*usb charge status*/
230 /*-------------------------------------------------------------------------*/
236 unsigned int unflushed_bytes;
239 unsigned int prevent_medium_removal : 1;
240 unsigned int registered : 1;
241 unsigned int info_valid : 1;
245 u32 unit_attention_data;
250 #define backing_file_is_open(curlun) ((curlun)->filp != NULL)
253 static struct lun *dev_to_lun(struct device *dev)
255 return container_of(dev, struct lun, dev);
258 /* Big enough to hold our biggest descriptor */
259 #define EP0_BUFSIZE 256
261 /* Number of buffers we will use. 2 is enough for double-buffering */
262 #define NUM_BUFFERS 2
264 enum fsg_buffer_state {
272 enum fsg_buffer_state state;
273 struct fsg_buffhd *next;
275 /* The NetChip 2280 is faster, and handles some protocol faults
276 * better, if we don't submit any short bulk-out read requests.
277 * So we will record the intended request length here. */
278 unsigned int bulk_out_intended_length;
280 struct usb_request *inreq;
282 struct usb_request *outreq;
287 /* This one isn't used anywhere */
288 FSG_STATE_COMMAND_PHASE = -10,
290 FSG_STATE_DATA_PHASE,
291 FSG_STATE_STATUS_PHASE,
294 FSG_STATE_ABORT_BULK_OUT,
296 FSG_STATE_CONFIG_CHANGE,
301 enum data_direction {
302 DATA_DIR_UNKNOWN = 0,
309 struct usb_function function;
310 struct usb_composite_dev *cdev;
312 /* optional "usb_mass_storage" platform device */
313 struct platform_device *pdev;
315 /* lock protects: state and all the req_busy's */
318 /* filesem protects: backing files in use */
319 struct rw_semaphore filesem;
321 /* reference counting: wait until all LUNs are released */
324 unsigned int bulk_out_maxpacket;
325 enum fsg_state state; /* For exception handling */
327 u8 config, new_config;
329 unsigned int running : 1;
330 unsigned int bulk_in_enabled : 1;
331 unsigned int bulk_out_enabled : 1;
332 unsigned int phase_error : 1;
333 unsigned int short_packet_received : 1;
334 unsigned int bad_lun_okay : 1;
336 unsigned long atomic_bitflags;
338 #define CLEAR_BULK_HALTS 1
341 struct usb_ep *bulk_in;
342 struct usb_ep *bulk_out;
344 struct fsg_buffhd *next_buffhd_to_fill;
345 struct fsg_buffhd *next_buffhd_to_drain;
346 struct fsg_buffhd buffhds[NUM_BUFFERS];
348 int thread_wakeup_needed;
349 struct completion thread_notifier;
350 struct task_struct *thread_task;
353 u8 cmnd[MAX_COMMAND_SIZE];
354 enum data_direction data_dir;
356 u32 data_size_from_cmnd;
371 struct switch_dev sdev;
373 struct wake_lock wake_lock;
376 static inline struct fsg_dev *func_to_dev(struct usb_function *f)
378 return container_of(f, struct fsg_dev, function);
381 static int exception_in_progress(struct fsg_dev *fsg)
383 return (fsg->state > FSG_STATE_IDLE);
386 /* Make bulk-out requests be divisible by the maxpacket size */
387 static void set_bulk_out_req_length(struct fsg_dev *fsg,
388 struct fsg_buffhd *bh, unsigned int length)
392 bh->bulk_out_intended_length = length;
393 rem = length % fsg->bulk_out_maxpacket;
395 length += fsg->bulk_out_maxpacket - rem;
396 bh->outreq->length = length;
399 static struct fsg_dev *the_fsg;
401 static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun);
402 static void close_all_backing_files(struct fsg_dev *fsg);
403 static int fsync_sub(struct lun *curlun);
405 /*-------------------------------------------------------------------------*/
409 static void dump_msg(struct fsg_dev *fsg, const char *label,
410 const u8 *buf, unsigned int length)
413 DBG(fsg, "%s, length %u:\n", label, length);
414 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
415 16, 1, buf, length, 0);
419 static void dump_cdb(struct fsg_dev *fsg)
424 static void dump_msg(struct fsg_dev *fsg, const char *label,
425 const u8 *buf, unsigned int length)
430 static void dump_cdb(struct fsg_dev *fsg)
432 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,
433 16, 1, fsg->cmnd, fsg->cmnd_size, 0);
438 static void dump_cdb(struct fsg_dev *fsg)
441 #endif /* VERBOSE_DEBUG */
442 #endif /* DUMP_MSGS */
445 /*-------------------------------------------------------------------------*/
447 /* Routines for unaligned data access */
449 static u16 get_be16(u8 *buf)
451 return ((u16) buf[0] << 8) | ((u16) buf[1]);
454 static u32 get_be32(u8 *buf)
456 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
457 ((u32) buf[2] << 8) | ((u32) buf[3]);
460 static void put_be16(u8 *buf, u16 val)
466 static void put_be32(u8 *buf, u32 val)
474 static void set_msc_connect_flag( int connected )
476 printk("%s status = %d 20101216\n" , __func__, connected);
477 if( usb_msc_connected == connected )
479 usb_msc_connected = connected;//usb mass storage is ok
482 int get_msc_connect_flag( void )
484 return usb_msc_connected;
486 EXPORT_SYMBOL(get_msc_connect_flag);
488 /*-------------------------------------------------------------------------*/
491 * DESCRIPTORS ... most are static, but strings and (full) configuration
492 * descriptors are built on demand. Also the (static) config and interface
493 * descriptors are adjusted during fsg_bind().
496 /* There is only one interface. */
498 static struct usb_interface_descriptor
500 .bLength = sizeof intf_desc,
501 .bDescriptorType = USB_DT_INTERFACE,
503 .bNumEndpoints = 2, /* Adjusted during fsg_bind() */
504 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
505 .bInterfaceSubClass = US_SC_SCSI,
506 .bInterfaceProtocol = US_PR_BULK,
509 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
510 * and interrupt-in. */
512 static struct usb_endpoint_descriptor
514 .bLength = USB_DT_ENDPOINT_SIZE,
515 .bDescriptorType = USB_DT_ENDPOINT,
517 .bEndpointAddress = USB_DIR_IN,
518 .bmAttributes = USB_ENDPOINT_XFER_BULK,
519 /* wMaxPacketSize set by autoconfiguration */
522 static struct usb_endpoint_descriptor
524 .bLength = USB_DT_ENDPOINT_SIZE,
525 .bDescriptorType = USB_DT_ENDPOINT,
527 .bEndpointAddress = USB_DIR_OUT,
528 .bmAttributes = USB_ENDPOINT_XFER_BULK,
529 /* wMaxPacketSize set by autoconfiguration */
532 static struct usb_descriptor_header *fs_function[] = {
533 (struct usb_descriptor_header *) &intf_desc,
534 (struct usb_descriptor_header *) &fs_bulk_in_desc,
535 (struct usb_descriptor_header *) &fs_bulk_out_desc,
538 #define FS_FUNCTION_PRE_EP_ENTRIES 2
541 static struct usb_endpoint_descriptor
543 .bLength = USB_DT_ENDPOINT_SIZE,
544 .bDescriptorType = USB_DT_ENDPOINT,
546 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
547 .bmAttributes = USB_ENDPOINT_XFER_BULK,
548 .wMaxPacketSize = __constant_cpu_to_le16(512),
551 static struct usb_endpoint_descriptor
553 .bLength = USB_DT_ENDPOINT_SIZE,
554 .bDescriptorType = USB_DT_ENDPOINT,
556 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
557 .bmAttributes = USB_ENDPOINT_XFER_BULK,
558 .wMaxPacketSize = __constant_cpu_to_le16(512),
559 .bInterval = 1, /* NAK every 1 uframe */
563 static struct usb_descriptor_header *hs_function[] = {
564 (struct usb_descriptor_header *) &intf_desc,
565 (struct usb_descriptor_header *) &hs_bulk_in_desc,
566 (struct usb_descriptor_header *) &hs_bulk_out_desc,
570 /* Maxpacket and other transfer characteristics vary by speed. */
571 static struct usb_endpoint_descriptor *
572 ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
573 struct usb_endpoint_descriptor *hs)
575 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
580 /*-------------------------------------------------------------------------*/
582 /* These routines may be called in process context or in_irq */
584 /* Caller must hold fsg->lock */
585 static void wakeup_thread(struct fsg_dev *fsg)
587 /* Tell the main thread that something has happened */
588 fsg->thread_wakeup_needed = 1;
589 if (fsg->thread_task)
590 wake_up_process(fsg->thread_task);
594 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
598 DBG(fsg, "raise_exception %d\n", (int)new_state);
599 /* Do nothing if a higher-priority exception is already in progress.
600 * If a lower-or-equal priority exception is in progress, preempt it
601 * and notify the main thread by sending it a signal. */
602 spin_lock_irqsave(&fsg->lock, flags);
603 if (fsg->state <= new_state) {
604 fsg->state = new_state;
605 if (fsg->thread_task)
606 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
609 spin_unlock_irqrestore(&fsg->lock, flags);
613 /*-------------------------------------------------------------------------*/
615 /* Bulk and interrupt endpoint completion handlers.
616 * These always run in_irq. */
618 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
620 struct fsg_dev *fsg = ep->driver_data;
621 struct fsg_buffhd *bh = req->context;
624 if (req->status || req->actual != req->length)
625 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
626 req->status, req->actual, req->length);
628 /* Hold the lock while we update the request and buffer states */
630 spin_lock_irqsave(&fsg->lock, flags);
632 bh->state = BUF_STATE_EMPTY;
634 spin_unlock_irqrestore(&fsg->lock, flags);
637 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
639 struct fsg_dev *fsg = ep->driver_data;
640 struct fsg_buffhd *bh = req->context;
643 dump_msg(fsg, "bulk-out", req->buf, req->actual);
644 if (req->status || req->actual != bh->bulk_out_intended_length)
645 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
646 req->status, req->actual,
647 bh->bulk_out_intended_length);
649 /* Hold the lock while we update the request and buffer states */
651 spin_lock_irqsave(&fsg->lock, flags);
653 bh->state = BUF_STATE_FULL;
655 spin_unlock_irqrestore(&fsg->lock, flags);
658 static int fsg_function_setup(struct usb_function *f,
659 const struct usb_ctrlrequest *ctrl)
661 struct fsg_dev *fsg = func_to_dev(f);
662 struct usb_composite_dev *cdev = fsg->cdev;
663 int value = -EOPNOTSUPP;
664 u16 w_index = le16_to_cpu(ctrl->wIndex);
665 u16 w_value = le16_to_cpu(ctrl->wValue);
666 u16 w_length = le16_to_cpu(ctrl->wLength);
668 DBG(fsg, "fsg_function_setup\n");
669 /* Handle Bulk-only class-specific requests */
670 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
671 DBG(fsg, "USB_TYPE_CLASS\n");
672 switch (ctrl->bRequest) {
673 case USB_BULK_RESET_REQUEST:
674 if (ctrl->bRequestType != (USB_DIR_OUT |
675 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
677 if (w_index != 0 || w_value != 0) {
682 /* Raise an exception to stop the current operation
683 * and reinitialize our state. */
684 DBG(fsg, "bulk reset request\n");
685 raise_exception(fsg, FSG_STATE_RESET);
689 case USB_BULK_GET_MAX_LUN_REQUEST:
690 if (ctrl->bRequestType != (USB_DIR_IN |
691 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
693 if (w_index != 0 || w_value != 0) {
697 VDBG(fsg, "get max LUN\n");
698 *(u8 *)cdev->req->buf = fsg->nluns - 1;
704 /* respond with data transfer or status phase? */
707 cdev->req->zero = value < w_length;
708 cdev->req->length = value;
709 rc = usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
711 printk("%s setup response queue error\n", __func__);
714 if (value == -EOPNOTSUPP)
716 "unknown class-specific control req "
717 "%02x.%02x v%04x i%04x l%u\n",
718 ctrl->bRequestType, ctrl->bRequest,
719 le16_to_cpu(ctrl->wValue), w_index, w_length);
723 /*-------------------------------------------------------------------------*/
725 /* All the following routines run in process context */
728 /* Use this for bulk or interrupt transfers, not ep0 */
729 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
730 struct usb_request *req, int *pbusy,
731 enum fsg_buffer_state *state)
736 DBG(fsg, "start_transfer req: %p, req->buf: %p\n", req, req->buf);
737 if (ep == fsg->bulk_in)
738 dump_msg(fsg, "bulk-in", req->buf, req->length);
740 spin_lock_irqsave(&fsg->lock, flags);
742 *state = BUF_STATE_BUSY;
743 spin_unlock_irqrestore(&fsg->lock, flags);
744 rc = usb_ep_queue(ep, req, GFP_KERNEL);
747 *state = BUF_STATE_EMPTY;
749 /* We can't do much more than wait for a reset */
751 /* Note: currently the net2280 driver fails zero-length
752 * submissions if DMA is enabled. */
753 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
755 WARN(fsg, "error in submission: %s --> %d\n",
756 (ep == fsg->bulk_in ? "bulk-in" : "bulk-out"),
762 static int sleep_thread(struct fsg_dev *fsg)
766 /* Wait until a signal arrives or we are woken up */
769 set_current_state(TASK_INTERRUPTIBLE);
770 if (signal_pending(current)) {
774 if (fsg->thread_wakeup_needed)
778 __set_current_state(TASK_RUNNING);
779 fsg->thread_wakeup_needed = 0;
784 /*-------------------------------------------------------------------------*/
786 static int do_read(struct fsg_dev *fsg)
788 struct lun *curlun = fsg->curlun;
790 struct fsg_buffhd *bh;
793 loff_t file_offset, file_offset_tmp;
795 unsigned int partial_page;
798 /* Get the starting Logical Block Address and check that it's
800 if (fsg->cmnd[0] == SC_READ_6)
801 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
803 lba = get_be32(&fsg->cmnd[2]);
805 /* We allow DPO (Disable Page Out = don't save data in the
806 * cache) and FUA (Force Unit Access = don't read from the
807 * cache), but we don't implement them. */
808 if ((fsg->cmnd[1] & ~0x18) != 0) {
809 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
813 if (lba >= curlun->num_sectors) {
814 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
817 file_offset = ((loff_t) lba) << 9;
819 /* Carry out the file reads */
820 amount_left = fsg->data_size_from_cmnd;
821 if (unlikely(amount_left == 0))
822 return -EIO; /* No default reply */
826 /* Figure out how much we need to read:
827 * Try to read the remaining amount.
828 * But don't read more than the buffer size.
829 * And don't try to read past the end of the file.
830 * Finally, if we're not at a page boundary, don't read past
832 * If this means reading 0 then we were asked to read past
833 * the end of file. */
834 amount = min((unsigned int) amount_left,
835 (unsigned int)fsg->buf_size);
836 amount = min((loff_t) amount,
837 curlun->file_length - file_offset);
838 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
839 if (partial_page > 0)
840 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
844 * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
845 * because of the DOEPTSIZ.PKTCNT has only 10 bits
847 if((fsg->cdev->gadget->speed != USB_SPEED_HIGH)&&(amount >0x8000))
850 /* Wait for the next buffer to become available */
851 bh = fsg->next_buffhd_to_fill;
852 while (bh->state != BUF_STATE_EMPTY) {
853 rc = sleep_thread(fsg);
858 /* If we were asked to read past the end of file,
859 * end with an empty buffer. */
862 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
863 curlun->sense_data_info = file_offset >> 9;
864 curlun->info_valid = 1;
865 bh->inreq->length = 0;
866 bh->state = BUF_STATE_FULL;
870 /* Perform the read */
871 file_offset_tmp = file_offset;
872 nread = vfs_read(curlun->filp,
873 (char __user *) bh->buf,
874 amount, &file_offset_tmp);
875 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
876 (unsigned long long) file_offset,
878 if (signal_pending(current))
882 LDBG(curlun, "error in file read: %d\n",
885 } else if (nread < amount) {
886 LDBG(curlun, "partial file read: %d/%u\n",
887 (int) nread, amount);
888 nread -= (nread & 511); /* Round down to a block */
890 file_offset += nread;
891 amount_left -= nread;
892 fsg->residue -= nread;
893 bh->inreq->length = nread;
894 bh->state = BUF_STATE_FULL;
896 /* If an error occurred, report it and its position */
897 if (nread < amount) {
898 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
899 curlun->sense_data_info = file_offset >> 9;
900 curlun->info_valid = 1;
904 if (amount_left == 0)
905 break; /* No more left to read */
907 /* Send this buffer and go read some more */
908 start_transfer(fsg, fsg->bulk_in, bh->inreq,
909 &bh->inreq_busy, &bh->state);
910 fsg->next_buffhd_to_fill = bh->next;
913 return -EIO; /* No default reply */
917 /*-------------------------------------------------------------------------*/
919 static int do_write(struct fsg_dev *fsg)
921 struct lun *curlun = fsg->curlun;
923 struct fsg_buffhd *bh;
925 u32 amount_left_to_req, amount_left_to_write;
926 loff_t usb_offset, file_offset, file_offset_tmp;
928 unsigned int partial_page;
933 curlun->sense_data = SS_WRITE_PROTECTED;
936 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
938 /* Get the starting Logical Block Address and check that it's
940 if (fsg->cmnd[0] == SC_WRITE_6)
941 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
943 lba = get_be32(&fsg->cmnd[2]);
945 /* We allow DPO (Disable Page Out = don't save data in the
946 * cache) and FUA (Force Unit Access = write directly to the
947 * medium). We don't implement DPO; we implement FUA by
948 * performing synchronous output. */
949 if ((fsg->cmnd[1] & ~0x18) != 0) {
950 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
953 if (fsg->cmnd[1] & 0x08) /* FUA */
954 curlun->filp->f_flags |= O_SYNC;
956 if (lba >= curlun->num_sectors) {
957 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
961 /* Carry out the file writes */
963 file_offset = usb_offset = ((loff_t) lba) << 9;
964 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
966 while (amount_left_to_write > 0) {
968 /* Queue a request for more data from the host */
969 bh = fsg->next_buffhd_to_fill;
970 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
972 /* Figure out how much we want to get:
973 * Try to get the remaining amount.
974 * But don't get more than the buffer size.
975 * And don't try to go past the end of the file.
976 * If we're not at a page boundary,
977 * don't go past the next page.
978 * If this means getting 0, then we were asked
979 * to write past the end of file.
980 * Finally, round down to a block boundary. */
981 amount = min(amount_left_to_req, (u32)fsg->buf_size);
982 amount = min((loff_t) amount, curlun->file_length -
984 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
985 if (partial_page > 0)
987 (unsigned int) PAGE_CACHE_SIZE - partial_page);
992 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
993 curlun->sense_data_info = usb_offset >> 9;
994 curlun->info_valid = 1;
997 amount -= (amount & 511);
1000 /* Why were we were asked to transfer a
1006 /* Get the next buffer */
1007 usb_offset += amount;
1008 fsg->usb_amount_left -= amount;
1009 amount_left_to_req -= amount;
1010 if (amount_left_to_req == 0)
1014 * max size for dwc_otg ctonroller is 64(max pkt sizt) * 1023(pkt)
1015 * because of the DOEPTSIZ.PKTCNT has only 10 bits
1017 if((fsg->cdev->gadget->speed != USB_SPEED_HIGH)&&(amount >0x8000))
1020 /* amount is always divisible by 512, hence by
1021 * the bulk-out maxpacket size */
1022 bh->outreq->length = bh->bulk_out_intended_length =
1024 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1025 &bh->outreq_busy, &bh->state);
1026 fsg->next_buffhd_to_fill = bh->next;
1030 /* Write the received data to the backing file */
1031 bh = fsg->next_buffhd_to_drain;
1032 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
1033 break; /* We stopped early */
1034 if (bh->state == BUF_STATE_FULL) {
1036 fsg->next_buffhd_to_drain = bh->next;
1037 bh->state = BUF_STATE_EMPTY;
1039 /* Did something go wrong with the transfer? */
1040 if (bh->outreq->status != 0) {
1041 curlun->sense_data = SS_COMMUNICATION_FAILURE;
1042 curlun->sense_data_info = file_offset >> 9;
1043 curlun->info_valid = 1;
1047 amount = bh->outreq->actual;
1048 if (curlun->file_length - file_offset < amount) {
1050 "write %u @ %llu beyond end %llu\n",
1051 amount, (unsigned long long) file_offset,
1052 (unsigned long long) curlun->file_length);
1053 amount = curlun->file_length - file_offset;
1056 /* Perform the write */
1057 file_offset_tmp = file_offset;
1058 nwritten = vfs_write(curlun->filp,
1059 (char __user *) bh->buf,
1060 amount, &file_offset_tmp);
1061 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1062 (unsigned long long) file_offset,
1064 if (signal_pending(current))
1065 return -EINTR; /* Interrupted! */
1068 LDBG(curlun, "error in file write: %d\n",
1071 } else if (nwritten < amount) {
1072 LDBG(curlun, "partial file write: %d/%u\n",
1073 (int) nwritten, amount);
1074 nwritten -= (nwritten & 511);
1075 /* Round down to a block */
1077 file_offset += nwritten;
1078 amount_left_to_write -= nwritten;
1079 fsg->residue -= nwritten;
1081 #ifdef MAX_UNFLUSHED_BYTES
1082 curlun->unflushed_bytes += nwritten;
1083 if (curlun->unflushed_bytes >= MAX_UNFLUSHED_BYTES) {
1085 curlun->unflushed_bytes = 0;
1088 /* If an error occurred, report it and its position */
1089 if (nwritten < amount) {
1090 curlun->sense_data = SS_WRITE_ERROR;
1091 curlun->sense_data_info = file_offset >> 9;
1092 curlun->info_valid = 1;
1096 /* Did the host decide to stop early? */
1097 if (bh->outreq->actual != bh->outreq->length) {
1098 fsg->short_packet_received = 1;
1104 /* Wait for something to happen */
1105 rc = sleep_thread(fsg);
1110 return -EIO; /* No default reply */
1114 /*-------------------------------------------------------------------------*/
1116 /* Sync the file data, don't bother with the metadata.
1117 * The caller must own fsg->filesem.
1118 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1119 static int fsync_sub(struct lun *curlun)
1121 struct file *filp = curlun->filp;
1122 struct inode *inode;
1125 if (curlun->ro || !filp)
1127 if (!filp->f_op->fsync)
1130 inode = filp->f_path.dentry->d_inode;
1131 mutex_lock(&inode->i_mutex);
1132 rc = filemap_fdatawrite(inode->i_mapping);
1133 err = filp->f_op->fsync(filp, filp->f_path.dentry, 1);
1136 err = filemap_fdatawait(inode->i_mapping);
1139 mutex_unlock(&inode->i_mutex);
1140 VLDBG(curlun, "fdatasync -> %d\n", rc);
1144 static void fsync_all(struct fsg_dev *fsg)
1148 for (i = 0; i < fsg->nluns; ++i)
1149 fsync_sub(&fsg->luns[i]);
1152 static int do_synchronize_cache(struct fsg_dev *fsg)
1154 struct lun *curlun = fsg->curlun;
1157 /* We ignore the requested LBA and write out all file's
1158 * dirty data buffers. */
1159 rc = fsync_sub(curlun);
1161 curlun->sense_data = SS_WRITE_ERROR;
1166 /*-------------------------------------------------------------------------*/
1169 static void invalidate_sub(struct lun *curlun)
1171 struct file *filp = curlun->filp;
1172 struct inode *inode = filp->f_path.dentry->d_inode;
1175 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1176 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1179 static int do_verify(struct fsg_dev *fsg)
1181 struct lun *curlun = fsg->curlun;
1183 u32 verification_length;
1184 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1185 loff_t file_offset, file_offset_tmp;
1187 unsigned int amount;
1190 /* Get the starting Logical Block Address and check that it's
1192 lba = get_be32(&fsg->cmnd[2]);
1193 if (lba >= curlun->num_sectors) {
1194 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1198 /* We allow DPO (Disable Page Out = don't save data in the
1199 * cache) but we don't implement it. */
1200 if ((fsg->cmnd[1] & ~0x10) != 0) {
1201 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1205 verification_length = get_be16(&fsg->cmnd[7]);
1206 if (unlikely(verification_length == 0))
1207 return -EIO; /* No default reply */
1209 /* Prepare to carry out the file verify */
1210 amount_left = verification_length << 9;
1211 file_offset = ((loff_t) lba) << 9;
1213 /* Write out all the dirty buffers before invalidating them */
1215 if (signal_pending(current))
1218 invalidate_sub(curlun);
1219 if (signal_pending(current))
1222 /* Just try to read the requested blocks */
1223 while (amount_left > 0) {
1225 /* Figure out how much we need to read:
1226 * Try to read the remaining amount, but not more than
1228 * And don't try to read past the end of the file.
1229 * If this means reading 0 then we were asked to read
1230 * past the end of file. */
1231 amount = min((unsigned int) amount_left,
1232 (unsigned int)fsg->buf_size);
1233 amount = min((loff_t) amount,
1234 curlun->file_length - file_offset);
1236 curlun->sense_data =
1237 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1238 curlun->sense_data_info = file_offset >> 9;
1239 curlun->info_valid = 1;
1243 /* Perform the read */
1244 file_offset_tmp = file_offset;
1245 nread = vfs_read(curlun->filp,
1246 (char __user *) bh->buf,
1247 amount, &file_offset_tmp);
1248 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1249 (unsigned long long) file_offset,
1251 if (signal_pending(current))
1255 LDBG(curlun, "error in file verify: %d\n",
1258 } else if (nread < amount) {
1259 LDBG(curlun, "partial file verify: %d/%u\n",
1260 (int) nread, amount);
1261 nread -= (nread & 511); /* Round down to a sector */
1264 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1265 curlun->sense_data_info = file_offset >> 9;
1266 curlun->info_valid = 1;
1269 file_offset += nread;
1270 amount_left -= nread;
1276 /*-------------------------------------------------------------------------*/
1278 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1280 u8 *buf = (u8 *) bh->buf;
1282 if (!fsg->curlun) { /* Unsupported LUNs are okay */
1283 fsg->bad_lun_okay = 1;
1285 buf[0] = 0x7f; /* Unsupported, no device-type */
1289 memset(buf, 0, 8); /* Non-removable, direct-access device */
1291 buf[1] = 0x80; /* set removable bit */
1292 buf[2] = 2; /* ANSI SCSI level 2 */
1293 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1294 buf[4] = 31; /* Additional length */
1295 /* No special options */
1296 sprintf(buf + 8, "%-8s%-16s%04x", fsg->vendor,
1297 fsg->product, fsg->release);
1302 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1304 struct lun *curlun = fsg->curlun;
1305 u8 *buf = (u8 *) bh->buf;
1310 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1312 * If a REQUEST SENSE command is received from an initiator
1313 * with a pending unit attention condition (before the target
1314 * generates the contingent allegiance condition), then the
1315 * target shall either:
1316 * a) report any pending sense data and preserve the unit
1317 * attention condition on the logical unit, or,
1318 * b) report the unit attention condition, may discard any
1319 * pending sense data, and clear the unit attention
1320 * condition on the logical unit for that initiator.
1322 * FSG normally uses option a); enable this code to use option b).
1325 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1326 curlun->sense_data = curlun->unit_attention_data;
1327 curlun->unit_attention_data = SS_NO_SENSE;
1331 if (!curlun) { /* Unsupported LUNs are okay */
1332 fsg->bad_lun_okay = 1;
1333 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1337 sd = curlun->sense_data;
1338 sdinfo = curlun->sense_data_info;
1339 valid = curlun->info_valid << 7;
1340 curlun->sense_data = SS_NO_SENSE;
1341 curlun->sense_data_info = 0;
1342 curlun->info_valid = 0;
1346 buf[0] = valid | 0x70; /* Valid, current error */
1348 put_be32(&buf[3], sdinfo); /* Sense information */
1349 buf[7] = 18 - 8; /* Additional sense length */
1356 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1358 struct lun *curlun = fsg->curlun;
1359 u32 lba = get_be32(&fsg->cmnd[2]);
1360 int pmi = fsg->cmnd[8];
1361 u8 *buf = (u8 *) bh->buf;
1363 /* Check the PMI and LBA fields */
1364 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1365 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1369 put_be32(&buf[0], curlun->num_sectors - 1); /* Max logical block */
1370 put_be32(&buf[4], 512); /* Block length */
1375 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1377 struct lun *curlun = fsg->curlun;
1378 int mscmnd = fsg->cmnd[0];
1379 u8 *buf = (u8 *) bh->buf;
1382 int changeable_values, all_pages;
1386 if ((fsg->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1387 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1390 pc = fsg->cmnd[2] >> 6;
1391 page_code = fsg->cmnd[2] & 0x3f;
1393 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1396 changeable_values = (pc == 1);
1397 all_pages = (page_code == 0x3f);
1399 /* Write the mode parameter header. Fixed values are: default
1400 * medium type, no cache control (DPOFUA), and no block descriptors.
1401 * The only variable value is the WriteProtect bit. We will fill in
1402 * the mode data length later. */
1404 if (mscmnd == SC_MODE_SENSE_6) {
1405 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1408 } else { /* SC_MODE_SENSE_10 */
1409 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1414 /* No block descriptors */
1416 /* Disabled to workaround USB reset problems with a Vista host.
1419 /* The mode pages, in numerical order. The only page we support
1420 * is the Caching page. */
1421 if (page_code == 0x08 || all_pages) {
1423 buf[0] = 0x08; /* Page code */
1424 buf[1] = 10; /* Page length */
1425 memset(buf+2, 0, 10); /* None of the fields are changeable */
1427 if (!changeable_values) {
1428 buf[2] = 0x04; /* Write cache enable, */
1429 /* Read cache not disabled */
1430 /* No cache retention priorities */
1431 put_be16(&buf[4], 0xffff); /* Don't disable prefetch */
1432 /* Minimum prefetch = 0 */
1433 put_be16(&buf[8], 0xffff); /* Maximum prefetch */
1434 /* Maximum prefetch ceiling */
1435 put_be16(&buf[10], 0xffff);
1443 /* Check that a valid page was requested and the mode data length
1444 * isn't too long. */
1446 if (!valid_page || len > limit) {
1447 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1451 /* Store the mode data length */
1452 if (mscmnd == SC_MODE_SENSE_6)
1455 put_be16(buf0, len - 2);
1459 static int do_start_stop(struct fsg_dev *fsg)
1461 struct lun *curlun = fsg->curlun;
1464 /* int immed = fsg->cmnd[1] & 0x01; */
1465 loej = fsg->cmnd[4] & 0x02;
1466 start = fsg->cmnd[4] & 0x01;
1469 /* eject request from the host */
1470 if (backing_file_is_open(curlun)) {
1471 close_backing_file(fsg, curlun);
1472 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
1479 static int do_prevent_allow(struct fsg_dev *fsg)
1481 struct lun *curlun = fsg->curlun;
1484 prevent = fsg->cmnd[4] & 0x01;
1485 if ((fsg->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1486 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1490 if (curlun->prevent_medium_removal && !prevent)
1492 curlun->prevent_medium_removal = prevent;
1497 static int do_read_format_capacities(struct fsg_dev *fsg,
1498 struct fsg_buffhd *bh)
1500 struct lun *curlun = fsg->curlun;
1501 u8 *buf = (u8 *) bh->buf;
1503 buf[0] = buf[1] = buf[2] = 0;
1504 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1507 put_be32(&buf[0], curlun->num_sectors); /* Number of blocks */
1508 put_be32(&buf[4], 512); /* Block length */
1509 buf[4] = 0x02; /* Current capacity */
1514 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1516 struct lun *curlun = fsg->curlun;
1518 /* We don't support MODE SELECT */
1519 curlun->sense_data = SS_INVALID_COMMAND;
1524 /*-------------------------------------------------------------------------*/
1526 static int write_zero(struct fsg_dev *fsg)
1528 struct fsg_buffhd *bh;
1531 DBG(fsg, "write_zero\n");
1532 /* Wait for the next buffer to become available */
1533 bh = fsg->next_buffhd_to_fill;
1534 while (bh->state != BUF_STATE_EMPTY) {
1535 rc = sleep_thread(fsg);
1540 bh->inreq->length = 0;
1541 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1542 &bh->inreq_busy, &bh->state);
1544 fsg->next_buffhd_to_fill = bh->next;
1549 static int throw_away_data(struct fsg_dev *fsg)
1551 struct fsg_buffhd *bh;
1555 DBG(fsg, "throw_away_data\n");
1556 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1557 fsg->usb_amount_left > 0) {
1559 /* Throw away the data in a filled buffer */
1560 if (bh->state == BUF_STATE_FULL) {
1562 bh->state = BUF_STATE_EMPTY;
1563 fsg->next_buffhd_to_drain = bh->next;
1565 /* A short packet or an error ends everything */
1566 if (bh->outreq->actual != bh->outreq->length ||
1567 bh->outreq->status != 0) {
1568 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1574 /* Try to submit another request if we need one */
1575 bh = fsg->next_buffhd_to_fill;
1576 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1577 amount = min(fsg->usb_amount_left, (u32) fsg->buf_size);
1579 /* amount is always divisible by 512, hence by
1580 * the bulk-out maxpacket size */
1581 bh->outreq->length = bh->bulk_out_intended_length =
1583 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1584 &bh->outreq_busy, &bh->state);
1585 fsg->next_buffhd_to_fill = bh->next;
1586 fsg->usb_amount_left -= amount;
1590 /* Otherwise wait for something to happen */
1591 rc = sleep_thread(fsg);
1599 static int finish_reply(struct fsg_dev *fsg)
1601 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1604 switch (fsg->data_dir) {
1606 break; /* Nothing to send */
1608 case DATA_DIR_UNKNOWN:
1612 /* All but the last buffer of data must have already been sent */
1613 case DATA_DIR_TO_HOST:
1614 if (fsg->data_size == 0)
1615 ; /* Nothing to send */
1617 /* If there's no residue, simply send the last buffer */
1618 else if (fsg->residue == 0) {
1619 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1620 &bh->inreq_busy, &bh->state);
1621 fsg->next_buffhd_to_fill = bh->next;
1623 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1624 &bh->inreq_busy, &bh->state);
1625 fsg->next_buffhd_to_fill = bh->next;
1627 /* this is unnecessary, and was causing problems with MacOS */
1628 if (bh->inreq->length > 0)
1634 /* We have processed all we want from the data the host has sent.
1635 * There may still be outstanding bulk-out requests. */
1636 case DATA_DIR_FROM_HOST:
1637 if (fsg->residue == 0)
1638 ; /* Nothing to receive */
1640 /* Did the host stop sending unexpectedly early? */
1641 else if (fsg->short_packet_received) {
1642 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1646 /* We haven't processed all the incoming data. Even though
1647 * we may be allowed to stall, doing so would cause a race.
1648 * The controller may already have ACK'ed all the remaining
1649 * bulk-out packets, in which case the host wouldn't see a
1650 * STALL. Not realizing the endpoint was halted, it wouldn't
1651 * clear the halt -- leading to problems later on. */
1653 fsg_set_halt(fsg, fsg->bulk_out);
1654 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1658 /* We can't stall. Read in the excess data and throw it
1661 rc = throw_away_data(fsg);
1668 static int send_status(struct fsg_dev *fsg)
1670 struct lun *curlun = fsg->curlun;
1671 struct fsg_buffhd *bh;
1673 u8 status = USB_STATUS_PASS;
1675 struct bulk_cs_wrap *csw;
1677 DBG(fsg, "send_status\n");
1678 /* Wait for the next buffer to become available */
1679 bh = fsg->next_buffhd_to_fill;
1680 while (bh->state != BUF_STATE_EMPTY) {
1681 rc = sleep_thread(fsg);
1687 sd = curlun->sense_data;
1688 sdinfo = curlun->sense_data_info;
1689 } else if (fsg->bad_lun_okay)
1692 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1694 if (fsg->phase_error) {
1695 DBG(fsg, "sending phase-error status\n");
1696 status = USB_STATUS_PHASE_ERROR;
1697 sd = SS_INVALID_COMMAND;
1698 } else if (sd != SS_NO_SENSE) {
1699 DBG(fsg, "sending command-failure status\n");
1700 status = USB_STATUS_FAIL;
1701 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1703 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1708 /* Store and send the Bulk-only CSW */
1709 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
1710 csw->Tag = fsg->tag;
1711 csw->Residue = cpu_to_le32(fsg->residue);
1712 csw->Status = status;
1714 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1715 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1716 &bh->inreq_busy, &bh->state);
1718 fsg->next_buffhd_to_fill = bh->next;
1723 /*-------------------------------------------------------------------------*/
1725 /* Check whether the command is properly formed and whether its data size
1726 * and direction agree with the values we already have. */
1727 static int check_command(struct fsg_dev *fsg, int cmnd_size,
1728 enum data_direction data_dir, unsigned int mask,
1729 int needs_medium, const char *name)
1732 int lun = fsg->cmnd[1] >> 5;
1733 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1738 if (fsg->data_dir != DATA_DIR_UNKNOWN)
1739 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1741 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1742 name, cmnd_size, dirletter[(int) data_dir],
1743 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
1745 /* We can't reply at all until we know the correct data direction
1747 if (fsg->data_size_from_cmnd == 0)
1748 data_dir = DATA_DIR_NONE;
1749 if (fsg->data_dir == DATA_DIR_UNKNOWN) { /* CB or CBI */
1750 fsg->data_dir = data_dir;
1751 fsg->data_size = fsg->data_size_from_cmnd;
1753 } else { /* Bulk-only */
1754 if (fsg->data_size < fsg->data_size_from_cmnd) {
1756 /* Host data size < Device data size is a phase error.
1757 * Carry out the command, but only transfer as much
1758 * as we are allowed. */
1759 DBG(fsg, "phase error 1\n");
1760 fsg->data_size_from_cmnd = fsg->data_size;
1761 fsg->phase_error = 1;
1764 fsg->residue = fsg->usb_amount_left = fsg->data_size;
1766 /* Conflicting data directions is a phase error */
1767 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
1768 fsg->phase_error = 1;
1769 DBG(fsg, "phase error 2\n");
1773 /* Verify the length of the command itself */
1774 if (cmnd_size != fsg->cmnd_size) {
1776 /* Special case workaround: MS-Windows issues REQUEST_SENSE
1777 * and INQUIRY commands with cbw->Length == 12 (it should be 6). */
1778 if ((fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
1779 || (fsg->cmnd[0] == SC_INQUIRY && fsg->cmnd_size == 12))
1780 cmnd_size = fsg->cmnd_size;
1782 fsg->phase_error = 1;
1787 /* Check that the LUN values are consistent */
1788 if (fsg->lun != lun)
1789 DBG(fsg, "using LUN %d from CBW, "
1790 "not LUN %d from CDB\n",
1794 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
1795 fsg->curlun = curlun = &fsg->luns[fsg->lun];
1796 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
1797 curlun->sense_data = SS_NO_SENSE;
1798 curlun->sense_data_info = 0;
1799 curlun->info_valid = 0;
1802 fsg->curlun = curlun = NULL;
1803 fsg->bad_lun_okay = 0;
1805 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1806 * to use unsupported LUNs; all others may not. */
1807 if (fsg->cmnd[0] != SC_INQUIRY &&
1808 fsg->cmnd[0] != SC_REQUEST_SENSE) {
1809 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
1814 /* If a unit attention condition exists, only INQUIRY and
1815 * REQUEST SENSE commands are allowed; anything else must fail. */
1816 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1817 fsg->cmnd[0] != SC_INQUIRY &&
1818 fsg->cmnd[0] != SC_REQUEST_SENSE) {
1819 curlun->sense_data = curlun->unit_attention_data;
1820 curlun->unit_attention_data = SS_NO_SENSE;
1824 /* Check that only command bytes listed in the mask are non-zero */
1825 fsg->cmnd[1] &= 0x1f; /* Mask away the LUN */
1826 for (i = 1; i < cmnd_size; ++i) {
1827 if (fsg->cmnd[i] && !(mask & (1 << i))) {
1829 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1830 DBG(fsg, "SS_INVALID_FIELD_IN_CDB\n");
1835 /* If the medium isn't mounted and the command needs to access
1836 * it, return an error. */
1837 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
1838 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1839 DBG(fsg, "SS_MEDIUM_NOT_PRESENT\n");
1847 #ifdef CONFIG_ARCH_RK29
1848 static void deferred_restart(struct work_struct *dummy)
1851 kernel_restart("loader");
1853 static DECLARE_WORK(restart_work, deferred_restart);
1856 static int do_scsi_command(struct fsg_dev *fsg)
1858 struct fsg_buffhd *bh;
1860 int reply = -EINVAL;
1862 static char unknown[16];
1866 /* Wait for the next buffer to become available for data or status */
1867 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
1868 while (bh->state != BUF_STATE_EMPTY) {
1869 rc = sleep_thread(fsg);
1873 fsg->phase_error = 0;
1874 fsg->short_packet_received = 0;
1876 down_read(&fsg->filesem); /* We're using the backing file */
1877 switch (fsg->cmnd[0]) {
1880 fsg->data_size_from_cmnd = fsg->cmnd[4];
1881 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1884 reply = do_inquiry(fsg, bh);
1887 case SC_MODE_SELECT_6:
1888 fsg->data_size_from_cmnd = fsg->cmnd[4];
1889 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
1891 "MODE SELECT(6)")) == 0)
1892 reply = do_mode_select(fsg, bh);
1895 case SC_MODE_SELECT_10:
1896 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1897 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
1899 "MODE SELECT(10)")) == 0)
1900 reply = do_mode_select(fsg, bh);
1903 case SC_MODE_SENSE_6:
1904 fsg->data_size_from_cmnd = fsg->cmnd[4];
1905 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1906 (1<<1) | (1<<2) | (1<<4), 0,
1907 "MODE SENSE(6)")) == 0)
1908 reply = do_mode_sense(fsg, bh);
1911 case SC_MODE_SENSE_10:
1912 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1913 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1914 (1<<1) | (1<<2) | (3<<7), 0,
1915 "MODE SENSE(10)")) == 0)
1916 reply = do_mode_sense(fsg, bh);
1919 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1920 fsg->data_size_from_cmnd = 0;
1921 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
1923 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
1924 reply = do_prevent_allow(fsg);
1929 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1930 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1933 reply = do_read(fsg);
1937 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
1938 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1939 (1<<1) | (0xf<<2) | (3<<7), 1,
1941 reply = do_read(fsg);
1945 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
1946 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
1947 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1949 reply = do_read(fsg);
1952 case SC_READ_CAPACITY:
1953 fsg->data_size_from_cmnd = 8;
1954 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1955 (0xf<<2) | (1<<8), 1,
1956 "READ CAPACITY")) == 0)
1957 reply = do_read_capacity(fsg, bh);
1960 case SC_READ_FORMAT_CAPACITIES:
1961 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1962 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1964 "READ FORMAT CAPACITIES")) == 0)
1965 reply = do_read_format_capacities(fsg, bh);
1968 case SC_REQUEST_SENSE:
1969 fsg->data_size_from_cmnd = fsg->cmnd[4];
1970 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1972 "REQUEST SENSE")) == 0)
1973 reply = do_request_sense(fsg, bh);
1976 case SC_START_STOP_UNIT:
1977 fsg->data_size_from_cmnd = 0;
1978 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
1980 "START-STOP UNIT")) == 0)
1981 reply = do_start_stop(fsg);
1984 case SC_SYNCHRONIZE_CACHE:
1985 fsg->data_size_from_cmnd = 0;
1986 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
1987 (0xf<<2) | (3<<7), 1,
1988 "SYNCHRONIZE CACHE")) == 0)
1989 reply = do_synchronize_cache(fsg);
1992 case SC_TEST_UNIT_READY:
1993 fsg->data_size_from_cmnd = 0;
1994 reply = check_command(fsg, 6, DATA_DIR_NONE,
1999 /* Although optional, this command is used by MS-Windows. We
2000 * support a minimal version: BytChk must be 0. */
2002 fsg->data_size_from_cmnd = 0;
2003 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
2004 (1<<1) | (0xf<<2) | (3<<7), 1,
2006 reply = 0;//do_verify(fsg);//zyf 20100302
2011 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2012 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
2015 reply = do_write(fsg);
2019 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
2020 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
2021 (1<<1) | (0xf<<2) | (3<<7), 1,
2023 reply = do_write(fsg);
2027 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
2028 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
2029 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2031 reply = do_write(fsg);
2034 /* Some mandatory commands that we recognize but don't implement.
2035 * They don't mean much in this setting. It's left as an exercise
2036 * for anyone interested to implement RESERVE and RELEASE in terms
2037 * of Posix locks. */
2038 case SC_FORMAT_UNIT:
2041 case SC_SEND_DIAGNOSTIC:
2045 fsg->data_size_from_cmnd = 0;
2046 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
2047 if ((reply = check_command(fsg, fsg->cmnd_size,
2048 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
2049 fsg->curlun->sense_data = SS_INVALID_COMMAND;
2053 #ifdef CONFIG_ARCH_RK29
2055 if (fsg->cmnd_size >= 6 && fsg->cmnd[1] == 0xe0 &&
2056 fsg->cmnd[2] == 0xff && fsg->cmnd[3] == 0xff &&
2057 fsg->cmnd[4] == 0xff && fsg->cmnd[5] == 0xfe) {
2058 schedule_work(&restart_work);
2063 up_read(&fsg->filesem);
2065 VDBG(fsg, "reply: %d, fsg->data_size_from_cmnd: %d\n",
2066 reply, fsg->data_size_from_cmnd);
2067 if (reply == -EINTR || signal_pending(current))
2070 /* Set up the single reply buffer for finish_reply() */
2071 if (reply == -EINVAL)
2072 reply = 0; /* Error reply length */
2073 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2074 reply = min((u32) reply, fsg->data_size_from_cmnd);
2075 bh->inreq->length = reply;
2076 bh->state = BUF_STATE_FULL;
2077 fsg->residue -= reply;
2078 } /* Otherwise it's already set */
2084 /*-------------------------------------------------------------------------*/
2086 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2088 struct usb_request *req = bh->outreq;
2089 struct bulk_cb_wrap *cbw = req->buf;
2091 /* Was this a real packet? */
2095 /* Is the CBW valid? */
2096 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2097 cbw->Signature != __constant_cpu_to_le32(
2099 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2101 le32_to_cpu(cbw->Signature));
2105 /* Is the CBW meaningful? */
2106 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2107 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2108 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2110 cbw->Lun, cbw->Flags, cbw->Length);
2114 /* Save the command for later */
2115 fsg->cmnd_size = cbw->Length;
2116 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2117 if (cbw->Flags & USB_BULK_IN_FLAG)
2118 fsg->data_dir = DATA_DIR_TO_HOST;
2120 fsg->data_dir = DATA_DIR_FROM_HOST;
2121 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2122 if (fsg->data_size == 0)
2123 fsg->data_dir = DATA_DIR_NONE;
2124 fsg->lun = cbw->Lun;
2125 fsg->tag = cbw->Tag;
2130 static int get_next_command(struct fsg_dev *fsg)
2132 struct fsg_buffhd *bh;
2135 /* Wait for the next buffer to become available */
2136 bh = fsg->next_buffhd_to_fill;
2137 while (bh->state != BUF_STATE_EMPTY) {
2138 rc = sleep_thread(fsg);
2140 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2141 bh->outreq_busy = 0;
2142 bh->state = BUF_STATE_EMPTY;
2147 /* Queue a request to read a Bulk-only CBW */
2148 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2149 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2150 &bh->outreq_busy, &bh->state);
2152 /* We will drain the buffer in software, which means we
2153 * can reuse it for the next filling. No need to advance
2154 * next_buffhd_to_fill. */
2156 /* Wait for the CBW to arrive */
2157 while (bh->state != BUF_STATE_FULL) {
2158 rc = sleep_thread(fsg);
2160 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2161 bh->outreq_busy = 0;
2162 bh->state = BUF_STATE_EMPTY;
2167 rc = received_cbw(fsg, bh);
2168 bh->state = BUF_STATE_EMPTY;
2174 /*-------------------------------------------------------------------------*/
2176 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2177 const struct usb_endpoint_descriptor *d)
2181 DBG(fsg, "usb_ep_enable %s\n", ep->name);
2182 ep->driver_data = fsg;
2183 rc = usb_ep_enable(ep, d);
2185 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2189 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2190 struct usb_request **preq)
2192 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2195 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2200 * Reset interface setting and re-init endpoint state (toggle etc).
2201 * Call with altsetting < 0 to disable the interface. The only other
2202 * available altsetting is 0, which enables the interface.
2204 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2206 struct usb_composite_dev *cdev = fsg->cdev;
2209 const struct usb_endpoint_descriptor *d;
2212 DBG(fsg, "reset interface\n");
2214 /* Disable the endpoints */
2215 if (fsg->bulk_in_enabled) {
2216 DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_in->name);
2217 usb_ep_disable(fsg->bulk_in);
2218 fsg->bulk_in_enabled = 0;
2220 if (fsg->bulk_out_enabled) {
2221 DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_out->name);
2222 usb_ep_disable(fsg->bulk_out);
2223 fsg->bulk_out_enabled = 0;
2226 /* Deallocate the requests */
2227 for (i = 0; i < NUM_BUFFERS; ++i) {
2228 struct fsg_buffhd *bh = &fsg->buffhds[i];
2230 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2234 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2241 if (altsetting < 0 || rc != 0)
2244 DBG(fsg, "set interface %d\n", altsetting);
2246 /* Enable the endpoints */
2247 d = ep_desc(cdev->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
2248 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2250 fsg->bulk_in_enabled = 1;
2252 d = ep_desc(cdev->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
2253 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2255 fsg->bulk_out_enabled = 1;
2256 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2258 /* Allocate the requests */
2259 for (i = 0; i < NUM_BUFFERS; ++i) {
2260 struct fsg_buffhd *bh = &fsg->buffhds[i];
2262 rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq);
2265 rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq);
2268 bh->inreq->buf = bh->outreq->buf = bh->buf;
2269 bh->inreq->context = bh->outreq->context = bh;
2270 bh->inreq->complete = bulk_in_complete;
2271 bh->outreq->complete = bulk_out_complete;
2275 for (i = 0; i < fsg->nluns; ++i)
2276 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2281 static void adjust_wake_lock(struct fsg_dev *fsg)
2285 unsigned long flags;
2287 spin_lock_irqsave(&fsg->lock, flags);
2290 for (i = 0; i < fsg->nluns; ++i) {
2291 if (backing_file_is_open(&fsg->luns[i]))
2297 wake_lock(&fsg->wake_lock);
2299 wake_unlock(&fsg->wake_lock);
2301 spin_unlock_irqrestore(&fsg->lock, flags);
2305 * Change our operational configuration. This code must agree with the code
2306 * that returns config descriptors, and with interface altsetting code.
2308 * It's also responsible for power management interactions. Some
2309 * configurations might not work with our current power sources.
2310 * For now we just assume the gadget is always self-powered.
2312 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2316 /* Disable the single interface */
2317 if (fsg->config != 0) {
2318 DBG(fsg, "reset config\n");
2320 rc = do_set_interface(fsg, -1);
2323 /* Enable the interface */
2324 if (new_config != 0) {
2325 fsg->config = new_config;
2326 if ((rc = do_set_interface(fsg, 0)) != 0)
2327 fsg->config = 0; // Reset on errors
2329 set_msc_connect_flag( 1 );
2332 switch_set_state(&fsg->sdev, new_config);
2333 adjust_wake_lock(fsg);
2338 /*-------------------------------------------------------------------------*/
2339 static void handle_exception(struct fsg_dev *fsg)
2345 struct fsg_buffhd *bh;
2346 enum fsg_state old_state;
2350 unsigned long flags;
2352 DBG(fsg, "handle_exception state: %d\n", (int)fsg->state);
2353 /* Clear the existing signals. Anything but SIGUSR1 is converted
2354 * into a high-priority EXIT exception. */
2356 sig = dequeue_signal_lock(current, ¤t->blocked, &info);
2359 if (sig != SIGUSR1) {
2360 if (fsg->state < FSG_STATE_EXIT)
2361 DBG(fsg, "Main thread exiting on signal\n");
2362 raise_exception(fsg, FSG_STATE_EXIT);
2366 /* Cancel all the pending transfers */
2367 for (i = 0; i < NUM_BUFFERS; ++i) {
2368 bh = &fsg->buffhds[i];
2370 usb_ep_dequeue(fsg->bulk_in, bh->inreq);
2371 if (bh->outreq_busy)
2372 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2375 /* Wait until everything is idle */
2378 for (i = 0; i < NUM_BUFFERS; ++i) {
2379 bh = &fsg->buffhds[i];
2380 num_active += bh->outreq_busy;
2382 if (num_active == 0)
2384 if (sleep_thread(fsg))
2389 * Do NOT flush the fifo after set_interface()
2390 * Otherwise, it results in some data being lost
2392 if ((fsg->state != FSG_STATE_CONFIG_CHANGE) ||
2393 (fsg->new_config != 1)) {
2394 /* Clear out the controller's fifos */
2395 if (fsg->bulk_in_enabled)
2396 usb_ep_fifo_flush(fsg->bulk_in);
2397 if (fsg->bulk_out_enabled)
2398 usb_ep_fifo_flush(fsg->bulk_out);
2400 /* Reset the I/O buffer states and pointers, the SCSI
2401 * state, and the exception. Then invoke the handler. */
2402 spin_lock_irqsave(&fsg->lock, flags);
2404 for (i = 0; i < NUM_BUFFERS; ++i) {
2405 bh = &fsg->buffhds[i];
2406 bh->state = BUF_STATE_EMPTY;
2408 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2411 new_config = fsg->new_config;
2412 old_state = fsg->state;
2414 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2415 fsg->state = FSG_STATE_STATUS_PHASE;
2417 for (i = 0; i < fsg->nluns; ++i) {
2418 curlun = &fsg->luns[i];
2419 curlun->prevent_medium_removal = 0;
2420 curlun->sense_data = curlun->unit_attention_data =
2422 curlun->sense_data_info = 0;
2423 curlun->info_valid = 0;
2425 fsg->state = FSG_STATE_IDLE;
2427 spin_unlock_irqrestore(&fsg->lock, flags);
2429 /* Carry out any extra actions required for the exception */
2430 switch (old_state) {
2434 case FSG_STATE_ABORT_BULK_OUT:
2435 DBG(fsg, "FSG_STATE_ABORT_BULK_OUT\n");
2436 spin_lock_irqsave(&fsg->lock, flags);
2437 if (fsg->state == FSG_STATE_STATUS_PHASE)
2438 fsg->state = FSG_STATE_IDLE;
2439 spin_unlock_irqrestore(&fsg->lock, flags);
2442 case FSG_STATE_RESET:
2443 /* really not much to do here */
2446 case FSG_STATE_CONFIG_CHANGE:
2447 rc = do_set_config(fsg, new_config);
2448 if (new_config == 0) {
2449 /* We're using the backing file */
2450 down_read(&fsg->filesem);
2452 up_read(&fsg->filesem);
2456 case FSG_STATE_EXIT:
2457 case FSG_STATE_TERMINATED:
2458 do_set_config(fsg, 0); /* Free resources */
2459 spin_lock_irqsave(&fsg->lock, flags);
2460 fsg->state = FSG_STATE_TERMINATED; /* Stop the thread */
2461 spin_unlock_irqrestore(&fsg->lock, flags);
2467 /*-------------------------------------------------------------------------*/
2469 static int fsg_main_thread(void *fsg_)
2471 struct fsg_dev *fsg = fsg_;
2472 unsigned long flags;
2474 /* Allow the thread to be killed by a signal, but set the signal mask
2475 * to block everything but INT, TERM, KILL, and USR1. */
2476 allow_signal(SIGINT);
2477 allow_signal(SIGTERM);
2478 allow_signal(SIGKILL);
2479 allow_signal(SIGUSR1);
2481 /* Allow the thread to be frozen */
2484 /* Arrange for userspace references to be interpreted as kernel
2485 * pointers. That way we can pass a kernel pointer to a routine
2486 * that expects a __user pointer and it will work okay. */
2490 while (fsg->state != FSG_STATE_TERMINATED) {
2491 if (exception_in_progress(fsg) || signal_pending(current)) {
2492 handle_exception(fsg);
2496 if (!fsg->running) {
2501 if (get_next_command(fsg))
2504 spin_lock_irqsave(&fsg->lock, flags);
2505 if (!exception_in_progress(fsg))
2506 fsg->state = FSG_STATE_DATA_PHASE;
2507 spin_unlock_irqrestore(&fsg->lock, flags);
2509 if (do_scsi_command(fsg) || finish_reply(fsg))
2512 spin_lock_irqsave(&fsg->lock, flags);
2513 if (!exception_in_progress(fsg))
2514 fsg->state = FSG_STATE_STATUS_PHASE;
2515 spin_unlock_irqrestore(&fsg->lock, flags);
2517 if (send_status(fsg))
2520 spin_lock_irqsave(&fsg->lock, flags);
2521 if (!exception_in_progress(fsg))
2522 fsg->state = FSG_STATE_IDLE;
2523 spin_unlock_irqrestore(&fsg->lock, flags);
2526 spin_lock_irqsave(&fsg->lock, flags);
2527 fsg->thread_task = NULL;
2528 spin_unlock_irqrestore(&fsg->lock, flags);
2530 /* In case we are exiting because of a signal, unregister the
2531 * gadget driver and close the backing file. */
2532 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2533 close_all_backing_files(fsg);
2535 /* Let the unbind and cleanup routines know the thread has exited */
2536 complete_and_exit(&fsg->thread_notifier, 0);
2540 /*-------------------------------------------------------------------------*/
2542 /* If the next two routines are called while the gadget is registered,
2543 * the caller must own fsg->filesem for writing. */
2545 static int open_backing_file(struct fsg_dev *fsg, struct lun *curlun,
2546 const char *filename)
2549 struct file *filp = NULL;
2551 struct inode *inode = NULL;
2555 /* R/W if we can, R/O if we must */
2558 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
2559 if (-EROFS == PTR_ERR(filp))
2563 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
2565 LINFO(curlun, "unable to open backing file: %s\n", filename);
2566 return PTR_ERR(filp);
2569 if (!(filp->f_mode & FMODE_WRITE))
2572 if (filp->f_path.dentry)
2573 inode = filp->f_path.dentry->d_inode;
2574 if (inode && S_ISBLK(inode->i_mode)) {
2575 if (bdev_read_only(inode->i_bdev))
2577 } else if (!inode || !S_ISREG(inode->i_mode)) {
2578 LINFO(curlun, "invalid file type: %s\n", filename);
2582 /* If we can't read the file, it's no good.
2583 * If we can't write the file, use it read-only. */
2584 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
2585 LINFO(curlun, "file not readable: %s\n", filename);
2588 if (!(filp->f_op->write || filp->f_op->aio_write))
2591 size = i_size_read(inode->i_mapping->host);
2593 LINFO(curlun, "unable to find file size: %s\n", filename);
2597 num_sectors = size >> 9; /* File size in 512-byte sectors */
2598 if (num_sectors == 0) {
2599 LINFO(curlun, "file too small: %s\n", filename);
2606 curlun->filp = filp;
2607 curlun->file_length = size;
2608 curlun->unflushed_bytes = 0;
2609 curlun->num_sectors = num_sectors;
2610 LDBG(curlun, "open backing file: %s size: %lld num_sectors: %lld\n",
2611 filename, size, num_sectors);
2613 adjust_wake_lock(fsg);
2616 filp_close(filp, current->files);
2621 static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun)
2627 * XXX: San: Ugly hack here added to ensure that
2628 * our pages get synced to disk.
2629 * Also drop caches here just to be extra-safe
2631 rc = vfs_fsync(curlun->filp, curlun->filp->f_path.dentry, 1);
2633 printk(KERN_ERR "ums: Error syncing data (%d)\n", rc);
2634 /* drop_pagecache and drop_slab are no longer available */
2635 /* drop_pagecache(); */
2638 LDBG(curlun, "close backing file\n");
2640 curlun->filp = NULL;
2641 adjust_wake_lock(fsg);
2645 static void close_all_backing_files(struct fsg_dev *fsg)
2649 for (i = 0; i < fsg->nluns; ++i)
2650 close_backing_file(fsg, &fsg->luns[i]);
2653 static ssize_t show_file(struct device *dev, struct device_attribute *attr,
2656 struct lun *curlun = dev_to_lun(dev);
2657 struct fsg_dev *fsg = dev_get_drvdata(dev);
2661 down_read(&fsg->filesem);
2662 if (backing_file_is_open(curlun)) { /* Get the complete pathname */
2663 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
2668 memmove(buf, p, rc);
2669 buf[rc] = '\n'; /* Add a newline */
2672 } else { /* No file, return 0 bytes */
2676 up_read(&fsg->filesem);
2680 static ssize_t store_file(struct device *dev, struct device_attribute *attr,
2681 const char *buf, size_t count)
2683 struct lun *curlun = dev_to_lun(dev);
2684 struct fsg_dev *fsg = dev_get_drvdata(dev);
2687 DBG(fsg, "store_file: \"%s\"\n", buf);
2688 printk("store_file: \"%s\"\n", buf);
2690 /* disabled because we need to allow closing the backing file if the media was removed */
2691 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
2692 LDBG(curlun, "eject attempt prevented\n");
2693 return -EBUSY; /* "Door is locked" */
2697 /* Remove a trailing newline */
2698 if (count > 0 && buf[count-1] == '\n')
2699 ((char *) buf)[count-1] = 0;
2701 /* Eject current medium */
2702 down_write(&fsg->filesem);
2703 if (backing_file_is_open(curlun)) {
2704 close_backing_file(fsg, curlun);
2705 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2708 /* Load new medium */
2709 if (count > 0 && buf[0]) {
2710 rc = open_backing_file(fsg, curlun, buf);
2712 curlun->unit_attention_data =
2713 SS_NOT_READY_TO_READY_TRANSITION;
2715 up_write(&fsg->filesem);
2716 return (rc < 0 ? rc : count);
2720 static DEVICE_ATTR(file, 0444, show_file, store_file);
2722 /*-------------------------------------------------------------------------*/
2724 static void fsg_release(struct kref *ref)
2726 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
2732 static void lun_release(struct device *dev)
2734 struct fsg_dev *fsg = dev_get_drvdata(dev);
2736 kref_put(&fsg->ref, fsg_release);
2740 /*-------------------------------------------------------------------------*/
2742 static int __init fsg_alloc(void)
2744 struct fsg_dev *fsg;
2746 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
2749 spin_lock_init(&fsg->lock);
2750 init_rwsem(&fsg->filesem);
2751 kref_init(&fsg->ref);
2752 init_completion(&fsg->thread_notifier);
2758 static ssize_t print_switch_name(struct switch_dev *sdev, char *buf)
2760 return sprintf(buf, "%s\n", DRIVER_NAME);
2763 static ssize_t print_switch_state(struct switch_dev *sdev, char *buf)
2765 struct fsg_dev *fsg = container_of(sdev, struct fsg_dev, sdev);
2766 return sprintf(buf, "%s\n", (fsg->config ? "online" : "offline"));
2770 fsg_function_unbind(struct usb_configuration *c, struct usb_function *f)
2772 struct fsg_dev *fsg = func_to_dev(f);
2776 DBG(fsg, "fsg_function_unbind\n");
2777 clear_bit(REGISTERED, &fsg->atomic_bitflags);
2779 /* Unregister the sysfs attribute files and the LUNs */
2780 for (i = 0; i < fsg->nluns; ++i) {
2781 curlun = &fsg->luns[i];
2782 if (curlun->registered) {
2783 device_remove_file(&curlun->dev, &dev_attr_file);
2784 device_unregister(&curlun->dev);
2785 curlun->registered = 0;
2789 /* If the thread isn't already dead, tell it to exit now */
2790 if (fsg->state != FSG_STATE_TERMINATED) {
2791 raise_exception(fsg, FSG_STATE_EXIT);
2792 wait_for_completion(&fsg->thread_notifier);
2794 /* The cleanup routine waits for this completion also */
2795 complete(&fsg->thread_notifier);
2798 /* Free the data buffers */
2799 for (i = 0; i < NUM_BUFFERS; ++i)
2800 kfree(fsg->buffhds[i].buf);
2801 switch_dev_unregister(&fsg->sdev);
2805 fsg_function_bind(struct usb_configuration *c, struct usb_function *f)
2807 struct usb_composite_dev *cdev = c->cdev;
2808 struct fsg_dev *fsg = func_to_dev(f);
2817 DBG(fsg, "fsg_function_bind\n");
2819 dev_attr_file.attr.mode = 0644;
2821 /* Find out how many LUNs there should be */
2826 ERROR(fsg, "invalid number of LUNs: %d\n", i);
2831 /* Create the LUNs, open their backing files, and register the
2832 * LUN devices in sysfs. */
2833 fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL);
2840 for (i = 0; i < fsg->nluns; ++i) {
2841 curlun = &fsg->luns[i];
2843 curlun->dev.release = lun_release;
2844 /* use "usb_mass_storage" platform device as parent if available */
2846 curlun->dev.parent = &fsg->pdev->dev;
2848 curlun->dev.parent = &cdev->gadget->dev;
2849 dev_set_drvdata(&curlun->dev, fsg);
2850 dev_set_name(&curlun->dev,"lun%d", i);
2852 rc = device_register(&curlun->dev);
2854 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
2857 rc = device_create_file(&curlun->dev, &dev_attr_file);
2859 ERROR(fsg, "device_create_file failed: %d\n", rc);
2860 device_unregister(&curlun->dev);
2863 curlun->registered = 1;
2864 kref_get(&fsg->ref);
2867 /* allocate interface ID(s) */
2868 id = usb_interface_id(c, f);
2871 intf_desc.bInterfaceNumber = id;
2873 ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_in_desc);
2876 ep->driver_data = fsg; /* claim the endpoint */
2879 ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_out_desc);
2882 ep->driver_data = fsg; /* claim the endpoint */
2887 if (gadget_is_dualspeed(cdev->gadget)) {
2888 /* Assume endpoint addresses are the same for both speeds */
2889 hs_bulk_in_desc.bEndpointAddress =
2890 fs_bulk_in_desc.bEndpointAddress;
2891 hs_bulk_out_desc.bEndpointAddress =
2892 fs_bulk_out_desc.bEndpointAddress;
2894 f->hs_descriptors = hs_function;
2897 /* Allocate the data buffers */
2898 for (i = 0; i < NUM_BUFFERS; ++i) {
2899 struct fsg_buffhd *bh = &fsg->buffhds[i];
2901 /* Allocate for the bulk-in endpoint. We assume that
2902 * the buffer will also work with the bulk-out (and
2903 * interrupt-in) endpoint. */
2904 bh->buf = kmalloc(fsg->buf_size, GFP_KERNEL);
2909 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
2911 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
2913 if (IS_ERR(fsg->thread_task)) {
2914 rc = PTR_ERR(fsg->thread_task);
2915 ERROR(fsg, "kthread_create failed: %d\n", rc);
2919 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
2921 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2922 for (i = 0; i < fsg->nluns; ++i) {
2923 curlun = &fsg->luns[i];
2924 if (backing_file_is_open(curlun)) {
2927 p = d_path(&curlun->filp->f_path,
2932 LINFO(curlun, "ro=%d, file: %s\n",
2933 curlun->ro, (p ? p : "(error)"));
2938 set_bit(REGISTERED, &fsg->atomic_bitflags);
2940 /* Tell the thread to start working */
2941 wake_up_process(fsg->thread_task);
2945 ERROR(fsg, "unable to autoconfigure all endpoints\n");
2949 DBG(fsg, "fsg_function_bind failed: %d\n", rc);
2950 fsg->state = FSG_STATE_TERMINATED; /* The thread is dead */
2951 fsg_function_unbind(c, f);
2952 close_all_backing_files(fsg);
2956 static int fsg_function_set_alt(struct usb_function *f,
2957 unsigned intf, unsigned alt)
2959 struct fsg_dev *fsg = func_to_dev(f);
2960 DBG(fsg, "fsg_function_set_alt intf: %d alt: %d\n", intf, alt);
2961 fsg->new_config = 1;
2962 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
2966 static void fsg_function_disable(struct usb_function *f)
2968 struct fsg_dev *fsg = func_to_dev(f);
2969 DBG(fsg, "fsg_function_disable\n");
2970 fsg->new_config = 0;
2971 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
2973 set_msc_connect_flag(0);
2976 static enum power_supply_property usb_props[] = {
2977 // POWER_SUPPLY_PROP_STATUS,
2978 POWER_SUPPLY_PROP_ONLINE,
2981 static int usb_get_property(struct power_supply *psy,
2982 enum power_supply_property psp,
2983 union power_supply_propval *val)
2988 case POWER_SUPPLY_PROP_ONLINE:
2989 #ifndef CONFIG_DWC_OTG_HOST_ONLY
2990 val->intval = get_msc_connect_flag();
3002 int usb_power_supply_register(struct device* parent)
3004 struct power_supply *ps;
3007 ps = kzalloc(sizeof(*ps), GFP_KERNEL);
3009 dev_err(parent, "failed to allocate power supply data\n");
3014 ps->type = POWER_SUPPLY_TYPE_USB;
3015 ps->properties = usb_props;
3016 ps->num_properties = ARRAY_SIZE(usb_props);
3017 ps->get_property = usb_get_property;
3018 ps->external_power_changed = NULL;
3019 retval = power_supply_register(parent, ps);
3021 dev_err(parent, "failed to register battery\n");
3028 static int __init fsg_probe(struct platform_device *pdev)
3030 struct usb_mass_storage_platform_data *pdata = pdev->dev.platform_data;
3031 struct fsg_dev *fsg = the_fsg;
3035 printk(KERN_INFO "fsg_probe pdata: %p\n", pdata);
3039 fsg->vendor = pdata->vendor;
3042 fsg->product = pdata->product;
3045 fsg->release = pdata->release;
3046 fsg->nluns = pdata->nluns;
3050 * Initialize usb power supply
3052 retval = usb_power_supply_register(&pdev->dev);
3055 dev_err(&pdev->dev, "usb_power_supply_register failed\n");
3061 static struct platform_driver fsg_platform_driver = {
3062 .driver = { .name = "usb_mass_storage", },
3066 int mass_storage_bind_config(struct usb_configuration *c)
3069 struct fsg_dev *fsg;
3071 printk("mass_storage_bind_config\n");
3077 spin_lock_init(&fsg->lock);
3078 init_rwsem(&fsg->filesem);
3079 kref_init(&fsg->ref);
3080 init_completion(&fsg->thread_notifier);
3082 the_fsg->buf_size = BULK_BUFFER_SIZE;
3083 the_fsg->sdev.name = DRIVER_NAME;
3084 the_fsg->sdev.print_name = print_switch_name;
3085 the_fsg->sdev.print_state = print_switch_state;
3086 rc = switch_dev_register(&the_fsg->sdev);
3088 goto err_switch_dev_register;
3090 rc = platform_driver_register(&fsg_platform_driver);
3092 goto err_platform_driver_register;
3094 wake_lock_init(&the_fsg->wake_lock, WAKE_LOCK_SUSPEND,
3095 "usb_mass_storage");
3097 fsg->cdev = c->cdev;
3098 fsg->function.name = shortname;
3099 fsg->function.descriptors = fs_function;
3100 fsg->function.bind = fsg_function_bind;
3101 fsg->function.unbind = fsg_function_unbind;
3102 fsg->function.setup = fsg_function_setup;
3103 fsg->function.set_alt = fsg_function_set_alt;
3104 fsg->function.disable = fsg_function_disable;
3106 rc = usb_add_function(c, &fsg->function);
3108 goto err_usb_add_function;
3113 err_usb_add_function:
3114 wake_lock_destroy(&the_fsg->wake_lock);
3115 platform_driver_unregister(&fsg_platform_driver);
3116 err_platform_driver_register:
3117 switch_dev_unregister(&the_fsg->sdev);
3118 err_switch_dev_register:
3119 kref_put(&the_fsg->ref, fsg_release);
3124 static struct android_usb_function mass_storage_function = {
3125 .name = "usb_mass_storage",
3126 .bind_config = mass_storage_bind_config,
3129 static int __init init(void)
3131 printk(KERN_INFO "f_mass_storage init\n");
3132 android_register_function(&mass_storage_function);