2 * f_mass_storage.c -- Mass Storage USB Composite Function
4 * Copyright (C) 2003-2008 Alan Stern
5 * Copyright (C) 2009 Samsung Electronics
6 * Author: Michal Nazarewicz <m.nazarewicz@samsung.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions, and the following disclaimer,
14 * without modification.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. The names of the above-listed copyright holders may not be used
19 * to endorse or promote products derived from this software without
20 * specific prior written permission.
22 * ALTERNATIVELY, this software may be distributed under the terms of the
23 * GNU General Public License ("GPL") as published by the Free Software
24 * Foundation, either version 2 of that License or (at your option) any
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
28 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
31 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
33 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
34 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
35 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
36 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
37 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 * The Mass Storage Function acts as a USB Mass Storage device,
43 * appearing to the host as a disk drive or as a CD-ROM drive. In
44 * addition to providing an example of a genuinely useful composite
45 * function for a USB device, it also illustrates a technique of
46 * double-buffering for increased throughput.
48 * Function supports multiple logical units (LUNs). Backing storage
49 * for each LUN is provided by a regular file or a block device.
50 * Access for each LUN can be limited to read-only. Moreover, the
51 * function can indicate that LUN is removable and/or CD-ROM. (The
52 * later implies read-only access.)
54 * MSF is configured by specifying a fsg_config structure. It has the
57 * nluns Number of LUNs function have (anywhere from 1
58 * to FSG_MAX_LUNS which is 8).
59 * luns An array of LUN configuration values. This
60 * should be filled for each LUN that
61 * function will include (ie. for "nluns"
62 * LUNs). Each element of the array has
63 * the following fields:
64 * ->filename The path to the backing file for the LUN.
65 * Required if LUN is not marked as
67 * ->ro Flag specifying access to the LUN shall be
68 * read-only. This is implied if CD-ROM
69 * emulation is enabled as well as when
70 * it was impossible to open "filename"
72 * ->removable Flag specifying that LUN shall be indicated as
74 * ->cdrom Flag specifying that LUN shall be reported as
77 * lun_name_format A printf-like format for names of the LUN
78 * devices. This determines how the
79 * directory in sysfs will be named.
80 * Unless you are using several MSFs in
81 * a single gadget (as opposed to single
82 * MSF in many configurations) you may
83 * leave it as NULL (in which case
84 * "lun%d" will be used). In the format
85 * you can use "%d" to index LUNs for
86 * MSF's with more than one LUN. (Beware
87 * that there is only one integer given
88 * as an argument for the format and
89 * specifying invalid format may cause
90 * unspecified behaviour.)
91 * thread_name Name of the kernel thread process used by the
92 * MSF. You can safely set it to NULL
93 * (in which case default "file-storage"
98 * release Information used as a reply to INQUIRY
99 * request. To use default set to NULL,
100 * NULL, 0xffff respectively. The first
101 * field should be 8 and the second 16
102 * characters or less.
104 * can_stall Set to permit function to halt bulk endpoints.
105 * Disabled on some USB devices known not
106 * to work correctly. You should set it
109 * If "removable" is not set for a LUN then a backing file must be
110 * specified. If it is set, then NULL filename means the LUN's medium
111 * is not loaded (an empty string as "filename" in the fsg_config
112 * structure causes error). The CD-ROM emulation includes a single
113 * data track and no audio tracks; hence there need be only one
114 * backing file per LUN. Note also that the CD-ROM block length is
115 * set to 512 rather than the more common value 2048.
118 * MSF includes support for module parameters. If gadget using it
119 * decides to use it, the following module parameters will be
122 * file=filename[,filename...]
123 * Names of the files or block devices used for
125 * ro=b[,b...] Default false, boolean for read-only access.
127 * Default true, boolean for removable media.
128 * cdrom=b[,b...] Default false, boolean for whether to emulate
130 * luns=N Default N = number of filenames, number of
132 * stall Default determined according to the type of
133 * USB device controller (usually true),
134 * boolean to permit the driver to halt
137 * The module parameters may be prefixed with some string. You need
138 * to consult gadget's documentation or source to verify whether it is
139 * using those module parameters and if it does what are the prefixes
140 * (look for FSG_MODULE_PARAMETERS() macro usage, what's inside it is
144 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
145 * needed. The memory requirement amounts to two 16K buffers, size
146 * configurable by a parameter. Support is included for both
147 * full-speed and high-speed operation.
149 * Note that the driver is slightly non-portable in that it assumes a
150 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
151 * interrupt-in endpoints. With most device controllers this isn't an
152 * issue, but there may be some with hardware restrictions that prevent
153 * a buffer from being used by more than one endpoint.
156 * The pathnames of the backing files and the ro settings are
157 * available in the attribute files "file" and "ro" in the lun<n> (or
158 * to be more precise in a directory which name comes from
159 * "lun_name_format" option!) subdirectory of the gadget's sysfs
160 * directory. If the "removable" option is set, writing to these
161 * files will simulate ejecting/loading the medium (writing an empty
162 * line means eject) and adjusting a write-enable tab. Changes to the
163 * ro setting are not allowed when the medium is loaded or if CD-ROM
164 * emulation is being used.
166 * When a LUN receive an "eject" SCSI request (Start/Stop Unit),
167 * if the LUN is removable, the backing file is released to simulate
171 * This function is heavily based on "File-backed Storage Gadget" by
172 * Alan Stern which in turn is heavily based on "Gadget Zero" by David
173 * Brownell. The driver's SCSI command interface was based on the
174 * "Information technology - Small Computer System Interface - 2"
175 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
176 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
177 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
178 * was based on the "Universal Serial Bus Mass Storage Class UFI
179 * Command Specification" document, Revision 1.0, December 14, 1998,
181 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
188 * The MSF is fairly straightforward. There is a main kernel
189 * thread that handles most of the work. Interrupt routines field
190 * callbacks from the controller driver: bulk- and interrupt-request
191 * completion notifications, endpoint-0 events, and disconnect events.
192 * Completion events are passed to the main thread by wakeup calls. Many
193 * ep0 requests are handled at interrupt time, but SetInterface,
194 * SetConfiguration, and device reset requests are forwarded to the
195 * thread in the form of "exceptions" using SIGUSR1 signals (since they
196 * should interrupt any ongoing file I/O operations).
198 * The thread's main routine implements the standard command/data/status
199 * parts of a SCSI interaction. It and its subroutines are full of tests
200 * for pending signals/exceptions -- all this polling is necessary since
201 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
202 * indication that the driver really wants to be running in userspace.)
203 * An important point is that so long as the thread is alive it keeps an
204 * open reference to the backing file. This will prevent unmounting
205 * the backing file's underlying filesystem and could cause problems
206 * during system shutdown, for example. To prevent such problems, the
207 * thread catches INT, TERM, and KILL signals and converts them into
210 * In normal operation the main thread is started during the gadget's
211 * fsg_bind() callback and stopped during fsg_unbind(). But it can
212 * also exit when it receives a signal, and there's no point leaving
213 * the gadget running when the thread is dead. At of this moment, MSF
214 * provides no way to deregister the gadget when thread dies -- maybe
215 * a callback functions is needed.
217 * To provide maximum throughput, the driver uses a circular pipeline of
218 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
219 * arbitrarily long; in practice the benefits don't justify having more
220 * than 2 stages (i.e., double buffering). But it helps to think of the
221 * pipeline as being a long one. Each buffer head contains a bulk-in and
222 * a bulk-out request pointer (since the buffer can be used for both
223 * output and input -- directions always are given from the host's
224 * point of view) as well as a pointer to the buffer and various state
227 * Use of the pipeline follows a simple protocol. There is a variable
228 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
229 * At any time that buffer head may still be in use from an earlier
230 * request, so each buffer head has a state variable indicating whether
231 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
232 * buffer head to be EMPTY, filling the buffer either by file I/O or by
233 * USB I/O (during which the buffer head is BUSY), and marking the buffer
234 * head FULL when the I/O is complete. Then the buffer will be emptied
235 * (again possibly by USB I/O, during which it is marked BUSY) and
236 * finally marked EMPTY again (possibly by a completion routine).
238 * A module parameter tells the driver to avoid stalling the bulk
239 * endpoints wherever the transport specification allows. This is
240 * necessary for some UDCs like the SuperH, which cannot reliably clear a
241 * halt on a bulk endpoint. However, under certain circumstances the
242 * Bulk-only specification requires a stall. In such cases the driver
243 * will halt the endpoint and set a flag indicating that it should clear
244 * the halt in software during the next device reset. Hopefully this
245 * will permit everything to work correctly. Furthermore, although the
246 * specification allows the bulk-out endpoint to halt when the host sends
247 * too much data, implementing this would cause an unavoidable race.
248 * The driver will always use the "no-stall" approach for OUT transfers.
250 * One subtle point concerns sending status-stage responses for ep0
251 * requests. Some of these requests, such as device reset, can involve
252 * interrupting an ongoing file I/O operation, which might take an
253 * arbitrarily long time. During that delay the host might give up on
254 * the original ep0 request and issue a new one. When that happens the
255 * driver should not notify the host about completion of the original
256 * request, as the host will no longer be waiting for it. So the driver
257 * assigns to each ep0 request a unique tag, and it keeps track of the
258 * tag value of the request associated with a long-running exception
259 * (device-reset, interface-change, or configuration-change). When the
260 * exception handler is finished, the status-stage response is submitted
261 * only if the current ep0 request tag is equal to the exception request
262 * tag. Thus only the most recently received ep0 request will get a
263 * status-stage response.
265 * Warning: This driver source file is too long. It ought to be split up
266 * into a header file plus about 3 separate .c files, to handle the details
267 * of the Gadget, USB Mass Storage, and SCSI protocols.
271 /* #define VERBOSE_DEBUG */
272 /* #define DUMP_MSGS */
275 #include <linux/blkdev.h>
276 #include <linux/completion.h>
277 #include <linux/dcache.h>
278 #include <linux/delay.h>
279 #include <linux/device.h>
280 #include <linux/fcntl.h>
281 #include <linux/file.h>
282 #include <linux/fs.h>
283 #include <linux/kref.h>
284 #include <linux/kthread.h>
285 #include <linux/limits.h>
286 #include <linux/rwsem.h>
287 #include <linux/slab.h>
288 #include <linux/spinlock.h>
289 #include <linux/string.h>
290 #include <linux/freezer.h>
291 #include <linux/utsname.h>
293 #include <linux/usb/ch9.h>
294 #include <linux/usb/gadget.h>
296 #include "gadget_chips.h"
298 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
299 #include <linux/usb/android_composite.h>
300 #include <linux/platform_device.h>
302 #define FUNCTION_NAME "usb_mass_storage"
305 /*------------------------------------------------------------------------*/
307 #define FSG_DRIVER_DESC "Mass Storage Function"
308 #define FSG_DRIVER_VERSION "2009/09/11"
310 static const char fsg_string_interface[] = "Mass Storage";
313 #define FSG_NO_INTR_EP 1
314 #define FSG_NO_DEVICE_STRINGS 1
316 #define FSG_NO_INTR_EP 1
318 #include "storage_common.c"
321 /*-------------------------------------------------------------------------*/
326 /* FSF callback functions */
327 struct fsg_operations {
328 /* Callback function to call when thread exits. If no
329 * callback is set or it returns value lower then zero MSF
330 * will force eject all LUNs it operates on (including those
331 * marked as non-removable or with prevent_medium_removal flag
333 int (*thread_exits)(struct fsg_common *common);
335 /* Called prior to ejection. Negative return means error,
336 * zero means to continue with ejection, positive means not to
338 int (*pre_eject)(struct fsg_common *common,
339 struct fsg_lun *lun, int num);
340 /* Called after ejection. Negative return means error, zero
341 * or positive is just a success. */
342 int (*post_eject)(struct fsg_common *common,
343 struct fsg_lun *lun, int num);
347 /* Data shared by all the FSG instances. */
349 struct usb_gadget *gadget;
350 struct fsg_dev *fsg, *new_fsg;
351 wait_queue_head_t fsg_wait;
353 /* filesem protects: backing files in use */
354 struct rw_semaphore filesem;
356 /* lock protects: state, all the req_busy's */
359 struct usb_ep *ep0; /* Copy of gadget->ep0 */
360 struct usb_request *ep0req; /* Copy of cdev->req */
361 unsigned int ep0_req_tag;
363 struct fsg_buffhd *next_buffhd_to_fill;
364 struct fsg_buffhd *next_buffhd_to_drain;
365 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
368 u8 cmnd[MAX_COMMAND_SIZE];
372 struct fsg_lun *luns;
373 struct fsg_lun *curlun;
375 unsigned int bulk_out_maxpacket;
376 enum fsg_state state; /* For exception handling */
377 unsigned int exception_req_tag;
379 enum data_direction data_dir;
381 u32 data_size_from_cmnd;
386 unsigned int can_stall:1;
387 unsigned int free_storage_on_release:1;
388 unsigned int phase_error:1;
389 unsigned int short_packet_received:1;
390 unsigned int bad_lun_okay:1;
391 unsigned int running:1;
393 int thread_wakeup_needed;
394 struct completion thread_notifier;
395 struct task_struct *thread_task;
397 /* Callback functions. */
398 const struct fsg_operations *ops;
399 /* Gadget's private data. */
402 /* Vendor (8 chars), product (16 chars), release (4
403 * hexadecimal digits) and NUL byte */
404 char inquiry_string[8 + 16 + 4 + 1];
412 struct fsg_lun_config {
413 const char *filename;
417 } luns[FSG_MAX_LUNS];
419 const char *lun_name_format;
420 const char *thread_name;
422 /* Callback functions. */
423 const struct fsg_operations *ops;
424 /* Gadget's private data. */
427 const char *vendor_name; /* 8 characters or less */
428 const char *product_name; /* 16 characters or less */
433 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
434 struct platform_device *pdev;
440 struct usb_function function;
441 struct usb_gadget *gadget; /* Copy of cdev->gadget */
442 struct fsg_common *common;
444 u16 interface_number;
446 unsigned int bulk_in_enabled:1;
447 unsigned int bulk_out_enabled:1;
449 unsigned long atomic_bitflags;
450 #define IGNORE_BULK_OUT 0
452 struct usb_ep *bulk_in;
453 struct usb_ep *bulk_out;
457 static inline int __fsg_is_set(struct fsg_common *common,
458 const char *func, unsigned line)
462 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
467 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
470 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
472 return container_of(f, struct fsg_dev, function);
476 typedef void (*fsg_routine_t)(struct fsg_dev *);
478 static int exception_in_progress(struct fsg_common *common)
480 return common->state > FSG_STATE_IDLE;
483 /* Make bulk-out requests be divisible by the maxpacket size */
484 static void set_bulk_out_req_length(struct fsg_common *common,
485 struct fsg_buffhd *bh, unsigned int length)
489 bh->bulk_out_intended_length = length;
490 rem = length % common->bulk_out_maxpacket;
492 length += common->bulk_out_maxpacket - rem;
493 bh->outreq->length = length;
496 /*-------------------------------------------------------------------------*/
498 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
502 if (ep == fsg->bulk_in)
504 else if (ep == fsg->bulk_out)
508 DBG(fsg, "%s set halt\n", name);
509 return usb_ep_set_halt(ep);
513 /*-------------------------------------------------------------------------*/
515 /* These routines may be called in process context or in_irq */
517 /* Caller must hold fsg->lock */
518 static void wakeup_thread(struct fsg_common *common)
520 /* Tell the main thread that something has happened */
521 common->thread_wakeup_needed = 1;
522 if (common->thread_task)
523 wake_up_process(common->thread_task);
527 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
531 /* Do nothing if a higher-priority exception is already in progress.
532 * If a lower-or-equal priority exception is in progress, preempt it
533 * and notify the main thread by sending it a signal. */
534 spin_lock_irqsave(&common->lock, flags);
535 if (common->state <= new_state) {
536 common->exception_req_tag = common->ep0_req_tag;
537 common->state = new_state;
538 if (common->thread_task)
539 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
540 common->thread_task);
542 spin_unlock_irqrestore(&common->lock, flags);
546 /*-------------------------------------------------------------------------*/
548 static int ep0_queue(struct fsg_common *common)
552 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
553 common->ep0->driver_data = common;
554 if (rc != 0 && rc != -ESHUTDOWN) {
555 /* We can't do much more than wait for a reset */
556 WARNING(common, "error in submission: %s --> %d\n",
557 common->ep0->name, rc);
562 /*-------------------------------------------------------------------------*/
564 /* Bulk and interrupt endpoint completion handlers.
565 * These always run in_irq. */
567 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
569 struct fsg_common *common = ep->driver_data;
570 struct fsg_buffhd *bh = req->context;
572 if (req->status || req->actual != req->length)
573 DBG(common, "%s --> %d, %u/%u\n", __func__,
574 req->status, req->actual, req->length);
575 if (req->status == -ECONNRESET) /* Request was cancelled */
576 usb_ep_fifo_flush(ep);
578 /* Hold the lock while we update the request and buffer states */
580 spin_lock(&common->lock);
582 bh->state = BUF_STATE_EMPTY;
583 wakeup_thread(common);
584 spin_unlock(&common->lock);
587 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
589 struct fsg_common *common = ep->driver_data;
590 struct fsg_buffhd *bh = req->context;
592 dump_msg(common, "bulk-out", req->buf, req->actual);
593 if (req->status || req->actual != bh->bulk_out_intended_length)
594 DBG(common, "%s --> %d, %u/%u\n", __func__,
595 req->status, req->actual,
596 bh->bulk_out_intended_length);
597 if (req->status == -ECONNRESET) /* Request was cancelled */
598 usb_ep_fifo_flush(ep);
600 /* Hold the lock while we update the request and buffer states */
602 spin_lock(&common->lock);
604 bh->state = BUF_STATE_FULL;
605 wakeup_thread(common);
606 spin_unlock(&common->lock);
610 /*-------------------------------------------------------------------------*/
612 /* Ep0 class-specific handlers. These always run in_irq. */
614 static int fsg_setup(struct usb_function *f,
615 const struct usb_ctrlrequest *ctrl)
617 struct fsg_dev *fsg = fsg_from_func(f);
618 struct usb_request *req = fsg->common->ep0req;
619 u16 w_index = le16_to_cpu(ctrl->wIndex);
620 u16 w_value = le16_to_cpu(ctrl->wValue);
621 u16 w_length = le16_to_cpu(ctrl->wLength);
623 if (!fsg_is_set(fsg->common))
626 switch (ctrl->bRequest) {
628 case USB_BULK_RESET_REQUEST:
629 if (ctrl->bRequestType !=
630 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
632 if (w_index != fsg->interface_number || w_value != 0)
635 /* Raise an exception to stop the current operation
636 * and reinitialize our state. */
637 DBG(fsg, "bulk reset request\n");
638 raise_exception(fsg->common, FSG_STATE_RESET);
639 return DELAYED_STATUS;
641 case USB_BULK_GET_MAX_LUN_REQUEST:
642 if (ctrl->bRequestType !=
643 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
645 if (w_index != fsg->interface_number || w_value != 0)
647 VDBG(fsg, "get max LUN\n");
648 *(u8 *) req->buf = fsg->common->nluns - 1;
650 /* Respond with data/status */
651 req->length = min((u16)1, w_length);
652 return ep0_queue(fsg->common);
656 "unknown class-specific control req "
657 "%02x.%02x v%04x i%04x l%u\n",
658 ctrl->bRequestType, ctrl->bRequest,
659 le16_to_cpu(ctrl->wValue), w_index, w_length);
664 /*-------------------------------------------------------------------------*/
666 /* All the following routines run in process context */
669 /* Use this for bulk or interrupt transfers, not ep0 */
670 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
671 struct usb_request *req, int *pbusy,
672 enum fsg_buffer_state *state)
676 if (ep == fsg->bulk_in)
677 dump_msg(fsg, "bulk-in", req->buf, req->length);
679 spin_lock_irq(&fsg->common->lock);
681 *state = BUF_STATE_BUSY;
682 spin_unlock_irq(&fsg->common->lock);
683 rc = usb_ep_queue(ep, req, GFP_KERNEL);
686 *state = BUF_STATE_EMPTY;
688 /* We can't do much more than wait for a reset */
690 /* Note: currently the net2280 driver fails zero-length
691 * submissions if DMA is enabled. */
692 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
694 WARNING(fsg, "error in submission: %s --> %d\n",
699 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
700 if (fsg_is_set(common)) \
701 start_transfer((common)->fsg, (common)->fsg->ep_name, \
702 req, pbusy, state); \
705 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
706 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
710 static int sleep_thread(struct fsg_common *common)
714 /* Wait until a signal arrives or we are woken up */
717 set_current_state(TASK_INTERRUPTIBLE);
718 if (signal_pending(current)) {
722 if (common->thread_wakeup_needed)
726 __set_current_state(TASK_RUNNING);
727 common->thread_wakeup_needed = 0;
732 /*-------------------------------------------------------------------------*/
734 static int do_read(struct fsg_common *common)
736 struct fsg_lun *curlun = common->curlun;
738 struct fsg_buffhd *bh;
741 loff_t file_offset, file_offset_tmp;
743 unsigned int partial_page;
746 /* Get the starting Logical Block Address and check that it's
748 if (common->cmnd[0] == SC_READ_6)
749 lba = get_unaligned_be24(&common->cmnd[1]);
751 lba = get_unaligned_be32(&common->cmnd[2]);
753 /* We allow DPO (Disable Page Out = don't save data in the
754 * cache) and FUA (Force Unit Access = don't read from the
755 * cache), but we don't implement them. */
756 if ((common->cmnd[1] & ~0x18) != 0) {
757 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
761 if (lba >= curlun->num_sectors) {
762 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
765 file_offset = ((loff_t) lba) << 9;
767 /* Carry out the file reads */
768 amount_left = common->data_size_from_cmnd;
769 if (unlikely(amount_left == 0))
770 return -EIO; /* No default reply */
774 /* Figure out how much we need to read:
775 * Try to read the remaining amount.
776 * But don't read more than the buffer size.
777 * And don't try to read past the end of the file.
778 * Finally, if we're not at a page boundary, don't read past
780 * If this means reading 0 then we were asked to read past
781 * the end of file. */
782 amount = min(amount_left, FSG_BUFLEN);
783 amount = min((loff_t) amount,
784 curlun->file_length - file_offset);
785 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
786 if (partial_page > 0)
787 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
790 /* Wait for the next buffer to become available */
791 bh = common->next_buffhd_to_fill;
792 while (bh->state != BUF_STATE_EMPTY) {
793 rc = sleep_thread(common);
798 /* If we were asked to read past the end of file,
799 * end with an empty buffer. */
802 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
803 curlun->sense_data_info = file_offset >> 9;
804 curlun->info_valid = 1;
805 bh->inreq->length = 0;
806 bh->state = BUF_STATE_FULL;
810 /* Perform the read */
811 file_offset_tmp = file_offset;
812 nread = vfs_read(curlun->filp,
813 (char __user *) bh->buf,
814 amount, &file_offset_tmp);
815 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
816 (unsigned long long) file_offset,
818 if (signal_pending(current))
822 LDBG(curlun, "error in file read: %d\n",
825 } else if (nread < amount) {
826 LDBG(curlun, "partial file read: %d/%u\n",
827 (int) nread, amount);
828 nread -= (nread & 511); /* Round down to a block */
830 file_offset += nread;
831 amount_left -= nread;
832 common->residue -= nread;
833 bh->inreq->length = nread;
834 bh->state = BUF_STATE_FULL;
836 /* If an error occurred, report it and its position */
837 if (nread < amount) {
838 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
839 curlun->sense_data_info = file_offset >> 9;
840 curlun->info_valid = 1;
844 if (amount_left == 0)
845 break; /* No more left to read */
847 /* Send this buffer and go read some more */
849 START_TRANSFER_OR(common, bulk_in, bh->inreq,
850 &bh->inreq_busy, &bh->state)
851 /* Don't know what to do if
852 * common->fsg is NULL */
854 common->next_buffhd_to_fill = bh->next;
857 return -EIO; /* No default reply */
861 /*-------------------------------------------------------------------------*/
863 static int do_write(struct fsg_common *common)
865 struct fsg_lun *curlun = common->curlun;
867 struct fsg_buffhd *bh;
869 u32 amount_left_to_req, amount_left_to_write;
870 loff_t usb_offset, file_offset, file_offset_tmp;
872 unsigned int partial_page;
877 curlun->sense_data = SS_WRITE_PROTECTED;
880 spin_lock(&curlun->filp->f_lock);
881 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
882 spin_unlock(&curlun->filp->f_lock);
884 /* Get the starting Logical Block Address and check that it's
886 if (common->cmnd[0] == SC_WRITE_6)
887 lba = get_unaligned_be24(&common->cmnd[1]);
889 lba = get_unaligned_be32(&common->cmnd[2]);
891 /* We allow DPO (Disable Page Out = don't save data in the
892 * cache) and FUA (Force Unit Access = write directly to the
893 * medium). We don't implement DPO; we implement FUA by
894 * performing synchronous output. */
895 if (common->cmnd[1] & ~0x18) {
896 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
899 if (common->cmnd[1] & 0x08) { /* FUA */
900 spin_lock(&curlun->filp->f_lock);
901 curlun->filp->f_flags |= O_SYNC;
902 spin_unlock(&curlun->filp->f_lock);
905 if (lba >= curlun->num_sectors) {
906 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
910 /* Carry out the file writes */
912 file_offset = usb_offset = ((loff_t) lba) << 9;
913 amount_left_to_req = common->data_size_from_cmnd;
914 amount_left_to_write = common->data_size_from_cmnd;
916 while (amount_left_to_write > 0) {
918 /* Queue a request for more data from the host */
919 bh = common->next_buffhd_to_fill;
920 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
922 /* Figure out how much we want to get:
923 * Try to get the remaining amount.
924 * But don't get more than the buffer size.
925 * And don't try to go past the end of the file.
926 * If we're not at a page boundary,
927 * don't go past the next page.
928 * If this means getting 0, then we were asked
929 * to write past the end of file.
930 * Finally, round down to a block boundary. */
931 amount = min(amount_left_to_req, FSG_BUFLEN);
932 amount = min((loff_t) amount, curlun->file_length -
934 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
935 if (partial_page > 0)
937 (unsigned int) PAGE_CACHE_SIZE - partial_page);
942 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
943 curlun->sense_data_info = usb_offset >> 9;
944 curlun->info_valid = 1;
947 amount -= (amount & 511);
950 /* Why were we were asked to transfer a
956 /* Get the next buffer */
957 usb_offset += amount;
958 common->usb_amount_left -= amount;
959 amount_left_to_req -= amount;
960 if (amount_left_to_req == 0)
963 /* amount is always divisible by 512, hence by
964 * the bulk-out maxpacket size */
965 bh->outreq->length = amount;
966 bh->bulk_out_intended_length = amount;
967 bh->outreq->short_not_ok = 1;
968 START_TRANSFER_OR(common, bulk_out, bh->outreq,
969 &bh->outreq_busy, &bh->state)
970 /* Don't know what to do if
971 * common->fsg is NULL */
973 common->next_buffhd_to_fill = bh->next;
977 /* Write the received data to the backing file */
978 bh = common->next_buffhd_to_drain;
979 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
980 break; /* We stopped early */
981 if (bh->state == BUF_STATE_FULL) {
983 common->next_buffhd_to_drain = bh->next;
984 bh->state = BUF_STATE_EMPTY;
986 /* Did something go wrong with the transfer? */
987 if (bh->outreq->status != 0) {
988 curlun->sense_data = SS_COMMUNICATION_FAILURE;
989 curlun->sense_data_info = file_offset >> 9;
990 curlun->info_valid = 1;
994 amount = bh->outreq->actual;
995 if (curlun->file_length - file_offset < amount) {
997 "write %u @ %llu beyond end %llu\n",
998 amount, (unsigned long long) file_offset,
999 (unsigned long long) curlun->file_length);
1000 amount = curlun->file_length - file_offset;
1003 /* Perform the write */
1004 file_offset_tmp = file_offset;
1005 nwritten = vfs_write(curlun->filp,
1006 (char __user *) bh->buf,
1007 amount, &file_offset_tmp);
1008 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1009 (unsigned long long) file_offset,
1011 if (signal_pending(current))
1012 return -EINTR; /* Interrupted! */
1015 LDBG(curlun, "error in file write: %d\n",
1018 } else if (nwritten < amount) {
1019 LDBG(curlun, "partial file write: %d/%u\n",
1020 (int) nwritten, amount);
1021 nwritten -= (nwritten & 511);
1022 /* Round down to a block */
1024 file_offset += nwritten;
1025 amount_left_to_write -= nwritten;
1026 common->residue -= nwritten;
1028 /* If an error occurred, report it and its position */
1029 if (nwritten < amount) {
1030 curlun->sense_data = SS_WRITE_ERROR;
1031 curlun->sense_data_info = file_offset >> 9;
1032 curlun->info_valid = 1;
1036 /* Did the host decide to stop early? */
1037 if (bh->outreq->actual != bh->outreq->length) {
1038 common->short_packet_received = 1;
1044 /* Wait for something to happen */
1045 rc = sleep_thread(common);
1050 return -EIO; /* No default reply */
1054 /*-------------------------------------------------------------------------*/
1056 static int do_synchronize_cache(struct fsg_common *common)
1058 struct fsg_lun *curlun = common->curlun;
1061 /* We ignore the requested LBA and write out all file's
1062 * dirty data buffers. */
1063 rc = fsg_lun_fsync_sub(curlun);
1065 curlun->sense_data = SS_WRITE_ERROR;
1070 /*-------------------------------------------------------------------------*/
1072 static void invalidate_sub(struct fsg_lun *curlun)
1074 struct file *filp = curlun->filp;
1075 struct inode *inode = filp->f_path.dentry->d_inode;
1078 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1079 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1082 static int do_verify(struct fsg_common *common)
1084 struct fsg_lun *curlun = common->curlun;
1086 u32 verification_length;
1087 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1088 loff_t file_offset, file_offset_tmp;
1090 unsigned int amount;
1093 /* Get the starting Logical Block Address and check that it's
1095 lba = get_unaligned_be32(&common->cmnd[2]);
1096 if (lba >= curlun->num_sectors) {
1097 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1101 /* We allow DPO (Disable Page Out = don't save data in the
1102 * cache) but we don't implement it. */
1103 if (common->cmnd[1] & ~0x10) {
1104 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1108 verification_length = get_unaligned_be16(&common->cmnd[7]);
1109 if (unlikely(verification_length == 0))
1110 return -EIO; /* No default reply */
1112 /* Prepare to carry out the file verify */
1113 amount_left = verification_length << 9;
1114 file_offset = ((loff_t) lba) << 9;
1116 /* Write out all the dirty buffers before invalidating them */
1117 fsg_lun_fsync_sub(curlun);
1118 if (signal_pending(current))
1121 invalidate_sub(curlun);
1122 if (signal_pending(current))
1125 /* Just try to read the requested blocks */
1126 while (amount_left > 0) {
1128 /* Figure out how much we need to read:
1129 * Try to read the remaining amount, but not more than
1131 * And don't try to read past the end of the file.
1132 * If this means reading 0 then we were asked to read
1133 * past the end of file. */
1134 amount = min(amount_left, FSG_BUFLEN);
1135 amount = min((loff_t) amount,
1136 curlun->file_length - file_offset);
1138 curlun->sense_data =
1139 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1140 curlun->sense_data_info = file_offset >> 9;
1141 curlun->info_valid = 1;
1145 /* Perform the read */
1146 file_offset_tmp = file_offset;
1147 nread = vfs_read(curlun->filp,
1148 (char __user *) bh->buf,
1149 amount, &file_offset_tmp);
1150 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1151 (unsigned long long) file_offset,
1153 if (signal_pending(current))
1157 LDBG(curlun, "error in file verify: %d\n",
1160 } else if (nread < amount) {
1161 LDBG(curlun, "partial file verify: %d/%u\n",
1162 (int) nread, amount);
1163 nread -= (nread & 511); /* Round down to a sector */
1166 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1167 curlun->sense_data_info = file_offset >> 9;
1168 curlun->info_valid = 1;
1171 file_offset += nread;
1172 amount_left -= nread;
1178 /*-------------------------------------------------------------------------*/
1180 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1182 struct fsg_lun *curlun = common->curlun;
1183 u8 *buf = (u8 *) bh->buf;
1185 if (!curlun) { /* Unsupported LUNs are okay */
1186 common->bad_lun_okay = 1;
1188 buf[0] = 0x7f; /* Unsupported, no device-type */
1189 buf[4] = 31; /* Additional length */
1193 buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1194 buf[1] = curlun->removable ? 0x80 : 0;
1195 buf[2] = 2; /* ANSI SCSI level 2 */
1196 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1197 buf[4] = 31; /* Additional length */
1198 buf[5] = 0; /* No special options */
1201 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1206 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1208 struct fsg_lun *curlun = common->curlun;
1209 u8 *buf = (u8 *) bh->buf;
1214 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1216 * If a REQUEST SENSE command is received from an initiator
1217 * with a pending unit attention condition (before the target
1218 * generates the contingent allegiance condition), then the
1219 * target shall either:
1220 * a) report any pending sense data and preserve the unit
1221 * attention condition on the logical unit, or,
1222 * b) report the unit attention condition, may discard any
1223 * pending sense data, and clear the unit attention
1224 * condition on the logical unit for that initiator.
1226 * FSG normally uses option a); enable this code to use option b).
1229 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1230 curlun->sense_data = curlun->unit_attention_data;
1231 curlun->unit_attention_data = SS_NO_SENSE;
1235 if (!curlun) { /* Unsupported LUNs are okay */
1236 common->bad_lun_okay = 1;
1237 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1241 sd = curlun->sense_data;
1242 sdinfo = curlun->sense_data_info;
1243 valid = curlun->info_valid << 7;
1244 curlun->sense_data = SS_NO_SENSE;
1245 curlun->sense_data_info = 0;
1246 curlun->info_valid = 0;
1250 buf[0] = valid | 0x70; /* Valid, current error */
1252 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1253 buf[7] = 18 - 8; /* Additional sense length */
1260 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1262 struct fsg_lun *curlun = common->curlun;
1263 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1264 int pmi = common->cmnd[8];
1265 u8 *buf = (u8 *) bh->buf;
1267 /* Check the PMI and LBA fields */
1268 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1269 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1273 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1274 /* Max logical block */
1275 put_unaligned_be32(512, &buf[4]); /* Block length */
1280 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1282 struct fsg_lun *curlun = common->curlun;
1283 int msf = common->cmnd[1] & 0x02;
1284 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1285 u8 *buf = (u8 *) bh->buf;
1287 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1288 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1291 if (lba >= curlun->num_sectors) {
1292 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1297 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1298 store_cdrom_address(&buf[4], msf, lba);
1303 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1305 struct fsg_lun *curlun = common->curlun;
1306 int msf = common->cmnd[1] & 0x02;
1307 int start_track = common->cmnd[6];
1308 u8 *buf = (u8 *) bh->buf;
1310 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1312 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1317 buf[1] = (20-2); /* TOC data length */
1318 buf[2] = 1; /* First track number */
1319 buf[3] = 1; /* Last track number */
1320 buf[5] = 0x16; /* Data track, copying allowed */
1321 buf[6] = 0x01; /* Only track is number 1 */
1322 store_cdrom_address(&buf[8], msf, 0);
1324 buf[13] = 0x16; /* Lead-out track is data */
1325 buf[14] = 0xAA; /* Lead-out track number */
1326 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1331 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1333 struct fsg_lun *curlun = common->curlun;
1334 int mscmnd = common->cmnd[0];
1335 u8 *buf = (u8 *) bh->buf;
1338 int changeable_values, all_pages;
1342 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1343 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1346 pc = common->cmnd[2] >> 6;
1347 page_code = common->cmnd[2] & 0x3f;
1349 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1352 changeable_values = (pc == 1);
1353 all_pages = (page_code == 0x3f);
1355 /* Write the mode parameter header. Fixed values are: default
1356 * medium type, no cache control (DPOFUA), and no block descriptors.
1357 * The only variable value is the WriteProtect bit. We will fill in
1358 * the mode data length later. */
1360 if (mscmnd == SC_MODE_SENSE_6) {
1361 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1364 } else { /* SC_MODE_SENSE_10 */
1365 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1367 limit = 65535; /* Should really be FSG_BUFLEN */
1370 /* No block descriptors */
1372 /* The mode pages, in numerical order. The only page we support
1373 * is the Caching page. */
1374 if (page_code == 0x08 || all_pages) {
1376 buf[0] = 0x08; /* Page code */
1377 buf[1] = 10; /* Page length */
1378 memset(buf+2, 0, 10); /* None of the fields are changeable */
1380 if (!changeable_values) {
1381 buf[2] = 0x04; /* Write cache enable, */
1382 /* Read cache not disabled */
1383 /* No cache retention priorities */
1384 put_unaligned_be16(0xffff, &buf[4]);
1385 /* Don't disable prefetch */
1386 /* Minimum prefetch = 0 */
1387 put_unaligned_be16(0xffff, &buf[8]);
1388 /* Maximum prefetch */
1389 put_unaligned_be16(0xffff, &buf[10]);
1390 /* Maximum prefetch ceiling */
1395 /* Check that a valid page was requested and the mode data length
1396 * isn't too long. */
1398 if (!valid_page || len > limit) {
1399 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1403 /* Store the mode data length */
1404 if (mscmnd == SC_MODE_SENSE_6)
1407 put_unaligned_be16(len - 2, buf0);
1412 static int do_start_stop(struct fsg_common *common)
1414 struct fsg_lun *curlun = common->curlun;
1419 } else if (!curlun->removable) {
1420 curlun->sense_data = SS_INVALID_COMMAND;
1422 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1423 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1424 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1428 loej = common->cmnd[4] & 0x02;
1429 start = common->cmnd[4] & 0x01;
1431 /* Our emulation doesn't support mounting; the medium is
1432 * available for use as soon as it is loaded. */
1434 if (!fsg_lun_is_open(curlun)) {
1435 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1441 /* Are we allowed to unload the media? */
1442 if (curlun->prevent_medium_removal) {
1443 LDBG(curlun, "unload attempt prevented\n");
1444 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1451 /* Simulate an unload/eject */
1452 if (common->ops && common->ops->pre_eject) {
1453 int r = common->ops->pre_eject(common, curlun,
1454 curlun - common->luns);
1455 if (unlikely(r < 0))
1461 up_read(&common->filesem);
1462 down_write(&common->filesem);
1463 fsg_lun_close(curlun);
1464 up_write(&common->filesem);
1465 down_read(&common->filesem);
1467 return common->ops && common->ops->post_eject
1468 ? min(0, common->ops->post_eject(common, curlun,
1469 curlun - common->luns))
1474 static int do_prevent_allow(struct fsg_common *common)
1476 struct fsg_lun *curlun = common->curlun;
1479 if (!common->curlun) {
1481 } else if (!common->curlun->removable) {
1482 common->curlun->sense_data = SS_INVALID_COMMAND;
1486 prevent = common->cmnd[4] & 0x01;
1487 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1488 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1492 if (curlun->prevent_medium_removal && !prevent)
1493 fsg_lun_fsync_sub(curlun);
1494 curlun->prevent_medium_removal = prevent;
1499 static int do_read_format_capacities(struct fsg_common *common,
1500 struct fsg_buffhd *bh)
1502 struct fsg_lun *curlun = common->curlun;
1503 u8 *buf = (u8 *) bh->buf;
1505 buf[0] = buf[1] = buf[2] = 0;
1506 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1509 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1510 /* Number of blocks */
1511 put_unaligned_be32(512, &buf[4]); /* Block length */
1512 buf[4] = 0x02; /* Current capacity */
1517 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1519 struct fsg_lun *curlun = common->curlun;
1521 /* We don't support MODE SELECT */
1523 curlun->sense_data = SS_INVALID_COMMAND;
1528 /*-------------------------------------------------------------------------*/
1530 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1534 rc = fsg_set_halt(fsg, fsg->bulk_in);
1536 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1538 if (rc != -EAGAIN) {
1539 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1544 /* Wait for a short time and then try again */
1545 if (msleep_interruptible(100) != 0)
1547 rc = usb_ep_set_halt(fsg->bulk_in);
1552 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1556 DBG(fsg, "bulk-in set wedge\n");
1557 rc = usb_ep_set_wedge(fsg->bulk_in);
1559 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1561 if (rc != -EAGAIN) {
1562 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1567 /* Wait for a short time and then try again */
1568 if (msleep_interruptible(100) != 0)
1570 rc = usb_ep_set_wedge(fsg->bulk_in);
1575 static int pad_with_zeros(struct fsg_dev *fsg)
1577 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1578 u32 nkeep = bh->inreq->length;
1582 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1583 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1584 while (fsg->common->usb_amount_left > 0) {
1586 /* Wait for the next buffer to be free */
1587 while (bh->state != BUF_STATE_EMPTY) {
1588 rc = sleep_thread(fsg->common);
1593 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1594 memset(bh->buf + nkeep, 0, nsend - nkeep);
1595 bh->inreq->length = nsend;
1596 bh->inreq->zero = 0;
1597 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1598 &bh->inreq_busy, &bh->state);
1599 bh = fsg->common->next_buffhd_to_fill = bh->next;
1600 fsg->common->usb_amount_left -= nsend;
1606 static int throw_away_data(struct fsg_common *common)
1608 struct fsg_buffhd *bh;
1612 for (bh = common->next_buffhd_to_drain;
1613 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1614 bh = common->next_buffhd_to_drain) {
1616 /* Throw away the data in a filled buffer */
1617 if (bh->state == BUF_STATE_FULL) {
1619 bh->state = BUF_STATE_EMPTY;
1620 common->next_buffhd_to_drain = bh->next;
1622 /* A short packet or an error ends everything */
1623 if (bh->outreq->actual != bh->outreq->length ||
1624 bh->outreq->status != 0) {
1625 raise_exception(common,
1626 FSG_STATE_ABORT_BULK_OUT);
1632 /* Try to submit another request if we need one */
1633 bh = common->next_buffhd_to_fill;
1634 if (bh->state == BUF_STATE_EMPTY
1635 && common->usb_amount_left > 0) {
1636 amount = min(common->usb_amount_left, FSG_BUFLEN);
1638 /* amount is always divisible by 512, hence by
1639 * the bulk-out maxpacket size */
1640 bh->outreq->length = amount;
1641 bh->bulk_out_intended_length = amount;
1642 bh->outreq->short_not_ok = 1;
1643 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1644 &bh->outreq_busy, &bh->state)
1645 /* Don't know what to do if
1646 * common->fsg is NULL */
1648 common->next_buffhd_to_fill = bh->next;
1649 common->usb_amount_left -= amount;
1653 /* Otherwise wait for something to happen */
1654 rc = sleep_thread(common);
1662 static int finish_reply(struct fsg_common *common)
1664 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1667 switch (common->data_dir) {
1669 break; /* Nothing to send */
1671 /* If we don't know whether the host wants to read or write,
1672 * this must be CB or CBI with an unknown command. We mustn't
1673 * try to send or receive any data. So stall both bulk pipes
1674 * if we can and wait for a reset. */
1675 case DATA_DIR_UNKNOWN:
1676 if (!common->can_stall) {
1678 } else if (fsg_is_set(common)) {
1679 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1680 rc = halt_bulk_in_endpoint(common->fsg);
1682 /* Don't know what to do if common->fsg is NULL */
1687 /* All but the last buffer of data must have already been sent */
1688 case DATA_DIR_TO_HOST:
1689 if (common->data_size == 0) {
1690 /* Nothing to send */
1692 /* If there's no residue, simply send the last buffer */
1693 } else if (common->residue == 0) {
1694 bh->inreq->zero = 0;
1695 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1696 &bh->inreq_busy, &bh->state)
1698 common->next_buffhd_to_fill = bh->next;
1700 /* For Bulk-only, if we're allowed to stall then send the
1701 * short packet and halt the bulk-in endpoint. If we can't
1702 * stall, pad out the remaining data with 0's. */
1703 } else if (common->can_stall) {
1704 bh->inreq->zero = 1;
1705 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1706 &bh->inreq_busy, &bh->state)
1707 /* Don't know what to do if
1708 * common->fsg is NULL */
1710 common->next_buffhd_to_fill = bh->next;
1712 rc = halt_bulk_in_endpoint(common->fsg);
1713 } else if (fsg_is_set(common)) {
1714 rc = pad_with_zeros(common->fsg);
1716 /* Don't know what to do if common->fsg is NULL */
1721 /* We have processed all we want from the data the host has sent.
1722 * There may still be outstanding bulk-out requests. */
1723 case DATA_DIR_FROM_HOST:
1724 if (common->residue == 0) {
1725 /* Nothing to receive */
1727 /* Did the host stop sending unexpectedly early? */
1728 } else if (common->short_packet_received) {
1729 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1732 /* We haven't processed all the incoming data. Even though
1733 * we may be allowed to stall, doing so would cause a race.
1734 * The controller may already have ACK'ed all the remaining
1735 * bulk-out packets, in which case the host wouldn't see a
1736 * STALL. Not realizing the endpoint was halted, it wouldn't
1737 * clear the halt -- leading to problems later on. */
1739 } else if (common->can_stall) {
1740 if (fsg_is_set(common))
1741 fsg_set_halt(common->fsg,
1742 common->fsg->bulk_out);
1743 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1747 /* We can't stall. Read in the excess data and throw it
1750 rc = throw_away_data(common);
1758 static int send_status(struct fsg_common *common)
1760 struct fsg_lun *curlun = common->curlun;
1761 struct fsg_buffhd *bh;
1762 struct bulk_cs_wrap *csw;
1764 u8 status = USB_STATUS_PASS;
1767 /* Wait for the next buffer to become available */
1768 bh = common->next_buffhd_to_fill;
1769 while (bh->state != BUF_STATE_EMPTY) {
1770 rc = sleep_thread(common);
1776 sd = curlun->sense_data;
1777 sdinfo = curlun->sense_data_info;
1778 } else if (common->bad_lun_okay)
1781 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1783 if (common->phase_error) {
1784 DBG(common, "sending phase-error status\n");
1785 status = USB_STATUS_PHASE_ERROR;
1786 sd = SS_INVALID_COMMAND;
1787 } else if (sd != SS_NO_SENSE) {
1788 DBG(common, "sending command-failure status\n");
1789 status = USB_STATUS_FAIL;
1790 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1792 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1795 /* Store and send the Bulk-only CSW */
1796 csw = (void *)bh->buf;
1798 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1799 csw->Tag = common->tag;
1800 csw->Residue = cpu_to_le32(common->residue);
1801 csw->Status = status;
1803 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1804 bh->inreq->zero = 0;
1805 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1806 &bh->inreq_busy, &bh->state)
1807 /* Don't know what to do if common->fsg is NULL */
1810 common->next_buffhd_to_fill = bh->next;
1815 /*-------------------------------------------------------------------------*/
1817 /* Check whether the command is properly formed and whether its data size
1818 * and direction agree with the values we already have. */
1819 static int check_command(struct fsg_common *common, int cmnd_size,
1820 enum data_direction data_dir, unsigned int mask,
1821 int needs_medium, const char *name)
1824 int lun = common->cmnd[1] >> 5;
1825 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1827 struct fsg_lun *curlun;
1830 if (common->data_dir != DATA_DIR_UNKNOWN)
1831 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1833 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1834 name, cmnd_size, dirletter[(int) data_dir],
1835 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1837 /* We can't reply at all until we know the correct data direction
1839 if (common->data_size_from_cmnd == 0)
1840 data_dir = DATA_DIR_NONE;
1841 if (common->data_size < common->data_size_from_cmnd) {
1842 /* Host data size < Device data size is a phase error.
1843 * Carry out the command, but only transfer as much as
1844 * we are allowed. */
1845 common->data_size_from_cmnd = common->data_size;
1846 common->phase_error = 1;
1848 common->residue = common->data_size;
1849 common->usb_amount_left = common->data_size;
1851 /* Conflicting data directions is a phase error */
1852 if (common->data_dir != data_dir
1853 && common->data_size_from_cmnd > 0) {
1854 common->phase_error = 1;
1858 /* Verify the length of the command itself */
1859 if (cmnd_size != common->cmnd_size) {
1861 /* Special case workaround: There are plenty of buggy SCSI
1862 * implementations. Many have issues with cbw->Length
1863 * field passing a wrong command size. For those cases we
1864 * always try to work around the problem by using the length
1865 * sent by the host side provided it is at least as large
1866 * as the correct command length.
1867 * Examples of such cases would be MS-Windows, which issues
1868 * REQUEST SENSE with cbw->Length == 12 where it should
1869 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1870 * REQUEST SENSE with cbw->Length == 10 where it should
1873 if (cmnd_size <= common->cmnd_size) {
1874 DBG(common, "%s is buggy! Expected length %d "
1875 "but we got %d\n", name,
1876 cmnd_size, common->cmnd_size);
1877 cmnd_size = common->cmnd_size;
1879 common->phase_error = 1;
1884 /* Check that the LUN values are consistent */
1885 if (common->lun != lun)
1886 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1890 if (common->lun >= 0 && common->lun < common->nluns) {
1891 curlun = &common->luns[common->lun];
1892 common->curlun = curlun;
1893 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1894 curlun->sense_data = SS_NO_SENSE;
1895 curlun->sense_data_info = 0;
1896 curlun->info_valid = 0;
1899 common->curlun = NULL;
1901 common->bad_lun_okay = 0;
1903 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1904 * to use unsupported LUNs; all others may not. */
1905 if (common->cmnd[0] != SC_INQUIRY &&
1906 common->cmnd[0] != SC_REQUEST_SENSE) {
1907 DBG(common, "unsupported LUN %d\n", common->lun);
1912 /* If a unit attention condition exists, only INQUIRY and
1913 * REQUEST SENSE commands are allowed; anything else must fail. */
1914 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1915 common->cmnd[0] != SC_INQUIRY &&
1916 common->cmnd[0] != SC_REQUEST_SENSE) {
1917 curlun->sense_data = curlun->unit_attention_data;
1918 curlun->unit_attention_data = SS_NO_SENSE;
1922 /* Check that only command bytes listed in the mask are non-zero */
1923 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1924 for (i = 1; i < cmnd_size; ++i) {
1925 if (common->cmnd[i] && !(mask & (1 << i))) {
1927 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1932 /* If the medium isn't mounted and the command needs to access
1933 * it, return an error. */
1934 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1935 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1943 static int do_scsi_command(struct fsg_common *common)
1945 struct fsg_buffhd *bh;
1947 int reply = -EINVAL;
1949 static char unknown[16];
1953 /* Wait for the next buffer to become available for data or status */
1954 bh = common->next_buffhd_to_fill;
1955 common->next_buffhd_to_drain = bh;
1956 while (bh->state != BUF_STATE_EMPTY) {
1957 rc = sleep_thread(common);
1961 common->phase_error = 0;
1962 common->short_packet_received = 0;
1964 down_read(&common->filesem); /* We're using the backing file */
1965 switch (common->cmnd[0]) {
1968 common->data_size_from_cmnd = common->cmnd[4];
1969 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1973 reply = do_inquiry(common, bh);
1976 case SC_MODE_SELECT_6:
1977 common->data_size_from_cmnd = common->cmnd[4];
1978 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1982 reply = do_mode_select(common, bh);
1985 case SC_MODE_SELECT_10:
1986 common->data_size_from_cmnd =
1987 get_unaligned_be16(&common->cmnd[7]);
1988 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1992 reply = do_mode_select(common, bh);
1995 case SC_MODE_SENSE_6:
1996 common->data_size_from_cmnd = common->cmnd[4];
1997 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1998 (1<<1) | (1<<2) | (1<<4), 0,
2001 reply = do_mode_sense(common, bh);
2004 case SC_MODE_SENSE_10:
2005 common->data_size_from_cmnd =
2006 get_unaligned_be16(&common->cmnd[7]);
2007 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2008 (1<<1) | (1<<2) | (3<<7), 0,
2011 reply = do_mode_sense(common, bh);
2014 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
2015 common->data_size_from_cmnd = 0;
2016 reply = check_command(common, 6, DATA_DIR_NONE,
2018 "PREVENT-ALLOW MEDIUM REMOVAL");
2020 reply = do_prevent_allow(common);
2024 i = common->cmnd[4];
2025 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2026 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2030 reply = do_read(common);
2034 common->data_size_from_cmnd =
2035 get_unaligned_be16(&common->cmnd[7]) << 9;
2036 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2037 (1<<1) | (0xf<<2) | (3<<7), 1,
2040 reply = do_read(common);
2044 common->data_size_from_cmnd =
2045 get_unaligned_be32(&common->cmnd[6]) << 9;
2046 reply = check_command(common, 12, DATA_DIR_TO_HOST,
2047 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2050 reply = do_read(common);
2053 case SC_READ_CAPACITY:
2054 common->data_size_from_cmnd = 8;
2055 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2056 (0xf<<2) | (1<<8), 1,
2059 reply = do_read_capacity(common, bh);
2062 case SC_READ_HEADER:
2063 if (!common->curlun || !common->curlun->cdrom)
2065 common->data_size_from_cmnd =
2066 get_unaligned_be16(&common->cmnd[7]);
2067 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2068 (3<<7) | (0x1f<<1), 1,
2071 reply = do_read_header(common, bh);
2075 if (!common->curlun || !common->curlun->cdrom)
2077 common->data_size_from_cmnd =
2078 get_unaligned_be16(&common->cmnd[7]);
2079 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2083 reply = do_read_toc(common, bh);
2086 case SC_READ_FORMAT_CAPACITIES:
2087 common->data_size_from_cmnd =
2088 get_unaligned_be16(&common->cmnd[7]);
2089 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2091 "READ FORMAT CAPACITIES");
2093 reply = do_read_format_capacities(common, bh);
2096 case SC_REQUEST_SENSE:
2097 common->data_size_from_cmnd = common->cmnd[4];
2098 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2102 reply = do_request_sense(common, bh);
2105 case SC_START_STOP_UNIT:
2106 common->data_size_from_cmnd = 0;
2107 reply = check_command(common, 6, DATA_DIR_NONE,
2111 reply = do_start_stop(common);
2114 case SC_SYNCHRONIZE_CACHE:
2115 common->data_size_from_cmnd = 0;
2116 reply = check_command(common, 10, DATA_DIR_NONE,
2117 (0xf<<2) | (3<<7), 1,
2118 "SYNCHRONIZE CACHE");
2120 reply = do_synchronize_cache(common);
2123 case SC_TEST_UNIT_READY:
2124 common->data_size_from_cmnd = 0;
2125 reply = check_command(common, 6, DATA_DIR_NONE,
2130 /* Although optional, this command is used by MS-Windows. We
2131 * support a minimal version: BytChk must be 0. */
2133 common->data_size_from_cmnd = 0;
2134 reply = check_command(common, 10, DATA_DIR_NONE,
2135 (1<<1) | (0xf<<2) | (3<<7), 1,
2138 reply = do_verify(common);
2142 i = common->cmnd[4];
2143 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2144 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2148 reply = do_write(common);
2152 common->data_size_from_cmnd =
2153 get_unaligned_be16(&common->cmnd[7]) << 9;
2154 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2155 (1<<1) | (0xf<<2) | (3<<7), 1,
2158 reply = do_write(common);
2162 common->data_size_from_cmnd =
2163 get_unaligned_be32(&common->cmnd[6]) << 9;
2164 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2165 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2168 reply = do_write(common);
2171 /* Some mandatory commands that we recognize but don't implement.
2172 * They don't mean much in this setting. It's left as an exercise
2173 * for anyone interested to implement RESERVE and RELEASE in terms
2174 * of Posix locks. */
2175 case SC_FORMAT_UNIT:
2178 case SC_SEND_DIAGNOSTIC:
2183 common->data_size_from_cmnd = 0;
2184 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2185 reply = check_command(common, common->cmnd_size,
2186 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2188 common->curlun->sense_data = SS_INVALID_COMMAND;
2193 up_read(&common->filesem);
2195 if (reply == -EINTR || signal_pending(current))
2198 /* Set up the single reply buffer for finish_reply() */
2199 if (reply == -EINVAL)
2200 reply = 0; /* Error reply length */
2201 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2202 reply = min((u32) reply, common->data_size_from_cmnd);
2203 bh->inreq->length = reply;
2204 bh->state = BUF_STATE_FULL;
2205 common->residue -= reply;
2206 } /* Otherwise it's already set */
2212 /*-------------------------------------------------------------------------*/
2214 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2216 struct usb_request *req = bh->outreq;
2217 struct fsg_bulk_cb_wrap *cbw = req->buf;
2218 struct fsg_common *common = fsg->common;
2220 /* Was this a real packet? Should it be ignored? */
2221 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2224 /* Is the CBW valid? */
2225 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2226 cbw->Signature != cpu_to_le32(
2228 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2230 le32_to_cpu(cbw->Signature));
2232 /* The Bulk-only spec says we MUST stall the IN endpoint
2233 * (6.6.1), so it's unavoidable. It also says we must
2234 * retain this state until the next reset, but there's
2235 * no way to tell the controller driver it should ignore
2236 * Clear-Feature(HALT) requests.
2238 * We aren't required to halt the OUT endpoint; instead
2239 * we can simply accept and discard any data received
2240 * until the next reset. */
2241 wedge_bulk_in_endpoint(fsg);
2242 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2246 /* Is the CBW meaningful? */
2247 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2248 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2249 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2251 cbw->Lun, cbw->Flags, cbw->Length);
2253 /* We can do anything we want here, so let's stall the
2254 * bulk pipes if we are allowed to. */
2255 if (common->can_stall) {
2256 fsg_set_halt(fsg, fsg->bulk_out);
2257 halt_bulk_in_endpoint(fsg);
2262 /* Save the command for later */
2263 common->cmnd_size = cbw->Length;
2264 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2265 if (cbw->Flags & USB_BULK_IN_FLAG)
2266 common->data_dir = DATA_DIR_TO_HOST;
2268 common->data_dir = DATA_DIR_FROM_HOST;
2269 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2270 if (common->data_size == 0)
2271 common->data_dir = DATA_DIR_NONE;
2272 common->lun = cbw->Lun;
2273 common->tag = cbw->Tag;
2278 static int get_next_command(struct fsg_common *common)
2280 struct fsg_buffhd *bh;
2283 /* Wait for the next buffer to become available */
2284 bh = common->next_buffhd_to_fill;
2285 while (bh->state != BUF_STATE_EMPTY) {
2286 rc = sleep_thread(common);
2291 /* Queue a request to read a Bulk-only CBW */
2292 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2293 bh->outreq->short_not_ok = 1;
2294 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2295 &bh->outreq_busy, &bh->state)
2296 /* Don't know what to do if common->fsg is NULL */
2299 /* We will drain the buffer in software, which means we
2300 * can reuse it for the next filling. No need to advance
2301 * next_buffhd_to_fill. */
2303 /* Wait for the CBW to arrive */
2304 while (bh->state != BUF_STATE_FULL) {
2305 rc = sleep_thread(common);
2310 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2311 bh->state = BUF_STATE_EMPTY;
2317 /*-------------------------------------------------------------------------*/
2319 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2320 const struct usb_endpoint_descriptor *d)
2324 ep->driver_data = common;
2325 rc = usb_ep_enable(ep, d);
2327 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2331 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2332 struct usb_request **preq)
2334 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2337 ERROR(common, "can't allocate request for %s\n", ep->name);
2341 /* Reset interface setting and re-init endpoint state (toggle etc). */
2342 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2344 const struct usb_endpoint_descriptor *d;
2345 struct fsg_dev *fsg;
2348 if (common->running)
2349 DBG(common, "reset interface\n");
2352 /* Deallocate the requests */
2356 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2357 struct fsg_buffhd *bh = &common->buffhds[i];
2360 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2364 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2369 /* Disable the endpoints */
2370 if (fsg->bulk_in_enabled) {
2371 usb_ep_disable(fsg->bulk_in);
2372 fsg->bulk_in_enabled = 0;
2374 if (fsg->bulk_out_enabled) {
2375 usb_ep_disable(fsg->bulk_out);
2376 fsg->bulk_out_enabled = 0;
2380 wake_up(&common->fsg_wait);
2383 common->running = 0;
2387 common->fsg = new_fsg;
2390 /* Enable the endpoints */
2391 d = fsg_ep_desc(common->gadget,
2392 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2393 rc = enable_endpoint(common, fsg->bulk_in, d);
2396 fsg->bulk_in_enabled = 1;
2398 d = fsg_ep_desc(common->gadget,
2399 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2400 rc = enable_endpoint(common, fsg->bulk_out, d);
2403 fsg->bulk_out_enabled = 1;
2404 common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2405 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2407 /* Allocate the requests */
2408 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2409 struct fsg_buffhd *bh = &common->buffhds[i];
2411 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2414 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2417 bh->inreq->buf = bh->outreq->buf = bh->buf;
2418 bh->inreq->context = bh->outreq->context = bh;
2419 bh->inreq->complete = bulk_in_complete;
2420 bh->outreq->complete = bulk_out_complete;
2423 common->running = 1;
2424 for (i = 0; i < common->nluns; ++i)
2425 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2430 /****************************** ALT CONFIGS ******************************/
2433 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2435 struct fsg_dev *fsg = fsg_from_func(f);
2436 fsg->common->new_fsg = fsg;
2437 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2441 static void fsg_disable(struct usb_function *f)
2443 struct fsg_dev *fsg = fsg_from_func(f);
2444 fsg->common->new_fsg = NULL;
2445 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2449 /*-------------------------------------------------------------------------*/
2451 static void handle_exception(struct fsg_common *common)
2455 struct fsg_buffhd *bh;
2456 enum fsg_state old_state;
2457 struct fsg_lun *curlun;
2458 unsigned int exception_req_tag;
2460 /* Clear the existing signals. Anything but SIGUSR1 is converted
2461 * into a high-priority EXIT exception. */
2464 dequeue_signal_lock(current, ¤t->blocked, &info);
2467 if (sig != SIGUSR1) {
2468 if (common->state < FSG_STATE_EXIT)
2469 DBG(common, "Main thread exiting on signal\n");
2470 raise_exception(common, FSG_STATE_EXIT);
2474 /* Cancel all the pending transfers */
2475 if (likely(common->fsg)) {
2476 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2477 bh = &common->buffhds[i];
2479 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2480 if (bh->outreq_busy)
2481 usb_ep_dequeue(common->fsg->bulk_out,
2485 /* Wait until everything is idle */
2488 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2489 bh = &common->buffhds[i];
2490 num_active += bh->inreq_busy + bh->outreq_busy;
2492 if (num_active == 0)
2494 if (sleep_thread(common))
2498 /* Clear out the controller's fifos */
2499 if (common->fsg->bulk_in_enabled)
2500 usb_ep_fifo_flush(common->fsg->bulk_in);
2501 if (common->fsg->bulk_out_enabled)
2502 usb_ep_fifo_flush(common->fsg->bulk_out);
2505 /* Reset the I/O buffer states and pointers, the SCSI
2506 * state, and the exception. Then invoke the handler. */
2507 spin_lock_irq(&common->lock);
2509 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2510 bh = &common->buffhds[i];
2511 bh->state = BUF_STATE_EMPTY;
2513 common->next_buffhd_to_fill = &common->buffhds[0];
2514 common->next_buffhd_to_drain = &common->buffhds[0];
2515 exception_req_tag = common->exception_req_tag;
2516 old_state = common->state;
2518 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2519 common->state = FSG_STATE_STATUS_PHASE;
2521 for (i = 0; i < common->nluns; ++i) {
2522 curlun = &common->luns[i];
2523 curlun->prevent_medium_removal = 0;
2524 curlun->sense_data = SS_NO_SENSE;
2525 curlun->unit_attention_data = SS_NO_SENSE;
2526 curlun->sense_data_info = 0;
2527 curlun->info_valid = 0;
2529 common->state = FSG_STATE_IDLE;
2531 spin_unlock_irq(&common->lock);
2533 /* Carry out any extra actions required for the exception */
2534 switch (old_state) {
2535 case FSG_STATE_ABORT_BULK_OUT:
2536 send_status(common);
2537 spin_lock_irq(&common->lock);
2538 if (common->state == FSG_STATE_STATUS_PHASE)
2539 common->state = FSG_STATE_IDLE;
2540 spin_unlock_irq(&common->lock);
2543 case FSG_STATE_RESET:
2544 /* In case we were forced against our will to halt a
2545 * bulk endpoint, clear the halt now. (The SuperH UDC
2546 * requires this.) */
2547 if (!fsg_is_set(common))
2549 if (test_and_clear_bit(IGNORE_BULK_OUT,
2550 &common->fsg->atomic_bitflags))
2551 usb_ep_clear_halt(common->fsg->bulk_in);
2553 if (common->ep0_req_tag == exception_req_tag)
2554 ep0_queue(common); /* Complete the status stage */
2556 /* Technically this should go here, but it would only be
2557 * a waste of time. Ditto for the INTERFACE_CHANGE and
2558 * CONFIG_CHANGE cases. */
2559 /* for (i = 0; i < common->nluns; ++i) */
2560 /* common->luns[i].unit_attention_data = */
2561 /* SS_RESET_OCCURRED; */
2564 case FSG_STATE_CONFIG_CHANGE:
2565 do_set_interface(common, common->new_fsg);
2568 case FSG_STATE_EXIT:
2569 case FSG_STATE_TERMINATED:
2570 do_set_interface(common, NULL); /* Free resources */
2571 spin_lock_irq(&common->lock);
2572 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2573 spin_unlock_irq(&common->lock);
2576 case FSG_STATE_INTERFACE_CHANGE:
2577 case FSG_STATE_DISCONNECT:
2578 case FSG_STATE_COMMAND_PHASE:
2579 case FSG_STATE_DATA_PHASE:
2580 case FSG_STATE_STATUS_PHASE:
2581 case FSG_STATE_IDLE:
2587 /*-------------------------------------------------------------------------*/
2589 static int fsg_main_thread(void *common_)
2591 struct fsg_common *common = common_;
2593 /* Allow the thread to be killed by a signal, but set the signal mask
2594 * to block everything but INT, TERM, KILL, and USR1. */
2595 allow_signal(SIGINT);
2596 allow_signal(SIGTERM);
2597 allow_signal(SIGKILL);
2598 allow_signal(SIGUSR1);
2600 /* Allow the thread to be frozen */
2603 /* Arrange for userspace references to be interpreted as kernel
2604 * pointers. That way we can pass a kernel pointer to a routine
2605 * that expects a __user pointer and it will work okay. */
2609 while (common->state != FSG_STATE_TERMINATED) {
2610 if (exception_in_progress(common) || signal_pending(current)) {
2611 handle_exception(common);
2615 if (!common->running) {
2616 sleep_thread(common);
2620 if (get_next_command(common))
2623 spin_lock_irq(&common->lock);
2624 if (!exception_in_progress(common))
2625 common->state = FSG_STATE_DATA_PHASE;
2626 spin_unlock_irq(&common->lock);
2628 if (do_scsi_command(common) || finish_reply(common))
2631 spin_lock_irq(&common->lock);
2632 if (!exception_in_progress(common))
2633 common->state = FSG_STATE_STATUS_PHASE;
2634 spin_unlock_irq(&common->lock);
2636 if (send_status(common))
2639 spin_lock_irq(&common->lock);
2640 if (!exception_in_progress(common))
2641 common->state = FSG_STATE_IDLE;
2642 spin_unlock_irq(&common->lock);
2645 spin_lock_irq(&common->lock);
2646 common->thread_task = NULL;
2647 spin_unlock_irq(&common->lock);
2649 if (!common->ops || !common->ops->thread_exits
2650 || common->ops->thread_exits(common) < 0) {
2651 struct fsg_lun *curlun = common->luns;
2652 unsigned i = common->nluns;
2654 down_write(&common->filesem);
2655 for (; i--; ++curlun) {
2656 if (!fsg_lun_is_open(curlun))
2659 fsg_lun_close(curlun);
2660 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2662 up_write(&common->filesem);
2665 /* Let the unbind and cleanup routines know the thread has exited */
2666 complete_and_exit(&common->thread_notifier, 0);
2670 /*************************** DEVICE ATTRIBUTES ***************************/
2672 /* Write permission is checked per LUN in store_*() functions. */
2673 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2674 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2677 /****************************** FSG COMMON ******************************/
2679 static void fsg_common_release(struct kref *ref);
2681 static void fsg_lun_release(struct device *dev)
2683 /* Nothing needs to be done */
2686 static inline void fsg_common_get(struct fsg_common *common)
2688 kref_get(&common->ref);
2691 static inline void fsg_common_put(struct fsg_common *common)
2693 kref_put(&common->ref, fsg_common_release);
2697 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2698 struct usb_composite_dev *cdev,
2699 struct fsg_config *cfg)
2701 struct usb_gadget *gadget = cdev->gadget;
2702 struct fsg_buffhd *bh;
2703 struct fsg_lun *curlun;
2704 struct fsg_lun_config *lcfg;
2708 /* Find out how many LUNs there should be */
2710 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2711 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2712 return ERR_PTR(-EINVAL);
2717 common = kzalloc(sizeof *common, GFP_KERNEL);
2719 return ERR_PTR(-ENOMEM);
2720 common->free_storage_on_release = 1;
2722 memset(common, 0, sizeof common);
2723 common->free_storage_on_release = 0;
2726 common->ops = cfg->ops;
2727 common->private_data = cfg->private_data;
2729 common->gadget = gadget;
2730 common->ep0 = gadget->ep0;
2731 common->ep0req = cdev->req;
2733 /* Maybe allocate device-global string IDs, and patch descriptors */
2734 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2735 rc = usb_string_id(cdev);
2736 if (unlikely(rc < 0))
2738 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2739 fsg_intf_desc.iInterface = rc;
2742 /* Create the LUNs, open their backing files, and register the
2743 * LUN devices in sysfs. */
2744 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2745 if (unlikely(!curlun)) {
2749 common->luns = curlun;
2751 init_rwsem(&common->filesem);
2753 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2754 curlun->cdrom = !!lcfg->cdrom;
2755 curlun->ro = lcfg->cdrom || lcfg->ro;
2756 curlun->removable = lcfg->removable;
2757 curlun->dev.release = fsg_lun_release;
2759 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
2760 /* use "usb_mass_storage" platform device as parent */
2761 curlun->dev.parent = &cfg->pdev->dev;
2763 curlun->dev.parent = &gadget->dev;
2765 /* curlun->dev.driver = &fsg_driver.driver; XXX */
2766 dev_set_drvdata(&curlun->dev, &common->filesem);
2767 dev_set_name(&curlun->dev,
2768 cfg->lun_name_format
2769 ? cfg->lun_name_format
2773 rc = device_register(&curlun->dev);
2775 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2780 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2783 rc = device_create_file(&curlun->dev, &dev_attr_file);
2787 if (lcfg->filename) {
2788 rc = fsg_lun_open(curlun, lcfg->filename);
2791 } else if (!curlun->removable) {
2792 ERROR(common, "no file given for LUN%d\n", i);
2797 common->nluns = nluns;
2800 /* Data buffers cyclic list */
2801 bh = common->buffhds;
2802 i = FSG_NUM_BUFFERS;
2803 goto buffhds_first_it;
2808 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2809 if (unlikely(!bh->buf)) {
2814 bh->next = common->buffhds;
2817 /* Prepare inquiryString */
2818 if (cfg->release != 0xffff) {
2821 i = usb_gadget_controller_number(gadget);
2825 WARNING(common, "controller '%s' not recognized\n",
2830 #define OR(x, y) ((x) ? (x) : (y))
2831 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2833 OR(cfg->vendor_name, "Linux "),
2834 /* Assume product name dependent on the first LUN */
2835 OR(cfg->product_name, common->luns->cdrom
2836 ? "File-Stor Gadget"
2837 : "File-CD Gadget "),
2841 /* Some peripheral controllers are known not to be able to
2842 * halt bulk endpoints correctly. If one of them is present,
2845 common->can_stall = cfg->can_stall &&
2846 !(gadget_is_at91(common->gadget));
2849 spin_lock_init(&common->lock);
2850 kref_init(&common->ref);
2853 /* Tell the thread to start working */
2854 common->thread_task =
2855 kthread_create(fsg_main_thread, common,
2856 OR(cfg->thread_name, "file-storage"));
2857 if (IS_ERR(common->thread_task)) {
2858 rc = PTR_ERR(common->thread_task);
2861 init_completion(&common->thread_notifier);
2862 init_waitqueue_head(&common->fsg_wait);
2867 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2868 INFO(common, "Number of LUNs=%d\n", common->nluns);
2870 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2871 for (i = 0, nluns = common->nluns, curlun = common->luns;
2874 char *p = "(no medium)";
2875 if (fsg_lun_is_open(curlun)) {
2878 p = d_path(&curlun->filp->f_path,
2884 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
2885 curlun->removable ? "removable " : "",
2886 curlun->ro ? "read only " : "",
2887 curlun->cdrom ? "CD-ROM " : "",
2892 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
2894 wake_up_process(common->thread_task);
2900 common->nluns = i + 1;
2902 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2903 /* Call fsg_common_release() directly, ref might be not
2905 fsg_common_release(&common->ref);
2910 static void fsg_common_release(struct kref *ref)
2912 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2914 /* If the thread isn't already dead, tell it to exit now */
2915 if (common->state != FSG_STATE_TERMINATED) {
2916 raise_exception(common, FSG_STATE_EXIT);
2917 wait_for_completion(&common->thread_notifier);
2919 /* The cleanup routine waits for this completion also */
2920 complete(&common->thread_notifier);
2923 if (likely(common->luns)) {
2924 struct fsg_lun *lun = common->luns;
2925 unsigned i = common->nluns;
2927 /* In error recovery common->nluns may be zero. */
2928 for (; i; --i, ++lun) {
2929 device_remove_file(&lun->dev, &dev_attr_ro);
2930 device_remove_file(&lun->dev, &dev_attr_file);
2932 device_unregister(&lun->dev);
2935 kfree(common->luns);
2939 struct fsg_buffhd *bh = common->buffhds;
2940 unsigned i = FSG_NUM_BUFFERS;
2943 } while (++bh, --i);
2946 if (common->free_storage_on_release)
2951 /*-------------------------------------------------------------------------*/
2954 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2956 struct fsg_dev *fsg = fsg_from_func(f);
2957 struct fsg_common *common = fsg->common;
2959 DBG(fsg, "unbind\n");
2960 if (fsg->common->fsg == fsg) {
2961 fsg->common->new_fsg = NULL;
2962 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2963 /* FIXME: make interruptible or killable somehow? */
2964 wait_event(common->fsg_wait, common->fsg != fsg);
2967 fsg_common_put(common);
2968 usb_free_descriptors(fsg->function.descriptors);
2969 usb_free_descriptors(fsg->function.hs_descriptors);
2974 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2976 struct fsg_dev *fsg = fsg_from_func(f);
2977 struct usb_gadget *gadget = c->cdev->gadget;
2981 fsg->gadget = gadget;
2984 i = usb_interface_id(c, f);
2987 fsg_intf_desc.bInterfaceNumber = i;
2988 fsg->interface_number = i;
2990 /* Find all the endpoints we will use */
2991 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2994 ep->driver_data = fsg->common; /* claim the endpoint */
2997 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3000 ep->driver_data = fsg->common; /* claim the endpoint */
3003 /* Copy descriptors */
3004 f->descriptors = usb_copy_descriptors(fsg_fs_function);
3005 if (unlikely(!f->descriptors))
3008 if (gadget_is_dualspeed(gadget)) {
3009 /* Assume endpoint addresses are the same for both speeds */
3010 fsg_hs_bulk_in_desc.bEndpointAddress =
3011 fsg_fs_bulk_in_desc.bEndpointAddress;
3012 fsg_hs_bulk_out_desc.bEndpointAddress =
3013 fsg_fs_bulk_out_desc.bEndpointAddress;
3014 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
3015 if (unlikely(!f->hs_descriptors)) {
3016 usb_free_descriptors(f->descriptors);
3024 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3029 /****************************** ADD FUNCTION ******************************/
3031 static struct usb_gadget_strings *fsg_strings_array[] = {
3036 static int fsg_bind_config(struct usb_composite_dev *cdev,
3037 struct usb_configuration *c,
3038 struct fsg_common *common)
3040 struct fsg_dev *fsg;
3043 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3047 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
3048 fsg->function.name = FUNCTION_NAME;
3050 fsg->function.name = FSG_DRIVER_DESC;
3052 fsg->function.strings = fsg_strings_array;
3053 fsg->function.bind = fsg_bind;
3054 fsg->function.unbind = fsg_unbind;
3055 fsg->function.setup = fsg_setup;
3056 fsg->function.set_alt = fsg_set_alt;
3057 fsg->function.disable = fsg_disable;
3059 fsg->common = common;
3060 /* Our caller holds a reference to common structure so we
3061 * don't have to be worry about it being freed until we return
3062 * from this function. So instead of incrementing counter now
3063 * and decrement in error recovery we increment it only when
3064 * call to usb_add_function() was successful. */
3066 rc = usb_add_function(c, &fsg->function);
3070 fsg_common_get(fsg->common);
3074 static inline int __deprecated __maybe_unused
3075 fsg_add(struct usb_composite_dev *cdev,
3076 struct usb_configuration *c,
3077 struct fsg_common *common)
3079 return fsg_bind_config(cdev, c, common);
3083 /************************* Module parameters *************************/
3086 struct fsg_module_parameters {
3087 char *file[FSG_MAX_LUNS];
3088 int ro[FSG_MAX_LUNS];
3089 int removable[FSG_MAX_LUNS];
3090 int cdrom[FSG_MAX_LUNS];
3092 unsigned int file_count, ro_count, removable_count, cdrom_count;
3093 unsigned int luns; /* nluns */
3094 int stall; /* can_stall */
3098 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3099 module_param_array_named(prefix ## name, params.name, type, \
3100 &prefix ## params.name ## _count, \
3102 MODULE_PARM_DESC(prefix ## name, desc)
3104 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3105 module_param_named(prefix ## name, params.name, type, \
3107 MODULE_PARM_DESC(prefix ## name, desc)
3109 #define FSG_MODULE_PARAMETERS(prefix, params) \
3110 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3111 "names of backing files or devices"); \
3112 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3113 "true to force read-only"); \
3114 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3115 "true to simulate removable media"); \
3116 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3117 "true to simulate CD-ROM instead of disk"); \
3118 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3119 "number of LUNs"); \
3120 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3121 "false to prevent bulk stalls")
3125 fsg_config_from_params(struct fsg_config *cfg,
3126 const struct fsg_module_parameters *params)
3128 struct fsg_lun_config *lun;
3131 /* Configure LUNs */
3133 min(params->luns ?: (params->file_count ?: 1u),
3134 (unsigned)FSG_MAX_LUNS);
3135 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3136 lun->ro = !!params->ro[i];
3137 lun->cdrom = !!params->cdrom[i];
3138 lun->removable = /* Removable by default */
3139 params->removable_count <= i || params->removable[i];
3141 params->file_count > i && params->file[i][0]
3146 /* Let MSF use defaults */
3147 cfg->lun_name_format = 0;
3148 cfg->thread_name = 0;
3149 cfg->vendor_name = 0;
3150 cfg->product_name = 0;
3151 cfg->release = 0xffff;
3154 cfg->private_data = NULL;
3157 cfg->can_stall = params->stall;
3160 static inline struct fsg_common *
3161 fsg_common_from_params(struct fsg_common *common,
3162 struct usb_composite_dev *cdev,
3163 const struct fsg_module_parameters *params)
3164 __attribute__((unused));
3165 static inline struct fsg_common *
3166 fsg_common_from_params(struct fsg_common *common,
3167 struct usb_composite_dev *cdev,
3168 const struct fsg_module_parameters *params)
3170 struct fsg_config cfg;
3171 fsg_config_from_params(&cfg, params);
3172 return fsg_common_init(common, cdev, &cfg);
3175 #ifdef CONFIG_USB_ANDROID_MASS_STORAGE
3177 static struct fsg_config fsg_cfg;
3179 static int fsg_probe(struct platform_device *pdev)
3181 struct usb_mass_storage_platform_data *pdata = pdev->dev.platform_data;
3184 printk(KERN_INFO "fsg_probe pdev: %p, pdata: %p\n", pdev, pdata);
3188 nluns = pdata->nluns;
3189 if (nluns > FSG_MAX_LUNS)
3190 nluns = FSG_MAX_LUNS;
3191 fsg_cfg.nluns = nluns;
3192 for (i = 0; i < nluns; i++)
3193 fsg_cfg.luns[i].removable = 1;
3195 fsg_cfg.vendor_name = pdata->vendor;
3196 fsg_cfg.product_name = pdata->product;
3197 fsg_cfg.release = pdata->release;
3198 fsg_cfg.can_stall = 0;
3199 fsg_cfg.pdev = pdev;
3204 static struct platform_driver fsg_platform_driver = {
3205 .driver = { .name = FUNCTION_NAME, },
3209 int mass_storage_bind_config(struct usb_configuration *c)
3211 struct fsg_common *common = fsg_common_init(NULL, c->cdev, &fsg_cfg);
3214 return fsg_add(c->cdev, c, common);
3217 static struct android_usb_function mass_storage_function = {
3218 .name = FUNCTION_NAME,
3219 .bind_config = mass_storage_bind_config,
3222 static int __init init(void)
3225 printk(KERN_INFO "f_mass_storage init\n");
3226 rc = platform_driver_register(&fsg_platform_driver);
3229 android_register_function(&mass_storage_function);
3233 #endif /* CONFIG_USB_ANDROID_MASS_STORAGE */