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.
270 /* #define VERBOSE_DEBUG */
271 /* #define DUMP_MSGS */
277 #include <linux/err.h>
278 #include <linux/usb/ch9.h>
279 #include <linux/usb/gadget.h>
280 #include <usb_mass_storage.h>
282 #include <asm/unaligned.h>
283 #include <linux/usb/gadget.h>
284 #include <linux/usb/gadget.h>
285 #include <linux/usb/composite.h>
286 #include <usb/lin_gadget_compat.h>
288 /*------------------------------------------------------------------------*/
290 #define FSG_DRIVER_DESC "Mass Storage Function"
291 #define FSG_DRIVER_VERSION "2012/06/5"
293 static const char fsg_string_interface[] = "Mass Storage";
296 #define FSG_NO_INTR_EP 1
297 #define FSG_NO_DEVICE_STRINGS 1
299 #define FSG_NO_INTR_EP 1
301 #include "storage_common.c"
303 /*-------------------------------------------------------------------------*/
305 #define GFP_ATOMIC ((gfp_t) 0)
306 #define PAGE_CACHE_SHIFT 12
307 #define PAGE_CACHE_SIZE (1 << PAGE_CACHE_SHIFT)
308 #define kthread_create(...) __builtin_return_address(0)
309 #define wait_for_completion(...) do {} while (0)
311 struct kref {int x; };
312 struct completion {int x; };
314 inline void set_bit(int nr, volatile void *addr)
317 unsigned int *a = (unsigned int *) addr;
320 mask = 1 << (nr & 0x1f);
324 inline void clear_bit(int nr, volatile void *addr)
327 unsigned int *a = (unsigned int *) addr;
330 mask = 1 << (nr & 0x1f);
337 /* Data shared by all the FSG instances. */
339 struct usb_gadget *gadget;
340 struct fsg_dev *fsg, *new_fsg;
342 struct usb_ep *ep0; /* Copy of gadget->ep0 */
343 struct usb_request *ep0req; /* Copy of cdev->req */
344 unsigned int ep0_req_tag;
346 struct fsg_buffhd *next_buffhd_to_fill;
347 struct fsg_buffhd *next_buffhd_to_drain;
348 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
351 u8 cmnd[MAX_COMMAND_SIZE];
355 struct fsg_lun luns[FSG_MAX_LUNS];
357 unsigned int bulk_out_maxpacket;
358 enum fsg_state state; /* For exception handling */
359 unsigned int exception_req_tag;
361 enum data_direction data_dir;
363 u32 data_size_from_cmnd;
368 unsigned int can_stall:1;
369 unsigned int free_storage_on_release:1;
370 unsigned int phase_error:1;
371 unsigned int short_packet_received:1;
372 unsigned int bad_lun_okay:1;
373 unsigned int running:1;
375 int thread_wakeup_needed;
376 struct completion thread_notifier;
377 struct task_struct *thread_task;
379 /* Callback functions. */
380 const struct fsg_operations *ops;
381 /* Gadget's private data. */
384 const char *vendor_name; /* 8 characters or less */
385 const char *product_name; /* 16 characters or less */
388 /* Vendor (8 chars), product (16 chars), release (4
389 * hexadecimal digits) and NUL byte */
390 char inquiry_string[8 + 16 + 4 + 1];
397 struct fsg_lun_config {
398 const char *filename;
403 } luns[FSG_MAX_LUNS];
405 /* Callback functions. */
406 const struct fsg_operations *ops;
407 /* Gadget's private data. */
410 const char *vendor_name; /* 8 characters or less */
411 const char *product_name; /* 16 characters or less */
417 struct usb_function function;
418 struct usb_gadget *gadget; /* Copy of cdev->gadget */
419 struct fsg_common *common;
421 u16 interface_number;
423 unsigned int bulk_in_enabled:1;
424 unsigned int bulk_out_enabled:1;
426 unsigned long atomic_bitflags;
427 #define IGNORE_BULK_OUT 0
429 struct usb_ep *bulk_in;
430 struct usb_ep *bulk_out;
434 static inline int __fsg_is_set(struct fsg_common *common,
435 const char *func, unsigned line)
439 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
444 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
447 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
449 return container_of(f, struct fsg_dev, function);
453 typedef void (*fsg_routine_t)(struct fsg_dev *);
455 static int exception_in_progress(struct fsg_common *common)
457 return common->state > FSG_STATE_IDLE;
460 /* Make bulk-out requests be divisible by the maxpacket size */
461 static void set_bulk_out_req_length(struct fsg_common *common,
462 struct fsg_buffhd *bh, unsigned int length)
466 bh->bulk_out_intended_length = length;
467 rem = length % common->bulk_out_maxpacket;
469 length += common->bulk_out_maxpacket - rem;
470 bh->outreq->length = length;
473 /*-------------------------------------------------------------------------*/
475 struct ums_board_info *ums_info;
476 struct fsg_common *the_fsg_common;
478 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
482 if (ep == fsg->bulk_in)
484 else if (ep == fsg->bulk_out)
488 DBG(fsg, "%s set halt\n", name);
489 return usb_ep_set_halt(ep);
492 /*-------------------------------------------------------------------------*/
494 /* These routines may be called in process context or in_irq */
496 /* Caller must hold fsg->lock */
497 static void wakeup_thread(struct fsg_common *common)
499 common->thread_wakeup_needed = 1;
502 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
504 /* Do nothing if a higher-priority exception is already in progress.
505 * If a lower-or-equal priority exception is in progress, preempt it
506 * and notify the main thread by sending it a signal. */
507 if (common->state <= new_state) {
508 common->exception_req_tag = common->ep0_req_tag;
509 common->state = new_state;
510 common->thread_wakeup_needed = 1;
514 /*-------------------------------------------------------------------------*/
516 static int ep0_queue(struct fsg_common *common)
520 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
521 common->ep0->driver_data = common;
522 if (rc != 0 && rc != -ESHUTDOWN) {
523 /* We can't do much more than wait for a reset */
524 WARNING(common, "error in submission: %s --> %d\n",
525 common->ep0->name, rc);
530 /*-------------------------------------------------------------------------*/
532 /* Bulk and interrupt endpoint completion handlers.
533 * These always run in_irq. */
535 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
537 struct fsg_common *common = ep->driver_data;
538 struct fsg_buffhd *bh = req->context;
540 if (req->status || req->actual != req->length)
541 DBG(common, "%s --> %d, %u/%u\n", __func__,
542 req->status, req->actual, req->length);
543 if (req->status == -ECONNRESET) /* Request was cancelled */
544 usb_ep_fifo_flush(ep);
546 /* Hold the lock while we update the request and buffer states */
548 bh->state = BUF_STATE_EMPTY;
549 wakeup_thread(common);
552 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
554 struct fsg_common *common = ep->driver_data;
555 struct fsg_buffhd *bh = req->context;
557 dump_msg(common, "bulk-out", req->buf, req->actual);
558 if (req->status || req->actual != bh->bulk_out_intended_length)
559 DBG(common, "%s --> %d, %u/%u\n", __func__,
560 req->status, req->actual,
561 bh->bulk_out_intended_length);
562 if (req->status == -ECONNRESET) /* Request was cancelled */
563 usb_ep_fifo_flush(ep);
565 /* Hold the lock while we update the request and buffer states */
567 bh->state = BUF_STATE_FULL;
568 wakeup_thread(common);
571 /*-------------------------------------------------------------------------*/
573 /* Ep0 class-specific handlers. These always run in_irq. */
575 static int fsg_setup(struct usb_function *f,
576 const struct usb_ctrlrequest *ctrl)
578 struct fsg_dev *fsg = fsg_from_func(f);
579 struct usb_request *req = fsg->common->ep0req;
580 u16 w_index = get_unaligned_le16(&ctrl->wIndex);
581 u16 w_value = get_unaligned_le16(&ctrl->wValue);
582 u16 w_length = get_unaligned_le16(&ctrl->wLength);
584 if (!fsg_is_set(fsg->common))
587 switch (ctrl->bRequest) {
589 case USB_BULK_RESET_REQUEST:
590 if (ctrl->bRequestType !=
591 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
593 if (w_index != fsg->interface_number || w_value != 0)
596 /* Raise an exception to stop the current operation
597 * and reinitialize our state. */
598 DBG(fsg, "bulk reset request\n");
599 raise_exception(fsg->common, FSG_STATE_RESET);
600 return DELAYED_STATUS;
602 case USB_BULK_GET_MAX_LUN_REQUEST:
603 if (ctrl->bRequestType !=
604 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
606 if (w_index != fsg->interface_number || w_value != 0)
608 VDBG(fsg, "get max LUN\n");
609 *(u8 *) req->buf = fsg->common->nluns - 1;
611 /* Respond with data/status */
612 req->length = min((u16)1, w_length);
613 return ep0_queue(fsg->common);
617 "unknown class-specific control req "
618 "%02x.%02x v%04x i%04x l%u\n",
619 ctrl->bRequestType, ctrl->bRequest,
620 get_unaligned_le16(&ctrl->wValue), w_index, w_length);
624 /*-------------------------------------------------------------------------*/
626 /* All the following routines run in process context */
628 /* Use this for bulk or interrupt transfers, not ep0 */
629 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
630 struct usb_request *req, int *pbusy,
631 enum fsg_buffer_state *state)
635 if (ep == fsg->bulk_in)
636 dump_msg(fsg, "bulk-in", req->buf, req->length);
639 *state = BUF_STATE_BUSY;
640 rc = usb_ep_queue(ep, req, GFP_KERNEL);
643 *state = BUF_STATE_EMPTY;
645 /* We can't do much more than wait for a reset */
647 /* Note: currently the net2280 driver fails zero-length
648 * submissions if DMA is enabled. */
649 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
651 WARNING(fsg, "error in submission: %s --> %d\n",
656 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
657 if (fsg_is_set(common)) \
658 start_transfer((common)->fsg, (common)->fsg->ep_name, \
659 req, pbusy, state); \
662 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
663 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
665 static void busy_indicator(void)
693 static int sleep_thread(struct fsg_common *common)
698 /* Wait until a signal arrives or we are woken up */
700 if (common->thread_wakeup_needed)
709 usb_gadget_handle_interrupts();
711 common->thread_wakeup_needed = 0;
715 /*-------------------------------------------------------------------------*/
717 static int do_read(struct fsg_common *common)
719 struct fsg_lun *curlun = &common->luns[common->lun];
721 struct fsg_buffhd *bh;
726 unsigned int partial_page;
729 /* Get the starting Logical Block Address and check that it's
731 if (common->cmnd[0] == SC_READ_6)
732 lba = get_unaligned_be24(&common->cmnd[1]);
734 lba = get_unaligned_be32(&common->cmnd[2]);
736 /* We allow DPO (Disable Page Out = don't save data in the
737 * cache) and FUA (Force Unit Access = don't read from the
738 * cache), but we don't implement them. */
739 if ((common->cmnd[1] & ~0x18) != 0) {
740 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
744 if (lba >= curlun->num_sectors) {
745 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
748 file_offset = ((loff_t) lba) << 9;
750 /* Carry out the file reads */
751 amount_left = common->data_size_from_cmnd;
752 if (unlikely(amount_left == 0))
753 return -EIO; /* No default reply */
757 /* Figure out how much we need to read:
758 * Try to read the remaining amount.
759 * But don't read more than the buffer size.
760 * And don't try to read past the end of the file.
761 * Finally, if we're not at a page boundary, don't read past
763 * If this means reading 0 then we were asked to read past
764 * the end of file. */
765 amount = min(amount_left, FSG_BUFLEN);
766 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
767 if (partial_page > 0)
768 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
771 /* Wait for the next buffer to become available */
772 bh = common->next_buffhd_to_fill;
773 while (bh->state != BUF_STATE_EMPTY) {
774 rc = sleep_thread(common);
779 /* If we were asked to read past the end of file,
780 * end with an empty buffer. */
783 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
784 curlun->info_valid = 1;
785 bh->inreq->length = 0;
786 bh->state = BUF_STATE_FULL;
790 /* Perform the read */
792 rc = ums_info->read_sector(&(ums_info->ums_dev),
793 file_offset / SECTOR_SIZE,
794 amount / SECTOR_SIZE,
795 (char __user *)bh->buf);
800 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
801 (unsigned long long) file_offset,
805 LDBG(curlun, "error in file read: %d\n",
808 } else if (nread < amount) {
809 LDBG(curlun, "partial file read: %d/%u\n",
810 (int) nread, amount);
811 nread -= (nread & 511); /* Round down to a block */
813 file_offset += nread;
814 amount_left -= nread;
815 common->residue -= nread;
816 bh->inreq->length = nread;
817 bh->state = BUF_STATE_FULL;
819 /* If an error occurred, report it and its position */
820 if (nread < amount) {
821 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
822 curlun->info_valid = 1;
826 if (amount_left == 0)
827 break; /* No more left to read */
829 /* Send this buffer and go read some more */
831 START_TRANSFER_OR(common, bulk_in, bh->inreq,
832 &bh->inreq_busy, &bh->state)
833 /* Don't know what to do if
834 * common->fsg is NULL */
836 common->next_buffhd_to_fill = bh->next;
839 return -EIO; /* No default reply */
842 /*-------------------------------------------------------------------------*/
844 static int do_write(struct fsg_common *common)
846 struct fsg_lun *curlun = &common->luns[common->lun];
848 struct fsg_buffhd *bh;
850 u32 amount_left_to_req, amount_left_to_write;
851 loff_t usb_offset, file_offset;
853 unsigned int partial_page;
858 curlun->sense_data = SS_WRITE_PROTECTED;
862 /* Get the starting Logical Block Address and check that it's
864 if (common->cmnd[0] == SC_WRITE_6)
865 lba = get_unaligned_be24(&common->cmnd[1]);
867 lba = get_unaligned_be32(&common->cmnd[2]);
869 /* We allow DPO (Disable Page Out = don't save data in the
870 * cache) and FUA (Force Unit Access = write directly to the
871 * medium). We don't implement DPO; we implement FUA by
872 * performing synchronous output. */
873 if (common->cmnd[1] & ~0x18) {
874 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
878 if (lba >= curlun->num_sectors) {
879 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
883 /* Carry out the file writes */
885 file_offset = usb_offset = ((loff_t) lba) << 9;
886 amount_left_to_req = common->data_size_from_cmnd;
887 amount_left_to_write = common->data_size_from_cmnd;
889 while (amount_left_to_write > 0) {
891 /* Queue a request for more data from the host */
892 bh = common->next_buffhd_to_fill;
893 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
895 /* Figure out how much we want to get:
896 * Try to get the remaining amount.
897 * But don't get more than the buffer size.
898 * And don't try to go past the end of the file.
899 * If we're not at a page boundary,
900 * don't go past the next page.
901 * If this means getting 0, then we were asked
902 * to write past the end of file.
903 * Finally, round down to a block boundary. */
904 amount = min(amount_left_to_req, FSG_BUFLEN);
905 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
906 if (partial_page > 0)
908 (unsigned int) PAGE_CACHE_SIZE - partial_page);
913 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
914 curlun->info_valid = 1;
917 amount -= (amount & 511);
920 /* Why were we were asked to transfer a
926 /* Get the next buffer */
927 usb_offset += amount;
928 common->usb_amount_left -= amount;
929 amount_left_to_req -= amount;
930 if (amount_left_to_req == 0)
933 /* amount is always divisible by 512, hence by
934 * the bulk-out maxpacket size */
935 bh->outreq->length = amount;
936 bh->bulk_out_intended_length = amount;
937 bh->outreq->short_not_ok = 1;
938 START_TRANSFER_OR(common, bulk_out, bh->outreq,
939 &bh->outreq_busy, &bh->state)
940 /* Don't know what to do if
941 * common->fsg is NULL */
943 common->next_buffhd_to_fill = bh->next;
947 /* Write the received data to the backing file */
948 bh = common->next_buffhd_to_drain;
949 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
950 break; /* We stopped early */
951 if (bh->state == BUF_STATE_FULL) {
952 common->next_buffhd_to_drain = bh->next;
953 bh->state = BUF_STATE_EMPTY;
955 /* Did something go wrong with the transfer? */
956 if (bh->outreq->status != 0) {
957 curlun->sense_data = SS_COMMUNICATION_FAILURE;
958 curlun->info_valid = 1;
962 amount = bh->outreq->actual;
964 /* Perform the write */
965 rc = ums_info->write_sector(&(ums_info->ums_dev),
966 file_offset / SECTOR_SIZE,
967 amount / SECTOR_SIZE,
968 (char __user *)bh->buf);
973 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
974 (unsigned long long) file_offset,
978 LDBG(curlun, "error in file write: %d\n",
981 } else if (nwritten < amount) {
982 LDBG(curlun, "partial file write: %d/%u\n",
983 (int) nwritten, amount);
984 nwritten -= (nwritten & 511);
985 /* Round down to a block */
987 file_offset += nwritten;
988 amount_left_to_write -= nwritten;
989 common->residue -= nwritten;
991 /* If an error occurred, report it and its position */
992 if (nwritten < amount) {
993 curlun->sense_data = SS_WRITE_ERROR;
994 curlun->info_valid = 1;
998 /* Did the host decide to stop early? */
999 if (bh->outreq->actual != bh->outreq->length) {
1000 common->short_packet_received = 1;
1006 /* Wait for something to happen */
1007 rc = sleep_thread(common);
1012 return -EIO; /* No default reply */
1015 /*-------------------------------------------------------------------------*/
1017 static int do_synchronize_cache(struct fsg_common *common)
1022 /*-------------------------------------------------------------------------*/
1024 static int do_verify(struct fsg_common *common)
1026 struct fsg_lun *curlun = &common->luns[common->lun];
1028 u32 verification_length;
1029 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1032 unsigned int amount;
1036 /* Get the starting Logical Block Address and check that it's
1038 lba = get_unaligned_be32(&common->cmnd[2]);
1039 if (lba >= curlun->num_sectors) {
1040 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1044 /* We allow DPO (Disable Page Out = don't save data in the
1045 * cache) but we don't implement it. */
1046 if (common->cmnd[1] & ~0x10) {
1047 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1051 verification_length = get_unaligned_be16(&common->cmnd[7]);
1052 if (unlikely(verification_length == 0))
1053 return -EIO; /* No default reply */
1055 /* Prepare to carry out the file verify */
1056 amount_left = verification_length << 9;
1057 file_offset = ((loff_t) lba) << 9;
1059 /* Write out all the dirty buffers before invalidating them */
1061 /* Just try to read the requested blocks */
1062 while (amount_left > 0) {
1064 /* Figure out how much we need to read:
1065 * Try to read the remaining amount, but not more than
1067 * And don't try to read past the end of the file.
1068 * If this means reading 0 then we were asked to read
1069 * past the end of file. */
1070 amount = min(amount_left, FSG_BUFLEN);
1072 curlun->sense_data =
1073 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1074 curlun->info_valid = 1;
1078 /* Perform the read */
1080 rc = ums_info->read_sector(&(ums_info->ums_dev),
1081 file_offset / SECTOR_SIZE,
1082 amount / SECTOR_SIZE,
1083 (char __user *)bh->buf);
1088 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1089 (unsigned long long) file_offset,
1092 LDBG(curlun, "error in file verify: %d\n",
1095 } else if (nread < amount) {
1096 LDBG(curlun, "partial file verify: %d/%u\n",
1097 (int) nread, amount);
1098 nread -= (nread & 511); /* Round down to a sector */
1101 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1102 curlun->info_valid = 1;
1105 file_offset += nread;
1106 amount_left -= nread;
1111 /*-------------------------------------------------------------------------*/
1113 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1115 struct fsg_lun *curlun = &common->luns[common->lun];
1116 static const char vendor_id[] = "Linux ";
1117 u8 *buf = (u8 *) bh->buf;
1119 if (!curlun) { /* Unsupported LUNs are okay */
1120 common->bad_lun_okay = 1;
1122 buf[0] = 0x7f; /* Unsupported, no device-type */
1123 buf[4] = 31; /* Additional length */
1129 buf[2] = 2; /* ANSI SCSI level 2 */
1130 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1131 buf[4] = 31; /* Additional length */
1132 /* No special options */
1133 sprintf((char *) (buf + 8), "%-8s%-16s%04x", (char*) vendor_id ,
1134 ums_info->name, (u16) 0xffff);
1140 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1142 struct fsg_lun *curlun = &common->luns[common->lun];
1143 u8 *buf = (u8 *) bh->buf;
1148 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1150 * If a REQUEST SENSE command is received from an initiator
1151 * with a pending unit attention condition (before the target
1152 * generates the contingent allegiance condition), then the
1153 * target shall either:
1154 * a) report any pending sense data and preserve the unit
1155 * attention condition on the logical unit, or,
1156 * b) report the unit attention condition, may discard any
1157 * pending sense data, and clear the unit attention
1158 * condition on the logical unit for that initiator.
1160 * FSG normally uses option a); enable this code to use option b).
1163 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1164 curlun->sense_data = curlun->unit_attention_data;
1165 curlun->unit_attention_data = SS_NO_SENSE;
1169 if (!curlun) { /* Unsupported LUNs are okay */
1170 common->bad_lun_okay = 1;
1171 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1175 sd = curlun->sense_data;
1176 valid = curlun->info_valid << 7;
1177 curlun->sense_data = SS_NO_SENSE;
1178 curlun->info_valid = 0;
1182 buf[0] = valid | 0x70; /* Valid, current error */
1184 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1185 buf[7] = 18 - 8; /* Additional sense length */
1191 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1193 struct fsg_lun *curlun = &common->luns[common->lun];
1194 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1195 int pmi = common->cmnd[8];
1196 u8 *buf = (u8 *) bh->buf;
1198 /* Check the PMI and LBA fields */
1199 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1200 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1204 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1205 /* Max logical block */
1206 put_unaligned_be32(512, &buf[4]); /* Block length */
1210 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1212 struct fsg_lun *curlun = &common->luns[common->lun];
1213 int msf = common->cmnd[1] & 0x02;
1214 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1215 u8 *buf = (u8 *) bh->buf;
1217 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1218 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1221 if (lba >= curlun->num_sectors) {
1222 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1227 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1228 store_cdrom_address(&buf[4], msf, lba);
1233 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1235 struct fsg_lun *curlun = &common->luns[common->lun];
1236 int msf = common->cmnd[1] & 0x02;
1237 int start_track = common->cmnd[6];
1238 u8 *buf = (u8 *) bh->buf;
1240 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1242 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1247 buf[1] = (20-2); /* TOC data length */
1248 buf[2] = 1; /* First track number */
1249 buf[3] = 1; /* Last track number */
1250 buf[5] = 0x16; /* Data track, copying allowed */
1251 buf[6] = 0x01; /* Only track is number 1 */
1252 store_cdrom_address(&buf[8], msf, 0);
1254 buf[13] = 0x16; /* Lead-out track is data */
1255 buf[14] = 0xAA; /* Lead-out track number */
1256 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1261 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1263 struct fsg_lun *curlun = &common->luns[common->lun];
1264 int mscmnd = common->cmnd[0];
1265 u8 *buf = (u8 *) bh->buf;
1268 int changeable_values, all_pages;
1272 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1273 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1276 pc = common->cmnd[2] >> 6;
1277 page_code = common->cmnd[2] & 0x3f;
1279 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1282 changeable_values = (pc == 1);
1283 all_pages = (page_code == 0x3f);
1285 /* Write the mode parameter header. Fixed values are: default
1286 * medium type, no cache control (DPOFUA), and no block descriptors.
1287 * The only variable value is the WriteProtect bit. We will fill in
1288 * the mode data length later. */
1290 if (mscmnd == SC_MODE_SENSE_6) {
1291 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1294 } else { /* SC_MODE_SENSE_10 */
1295 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1297 limit = 65535; /* Should really be FSG_BUFLEN */
1300 /* No block descriptors */
1302 /* The mode pages, in numerical order. The only page we support
1303 * is the Caching page. */
1304 if (page_code == 0x08 || all_pages) {
1306 buf[0] = 0x08; /* Page code */
1307 buf[1] = 10; /* Page length */
1308 memset(buf+2, 0, 10); /* None of the fields are changeable */
1310 if (!changeable_values) {
1311 buf[2] = 0x04; /* Write cache enable, */
1312 /* Read cache not disabled */
1313 /* No cache retention priorities */
1314 put_unaligned_be16(0xffff, &buf[4]);
1315 /* Don't disable prefetch */
1316 /* Minimum prefetch = 0 */
1317 put_unaligned_be16(0xffff, &buf[8]);
1318 /* Maximum prefetch */
1319 put_unaligned_be16(0xffff, &buf[10]);
1320 /* Maximum prefetch ceiling */
1325 /* Check that a valid page was requested and the mode data length
1326 * isn't too long. */
1328 if (!valid_page || len > limit) {
1329 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1333 /* Store the mode data length */
1334 if (mscmnd == SC_MODE_SENSE_6)
1337 put_unaligned_be16(len - 2, buf0);
1342 static int do_start_stop(struct fsg_common *common)
1344 struct fsg_lun *curlun = &common->luns[common->lun];
1348 } else if (!curlun->removable) {
1349 curlun->sense_data = SS_INVALID_COMMAND;
1356 static int do_prevent_allow(struct fsg_common *common)
1358 struct fsg_lun *curlun = &common->luns[common->lun];
1361 if (!curlun->removable) {
1362 curlun->sense_data = SS_INVALID_COMMAND;
1366 prevent = common->cmnd[4] & 0x01;
1367 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1368 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1372 if (curlun->prevent_medium_removal && !prevent)
1373 fsg_lun_fsync_sub(curlun);
1374 curlun->prevent_medium_removal = prevent;
1379 static int do_read_format_capacities(struct fsg_common *common,
1380 struct fsg_buffhd *bh)
1382 struct fsg_lun *curlun = &common->luns[common->lun];
1383 u8 *buf = (u8 *) bh->buf;
1385 buf[0] = buf[1] = buf[2] = 0;
1386 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1389 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1390 /* Number of blocks */
1391 put_unaligned_be32(512, &buf[4]); /* Block length */
1392 buf[4] = 0x02; /* Current capacity */
1397 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1399 struct fsg_lun *curlun = &common->luns[common->lun];
1401 /* We don't support MODE SELECT */
1403 curlun->sense_data = SS_INVALID_COMMAND;
1408 /*-------------------------------------------------------------------------*/
1410 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1414 rc = fsg_set_halt(fsg, fsg->bulk_in);
1416 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1418 if (rc != -EAGAIN) {
1419 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1424 rc = usb_ep_set_halt(fsg->bulk_in);
1429 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1433 DBG(fsg, "bulk-in set wedge\n");
1434 rc = 0; /* usb_ep_set_wedge(fsg->bulk_in); */
1436 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1438 if (rc != -EAGAIN) {
1439 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1447 static int pad_with_zeros(struct fsg_dev *fsg)
1449 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1450 u32 nkeep = bh->inreq->length;
1454 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1455 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1456 while (fsg->common->usb_amount_left > 0) {
1458 /* Wait for the next buffer to be free */
1459 while (bh->state != BUF_STATE_EMPTY) {
1460 rc = sleep_thread(fsg->common);
1465 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1466 memset(bh->buf + nkeep, 0, nsend - nkeep);
1467 bh->inreq->length = nsend;
1468 bh->inreq->zero = 0;
1469 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1470 &bh->inreq_busy, &bh->state);
1471 bh = fsg->common->next_buffhd_to_fill = bh->next;
1472 fsg->common->usb_amount_left -= nsend;
1478 static int throw_away_data(struct fsg_common *common)
1480 struct fsg_buffhd *bh;
1484 for (bh = common->next_buffhd_to_drain;
1485 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1486 bh = common->next_buffhd_to_drain) {
1488 /* Throw away the data in a filled buffer */
1489 if (bh->state == BUF_STATE_FULL) {
1490 bh->state = BUF_STATE_EMPTY;
1491 common->next_buffhd_to_drain = bh->next;
1493 /* A short packet or an error ends everything */
1494 if (bh->outreq->actual != bh->outreq->length ||
1495 bh->outreq->status != 0) {
1496 raise_exception(common,
1497 FSG_STATE_ABORT_BULK_OUT);
1503 /* Try to submit another request if we need one */
1504 bh = common->next_buffhd_to_fill;
1505 if (bh->state == BUF_STATE_EMPTY
1506 && common->usb_amount_left > 0) {
1507 amount = min(common->usb_amount_left, FSG_BUFLEN);
1509 /* amount is always divisible by 512, hence by
1510 * the bulk-out maxpacket size */
1511 bh->outreq->length = amount;
1512 bh->bulk_out_intended_length = amount;
1513 bh->outreq->short_not_ok = 1;
1514 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1515 &bh->outreq_busy, &bh->state)
1516 /* Don't know what to do if
1517 * common->fsg is NULL */
1519 common->next_buffhd_to_fill = bh->next;
1520 common->usb_amount_left -= amount;
1524 /* Otherwise wait for something to happen */
1525 rc = sleep_thread(common);
1533 static int finish_reply(struct fsg_common *common)
1535 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1538 switch (common->data_dir) {
1540 break; /* Nothing to send */
1542 /* If we don't know whether the host wants to read or write,
1543 * this must be CB or CBI with an unknown command. We mustn't
1544 * try to send or receive any data. So stall both bulk pipes
1545 * if we can and wait for a reset. */
1546 case DATA_DIR_UNKNOWN:
1547 if (!common->can_stall) {
1549 } else if (fsg_is_set(common)) {
1550 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1551 rc = halt_bulk_in_endpoint(common->fsg);
1553 /* Don't know what to do if common->fsg is NULL */
1558 /* All but the last buffer of data must have already been sent */
1559 case DATA_DIR_TO_HOST:
1560 if (common->data_size == 0) {
1561 /* Nothing to send */
1563 /* If there's no residue, simply send the last buffer */
1564 } else if (common->residue == 0) {
1565 bh->inreq->zero = 0;
1566 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1567 &bh->inreq_busy, &bh->state)
1569 common->next_buffhd_to_fill = bh->next;
1571 /* For Bulk-only, if we're allowed to stall then send the
1572 * short packet and halt the bulk-in endpoint. If we can't
1573 * stall, pad out the remaining data with 0's. */
1574 } else if (common->can_stall) {
1575 bh->inreq->zero = 1;
1576 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1577 &bh->inreq_busy, &bh->state)
1578 /* Don't know what to do if
1579 * common->fsg is NULL */
1581 common->next_buffhd_to_fill = bh->next;
1583 rc = halt_bulk_in_endpoint(common->fsg);
1584 } else if (fsg_is_set(common)) {
1585 rc = pad_with_zeros(common->fsg);
1587 /* Don't know what to do if common->fsg is NULL */
1592 /* We have processed all we want from the data the host has sent.
1593 * There may still be outstanding bulk-out requests. */
1594 case DATA_DIR_FROM_HOST:
1595 if (common->residue == 0) {
1596 /* Nothing to receive */
1598 /* Did the host stop sending unexpectedly early? */
1599 } else if (common->short_packet_received) {
1600 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1603 /* We haven't processed all the incoming data. Even though
1604 * we may be allowed to stall, doing so would cause a race.
1605 * The controller may already have ACK'ed all the remaining
1606 * bulk-out packets, in which case the host wouldn't see a
1607 * STALL. Not realizing the endpoint was halted, it wouldn't
1608 * clear the halt -- leading to problems later on. */
1610 } else if (common->can_stall) {
1611 if (fsg_is_set(common))
1612 fsg_set_halt(common->fsg,
1613 common->fsg->bulk_out);
1614 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1618 /* We can't stall. Read in the excess data and throw it
1621 rc = throw_away_data(common);
1629 static int send_status(struct fsg_common *common)
1631 struct fsg_lun *curlun = &common->luns[common->lun];
1632 struct fsg_buffhd *bh;
1633 struct bulk_cs_wrap *csw;
1635 u8 status = USB_STATUS_PASS;
1638 /* Wait for the next buffer to become available */
1639 bh = common->next_buffhd_to_fill;
1640 while (bh->state != BUF_STATE_EMPTY) {
1641 rc = sleep_thread(common);
1647 sd = curlun->sense_data;
1648 else if (common->bad_lun_okay)
1651 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1653 if (common->phase_error) {
1654 DBG(common, "sending phase-error status\n");
1655 status = USB_STATUS_PHASE_ERROR;
1656 sd = SS_INVALID_COMMAND;
1657 } else if (sd != SS_NO_SENSE) {
1658 DBG(common, "sending command-failure status\n");
1659 status = USB_STATUS_FAIL;
1660 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1662 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1665 /* Store and send the Bulk-only CSW */
1666 csw = (void *)bh->buf;
1668 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1669 csw->Tag = common->tag;
1670 csw->Residue = cpu_to_le32(common->residue);
1671 csw->Status = status;
1673 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1674 bh->inreq->zero = 0;
1675 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1676 &bh->inreq_busy, &bh->state)
1677 /* Don't know what to do if common->fsg is NULL */
1680 common->next_buffhd_to_fill = bh->next;
1685 /*-------------------------------------------------------------------------*/
1687 /* Check whether the command is properly formed and whether its data size
1688 * and direction agree with the values we already have. */
1689 static int check_command(struct fsg_common *common, int cmnd_size,
1690 enum data_direction data_dir, unsigned int mask,
1691 int needs_medium, const char *name)
1694 int lun = common->cmnd[1] >> 5;
1695 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1697 struct fsg_lun *curlun;
1700 if (common->data_dir != DATA_DIR_UNKNOWN)
1701 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1703 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1704 name, cmnd_size, dirletter[(int) data_dir],
1705 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1707 /* We can't reply at all until we know the correct data direction
1709 if (common->data_size_from_cmnd == 0)
1710 data_dir = DATA_DIR_NONE;
1711 if (common->data_size < common->data_size_from_cmnd) {
1712 /* Host data size < Device data size is a phase error.
1713 * Carry out the command, but only transfer as much as
1714 * we are allowed. */
1715 common->data_size_from_cmnd = common->data_size;
1716 common->phase_error = 1;
1718 common->residue = common->data_size;
1719 common->usb_amount_left = common->data_size;
1721 /* Conflicting data directions is a phase error */
1722 if (common->data_dir != data_dir
1723 && common->data_size_from_cmnd > 0) {
1724 common->phase_error = 1;
1728 /* Verify the length of the command itself */
1729 if (cmnd_size != common->cmnd_size) {
1731 /* Special case workaround: There are plenty of buggy SCSI
1732 * implementations. Many have issues with cbw->Length
1733 * field passing a wrong command size. For those cases we
1734 * always try to work around the problem by using the length
1735 * sent by the host side provided it is at least as large
1736 * as the correct command length.
1737 * Examples of such cases would be MS-Windows, which issues
1738 * REQUEST SENSE with cbw->Length == 12 where it should
1739 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1740 * REQUEST SENSE with cbw->Length == 10 where it should
1743 if (cmnd_size <= common->cmnd_size) {
1744 DBG(common, "%s is buggy! Expected length %d "
1745 "but we got %d\n", name,
1746 cmnd_size, common->cmnd_size);
1747 cmnd_size = common->cmnd_size;
1749 common->phase_error = 1;
1754 /* Check that the LUN values are consistent */
1755 if (common->lun != lun)
1756 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1760 if (common->lun >= 0 && common->lun < common->nluns) {
1761 curlun = &common->luns[common->lun];
1762 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1763 curlun->sense_data = SS_NO_SENSE;
1764 curlun->info_valid = 0;
1768 common->bad_lun_okay = 0;
1770 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1771 * to use unsupported LUNs; all others may not. */
1772 if (common->cmnd[0] != SC_INQUIRY &&
1773 common->cmnd[0] != SC_REQUEST_SENSE) {
1774 DBG(common, "unsupported LUN %d\n", common->lun);
1779 /* If a unit attention condition exists, only INQUIRY and
1780 * REQUEST SENSE commands are allowed; anything else must fail. */
1781 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1782 common->cmnd[0] != SC_INQUIRY &&
1783 common->cmnd[0] != SC_REQUEST_SENSE) {
1784 curlun->sense_data = curlun->unit_attention_data;
1785 curlun->unit_attention_data = SS_NO_SENSE;
1789 /* Check that only command bytes listed in the mask are non-zero */
1790 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1791 for (i = 1; i < cmnd_size; ++i) {
1792 if (common->cmnd[i] && !(mask & (1 << i))) {
1794 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1803 static int do_scsi_command(struct fsg_common *common)
1805 struct fsg_buffhd *bh;
1807 int reply = -EINVAL;
1809 static char unknown[16];
1810 struct fsg_lun *curlun = &common->luns[common->lun];
1814 /* Wait for the next buffer to become available for data or status */
1815 bh = common->next_buffhd_to_fill;
1816 common->next_buffhd_to_drain = bh;
1817 while (bh->state != BUF_STATE_EMPTY) {
1818 rc = sleep_thread(common);
1822 common->phase_error = 0;
1823 common->short_packet_received = 0;
1825 down_read(&common->filesem); /* We're using the backing file */
1826 switch (common->cmnd[0]) {
1829 common->data_size_from_cmnd = common->cmnd[4];
1830 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1834 reply = do_inquiry(common, bh);
1837 case SC_MODE_SELECT_6:
1838 common->data_size_from_cmnd = common->cmnd[4];
1839 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1843 reply = do_mode_select(common, bh);
1846 case SC_MODE_SELECT_10:
1847 common->data_size_from_cmnd =
1848 get_unaligned_be16(&common->cmnd[7]);
1849 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1853 reply = do_mode_select(common, bh);
1856 case SC_MODE_SENSE_6:
1857 common->data_size_from_cmnd = common->cmnd[4];
1858 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1859 (1<<1) | (1<<2) | (1<<4), 0,
1862 reply = do_mode_sense(common, bh);
1865 case SC_MODE_SENSE_10:
1866 common->data_size_from_cmnd =
1867 get_unaligned_be16(&common->cmnd[7]);
1868 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1869 (1<<1) | (1<<2) | (3<<7), 0,
1872 reply = do_mode_sense(common, bh);
1875 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1876 common->data_size_from_cmnd = 0;
1877 reply = check_command(common, 6, DATA_DIR_NONE,
1879 "PREVENT-ALLOW MEDIUM REMOVAL");
1881 reply = do_prevent_allow(common);
1885 i = common->cmnd[4];
1886 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1887 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1891 reply = do_read(common);
1895 common->data_size_from_cmnd =
1896 get_unaligned_be16(&common->cmnd[7]) << 9;
1897 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1898 (1<<1) | (0xf<<2) | (3<<7), 1,
1901 reply = do_read(common);
1905 common->data_size_from_cmnd =
1906 get_unaligned_be32(&common->cmnd[6]) << 9;
1907 reply = check_command(common, 12, DATA_DIR_TO_HOST,
1908 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1911 reply = do_read(common);
1914 case SC_READ_CAPACITY:
1915 common->data_size_from_cmnd = 8;
1916 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1917 (0xf<<2) | (1<<8), 1,
1920 reply = do_read_capacity(common, bh);
1923 case SC_READ_HEADER:
1924 if (!common->luns[common->lun].cdrom)
1926 common->data_size_from_cmnd =
1927 get_unaligned_be16(&common->cmnd[7]);
1928 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1929 (3<<7) | (0x1f<<1), 1,
1932 reply = do_read_header(common, bh);
1936 if (!common->luns[common->lun].cdrom)
1938 common->data_size_from_cmnd =
1939 get_unaligned_be16(&common->cmnd[7]);
1940 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1944 reply = do_read_toc(common, bh);
1947 case SC_READ_FORMAT_CAPACITIES:
1948 common->data_size_from_cmnd =
1949 get_unaligned_be16(&common->cmnd[7]);
1950 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1952 "READ FORMAT CAPACITIES");
1954 reply = do_read_format_capacities(common, bh);
1957 case SC_REQUEST_SENSE:
1958 common->data_size_from_cmnd = common->cmnd[4];
1959 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1963 reply = do_request_sense(common, bh);
1966 case SC_START_STOP_UNIT:
1967 common->data_size_from_cmnd = 0;
1968 reply = check_command(common, 6, DATA_DIR_NONE,
1972 reply = do_start_stop(common);
1975 case SC_SYNCHRONIZE_CACHE:
1976 common->data_size_from_cmnd = 0;
1977 reply = check_command(common, 10, DATA_DIR_NONE,
1978 (0xf<<2) | (3<<7), 1,
1979 "SYNCHRONIZE CACHE");
1981 reply = do_synchronize_cache(common);
1984 case SC_TEST_UNIT_READY:
1985 common->data_size_from_cmnd = 0;
1986 reply = check_command(common, 6, DATA_DIR_NONE,
1991 /* Although optional, this command is used by MS-Windows. We
1992 * support a minimal version: BytChk must be 0. */
1994 common->data_size_from_cmnd = 0;
1995 reply = check_command(common, 10, DATA_DIR_NONE,
1996 (1<<1) | (0xf<<2) | (3<<7), 1,
1999 reply = do_verify(common);
2003 i = common->cmnd[4];
2004 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2005 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2009 reply = do_write(common);
2013 common->data_size_from_cmnd =
2014 get_unaligned_be16(&common->cmnd[7]) << 9;
2015 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2016 (1<<1) | (0xf<<2) | (3<<7), 1,
2019 reply = do_write(common);
2023 common->data_size_from_cmnd =
2024 get_unaligned_be32(&common->cmnd[6]) << 9;
2025 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2026 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2029 reply = do_write(common);
2032 /* Some mandatory commands that we recognize but don't implement.
2033 * They don't mean much in this setting. It's left as an exercise
2034 * for anyone interested to implement RESERVE and RELEASE in terms
2035 * of Posix locks. */
2036 case SC_FORMAT_UNIT:
2039 case SC_SEND_DIAGNOSTIC:
2044 common->data_size_from_cmnd = 0;
2045 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2046 reply = check_command(common, common->cmnd_size,
2047 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2049 curlun->sense_data = SS_INVALID_COMMAND;
2054 up_read(&common->filesem);
2056 if (reply == -EINTR)
2059 /* Set up the single reply buffer for finish_reply() */
2060 if (reply == -EINVAL)
2061 reply = 0; /* Error reply length */
2062 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2063 reply = min((u32) reply, common->data_size_from_cmnd);
2064 bh->inreq->length = reply;
2065 bh->state = BUF_STATE_FULL;
2066 common->residue -= reply;
2067 } /* Otherwise it's already set */
2072 /*-------------------------------------------------------------------------*/
2074 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2076 struct usb_request *req = bh->outreq;
2077 struct fsg_bulk_cb_wrap *cbw = req->buf;
2078 struct fsg_common *common = fsg->common;
2080 /* Was this a real packet? Should it be ignored? */
2081 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2084 /* Is the CBW valid? */
2085 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2086 cbw->Signature != cpu_to_le32(
2088 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2090 le32_to_cpu(cbw->Signature));
2092 /* The Bulk-only spec says we MUST stall the IN endpoint
2093 * (6.6.1), so it's unavoidable. It also says we must
2094 * retain this state until the next reset, but there's
2095 * no way to tell the controller driver it should ignore
2096 * Clear-Feature(HALT) requests.
2098 * We aren't required to halt the OUT endpoint; instead
2099 * we can simply accept and discard any data received
2100 * until the next reset. */
2101 wedge_bulk_in_endpoint(fsg);
2102 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2106 /* Is the CBW meaningful? */
2107 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2108 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2109 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2111 cbw->Lun, cbw->Flags, cbw->Length);
2113 /* We can do anything we want here, so let's stall the
2114 * bulk pipes if we are allowed to. */
2115 if (common->can_stall) {
2116 fsg_set_halt(fsg, fsg->bulk_out);
2117 halt_bulk_in_endpoint(fsg);
2122 /* Save the command for later */
2123 common->cmnd_size = cbw->Length;
2124 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2125 if (cbw->Flags & USB_BULK_IN_FLAG)
2126 common->data_dir = DATA_DIR_TO_HOST;
2128 common->data_dir = DATA_DIR_FROM_HOST;
2129 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2130 if (common->data_size == 0)
2131 common->data_dir = DATA_DIR_NONE;
2132 common->lun = cbw->Lun;
2133 common->tag = cbw->Tag;
2138 static int get_next_command(struct fsg_common *common)
2140 struct fsg_buffhd *bh;
2143 /* Wait for the next buffer to become available */
2144 bh = common->next_buffhd_to_fill;
2145 while (bh->state != BUF_STATE_EMPTY) {
2146 rc = sleep_thread(common);
2151 /* Queue a request to read a Bulk-only CBW */
2152 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2153 bh->outreq->short_not_ok = 1;
2154 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2155 &bh->outreq_busy, &bh->state)
2156 /* Don't know what to do if common->fsg is NULL */
2159 /* We will drain the buffer in software, which means we
2160 * can reuse it for the next filling. No need to advance
2161 * next_buffhd_to_fill. */
2163 /* Wait for the CBW to arrive */
2164 while (bh->state != BUF_STATE_FULL) {
2165 rc = sleep_thread(common);
2170 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2171 bh->state = BUF_STATE_EMPTY;
2177 /*-------------------------------------------------------------------------*/
2179 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2180 const struct usb_endpoint_descriptor *d)
2184 ep->driver_data = common;
2185 rc = usb_ep_enable(ep, d);
2187 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2191 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2192 struct usb_request **preq)
2194 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2197 ERROR(common, "can't allocate request for %s\n", ep->name);
2201 /* Reset interface setting and re-init endpoint state (toggle etc). */
2202 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2204 const struct usb_endpoint_descriptor *d;
2205 struct fsg_dev *fsg;
2208 if (common->running)
2209 DBG(common, "reset interface\n");
2212 /* Deallocate the requests */
2216 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2217 struct fsg_buffhd *bh = &common->buffhds[i];
2220 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2224 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2229 /* Disable the endpoints */
2230 if (fsg->bulk_in_enabled) {
2231 usb_ep_disable(fsg->bulk_in);
2232 fsg->bulk_in_enabled = 0;
2234 if (fsg->bulk_out_enabled) {
2235 usb_ep_disable(fsg->bulk_out);
2236 fsg->bulk_out_enabled = 0;
2240 /* wake_up(&common->fsg_wait); */
2243 common->running = 0;
2247 common->fsg = new_fsg;
2250 /* Enable the endpoints */
2251 d = fsg_ep_desc(common->gadget,
2252 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2253 rc = enable_endpoint(common, fsg->bulk_in, d);
2256 fsg->bulk_in_enabled = 1;
2258 d = fsg_ep_desc(common->gadget,
2259 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2260 rc = enable_endpoint(common, fsg->bulk_out, d);
2263 fsg->bulk_out_enabled = 1;
2264 common->bulk_out_maxpacket =
2265 le16_to_cpu(get_unaligned(&d->wMaxPacketSize));
2266 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2268 /* Allocate the requests */
2269 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2270 struct fsg_buffhd *bh = &common->buffhds[i];
2272 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2275 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2278 bh->inreq->buf = bh->outreq->buf = bh->buf;
2279 bh->inreq->context = bh->outreq->context = bh;
2280 bh->inreq->complete = bulk_in_complete;
2281 bh->outreq->complete = bulk_out_complete;
2284 common->running = 1;
2290 /****************************** ALT CONFIGS ******************************/
2293 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2295 struct fsg_dev *fsg = fsg_from_func(f);
2296 fsg->common->new_fsg = fsg;
2297 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2301 static void fsg_disable(struct usb_function *f)
2303 struct fsg_dev *fsg = fsg_from_func(f);
2304 fsg->common->new_fsg = NULL;
2305 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2308 /*-------------------------------------------------------------------------*/
2310 static void handle_exception(struct fsg_common *common)
2313 struct fsg_buffhd *bh;
2314 enum fsg_state old_state;
2315 struct fsg_lun *curlun;
2316 unsigned int exception_req_tag;
2318 /* Cancel all the pending transfers */
2320 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2321 bh = &common->buffhds[i];
2323 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2324 if (bh->outreq_busy)
2325 usb_ep_dequeue(common->fsg->bulk_out,
2329 /* Wait until everything is idle */
2332 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2333 bh = &common->buffhds[i];
2334 num_active += bh->inreq_busy + bh->outreq_busy;
2336 if (num_active == 0)
2338 if (sleep_thread(common))
2342 /* Clear out the controller's fifos */
2343 if (common->fsg->bulk_in_enabled)
2344 usb_ep_fifo_flush(common->fsg->bulk_in);
2345 if (common->fsg->bulk_out_enabled)
2346 usb_ep_fifo_flush(common->fsg->bulk_out);
2349 /* Reset the I/O buffer states and pointers, the SCSI
2350 * state, and the exception. Then invoke the handler. */
2352 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2353 bh = &common->buffhds[i];
2354 bh->state = BUF_STATE_EMPTY;
2356 common->next_buffhd_to_fill = &common->buffhds[0];
2357 common->next_buffhd_to_drain = &common->buffhds[0];
2358 exception_req_tag = common->exception_req_tag;
2359 old_state = common->state;
2361 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2362 common->state = FSG_STATE_STATUS_PHASE;
2364 for (i = 0; i < common->nluns; ++i) {
2365 curlun = &common->luns[i];
2366 curlun->sense_data = SS_NO_SENSE;
2367 curlun->info_valid = 0;
2369 common->state = FSG_STATE_IDLE;
2372 /* Carry out any extra actions required for the exception */
2373 switch (old_state) {
2374 case FSG_STATE_ABORT_BULK_OUT:
2375 send_status(common);
2377 if (common->state == FSG_STATE_STATUS_PHASE)
2378 common->state = FSG_STATE_IDLE;
2381 case FSG_STATE_RESET:
2382 /* In case we were forced against our will to halt a
2383 * bulk endpoint, clear the halt now. (The SuperH UDC
2384 * requires this.) */
2385 if (!fsg_is_set(common))
2387 if (test_and_clear_bit(IGNORE_BULK_OUT,
2388 &common->fsg->atomic_bitflags))
2389 usb_ep_clear_halt(common->fsg->bulk_in);
2391 if (common->ep0_req_tag == exception_req_tag)
2392 ep0_queue(common); /* Complete the status stage */
2396 case FSG_STATE_CONFIG_CHANGE:
2397 do_set_interface(common, common->new_fsg);
2400 case FSG_STATE_EXIT:
2401 case FSG_STATE_TERMINATED:
2402 do_set_interface(common, NULL); /* Free resources */
2403 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2406 case FSG_STATE_INTERFACE_CHANGE:
2407 case FSG_STATE_DISCONNECT:
2408 case FSG_STATE_COMMAND_PHASE:
2409 case FSG_STATE_DATA_PHASE:
2410 case FSG_STATE_STATUS_PHASE:
2411 case FSG_STATE_IDLE:
2416 /*-------------------------------------------------------------------------*/
2418 int fsg_main_thread(void *common_)
2420 struct fsg_common *common = the_fsg_common;
2423 if (exception_in_progress(common)) {
2424 handle_exception(common);
2428 if (!common->running) {
2429 sleep_thread(common);
2433 if (get_next_command(common))
2436 if (!exception_in_progress(common))
2437 common->state = FSG_STATE_DATA_PHASE;
2439 if (do_scsi_command(common) || finish_reply(common))
2442 if (!exception_in_progress(common))
2443 common->state = FSG_STATE_STATUS_PHASE;
2445 if (send_status(common))
2448 if (!exception_in_progress(common))
2449 common->state = FSG_STATE_IDLE;
2452 common->thread_task = NULL;
2457 static void fsg_common_release(struct kref *ref);
2459 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2460 struct usb_composite_dev *cdev)
2462 struct usb_gadget *gadget = cdev->gadget;
2463 struct fsg_buffhd *bh;
2464 struct fsg_lun *curlun;
2467 /* Find out how many LUNs there should be */
2469 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2470 printf("invalid number of LUNs: %u\n", nluns);
2471 return ERR_PTR(-EINVAL);
2476 common = calloc(sizeof *common, 1);
2478 return ERR_PTR(-ENOMEM);
2479 common->free_storage_on_release = 1;
2481 memset(common, 0, sizeof common);
2482 common->free_storage_on_release = 0;
2486 common->private_data = NULL;
2488 common->gadget = gadget;
2489 common->ep0 = gadget->ep0;
2490 common->ep0req = cdev->req;
2492 /* Maybe allocate device-global string IDs, and patch descriptors */
2493 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2494 rc = usb_string_id(cdev);
2495 if (unlikely(rc < 0))
2497 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2498 fsg_intf_desc.iInterface = rc;
2501 /* Create the LUNs, open their backing files, and register the
2502 * LUN devices in sysfs. */
2503 curlun = calloc(nluns, sizeof *curlun);
2508 common->nluns = nluns;
2510 for (i = 0; i < nluns; i++) {
2511 common->luns[i].removable = 1;
2513 rc = fsg_lun_open(&common->luns[i], "");
2519 /* Data buffers cyclic list */
2520 bh = common->buffhds;
2522 i = FSG_NUM_BUFFERS;
2523 goto buffhds_first_it;
2529 bh->outreq_busy = 0;
2530 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2531 if (unlikely(!bh->buf)) {
2536 bh->next = common->buffhds;
2538 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2541 "File-Store Gadget",
2544 /* Some peripheral controllers are known not to be able to
2545 * halt bulk endpoints correctly. If one of them is present,
2549 /* Tell the thread to start working */
2550 common->thread_task =
2551 kthread_create(fsg_main_thread, common,
2552 OR(cfg->thread_name, "file-storage"));
2553 if (IS_ERR(common->thread_task)) {
2554 rc = PTR_ERR(common->thread_task);
2560 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2561 INFO(common, "Number of LUNs=%d\n", common->nluns);
2566 common->nluns = i + 1;
2568 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2569 /* Call fsg_common_release() directly, ref might be not
2571 fsg_common_release(&common->ref);
2575 static void fsg_common_release(struct kref *ref)
2577 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2579 /* If the thread isn't already dead, tell it to exit now */
2580 if (common->state != FSG_STATE_TERMINATED) {
2581 raise_exception(common, FSG_STATE_EXIT);
2582 wait_for_completion(&common->thread_notifier);
2585 if (likely(common->luns)) {
2586 struct fsg_lun *lun = common->luns;
2587 unsigned i = common->nluns;
2589 /* In error recovery common->nluns may be zero. */
2590 for (; i; --i, ++lun)
2593 kfree(common->luns);
2597 struct fsg_buffhd *bh = common->buffhds;
2598 unsigned i = FSG_NUM_BUFFERS;
2601 } while (++bh, --i);
2604 if (common->free_storage_on_release)
2609 /*-------------------------------------------------------------------------*/
2612 * usb_copy_descriptors - copy a vector of USB descriptors
2613 * @src: null-terminated vector to copy
2614 * Context: initialization code, which may sleep
2616 * This makes a copy of a vector of USB descriptors. Its primary use
2617 * is to support usb_function objects which can have multiple copies,
2618 * each needing different descriptors. Functions may have static
2619 * tables of descriptors, which are used as templates and customized
2620 * with identifiers (for interfaces, strings, endpoints, and more)
2621 * as needed by a given function instance.
2623 struct usb_descriptor_header **
2624 usb_copy_descriptors(struct usb_descriptor_header **src)
2626 struct usb_descriptor_header **tmp;
2630 struct usb_descriptor_header **ret;
2632 /* count descriptors and their sizes; then add vector size */
2633 for (bytes = 0, n_desc = 0, tmp = src; *tmp; tmp++, n_desc++)
2634 bytes += (*tmp)->bLength;
2635 bytes += (n_desc + 1) * sizeof(*tmp);
2637 mem = kmalloc(bytes, GFP_KERNEL);
2641 /* fill in pointers starting at "tmp",
2642 * to descriptors copied starting at "mem";
2647 mem += (n_desc + 1) * sizeof(*tmp);
2649 memcpy(mem, *src, (*src)->bLength);
2652 mem += (*src)->bLength;
2662 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2664 struct fsg_dev *fsg = fsg_from_func(f);
2666 DBG(fsg, "unbind\n");
2667 if (fsg->common->fsg == fsg) {
2668 fsg->common->new_fsg = NULL;
2669 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2672 free(fsg->function.descriptors);
2673 free(fsg->function.hs_descriptors);
2677 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2679 struct fsg_dev *fsg = fsg_from_func(f);
2680 struct usb_gadget *gadget = c->cdev->gadget;
2683 fsg->gadget = gadget;
2686 i = usb_interface_id(c, f);
2689 fsg_intf_desc.bInterfaceNumber = i;
2690 fsg->interface_number = i;
2692 /* Find all the endpoints we will use */
2693 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2696 ep->driver_data = fsg->common; /* claim the endpoint */
2699 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2702 ep->driver_data = fsg->common; /* claim the endpoint */
2705 /* Copy descriptors */
2706 f->descriptors = usb_copy_descriptors(fsg_fs_function);
2707 if (unlikely(!f->descriptors))
2710 if (gadget_is_dualspeed(gadget)) {
2711 /* Assume endpoint addresses are the same for both speeds */
2712 fsg_hs_bulk_in_desc.bEndpointAddress =
2713 fsg_fs_bulk_in_desc.bEndpointAddress;
2714 fsg_hs_bulk_out_desc.bEndpointAddress =
2715 fsg_fs_bulk_out_desc.bEndpointAddress;
2716 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
2717 if (unlikely(!f->hs_descriptors)) {
2718 free(f->descriptors);
2725 ERROR(fsg, "unable to autoconfigure all endpoints\n");
2730 /****************************** ADD FUNCTION ******************************/
2732 static struct usb_gadget_strings *fsg_strings_array[] = {
2737 static int fsg_bind_config(struct usb_composite_dev *cdev,
2738 struct usb_configuration *c,
2739 struct fsg_common *common)
2741 struct fsg_dev *fsg;
2744 fsg = calloc(1, sizeof *fsg);
2747 fsg->function.name = FSG_DRIVER_DESC;
2748 fsg->function.strings = fsg_strings_array;
2749 fsg->function.bind = fsg_bind;
2750 fsg->function.unbind = fsg_unbind;
2751 fsg->function.setup = fsg_setup;
2752 fsg->function.set_alt = fsg_set_alt;
2753 fsg->function.disable = fsg_disable;
2755 fsg->common = common;
2757 /* Our caller holds a reference to common structure so we
2758 * don't have to be worry about it being freed until we return
2759 * from this function. So instead of incrementing counter now
2760 * and decrement in error recovery we increment it only when
2761 * call to usb_add_function() was successful. */
2763 rc = usb_add_function(c, &fsg->function);
2771 int fsg_add(struct usb_configuration *c)
2773 struct fsg_common *fsg_common;
2775 fsg_common = fsg_common_init(NULL, c->cdev);
2777 fsg_common->vendor_name = 0;
2778 fsg_common->product_name = 0;
2779 fsg_common->release = 0xffff;
2781 fsg_common->ops = NULL;
2782 fsg_common->private_data = NULL;
2784 the_fsg_common = fsg_common;
2786 return fsg_bind_config(c->cdev, c, fsg_common);
2789 int fsg_init(struct ums_board_info *ums)