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>
72 #include <linux/usb_usual.h>
73 #include <linux/usb/ch9.h>
74 #include <linux/usb/composite.h>
75 #include <linux/usb/gadget.h>
76 #include <linux/usb/android.h>
78 #include "f_mass_storage.h"
79 #include "gadget_chips.h"
82 #define BULK_BUFFER_SIZE 4096
84 /*-------------------------------------------------------------------------*/
86 #define DRIVER_NAME "usb_mass_storage"
89 static const char shortname[] = DRIVER_NAME;
92 #define LDBG(lun, fmt, args...) \
93 dev_dbg(&(lun)->dev , fmt , ## args)
94 #define MDBG(fmt,args...) \
95 printk(KERN_DEBUG DRIVER_NAME ": " fmt , ## args)
97 #define LDBG(lun, fmt, args...) \
99 #define MDBG(fmt,args...) \
108 #define VLDBG(lun, fmt, args...) \
110 #endif /* VERBOSE_DEBUG */
112 #define LERROR(lun, fmt, args...) \
113 dev_err(&(lun)->dev , fmt , ## args)
114 #define LWARN(lun, fmt, args...) \
115 dev_warn(&(lun)->dev , fmt , ## args)
116 #define LINFO(lun, fmt, args...) \
117 dev_info(&(lun)->dev , fmt , ## args)
119 #define MINFO(fmt,args...) \
120 printk(KERN_INFO DRIVER_NAME ": " fmt , ## args)
127 #define DBG(d, fmt, args...) \
128 dev_dbg(&(d)->cdev->gadget->dev , fmt , ## args)
129 #define VDBG(d, fmt, args...) \
130 dev_vdbg(&(d)->cdev->gadget->dev , fmt , ## args)
131 #define ERROR(d, fmt, args...) \
132 dev_err(&(d)->cdev->gadget->dev , fmt , ## args)
133 #define WARNING(d, fmt, args...) \
134 dev_warn(&(d)->cdev->gadget->dev , fmt , ## args)
135 #define INFO(d, fmt, args...) \
136 dev_info(&(d)->cdev->gadget->dev , fmt , ## args)
139 /*-------------------------------------------------------------------------*/
141 /* Bulk-only data structures */
143 /* Command Block Wrapper */
144 struct bulk_cb_wrap {
145 __le32 Signature; /* Contains 'USBC' */
146 u32 Tag; /* Unique per command id */
147 __le32 DataTransferLength; /* Size of the data */
148 u8 Flags; /* Direction in bit 7 */
149 u8 Lun; /* LUN (normally 0) */
150 u8 Length; /* Of the CDB, <= MAX_COMMAND_SIZE */
151 u8 CDB[16]; /* Command Data Block */
154 #define USB_BULK_CB_WRAP_LEN 31
155 #define USB_BULK_CB_SIG 0x43425355 /* Spells out USBC */
156 #define USB_BULK_IN_FLAG 0x80
158 /* Command Status Wrapper */
159 struct bulk_cs_wrap {
160 __le32 Signature; /* Should = 'USBS' */
161 u32 Tag; /* Same as original command */
162 __le32 Residue; /* Amount not transferred */
163 u8 Status; /* See below */
166 #define USB_BULK_CS_WRAP_LEN 13
167 #define USB_BULK_CS_SIG 0x53425355 /* Spells out 'USBS' */
168 #define USB_STATUS_PASS 0
169 #define USB_STATUS_FAIL 1
170 #define USB_STATUS_PHASE_ERROR 2
172 /* Bulk-only class specific requests */
173 #define USB_BULK_RESET_REQUEST 0xff
174 #define USB_BULK_GET_MAX_LUN_REQUEST 0xfe
176 /* Length of a SCSI Command Data Block */
177 #define MAX_COMMAND_SIZE 16
179 /* SCSI commands that we recognize */
180 #define SC_FORMAT_UNIT 0x04
181 #define SC_INQUIRY 0x12
182 #define SC_MODE_SELECT_6 0x15
183 #define SC_MODE_SELECT_10 0x55
184 #define SC_MODE_SENSE_6 0x1a
185 #define SC_MODE_SENSE_10 0x5a
186 #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
187 #define SC_READ_6 0x08
188 #define SC_READ_10 0x28
189 #define SC_READ_12 0xa8
190 #define SC_READ_CAPACITY 0x25
191 #define SC_READ_FORMAT_CAPACITIES 0x23
192 #define SC_RELEASE 0x17
193 #define SC_REQUEST_SENSE 0x03
194 #define SC_RESERVE 0x16
195 #define SC_SEND_DIAGNOSTIC 0x1d
196 #define SC_START_STOP_UNIT 0x1b
197 #define SC_SYNCHRONIZE_CACHE 0x35
198 #define SC_TEST_UNIT_READY 0x00
199 #define SC_VERIFY 0x2f
200 #define SC_WRITE_6 0x0a
201 #define SC_WRITE_10 0x2a
202 #define SC_WRITE_12 0xaa
204 /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
205 #define SS_NO_SENSE 0
206 #define SS_COMMUNICATION_FAILURE 0x040800
207 #define SS_INVALID_COMMAND 0x052000
208 #define SS_INVALID_FIELD_IN_CDB 0x052400
209 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
210 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
211 #define SS_MEDIUM_NOT_PRESENT 0x023a00
212 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
213 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800
214 #define SS_RESET_OCCURRED 0x062900
215 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
216 #define SS_UNRECOVERED_READ_ERROR 0x031100
217 #define SS_WRITE_ERROR 0x030c02
218 #define SS_WRITE_PROTECTED 0x072700
220 #define SK(x) ((u8) ((x) >> 16)) /* Sense Key byte, etc. */
221 #define ASC(x) ((u8) ((x) >> 8))
222 #define ASCQ(x) ((u8) (x))
225 /*-------------------------------------------------------------------------*/
233 unsigned int prevent_medium_removal : 1;
234 unsigned int registered : 1;
235 unsigned int info_valid : 1;
239 u32 unit_attention_data;
244 #define backing_file_is_open(curlun) ((curlun)->filp != NULL)
247 static struct lun *dev_to_lun(struct device *dev)
249 return container_of(dev, struct lun, dev);
252 /* Big enough to hold our biggest descriptor */
253 #define EP0_BUFSIZE 256
254 #define DELAYED_STATUS (EP0_BUFSIZE + 999) /* An impossibly large value */
256 /* Number of buffers we will use. 2 is enough for double-buffering */
257 #define NUM_BUFFERS 2
259 enum fsg_buffer_state {
267 enum fsg_buffer_state state;
268 struct fsg_buffhd *next;
270 /* The NetChip 2280 is faster, and handles some protocol faults
271 * better, if we don't submit any short bulk-out read requests.
272 * So we will record the intended request length here. */
273 unsigned int bulk_out_intended_length;
275 struct usb_request *inreq;
277 struct usb_request *outreq;
282 /* This one isn't used anywhere */
283 FSG_STATE_COMMAND_PHASE = -10,
285 FSG_STATE_DATA_PHASE,
286 FSG_STATE_STATUS_PHASE,
289 FSG_STATE_ABORT_BULK_OUT,
291 FSG_STATE_CONFIG_CHANGE,
296 enum data_direction {
297 DATA_DIR_UNKNOWN = 0,
304 struct usb_function function;
305 struct usb_composite_dev *cdev;
307 /* optional "usb_mass_storage" platform device */
308 struct platform_device *pdev;
310 /* lock protects: state and all the req_busy's */
313 /* filesem protects: backing files in use */
314 struct rw_semaphore filesem;
316 /* reference counting: wait until all LUNs are released */
319 unsigned int bulk_out_maxpacket;
320 enum fsg_state state; /* For exception handling */
322 u8 config, new_config;
324 unsigned int running : 1;
325 unsigned int bulk_in_enabled : 1;
326 unsigned int bulk_out_enabled : 1;
327 unsigned int phase_error : 1;
328 unsigned int short_packet_received : 1;
329 unsigned int bad_lun_okay : 1;
331 unsigned long atomic_bitflags;
333 #define CLEAR_BULK_HALTS 1
336 struct usb_ep *bulk_in;
337 struct usb_ep *bulk_out;
339 struct fsg_buffhd *next_buffhd_to_fill;
340 struct fsg_buffhd *next_buffhd_to_drain;
341 struct fsg_buffhd buffhds[NUM_BUFFERS];
343 int thread_wakeup_needed;
344 struct completion thread_notifier;
345 struct task_struct *thread_task;
348 u8 cmnd[MAX_COMMAND_SIZE];
349 enum data_direction data_dir;
351 u32 data_size_from_cmnd;
366 struct switch_dev sdev;
368 struct wake_lock wake_lock;
371 static inline struct fsg_dev *func_to_dev(struct usb_function *f)
373 return container_of(f, struct fsg_dev, function);
376 static int exception_in_progress(struct fsg_dev *fsg)
378 return (fsg->state > FSG_STATE_IDLE);
381 /* Make bulk-out requests be divisible by the maxpacket size */
382 static void set_bulk_out_req_length(struct fsg_dev *fsg,
383 struct fsg_buffhd *bh, unsigned int length)
387 bh->bulk_out_intended_length = length;
388 rem = length % fsg->bulk_out_maxpacket;
390 length += fsg->bulk_out_maxpacket - rem;
391 bh->outreq->length = length;
394 static struct fsg_dev *the_fsg;
396 static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun);
397 static void close_all_backing_files(struct fsg_dev *fsg);
400 /*-------------------------------------------------------------------------*/
404 static void dump_msg(struct fsg_dev *fsg, const char *label,
405 const u8 *buf, unsigned int length)
408 DBG(fsg, "%s, length %u:\n", label, length);
409 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
410 16, 1, buf, length, 0);
414 static void dump_cdb(struct fsg_dev *fsg)
419 static void dump_msg(struct fsg_dev *fsg, const char *label,
420 const u8 *buf, unsigned int length)
425 static void dump_cdb(struct fsg_dev *fsg)
427 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE,
428 16, 1, fsg->cmnd, fsg->cmnd_size, 0);
433 static void dump_cdb(struct fsg_dev *fsg)
436 #endif /* VERBOSE_DEBUG */
437 #endif /* DUMP_MSGS */
440 /*-------------------------------------------------------------------------*/
442 /* Routines for unaligned data access */
444 static u16 get_be16(u8 *buf)
446 return ((u16) buf[0] << 8) | ((u16) buf[1]);
449 static u32 get_be32(u8 *buf)
451 return ((u32) buf[0] << 24) | ((u32) buf[1] << 16) |
452 ((u32) buf[2] << 8) | ((u32) buf[3]);
455 static void put_be16(u8 *buf, u16 val)
461 static void put_be32(u8 *buf, u32 val)
469 /*-------------------------------------------------------------------------*/
472 * DESCRIPTORS ... most are static, but strings and (full) configuration
473 * descriptors are built on demand. Also the (static) config and interface
474 * descriptors are adjusted during fsg_bind().
477 /* There is only one interface. */
479 static struct usb_interface_descriptor
481 .bLength = sizeof intf_desc,
482 .bDescriptorType = USB_DT_INTERFACE,
484 .bNumEndpoints = 2, /* Adjusted during fsg_bind() */
485 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
486 .bInterfaceSubClass = US_SC_SCSI,
487 .bInterfaceProtocol = US_PR_BULK,
490 /* Three full-speed endpoint descriptors: bulk-in, bulk-out,
491 * and interrupt-in. */
493 static struct usb_endpoint_descriptor
495 .bLength = USB_DT_ENDPOINT_SIZE,
496 .bDescriptorType = USB_DT_ENDPOINT,
498 .bEndpointAddress = USB_DIR_IN,
499 .bmAttributes = USB_ENDPOINT_XFER_BULK,
500 /* wMaxPacketSize set by autoconfiguration */
503 static struct usb_endpoint_descriptor
505 .bLength = USB_DT_ENDPOINT_SIZE,
506 .bDescriptorType = USB_DT_ENDPOINT,
508 .bEndpointAddress = USB_DIR_OUT,
509 .bmAttributes = USB_ENDPOINT_XFER_BULK,
510 /* wMaxPacketSize set by autoconfiguration */
513 static struct usb_descriptor_header *fs_function[] = {
514 (struct usb_descriptor_header *) &intf_desc,
515 (struct usb_descriptor_header *) &fs_bulk_in_desc,
516 (struct usb_descriptor_header *) &fs_bulk_out_desc,
519 #define FS_FUNCTION_PRE_EP_ENTRIES 2
522 static struct usb_endpoint_descriptor
524 .bLength = USB_DT_ENDPOINT_SIZE,
525 .bDescriptorType = USB_DT_ENDPOINT,
527 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
528 .bmAttributes = USB_ENDPOINT_XFER_BULK,
529 .wMaxPacketSize = __constant_cpu_to_le16(512),
532 static struct usb_endpoint_descriptor
534 .bLength = USB_DT_ENDPOINT_SIZE,
535 .bDescriptorType = USB_DT_ENDPOINT,
537 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
538 .bmAttributes = USB_ENDPOINT_XFER_BULK,
539 .wMaxPacketSize = __constant_cpu_to_le16(512),
540 .bInterval = 1, /* NAK every 1 uframe */
544 static struct usb_descriptor_header *hs_function[] = {
545 (struct usb_descriptor_header *) &intf_desc,
546 (struct usb_descriptor_header *) &hs_bulk_in_desc,
547 (struct usb_descriptor_header *) &hs_bulk_out_desc,
551 /* Maxpacket and other transfer characteristics vary by speed. */
552 static struct usb_endpoint_descriptor *
553 ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *fs,
554 struct usb_endpoint_descriptor *hs)
556 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
561 /*-------------------------------------------------------------------------*/
563 /* These routines may be called in process context or in_irq */
565 /* Caller must hold fsg->lock */
566 static void wakeup_thread(struct fsg_dev *fsg)
568 /* Tell the main thread that something has happened */
569 fsg->thread_wakeup_needed = 1;
570 if (fsg->thread_task)
571 wake_up_process(fsg->thread_task);
575 static void raise_exception(struct fsg_dev *fsg, enum fsg_state new_state)
579 DBG(fsg, "raise_exception %d\n", (int)new_state);
580 /* Do nothing if a higher-priority exception is already in progress.
581 * If a lower-or-equal priority exception is in progress, preempt it
582 * and notify the main thread by sending it a signal. */
583 spin_lock_irqsave(&fsg->lock, flags);
584 if (fsg->state <= new_state) {
585 fsg->state = new_state;
586 if (fsg->thread_task)
587 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
590 spin_unlock_irqrestore(&fsg->lock, flags);
594 /*-------------------------------------------------------------------------*/
596 /* Bulk and interrupt endpoint completion handlers.
597 * These always run in_irq. */
599 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
601 struct fsg_dev *fsg = ep->driver_data;
602 struct fsg_buffhd *bh = req->context;
604 if (req->status || req->actual != req->length)
605 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
606 req->status, req->actual, req->length);
608 /* Hold the lock while we update the request and buffer states */
610 spin_lock(&fsg->lock);
612 bh->state = BUF_STATE_EMPTY;
614 spin_unlock(&fsg->lock);
617 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
619 struct fsg_dev *fsg = ep->driver_data;
620 struct fsg_buffhd *bh = req->context;
622 dump_msg(fsg, "bulk-out", req->buf, req->actual);
623 if (req->status || req->actual != bh->bulk_out_intended_length)
624 DBG(fsg, "%s --> %d, %u/%u\n", __func__,
625 req->status, req->actual,
626 bh->bulk_out_intended_length);
628 /* Hold the lock while we update the request and buffer states */
630 spin_lock(&fsg->lock);
632 bh->state = BUF_STATE_FULL;
634 spin_unlock(&fsg->lock);
637 static int fsg_function_setup(struct usb_function *f,
638 const struct usb_ctrlrequest *ctrl)
640 struct fsg_dev *fsg = func_to_dev(f);
641 struct usb_composite_dev *cdev = fsg->cdev;
642 int value = -EOPNOTSUPP;
643 u16 w_index = le16_to_cpu(ctrl->wIndex);
644 u16 w_value = le16_to_cpu(ctrl->wValue);
645 u16 w_length = le16_to_cpu(ctrl->wLength);
647 DBG(fsg, "fsg_function_setup\n");
648 /* Handle Bulk-only class-specific requests */
649 if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
650 DBG(fsg, "USB_TYPE_CLASS\n");
651 switch (ctrl->bRequest) {
652 case USB_BULK_RESET_REQUEST:
653 if (ctrl->bRequestType != (USB_DIR_OUT |
654 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
656 if (w_index != 0 || w_value != 0) {
661 /* Raise an exception to stop the current operation
662 * and reinitialize our state. */
663 DBG(fsg, "bulk reset request\n");
664 raise_exception(fsg, FSG_STATE_RESET);
665 value = DELAYED_STATUS;
668 case USB_BULK_GET_MAX_LUN_REQUEST:
669 if (ctrl->bRequestType != (USB_DIR_IN |
670 USB_TYPE_CLASS | USB_RECIP_INTERFACE))
672 if (w_index != 0 || w_value != 0) {
676 VDBG(fsg, "get max LUN\n");
677 *(u8 *)cdev->req->buf = fsg->nluns - 1;
683 if (value == -EOPNOTSUPP)
685 "unknown class-specific control req "
686 "%02x.%02x v%04x i%04x l%u\n",
687 ctrl->bRequestType, ctrl->bRequest,
688 le16_to_cpu(ctrl->wValue), w_index, w_length);
692 /*-------------------------------------------------------------------------*/
694 /* All the following routines run in process context */
697 /* Use this for bulk or interrupt transfers, not ep0 */
698 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
699 struct usb_request *req, int *pbusy,
700 enum fsg_buffer_state *state)
704 DBG(fsg, "start_transfer req: %p, req->buf: %p\n", req, req->buf);
705 if (ep == fsg->bulk_in)
706 dump_msg(fsg, "bulk-in", req->buf, req->length);
708 spin_lock_irq(&fsg->lock);
710 *state = BUF_STATE_BUSY;
711 spin_unlock_irq(&fsg->lock);
712 rc = usb_ep_queue(ep, req, GFP_KERNEL);
715 *state = BUF_STATE_EMPTY;
717 /* We can't do much more than wait for a reset */
719 /* Note: currently the net2280 driver fails zero-length
720 * submissions if DMA is enabled. */
721 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
723 WARN(fsg, "error in submission: %s --> %d\n",
724 (ep == fsg->bulk_in ? "bulk-in" : "bulk-out"),
730 static int sleep_thread(struct fsg_dev *fsg)
734 /* Wait until a signal arrives or we are woken up */
737 set_current_state(TASK_INTERRUPTIBLE);
738 if (signal_pending(current)) {
742 if (fsg->thread_wakeup_needed)
746 __set_current_state(TASK_RUNNING);
747 fsg->thread_wakeup_needed = 0;
752 /*-------------------------------------------------------------------------*/
754 static int do_read(struct fsg_dev *fsg)
756 struct lun *curlun = fsg->curlun;
758 struct fsg_buffhd *bh;
761 loff_t file_offset, file_offset_tmp;
763 unsigned int partial_page;
766 /* Get the starting Logical Block Address and check that it's
768 if (fsg->cmnd[0] == SC_READ_6)
769 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
771 lba = get_be32(&fsg->cmnd[2]);
773 /* We allow DPO (Disable Page Out = don't save data in the
774 * cache) and FUA (Force Unit Access = don't read from the
775 * cache), but we don't implement them. */
776 if ((fsg->cmnd[1] & ~0x18) != 0) {
777 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
781 if (lba >= curlun->num_sectors) {
782 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
785 file_offset = ((loff_t) lba) << 9;
787 /* Carry out the file reads */
788 amount_left = fsg->data_size_from_cmnd;
789 if (unlikely(amount_left == 0))
790 return -EIO; /* No default reply */
794 /* Figure out how much we need to read:
795 * Try to read the remaining amount.
796 * But don't read more than the buffer size.
797 * And don't try to read past the end of the file.
798 * Finally, if we're not at a page boundary, don't read past
800 * If this means reading 0 then we were asked to read past
801 * the end of file. */
802 amount = min((unsigned int) amount_left,
803 (unsigned int)fsg->buf_size);
804 amount = min((loff_t) amount,
805 curlun->file_length - file_offset);
806 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
807 if (partial_page > 0)
808 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
811 /* Wait for the next buffer to become available */
812 bh = fsg->next_buffhd_to_fill;
813 while (bh->state != BUF_STATE_EMPTY) {
814 rc = sleep_thread(fsg);
819 /* If we were asked to read past the end of file,
820 * end with an empty buffer. */
823 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
824 curlun->sense_data_info = file_offset >> 9;
825 curlun->info_valid = 1;
826 bh->inreq->length = 0;
827 bh->state = BUF_STATE_FULL;
831 /* Perform the read */
832 file_offset_tmp = file_offset;
833 nread = vfs_read(curlun->filp,
834 (char __user *) bh->buf,
835 amount, &file_offset_tmp);
836 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
837 (unsigned long long) file_offset,
839 if (signal_pending(current))
843 LDBG(curlun, "error in file read: %d\n",
846 } else if (nread < amount) {
847 LDBG(curlun, "partial file read: %d/%u\n",
848 (int) nread, amount);
849 nread -= (nread & 511); /* Round down to a block */
851 file_offset += nread;
852 amount_left -= nread;
853 fsg->residue -= nread;
854 bh->inreq->length = nread;
855 bh->state = BUF_STATE_FULL;
857 /* If an error occurred, report it and its position */
858 if (nread < amount) {
859 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
860 curlun->sense_data_info = file_offset >> 9;
861 curlun->info_valid = 1;
865 if (amount_left == 0)
866 break; /* No more left to read */
868 /* Send this buffer and go read some more */
869 start_transfer(fsg, fsg->bulk_in, bh->inreq,
870 &bh->inreq_busy, &bh->state);
871 fsg->next_buffhd_to_fill = bh->next;
874 return -EIO; /* No default reply */
878 /*-------------------------------------------------------------------------*/
880 static int do_write(struct fsg_dev *fsg)
882 struct lun *curlun = fsg->curlun;
884 struct fsg_buffhd *bh;
886 u32 amount_left_to_req, amount_left_to_write;
887 loff_t usb_offset, file_offset, file_offset_tmp;
889 unsigned int partial_page;
894 curlun->sense_data = SS_WRITE_PROTECTED;
897 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
899 /* Get the starting Logical Block Address and check that it's
901 if (fsg->cmnd[0] == SC_WRITE_6)
902 lba = (fsg->cmnd[1] << 16) | get_be16(&fsg->cmnd[2]);
904 lba = get_be32(&fsg->cmnd[2]);
906 /* We allow DPO (Disable Page Out = don't save data in the
907 * cache) and FUA (Force Unit Access = write directly to the
908 * medium). We don't implement DPO; we implement FUA by
909 * performing synchronous output. */
910 if ((fsg->cmnd[1] & ~0x18) != 0) {
911 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
914 if (fsg->cmnd[1] & 0x08) /* FUA */
915 curlun->filp->f_flags |= O_SYNC;
917 if (lba >= curlun->num_sectors) {
918 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
922 /* Carry out the file writes */
924 file_offset = usb_offset = ((loff_t) lba) << 9;
925 amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd;
927 while (amount_left_to_write > 0) {
929 /* Queue a request for more data from the host */
930 bh = fsg->next_buffhd_to_fill;
931 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
933 /* Figure out how much we want to get:
934 * Try to get the remaining amount.
935 * But don't get more than the buffer size.
936 * And don't try to go past the end of the file.
937 * If we're not at a page boundary,
938 * don't go past the next page.
939 * If this means getting 0, then we were asked
940 * to write past the end of file.
941 * Finally, round down to a block boundary. */
942 amount = min(amount_left_to_req, (u32)fsg->buf_size);
943 amount = min((loff_t) amount, curlun->file_length -
945 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
946 if (partial_page > 0)
948 (unsigned int) PAGE_CACHE_SIZE - partial_page);
953 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
954 curlun->sense_data_info = usb_offset >> 9;
955 curlun->info_valid = 1;
958 amount -= (amount & 511);
961 /* Why were we were asked to transfer a
967 /* Get the next buffer */
968 usb_offset += amount;
969 fsg->usb_amount_left -= amount;
970 amount_left_to_req -= amount;
971 if (amount_left_to_req == 0)
974 /* amount is always divisible by 512, hence by
975 * the bulk-out maxpacket size */
976 bh->outreq->length = bh->bulk_out_intended_length =
978 start_transfer(fsg, fsg->bulk_out, bh->outreq,
979 &bh->outreq_busy, &bh->state);
980 fsg->next_buffhd_to_fill = bh->next;
984 /* Write the received data to the backing file */
985 bh = fsg->next_buffhd_to_drain;
986 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
987 break; /* We stopped early */
988 if (bh->state == BUF_STATE_FULL) {
990 fsg->next_buffhd_to_drain = bh->next;
991 bh->state = BUF_STATE_EMPTY;
993 /* Did something go wrong with the transfer? */
994 if (bh->outreq->status != 0) {
995 curlun->sense_data = SS_COMMUNICATION_FAILURE;
996 curlun->sense_data_info = file_offset >> 9;
997 curlun->info_valid = 1;
1001 amount = bh->outreq->actual;
1002 if (curlun->file_length - file_offset < amount) {
1004 "write %u @ %llu beyond end %llu\n",
1005 amount, (unsigned long long) file_offset,
1006 (unsigned long long) curlun->file_length);
1007 amount = curlun->file_length - file_offset;
1010 /* Perform the write */
1011 file_offset_tmp = file_offset;
1012 nwritten = vfs_write(curlun->filp,
1013 (char __user *) bh->buf,
1014 amount, &file_offset_tmp);
1015 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1016 (unsigned long long) file_offset,
1018 if (signal_pending(current))
1019 return -EINTR; /* Interrupted! */
1022 LDBG(curlun, "error in file write: %d\n",
1025 } else if (nwritten < amount) {
1026 LDBG(curlun, "partial file write: %d/%u\n",
1027 (int) nwritten, amount);
1028 nwritten -= (nwritten & 511);
1029 /* Round down to a block */
1031 file_offset += nwritten;
1032 amount_left_to_write -= nwritten;
1033 fsg->residue -= nwritten;
1035 /* If an error occurred, report it and its position */
1036 if (nwritten < amount) {
1037 curlun->sense_data = SS_WRITE_ERROR;
1038 curlun->sense_data_info = file_offset >> 9;
1039 curlun->info_valid = 1;
1043 /* Did the host decide to stop early? */
1044 if (bh->outreq->actual != bh->outreq->length) {
1045 fsg->short_packet_received = 1;
1051 /* Wait for something to happen */
1052 rc = sleep_thread(fsg);
1057 return -EIO; /* No default reply */
1061 /*-------------------------------------------------------------------------*/
1063 /* Sync the file data, don't bother with the metadata.
1064 * The caller must own fsg->filesem.
1065 * This code was copied from fs/buffer.c:sys_fdatasync(). */
1066 static int fsync_sub(struct lun *curlun)
1068 struct file *filp = curlun->filp;
1069 struct inode *inode;
1072 if (curlun->ro || !filp)
1074 if (!filp->f_op->fsync)
1077 inode = filp->f_path.dentry->d_inode;
1078 mutex_lock(&inode->i_mutex);
1079 rc = filemap_fdatawrite(inode->i_mapping);
1080 err = filp->f_op->fsync(filp, filp->f_path.dentry, 1);
1083 err = filemap_fdatawait(inode->i_mapping);
1086 mutex_unlock(&inode->i_mutex);
1087 VLDBG(curlun, "fdatasync -> %d\n", rc);
1091 static void fsync_all(struct fsg_dev *fsg)
1095 for (i = 0; i < fsg->nluns; ++i)
1096 fsync_sub(&fsg->luns[i]);
1099 static int do_synchronize_cache(struct fsg_dev *fsg)
1101 struct lun *curlun = fsg->curlun;
1104 /* We ignore the requested LBA and write out all file's
1105 * dirty data buffers. */
1106 rc = fsync_sub(curlun);
1108 curlun->sense_data = SS_WRITE_ERROR;
1113 /*-------------------------------------------------------------------------*/
1115 static void invalidate_sub(struct lun *curlun)
1117 struct file *filp = curlun->filp;
1118 struct inode *inode = filp->f_path.dentry->d_inode;
1121 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1122 VLDBG(curlun, "invalidate_inode_pages -> %ld\n", rc);
1125 static int do_verify(struct fsg_dev *fsg)
1127 struct lun *curlun = fsg->curlun;
1129 u32 verification_length;
1130 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1131 loff_t file_offset, file_offset_tmp;
1133 unsigned int amount;
1136 /* Get the starting Logical Block Address and check that it's
1138 lba = get_be32(&fsg->cmnd[2]);
1139 if (lba >= curlun->num_sectors) {
1140 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1144 /* We allow DPO (Disable Page Out = don't save data in the
1145 * cache) but we don't implement it. */
1146 if ((fsg->cmnd[1] & ~0x10) != 0) {
1147 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1151 verification_length = get_be16(&fsg->cmnd[7]);
1152 if (unlikely(verification_length == 0))
1153 return -EIO; /* No default reply */
1155 /* Prepare to carry out the file verify */
1156 amount_left = verification_length << 9;
1157 file_offset = ((loff_t) lba) << 9;
1159 /* Write out all the dirty buffers before invalidating them */
1161 if (signal_pending(current))
1164 invalidate_sub(curlun);
1165 if (signal_pending(current))
1168 /* Just try to read the requested blocks */
1169 while (amount_left > 0) {
1171 /* Figure out how much we need to read:
1172 * Try to read the remaining amount, but not more than
1174 * And don't try to read past the end of the file.
1175 * If this means reading 0 then we were asked to read
1176 * past the end of file. */
1177 amount = min((unsigned int) amount_left,
1178 (unsigned int)fsg->buf_size);
1179 amount = min((loff_t) amount,
1180 curlun->file_length - file_offset);
1182 curlun->sense_data =
1183 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1184 curlun->sense_data_info = file_offset >> 9;
1185 curlun->info_valid = 1;
1189 /* Perform the read */
1190 file_offset_tmp = file_offset;
1191 nread = vfs_read(curlun->filp,
1192 (char __user *) bh->buf,
1193 amount, &file_offset_tmp);
1194 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1195 (unsigned long long) file_offset,
1197 if (signal_pending(current))
1201 LDBG(curlun, "error in file verify: %d\n",
1204 } else if (nread < amount) {
1205 LDBG(curlun, "partial file verify: %d/%u\n",
1206 (int) nread, amount);
1207 nread -= (nread & 511); /* Round down to a sector */
1210 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1211 curlun->sense_data_info = file_offset >> 9;
1212 curlun->info_valid = 1;
1215 file_offset += nread;
1216 amount_left -= nread;
1222 /*-------------------------------------------------------------------------*/
1224 static int do_inquiry(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1226 u8 *buf = (u8 *) bh->buf;
1228 if (!fsg->curlun) { /* Unsupported LUNs are okay */
1229 fsg->bad_lun_okay = 1;
1231 buf[0] = 0x7f; /* Unsupported, no device-type */
1235 memset(buf, 0, 8); /* Non-removable, direct-access device */
1237 buf[1] = 0x80; /* set removable bit */
1238 buf[2] = 2; /* ANSI SCSI level 2 */
1239 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1240 buf[4] = 31; /* Additional length */
1241 /* No special options */
1242 sprintf(buf + 8, "%-8s%-16s%04x", fsg->vendor,
1243 fsg->product, fsg->release);
1248 static int do_request_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1250 struct lun *curlun = fsg->curlun;
1251 u8 *buf = (u8 *) bh->buf;
1256 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1258 * If a REQUEST SENSE command is received from an initiator
1259 * with a pending unit attention condition (before the target
1260 * generates the contingent allegiance condition), then the
1261 * target shall either:
1262 * a) report any pending sense data and preserve the unit
1263 * attention condition on the logical unit, or,
1264 * b) report the unit attention condition, may discard any
1265 * pending sense data, and clear the unit attention
1266 * condition on the logical unit for that initiator.
1268 * FSG normally uses option a); enable this code to use option b).
1271 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1272 curlun->sense_data = curlun->unit_attention_data;
1273 curlun->unit_attention_data = SS_NO_SENSE;
1277 if (!curlun) { /* Unsupported LUNs are okay */
1278 fsg->bad_lun_okay = 1;
1279 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1283 sd = curlun->sense_data;
1284 sdinfo = curlun->sense_data_info;
1285 valid = curlun->info_valid << 7;
1286 curlun->sense_data = SS_NO_SENSE;
1287 curlun->sense_data_info = 0;
1288 curlun->info_valid = 0;
1292 buf[0] = valid | 0x70; /* Valid, current error */
1294 put_be32(&buf[3], sdinfo); /* Sense information */
1295 buf[7] = 18 - 8; /* Additional sense length */
1302 static int do_read_capacity(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1304 struct lun *curlun = fsg->curlun;
1305 u32 lba = get_be32(&fsg->cmnd[2]);
1306 int pmi = fsg->cmnd[8];
1307 u8 *buf = (u8 *) bh->buf;
1309 /* Check the PMI and LBA fields */
1310 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1311 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1315 put_be32(&buf[0], curlun->num_sectors - 1); /* Max logical block */
1316 put_be32(&buf[4], 512); /* Block length */
1321 static int do_mode_sense(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1323 struct lun *curlun = fsg->curlun;
1324 int mscmnd = fsg->cmnd[0];
1325 u8 *buf = (u8 *) bh->buf;
1328 int changeable_values, all_pages;
1332 if ((fsg->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1333 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1336 pc = fsg->cmnd[2] >> 6;
1337 page_code = fsg->cmnd[2] & 0x3f;
1339 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1342 changeable_values = (pc == 1);
1343 all_pages = (page_code == 0x3f);
1345 /* Write the mode parameter header. Fixed values are: default
1346 * medium type, no cache control (DPOFUA), and no block descriptors.
1347 * The only variable value is the WriteProtect bit. We will fill in
1348 * the mode data length later. */
1350 if (mscmnd == SC_MODE_SENSE_6) {
1351 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1354 } else { /* SC_MODE_SENSE_10 */
1355 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1360 /* No block descriptors */
1362 /* Disabled to workaround USB reset problems with a Vista host.
1365 /* The mode pages, in numerical order. The only page we support
1366 * is the Caching page. */
1367 if (page_code == 0x08 || all_pages) {
1369 buf[0] = 0x08; /* Page code */
1370 buf[1] = 10; /* Page length */
1371 memset(buf+2, 0, 10); /* None of the fields are changeable */
1373 if (!changeable_values) {
1374 buf[2] = 0x04; /* Write cache enable, */
1375 /* Read cache not disabled */
1376 /* No cache retention priorities */
1377 put_be16(&buf[4], 0xffff); /* Don't disable prefetch */
1378 /* Minimum prefetch = 0 */
1379 put_be16(&buf[8], 0xffff); /* Maximum prefetch */
1380 /* Maximum prefetch ceiling */
1381 put_be16(&buf[10], 0xffff);
1389 /* Check that a valid page was requested and the mode data length
1390 * isn't too long. */
1392 if (!valid_page || len > limit) {
1393 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1397 /* Store the mode data length */
1398 if (mscmnd == SC_MODE_SENSE_6)
1401 put_be16(buf0, len - 2);
1405 static int do_start_stop(struct fsg_dev *fsg)
1407 struct lun *curlun = fsg->curlun;
1410 /* int immed = fsg->cmnd[1] & 0x01; */
1411 loej = fsg->cmnd[4] & 0x02;
1412 start = fsg->cmnd[4] & 0x01;
1415 /* eject request from the host */
1416 if (backing_file_is_open(curlun)) {
1417 close_backing_file(fsg, curlun);
1418 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
1425 static int do_prevent_allow(struct fsg_dev *fsg)
1427 struct lun *curlun = fsg->curlun;
1430 prevent = fsg->cmnd[4] & 0x01;
1431 if ((fsg->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1432 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1436 if (curlun->prevent_medium_removal && !prevent)
1438 curlun->prevent_medium_removal = prevent;
1443 static int do_read_format_capacities(struct fsg_dev *fsg,
1444 struct fsg_buffhd *bh)
1446 struct lun *curlun = fsg->curlun;
1447 u8 *buf = (u8 *) bh->buf;
1449 buf[0] = buf[1] = buf[2] = 0;
1450 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1453 put_be32(&buf[0], curlun->num_sectors); /* Number of blocks */
1454 put_be32(&buf[4], 512); /* Block length */
1455 buf[4] = 0x02; /* Current capacity */
1460 static int do_mode_select(struct fsg_dev *fsg, struct fsg_buffhd *bh)
1462 struct lun *curlun = fsg->curlun;
1464 /* We don't support MODE SELECT */
1465 curlun->sense_data = SS_INVALID_COMMAND;
1470 /*-------------------------------------------------------------------------*/
1472 static int write_zero(struct fsg_dev *fsg)
1474 struct fsg_buffhd *bh;
1477 DBG(fsg, "write_zero\n");
1478 /* Wait for the next buffer to become available */
1479 bh = fsg->next_buffhd_to_fill;
1480 while (bh->state != BUF_STATE_EMPTY) {
1481 rc = sleep_thread(fsg);
1486 bh->inreq->length = 0;
1487 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1488 &bh->inreq_busy, &bh->state);
1490 fsg->next_buffhd_to_fill = bh->next;
1495 static int throw_away_data(struct fsg_dev *fsg)
1497 struct fsg_buffhd *bh;
1501 DBG(fsg, "throw_away_data\n");
1502 while ((bh = fsg->next_buffhd_to_drain)->state != BUF_STATE_EMPTY ||
1503 fsg->usb_amount_left > 0) {
1505 /* Throw away the data in a filled buffer */
1506 if (bh->state == BUF_STATE_FULL) {
1508 bh->state = BUF_STATE_EMPTY;
1509 fsg->next_buffhd_to_drain = bh->next;
1511 /* A short packet or an error ends everything */
1512 if (bh->outreq->actual != bh->outreq->length ||
1513 bh->outreq->status != 0) {
1514 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1520 /* Try to submit another request if we need one */
1521 bh = fsg->next_buffhd_to_fill;
1522 if (bh->state == BUF_STATE_EMPTY && fsg->usb_amount_left > 0) {
1523 amount = min(fsg->usb_amount_left, (u32) fsg->buf_size);
1525 /* amount is always divisible by 512, hence by
1526 * the bulk-out maxpacket size */
1527 bh->outreq->length = bh->bulk_out_intended_length =
1529 start_transfer(fsg, fsg->bulk_out, bh->outreq,
1530 &bh->outreq_busy, &bh->state);
1531 fsg->next_buffhd_to_fill = bh->next;
1532 fsg->usb_amount_left -= amount;
1536 /* Otherwise wait for something to happen */
1537 rc = sleep_thread(fsg);
1545 static int finish_reply(struct fsg_dev *fsg)
1547 struct fsg_buffhd *bh = fsg->next_buffhd_to_fill;
1550 switch (fsg->data_dir) {
1552 break; /* Nothing to send */
1554 case DATA_DIR_UNKNOWN:
1558 /* All but the last buffer of data must have already been sent */
1559 case DATA_DIR_TO_HOST:
1560 if (fsg->data_size == 0)
1561 ; /* Nothing to send */
1563 /* If there's no residue, simply send the last buffer */
1564 else if (fsg->residue == 0) {
1565 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1566 &bh->inreq_busy, &bh->state);
1567 fsg->next_buffhd_to_fill = bh->next;
1569 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1570 &bh->inreq_busy, &bh->state);
1571 fsg->next_buffhd_to_fill = bh->next;
1573 /* this is unnecessary, and was causing problems with MacOS */
1574 if (bh->inreq->length > 0)
1580 /* We have processed all we want from the data the host has sent.
1581 * There may still be outstanding bulk-out requests. */
1582 case DATA_DIR_FROM_HOST:
1583 if (fsg->residue == 0)
1584 ; /* Nothing to receive */
1586 /* Did the host stop sending unexpectedly early? */
1587 else if (fsg->short_packet_received) {
1588 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1592 /* We haven't processed all the incoming data. Even though
1593 * we may be allowed to stall, doing so would cause a race.
1594 * The controller may already have ACK'ed all the remaining
1595 * bulk-out packets, in which case the host wouldn't see a
1596 * STALL. Not realizing the endpoint was halted, it wouldn't
1597 * clear the halt -- leading to problems later on. */
1599 fsg_set_halt(fsg, fsg->bulk_out);
1600 raise_exception(fsg, FSG_STATE_ABORT_BULK_OUT);
1604 /* We can't stall. Read in the excess data and throw it
1607 rc = throw_away_data(fsg);
1614 static int send_status(struct fsg_dev *fsg)
1616 struct lun *curlun = fsg->curlun;
1617 struct fsg_buffhd *bh;
1619 u8 status = USB_STATUS_PASS;
1621 struct bulk_cs_wrap *csw;
1623 DBG(fsg, "send_status\n");
1624 /* Wait for the next buffer to become available */
1625 bh = fsg->next_buffhd_to_fill;
1626 while (bh->state != BUF_STATE_EMPTY) {
1627 rc = sleep_thread(fsg);
1633 sd = curlun->sense_data;
1634 sdinfo = curlun->sense_data_info;
1635 } else if (fsg->bad_lun_okay)
1638 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1640 if (fsg->phase_error) {
1641 DBG(fsg, "sending phase-error status\n");
1642 status = USB_STATUS_PHASE_ERROR;
1643 sd = SS_INVALID_COMMAND;
1644 } else if (sd != SS_NO_SENSE) {
1645 DBG(fsg, "sending command-failure status\n");
1646 status = USB_STATUS_FAIL;
1647 VDBG(fsg, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1649 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1654 /* Store and send the Bulk-only CSW */
1655 csw->Signature = __constant_cpu_to_le32(USB_BULK_CS_SIG);
1656 csw->Tag = fsg->tag;
1657 csw->Residue = cpu_to_le32(fsg->residue);
1658 csw->Status = status;
1660 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1661 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1662 &bh->inreq_busy, &bh->state);
1664 fsg->next_buffhd_to_fill = bh->next;
1669 /*-------------------------------------------------------------------------*/
1671 /* Check whether the command is properly formed and whether its data size
1672 * and direction agree with the values we already have. */
1673 static int check_command(struct fsg_dev *fsg, int cmnd_size,
1674 enum data_direction data_dir, unsigned int mask,
1675 int needs_medium, const char *name)
1678 int lun = fsg->cmnd[1] >> 5;
1679 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1684 if (fsg->data_dir != DATA_DIR_UNKNOWN)
1685 sprintf(hdlen, ", H%c=%u", dirletter[(int) fsg->data_dir],
1687 VDBG(fsg, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1688 name, cmnd_size, dirletter[(int) data_dir],
1689 fsg->data_size_from_cmnd, fsg->cmnd_size, hdlen);
1691 /* We can't reply at all until we know the correct data direction
1693 if (fsg->data_size_from_cmnd == 0)
1694 data_dir = DATA_DIR_NONE;
1695 if (fsg->data_dir == DATA_DIR_UNKNOWN) { /* CB or CBI */
1696 fsg->data_dir = data_dir;
1697 fsg->data_size = fsg->data_size_from_cmnd;
1699 } else { /* Bulk-only */
1700 if (fsg->data_size < fsg->data_size_from_cmnd) {
1702 /* Host data size < Device data size is a phase error.
1703 * Carry out the command, but only transfer as much
1704 * as we are allowed. */
1705 DBG(fsg, "phase error 1\n");
1706 fsg->data_size_from_cmnd = fsg->data_size;
1707 fsg->phase_error = 1;
1710 fsg->residue = fsg->usb_amount_left = fsg->data_size;
1712 /* Conflicting data directions is a phase error */
1713 if (fsg->data_dir != data_dir && fsg->data_size_from_cmnd > 0) {
1714 fsg->phase_error = 1;
1715 DBG(fsg, "phase error 2\n");
1719 /* Verify the length of the command itself */
1720 if (cmnd_size != fsg->cmnd_size) {
1722 /* Special case workaround: MS-Windows issues REQUEST SENSE
1723 * with cbw->Length == 12 (it should be 6). */
1724 if (fsg->cmnd[0] == SC_REQUEST_SENSE && fsg->cmnd_size == 12)
1725 cmnd_size = fsg->cmnd_size;
1727 fsg->phase_error = 1;
1732 /* Check that the LUN values are consistent */
1733 if (fsg->lun != lun)
1734 DBG(fsg, "using LUN %d from CBW, "
1735 "not LUN %d from CDB\n",
1739 if (fsg->lun >= 0 && fsg->lun < fsg->nluns) {
1740 fsg->curlun = curlun = &fsg->luns[fsg->lun];
1741 if (fsg->cmnd[0] != SC_REQUEST_SENSE) {
1742 curlun->sense_data = SS_NO_SENSE;
1743 curlun->sense_data_info = 0;
1744 curlun->info_valid = 0;
1747 fsg->curlun = curlun = NULL;
1748 fsg->bad_lun_okay = 0;
1750 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1751 * to use unsupported LUNs; all others may not. */
1752 if (fsg->cmnd[0] != SC_INQUIRY &&
1753 fsg->cmnd[0] != SC_REQUEST_SENSE) {
1754 DBG(fsg, "unsupported LUN %d\n", fsg->lun);
1759 /* If a unit attention condition exists, only INQUIRY and
1760 * REQUEST SENSE commands are allowed; anything else must fail. */
1761 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1762 fsg->cmnd[0] != SC_INQUIRY &&
1763 fsg->cmnd[0] != SC_REQUEST_SENSE) {
1764 curlun->sense_data = curlun->unit_attention_data;
1765 curlun->unit_attention_data = SS_NO_SENSE;
1769 /* Check that only command bytes listed in the mask are non-zero */
1770 fsg->cmnd[1] &= 0x1f; /* Mask away the LUN */
1771 for (i = 1; i < cmnd_size; ++i) {
1772 if (fsg->cmnd[i] && !(mask & (1 << i))) {
1774 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1775 DBG(fsg, "SS_INVALID_FIELD_IN_CDB\n");
1780 /* If the medium isn't mounted and the command needs to access
1781 * it, return an error. */
1782 if (curlun && !backing_file_is_open(curlun) && needs_medium) {
1783 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1784 DBG(fsg, "SS_MEDIUM_NOT_PRESENT\n");
1792 static int do_scsi_command(struct fsg_dev *fsg)
1794 struct fsg_buffhd *bh;
1796 int reply = -EINVAL;
1798 static char unknown[16];
1802 /* Wait for the next buffer to become available for data or status */
1803 bh = fsg->next_buffhd_to_drain = fsg->next_buffhd_to_fill;
1804 while (bh->state != BUF_STATE_EMPTY) {
1805 rc = sleep_thread(fsg);
1809 fsg->phase_error = 0;
1810 fsg->short_packet_received = 0;
1812 down_read(&fsg->filesem); /* We're using the backing file */
1813 switch (fsg->cmnd[0]) {
1816 fsg->data_size_from_cmnd = fsg->cmnd[4];
1817 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1820 reply = do_inquiry(fsg, bh);
1823 case SC_MODE_SELECT_6:
1824 fsg->data_size_from_cmnd = fsg->cmnd[4];
1825 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
1827 "MODE SELECT(6)")) == 0)
1828 reply = do_mode_select(fsg, bh);
1831 case SC_MODE_SELECT_10:
1832 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1833 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
1835 "MODE SELECT(10)")) == 0)
1836 reply = do_mode_select(fsg, bh);
1839 case SC_MODE_SENSE_6:
1840 fsg->data_size_from_cmnd = fsg->cmnd[4];
1841 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1842 (1<<1) | (1<<2) | (1<<4), 0,
1843 "MODE SENSE(6)")) == 0)
1844 reply = do_mode_sense(fsg, bh);
1847 case SC_MODE_SENSE_10:
1848 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1849 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1850 (1<<1) | (1<<2) | (3<<7), 0,
1851 "MODE SENSE(10)")) == 0)
1852 reply = do_mode_sense(fsg, bh);
1855 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1856 fsg->data_size_from_cmnd = 0;
1857 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
1859 "PREVENT-ALLOW MEDIUM REMOVAL")) == 0)
1860 reply = do_prevent_allow(fsg);
1865 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1866 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1869 reply = do_read(fsg);
1873 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
1874 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1875 (1<<1) | (0xf<<2) | (3<<7), 1,
1877 reply = do_read(fsg);
1881 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
1882 if ((reply = check_command(fsg, 12, DATA_DIR_TO_HOST,
1883 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1885 reply = do_read(fsg);
1888 case SC_READ_CAPACITY:
1889 fsg->data_size_from_cmnd = 8;
1890 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1891 (0xf<<2) | (1<<8), 1,
1892 "READ CAPACITY")) == 0)
1893 reply = do_read_capacity(fsg, bh);
1896 case SC_READ_FORMAT_CAPACITIES:
1897 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]);
1898 if ((reply = check_command(fsg, 10, DATA_DIR_TO_HOST,
1900 "READ FORMAT CAPACITIES")) == 0)
1901 reply = do_read_format_capacities(fsg, bh);
1904 case SC_REQUEST_SENSE:
1905 fsg->data_size_from_cmnd = fsg->cmnd[4];
1906 if ((reply = check_command(fsg, 6, DATA_DIR_TO_HOST,
1908 "REQUEST SENSE")) == 0)
1909 reply = do_request_sense(fsg, bh);
1912 case SC_START_STOP_UNIT:
1913 fsg->data_size_from_cmnd = 0;
1914 if ((reply = check_command(fsg, 6, DATA_DIR_NONE,
1916 "START-STOP UNIT")) == 0)
1917 reply = do_start_stop(fsg);
1920 case SC_SYNCHRONIZE_CACHE:
1921 fsg->data_size_from_cmnd = 0;
1922 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
1923 (0xf<<2) | (3<<7), 1,
1924 "SYNCHRONIZE CACHE")) == 0)
1925 reply = do_synchronize_cache(fsg);
1928 case SC_TEST_UNIT_READY:
1929 fsg->data_size_from_cmnd = 0;
1930 reply = check_command(fsg, 6, DATA_DIR_NONE,
1935 /* Although optional, this command is used by MS-Windows. We
1936 * support a minimal version: BytChk must be 0. */
1938 fsg->data_size_from_cmnd = 0;
1939 if ((reply = check_command(fsg, 10, DATA_DIR_NONE,
1940 (1<<1) | (0xf<<2) | (3<<7), 1,
1942 reply = do_verify(fsg);
1947 fsg->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1948 if ((reply = check_command(fsg, 6, DATA_DIR_FROM_HOST,
1951 reply = do_write(fsg);
1955 fsg->data_size_from_cmnd = get_be16(&fsg->cmnd[7]) << 9;
1956 if ((reply = check_command(fsg, 10, DATA_DIR_FROM_HOST,
1957 (1<<1) | (0xf<<2) | (3<<7), 1,
1959 reply = do_write(fsg);
1963 fsg->data_size_from_cmnd = get_be32(&fsg->cmnd[6]) << 9;
1964 if ((reply = check_command(fsg, 12, DATA_DIR_FROM_HOST,
1965 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1967 reply = do_write(fsg);
1970 /* Some mandatory commands that we recognize but don't implement.
1971 * They don't mean much in this setting. It's left as an exercise
1972 * for anyone interested to implement RESERVE and RELEASE in terms
1973 * of Posix locks. */
1974 case SC_FORMAT_UNIT:
1977 case SC_SEND_DIAGNOSTIC:
1981 fsg->data_size_from_cmnd = 0;
1982 sprintf(unknown, "Unknown x%02x", fsg->cmnd[0]);
1983 if ((reply = check_command(fsg, fsg->cmnd_size,
1984 DATA_DIR_UNKNOWN, 0xff, 0, unknown)) == 0) {
1985 fsg->curlun->sense_data = SS_INVALID_COMMAND;
1990 up_read(&fsg->filesem);
1992 VDBG(fsg, "reply: %d, fsg->data_size_from_cmnd: %d\n",
1993 reply, fsg->data_size_from_cmnd);
1994 if (reply == -EINTR || signal_pending(current))
1997 /* Set up the single reply buffer for finish_reply() */
1998 if (reply == -EINVAL)
1999 reply = 0; /* Error reply length */
2000 if (reply >= 0 && fsg->data_dir == DATA_DIR_TO_HOST) {
2001 reply = min((u32) reply, fsg->data_size_from_cmnd);
2002 bh->inreq->length = reply;
2003 bh->state = BUF_STATE_FULL;
2004 fsg->residue -= reply;
2005 } /* Otherwise it's already set */
2011 /*-------------------------------------------------------------------------*/
2013 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2015 struct usb_request *req = bh->outreq;
2016 struct bulk_cb_wrap *cbw = req->buf;
2018 /* Was this a real packet? */
2022 /* Is the CBW valid? */
2023 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2024 cbw->Signature != __constant_cpu_to_le32(
2026 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2028 le32_to_cpu(cbw->Signature));
2032 /* Is the CBW meaningful? */
2033 if (cbw->Lun >= MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2034 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2035 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2037 cbw->Lun, cbw->Flags, cbw->Length);
2041 /* Save the command for later */
2042 fsg->cmnd_size = cbw->Length;
2043 memcpy(fsg->cmnd, cbw->CDB, fsg->cmnd_size);
2044 if (cbw->Flags & USB_BULK_IN_FLAG)
2045 fsg->data_dir = DATA_DIR_TO_HOST;
2047 fsg->data_dir = DATA_DIR_FROM_HOST;
2048 fsg->data_size = le32_to_cpu(cbw->DataTransferLength);
2049 if (fsg->data_size == 0)
2050 fsg->data_dir = DATA_DIR_NONE;
2051 fsg->lun = cbw->Lun;
2052 fsg->tag = cbw->Tag;
2057 static int get_next_command(struct fsg_dev *fsg)
2059 struct fsg_buffhd *bh;
2062 /* Wait for the next buffer to become available */
2063 bh = fsg->next_buffhd_to_fill;
2064 while (bh->state != BUF_STATE_EMPTY) {
2065 rc = sleep_thread(fsg);
2070 /* Queue a request to read a Bulk-only CBW */
2071 set_bulk_out_req_length(fsg, bh, USB_BULK_CB_WRAP_LEN);
2072 start_transfer(fsg, fsg->bulk_out, bh->outreq,
2073 &bh->outreq_busy, &bh->state);
2075 /* We will drain the buffer in software, which means we
2076 * can reuse it for the next filling. No need to advance
2077 * next_buffhd_to_fill. */
2079 /* Wait for the CBW to arrive */
2080 while (bh->state != BUF_STATE_FULL) {
2081 rc = sleep_thread(fsg);
2083 usb_ep_dequeue(fsg->bulk_out, bh->outreq);
2084 bh->outreq_busy = 0;
2085 bh->state = BUF_STATE_EMPTY;
2090 rc = received_cbw(fsg, bh);
2091 bh->state = BUF_STATE_EMPTY;
2097 /*-------------------------------------------------------------------------*/
2099 static int enable_endpoint(struct fsg_dev *fsg, struct usb_ep *ep,
2100 const struct usb_endpoint_descriptor *d)
2104 DBG(fsg, "usb_ep_enable %s\n", ep->name);
2105 ep->driver_data = fsg;
2106 rc = usb_ep_enable(ep, d);
2108 ERROR(fsg, "can't enable %s, result %d\n", ep->name, rc);
2112 static int alloc_request(struct fsg_dev *fsg, struct usb_ep *ep,
2113 struct usb_request **preq)
2115 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2118 ERROR(fsg, "can't allocate request for %s\n", ep->name);
2123 * Reset interface setting and re-init endpoint state (toggle etc).
2124 * Call with altsetting < 0 to disable the interface. The only other
2125 * available altsetting is 0, which enables the interface.
2127 static int do_set_interface(struct fsg_dev *fsg, int altsetting)
2129 struct usb_composite_dev *cdev = fsg->cdev;
2132 const struct usb_endpoint_descriptor *d;
2135 DBG(fsg, "reset interface\n");
2137 /* Disable the endpoints */
2138 if (fsg->bulk_in_enabled) {
2139 DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_in->name);
2140 usb_ep_disable(fsg->bulk_in);
2141 fsg->bulk_in_enabled = 0;
2143 if (fsg->bulk_out_enabled) {
2144 DBG(fsg, "usb_ep_disable %s\n", fsg->bulk_out->name);
2145 usb_ep_disable(fsg->bulk_out);
2146 fsg->bulk_out_enabled = 0;
2149 /* Deallocate the requests */
2150 for (i = 0; i < NUM_BUFFERS; ++i) {
2151 struct fsg_buffhd *bh = &fsg->buffhds[i];
2153 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2157 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2164 if (altsetting < 0 || rc != 0)
2167 DBG(fsg, "set interface %d\n", altsetting);
2169 /* Enable the endpoints */
2170 d = ep_desc(cdev->gadget, &fs_bulk_in_desc, &hs_bulk_in_desc);
2171 if ((rc = enable_endpoint(fsg, fsg->bulk_in, d)) != 0)
2173 fsg->bulk_in_enabled = 1;
2175 d = ep_desc(cdev->gadget, &fs_bulk_out_desc, &hs_bulk_out_desc);
2176 if ((rc = enable_endpoint(fsg, fsg->bulk_out, d)) != 0)
2178 fsg->bulk_out_enabled = 1;
2179 fsg->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2181 /* Allocate the requests */
2182 for (i = 0; i < NUM_BUFFERS; ++i) {
2183 struct fsg_buffhd *bh = &fsg->buffhds[i];
2185 rc = alloc_request(fsg, fsg->bulk_in, &bh->inreq);
2188 rc = alloc_request(fsg, fsg->bulk_out, &bh->outreq);
2191 bh->inreq->buf = bh->outreq->buf = bh->buf;
2192 bh->inreq->context = bh->outreq->context = bh;
2193 bh->inreq->complete = bulk_in_complete;
2194 bh->outreq->complete = bulk_out_complete;
2198 for (i = 0; i < fsg->nluns; ++i)
2199 fsg->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2204 static void adjust_wake_lock(struct fsg_dev *fsg)
2209 spin_lock_irq(&fsg->lock);
2212 for (i = 0; i < fsg->nluns; ++i) {
2213 if (backing_file_is_open(&fsg->luns[i]))
2219 wake_lock(&fsg->wake_lock);
2221 wake_unlock(&fsg->wake_lock);
2223 spin_unlock_irq(&fsg->lock);
2227 * Change our operational configuration. This code must agree with the code
2228 * that returns config descriptors, and with interface altsetting code.
2230 * It's also responsible for power management interactions. Some
2231 * configurations might not work with our current power sources.
2232 * For now we just assume the gadget is always self-powered.
2234 static int do_set_config(struct fsg_dev *fsg, u8 new_config)
2238 if (new_config == fsg->config)
2241 /* Disable the single interface */
2242 if (fsg->config != 0) {
2243 DBG(fsg, "reset config\n");
2247 /* Enable the interface */
2248 if (new_config != 0)
2249 fsg->config = new_config;
2251 switch_set_state(&fsg->sdev, new_config);
2252 adjust_wake_lock(fsg);
2257 /*-------------------------------------------------------------------------*/
2259 static void handle_exception(struct fsg_dev *fsg)
2264 struct fsg_buffhd *bh;
2265 enum fsg_state old_state;
2270 DBG(fsg, "handle_exception state: %d\n", (int)fsg->state);
2271 /* Clear the existing signals. Anything but SIGUSR1 is converted
2272 * into a high-priority EXIT exception. */
2274 sig = dequeue_signal_lock(current, ¤t->blocked, &info);
2277 if (sig != SIGUSR1) {
2278 if (fsg->state < FSG_STATE_EXIT)
2279 DBG(fsg, "Main thread exiting on signal\n");
2280 raise_exception(fsg, FSG_STATE_EXIT);
2284 /* Clear out the controller's fifos */
2285 if (fsg->bulk_in_enabled)
2286 usb_ep_fifo_flush(fsg->bulk_in);
2287 if (fsg->bulk_out_enabled)
2288 usb_ep_fifo_flush(fsg->bulk_out);
2290 /* Reset the I/O buffer states and pointers, the SCSI
2291 * state, and the exception. Then invoke the handler. */
2292 spin_lock_irq(&fsg->lock);
2294 for (i = 0; i < NUM_BUFFERS; ++i) {
2295 bh = &fsg->buffhds[i];
2296 bh->state = BUF_STATE_EMPTY;
2298 fsg->next_buffhd_to_fill = fsg->next_buffhd_to_drain =
2301 new_config = fsg->new_config;
2302 old_state = fsg->state;
2304 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2305 fsg->state = FSG_STATE_STATUS_PHASE;
2307 for (i = 0; i < fsg->nluns; ++i) {
2308 curlun = &fsg->luns[i];
2309 curlun->prevent_medium_removal = 0;
2310 curlun->sense_data = curlun->unit_attention_data =
2312 curlun->sense_data_info = 0;
2313 curlun->info_valid = 0;
2315 fsg->state = FSG_STATE_IDLE;
2317 spin_unlock_irq(&fsg->lock);
2319 /* Carry out any extra actions required for the exception */
2320 switch (old_state) {
2324 case FSG_STATE_ABORT_BULK_OUT:
2325 DBG(fsg, "FSG_STATE_ABORT_BULK_OUT\n");
2326 spin_lock_irq(&fsg->lock);
2327 if (fsg->state == FSG_STATE_STATUS_PHASE)
2328 fsg->state = FSG_STATE_IDLE;
2329 spin_unlock_irq(&fsg->lock);
2332 case FSG_STATE_RESET:
2333 /* really not much to do here */
2336 case FSG_STATE_CONFIG_CHANGE:
2337 rc = do_set_config(fsg, new_config);
2338 if (new_config == 0) {
2339 /* We're using the backing file */
2340 down_read(&fsg->filesem);
2342 up_read(&fsg->filesem);
2346 case FSG_STATE_EXIT:
2347 case FSG_STATE_TERMINATED:
2349 fsg->new_config = 0;
2350 do_set_interface(fsg, -1);
2352 do_set_config(fsg, 0); /* Free resources */
2353 spin_lock_irq(&fsg->lock);
2354 fsg->state = FSG_STATE_TERMINATED; /* Stop the thread */
2355 spin_unlock_irq(&fsg->lock);
2361 /*-------------------------------------------------------------------------*/
2363 static int fsg_main_thread(void *fsg_)
2365 struct fsg_dev *fsg = fsg_;
2367 /* Allow the thread to be killed by a signal, but set the signal mask
2368 * to block everything but INT, TERM, KILL, and USR1. */
2369 allow_signal(SIGINT);
2370 allow_signal(SIGTERM);
2371 allow_signal(SIGKILL);
2372 allow_signal(SIGUSR1);
2374 /* Allow the thread to be frozen */
2377 /* Arrange for userspace references to be interpreted as kernel
2378 * pointers. That way we can pass a kernel pointer to a routine
2379 * that expects a __user pointer and it will work okay. */
2383 while (fsg->state != FSG_STATE_TERMINATED) {
2384 if (exception_in_progress(fsg) || signal_pending(current)) {
2385 handle_exception(fsg);
2389 if (!fsg->running) {
2394 if (get_next_command(fsg))
2397 spin_lock_irq(&fsg->lock);
2398 if (!exception_in_progress(fsg))
2399 fsg->state = FSG_STATE_DATA_PHASE;
2400 spin_unlock_irq(&fsg->lock);
2402 if (do_scsi_command(fsg) || finish_reply(fsg))
2405 spin_lock_irq(&fsg->lock);
2406 if (!exception_in_progress(fsg))
2407 fsg->state = FSG_STATE_STATUS_PHASE;
2408 spin_unlock_irq(&fsg->lock);
2410 if (send_status(fsg))
2413 spin_lock_irq(&fsg->lock);
2414 if (!exception_in_progress(fsg))
2415 fsg->state = FSG_STATE_IDLE;
2416 spin_unlock_irq(&fsg->lock);
2419 spin_lock_irq(&fsg->lock);
2420 fsg->thread_task = NULL;
2421 spin_unlock_irq(&fsg->lock);
2423 /* In case we are exiting because of a signal, unregister the
2424 * gadget driver and close the backing file. */
2425 if (test_and_clear_bit(REGISTERED, &fsg->atomic_bitflags))
2426 close_all_backing_files(fsg);
2428 /* Let the unbind and cleanup routines know the thread has exited */
2429 complete_and_exit(&fsg->thread_notifier, 0);
2433 /*-------------------------------------------------------------------------*/
2435 /* If the next two routines are called while the gadget is registered,
2436 * the caller must own fsg->filesem for writing. */
2438 static int open_backing_file(struct fsg_dev *fsg, struct lun *curlun,
2439 const char *filename)
2442 struct file *filp = NULL;
2444 struct inode *inode = NULL;
2448 /* R/W if we can, R/O if we must */
2451 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
2452 if (-EROFS == PTR_ERR(filp))
2456 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
2458 LINFO(curlun, "unable to open backing file: %s\n", filename);
2459 return PTR_ERR(filp);
2462 if (!(filp->f_mode & FMODE_WRITE))
2465 if (filp->f_path.dentry)
2466 inode = filp->f_path.dentry->d_inode;
2467 if (inode && S_ISBLK(inode->i_mode)) {
2468 if (bdev_read_only(inode->i_bdev))
2470 } else if (!inode || !S_ISREG(inode->i_mode)) {
2471 LINFO(curlun, "invalid file type: %s\n", filename);
2475 /* If we can't read the file, it's no good.
2476 * If we can't write the file, use it read-only. */
2477 if (!filp->f_op || !(filp->f_op->read || filp->f_op->aio_read)) {
2478 LINFO(curlun, "file not readable: %s\n", filename);
2481 if (!(filp->f_op->write || filp->f_op->aio_write))
2484 size = i_size_read(inode->i_mapping->host);
2486 LINFO(curlun, "unable to find file size: %s\n", filename);
2490 num_sectors = size >> 9; /* File size in 512-byte sectors */
2491 if (num_sectors == 0) {
2492 LINFO(curlun, "file too small: %s\n", filename);
2499 curlun->filp = filp;
2500 curlun->file_length = size;
2501 curlun->num_sectors = num_sectors;
2502 LDBG(curlun, "open backing file: %s size: %lld num_sectors: %lld\n",
2503 filename, size, num_sectors);
2505 adjust_wake_lock(fsg);
2508 filp_close(filp, current->files);
2513 static void close_backing_file(struct fsg_dev *fsg, struct lun *curlun)
2519 * XXX: San: Ugly hack here added to ensure that
2520 * our pages get synced to disk.
2521 * Also drop caches here just to be extra-safe
2523 rc = vfs_fsync(curlun->filp, curlun->filp->f_path.dentry, 1);
2525 printk(KERN_ERR "ums: Error syncing data (%d)\n", rc);
2526 /* drop_pagecache and drop_slab are no longer available */
2527 /* drop_pagecache(); */
2530 LDBG(curlun, "close backing file\n");
2532 curlun->filp = NULL;
2533 adjust_wake_lock(fsg);
2537 static void close_all_backing_files(struct fsg_dev *fsg)
2541 for (i = 0; i < fsg->nluns; ++i)
2542 close_backing_file(fsg, &fsg->luns[i]);
2545 static ssize_t show_file(struct device *dev, struct device_attribute *attr,
2548 struct lun *curlun = dev_to_lun(dev);
2549 struct fsg_dev *fsg = dev_get_drvdata(dev);
2553 down_read(&fsg->filesem);
2554 if (backing_file_is_open(curlun)) { /* Get the complete pathname */
2555 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
2560 memmove(buf, p, rc);
2561 buf[rc] = '\n'; /* Add a newline */
2564 } else { /* No file, return 0 bytes */
2568 up_read(&fsg->filesem);
2572 static ssize_t store_file(struct device *dev, struct device_attribute *attr,
2573 const char *buf, size_t count)
2575 struct lun *curlun = dev_to_lun(dev);
2576 struct fsg_dev *fsg = dev_get_drvdata(dev);
2579 DBG(fsg, "store_file: \"%s\"\n", buf);
2581 /* disabled because we need to allow closing the backing file if the media was removed */
2582 if (curlun->prevent_medium_removal && backing_file_is_open(curlun)) {
2583 LDBG(curlun, "eject attempt prevented\n");
2584 return -EBUSY; /* "Door is locked" */
2588 /* Remove a trailing newline */
2589 if (count > 0 && buf[count-1] == '\n')
2590 ((char *) buf)[count-1] = 0;
2592 /* Eject current medium */
2593 down_write(&fsg->filesem);
2594 if (backing_file_is_open(curlun)) {
2595 close_backing_file(fsg, curlun);
2596 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2599 /* Load new medium */
2600 if (count > 0 && buf[0]) {
2601 rc = open_backing_file(fsg, curlun, buf);
2603 curlun->unit_attention_data =
2604 SS_NOT_READY_TO_READY_TRANSITION;
2606 up_write(&fsg->filesem);
2607 return (rc < 0 ? rc : count);
2611 static DEVICE_ATTR(file, 0444, show_file, store_file);
2613 /*-------------------------------------------------------------------------*/
2615 static void fsg_release(struct kref *ref)
2617 struct fsg_dev *fsg = container_of(ref, struct fsg_dev, ref);
2623 static void lun_release(struct device *dev)
2625 struct fsg_dev *fsg = dev_get_drvdata(dev);
2627 kref_put(&fsg->ref, fsg_release);
2631 /*-------------------------------------------------------------------------*/
2633 static int __init fsg_alloc(void)
2635 struct fsg_dev *fsg;
2637 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
2640 spin_lock_init(&fsg->lock);
2641 init_rwsem(&fsg->filesem);
2642 kref_init(&fsg->ref);
2643 init_completion(&fsg->thread_notifier);
2649 static ssize_t print_switch_name(struct switch_dev *sdev, char *buf)
2651 return sprintf(buf, "%s\n", DRIVER_NAME);
2654 static ssize_t print_switch_state(struct switch_dev *sdev, char *buf)
2656 struct fsg_dev *fsg = container_of(sdev, struct fsg_dev, sdev);
2657 return sprintf(buf, "%s\n", (fsg->config ? "online" : "offline"));
2661 fsg_function_unbind(struct usb_configuration *c, struct usb_function *f)
2663 struct fsg_dev *fsg = func_to_dev(f);
2667 DBG(fsg, "fsg_function_unbind\n");
2668 clear_bit(REGISTERED, &fsg->atomic_bitflags);
2670 /* Unregister the sysfs attribute files and the LUNs */
2671 for (i = 0; i < fsg->nluns; ++i) {
2672 curlun = &fsg->luns[i];
2673 if (curlun->registered) {
2674 device_remove_file(&curlun->dev, &dev_attr_file);
2675 device_unregister(&curlun->dev);
2676 curlun->registered = 0;
2680 /* If the thread isn't already dead, tell it to exit now */
2681 if (fsg->state != FSG_STATE_TERMINATED) {
2682 raise_exception(fsg, FSG_STATE_EXIT);
2683 wait_for_completion(&fsg->thread_notifier);
2685 /* The cleanup routine waits for this completion also */
2686 complete(&fsg->thread_notifier);
2689 /* Free the data buffers */
2690 for (i = 0; i < NUM_BUFFERS; ++i)
2691 kfree(fsg->buffhds[i].buf);
2692 switch_dev_unregister(&fsg->sdev);
2696 fsg_function_bind(struct usb_configuration *c, struct usb_function *f)
2698 struct usb_composite_dev *cdev = c->cdev;
2699 struct fsg_dev *fsg = func_to_dev(f);
2708 DBG(fsg, "fsg_function_bind\n");
2710 dev_attr_file.attr.mode = 0644;
2712 /* Find out how many LUNs there should be */
2717 ERROR(fsg, "invalid number of LUNs: %d\n", i);
2722 /* Create the LUNs, open their backing files, and register the
2723 * LUN devices in sysfs. */
2724 fsg->luns = kzalloc(i * sizeof(struct lun), GFP_KERNEL);
2731 for (i = 0; i < fsg->nluns; ++i) {
2732 curlun = &fsg->luns[i];
2734 curlun->dev.release = lun_release;
2735 /* use "usb_mass_storage" platform device as parent if available */
2737 curlun->dev.parent = &fsg->pdev->dev;
2739 curlun->dev.parent = &cdev->gadget->dev;
2740 dev_set_drvdata(&curlun->dev, fsg);
2741 snprintf(curlun->dev.bus_id, BUS_ID_SIZE,
2744 rc = device_register(&curlun->dev);
2746 INFO(fsg, "failed to register LUN%d: %d\n", i, rc);
2749 rc = device_create_file(&curlun->dev, &dev_attr_file);
2751 ERROR(fsg, "device_create_file failed: %d\n", rc);
2752 device_unregister(&curlun->dev);
2755 curlun->registered = 1;
2756 kref_get(&fsg->ref);
2759 /* allocate interface ID(s) */
2760 id = usb_interface_id(c, f);
2763 intf_desc.bInterfaceNumber = id;
2765 ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_in_desc);
2768 ep->driver_data = fsg; /* claim the endpoint */
2771 ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_out_desc);
2774 ep->driver_data = fsg; /* claim the endpoint */
2779 if (gadget_is_dualspeed(cdev->gadget)) {
2780 /* Assume endpoint addresses are the same for both speeds */
2781 hs_bulk_in_desc.bEndpointAddress =
2782 fs_bulk_in_desc.bEndpointAddress;
2783 hs_bulk_out_desc.bEndpointAddress =
2784 fs_bulk_out_desc.bEndpointAddress;
2786 f->hs_descriptors = hs_function;
2789 /* Allocate the data buffers */
2790 for (i = 0; i < NUM_BUFFERS; ++i) {
2791 struct fsg_buffhd *bh = &fsg->buffhds[i];
2793 /* Allocate for the bulk-in endpoint. We assume that
2794 * the buffer will also work with the bulk-out (and
2795 * interrupt-in) endpoint. */
2796 bh->buf = kmalloc(fsg->buf_size, GFP_KERNEL);
2801 fsg->buffhds[NUM_BUFFERS - 1].next = &fsg->buffhds[0];
2803 fsg->thread_task = kthread_create(fsg_main_thread, fsg,
2805 if (IS_ERR(fsg->thread_task)) {
2806 rc = PTR_ERR(fsg->thread_task);
2807 ERROR(fsg, "kthread_create failed: %d\n", rc);
2811 INFO(fsg, "Number of LUNs=%d\n", fsg->nluns);
2813 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2814 for (i = 0; i < fsg->nluns; ++i) {
2815 curlun = &fsg->luns[i];
2816 if (backing_file_is_open(curlun)) {
2819 p = d_path(&curlun->filp->f_path,
2824 LINFO(curlun, "ro=%d, file: %s\n",
2825 curlun->ro, (p ? p : "(error)"));
2830 set_bit(REGISTERED, &fsg->atomic_bitflags);
2832 /* Tell the thread to start working */
2833 wake_up_process(fsg->thread_task);
2837 ERROR(fsg, "unable to autoconfigure all endpoints\n");
2841 DBG(fsg, "fsg_function_bind failed: %d\n", rc);
2842 fsg->state = FSG_STATE_TERMINATED; /* The thread is dead */
2843 fsg_function_unbind(c, f);
2844 close_all_backing_files(fsg);
2848 static int fsg_function_set_alt(struct usb_function *f,
2849 unsigned intf, unsigned alt)
2851 struct fsg_dev *fsg = func_to_dev(f);
2852 DBG(fsg, "fsg_function_set_alt intf: %d alt: %d\n", intf, alt);
2853 fsg->new_config = 1;
2854 do_set_interface(fsg, 0);
2855 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
2859 static void fsg_function_disable(struct usb_function *f)
2861 struct fsg_dev *fsg = func_to_dev(f);
2862 DBG(fsg, "fsg_function_disable\n");
2863 if (fsg->new_config)
2864 do_set_interface(fsg, -1);
2865 fsg->new_config = 0;
2866 raise_exception(fsg, FSG_STATE_CONFIG_CHANGE);
2869 static int __init fsg_probe(struct platform_device *pdev)
2871 struct usb_mass_storage_platform_data *pdata = pdev->dev.platform_data;
2872 struct fsg_dev *fsg = the_fsg;
2875 printk(KERN_INFO "fsg_probe pdata: %p\n", pdata);
2879 fsg->vendor = pdata->vendor;
2882 fsg->product = pdata->product;
2885 fsg->release = pdata->release;
2891 static struct platform_driver fsg_platform_driver = {
2892 .driver = { .name = "usb_mass_storage", },
2896 int __init mass_storage_function_add(struct usb_composite_dev *cdev,
2897 struct usb_configuration *c, int nluns)
2900 struct fsg_dev *fsg;
2902 printk(KERN_INFO "mass_storage_function_add\n");
2909 spin_lock_init(&fsg->lock);
2910 init_rwsem(&fsg->filesem);
2911 kref_init(&fsg->ref);
2912 init_completion(&fsg->thread_notifier);
2914 the_fsg->buf_size = BULK_BUFFER_SIZE;
2915 the_fsg->sdev.name = DRIVER_NAME;
2916 the_fsg->sdev.print_name = print_switch_name;
2917 the_fsg->sdev.print_state = print_switch_state;
2918 rc = switch_dev_register(&the_fsg->sdev);
2920 goto err_switch_dev_register;
2922 rc = platform_driver_register(&fsg_platform_driver);
2924 goto err_platform_driver_register;
2926 wake_lock_init(&the_fsg->wake_lock, WAKE_LOCK_SUSPEND,
2927 "usb_mass_storage");
2930 fsg->function.name = shortname;
2931 fsg->function.descriptors = fs_function;
2932 fsg->function.bind = fsg_function_bind;
2933 fsg->function.unbind = fsg_function_unbind;
2934 fsg->function.setup = fsg_function_setup;
2935 fsg->function.set_alt = fsg_function_set_alt;
2936 fsg->function.disable = fsg_function_disable;
2938 rc = usb_add_function(c, &fsg->function);
2940 goto err_usb_add_function;
2945 err_usb_add_function:
2946 platform_driver_unregister(&fsg_platform_driver);
2947 err_platform_driver_register:
2948 switch_dev_unregister(&the_fsg->sdev);
2949 err_switch_dev_register:
2950 kref_put(&the_fsg->ref, fsg_release);