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 * SPDX-License-Identifier: GPL-2.0+ BSD-3-Clause
13 * The Mass Storage Function acts as a USB Mass Storage device,
14 * appearing to the host as a disk drive or as a CD-ROM drive. In
15 * addition to providing an example of a genuinely useful composite
16 * function for a USB device, it also illustrates a technique of
17 * double-buffering for increased throughput.
19 * Function supports multiple logical units (LUNs). Backing storage
20 * for each LUN is provided by a regular file or a block device.
21 * Access for each LUN can be limited to read-only. Moreover, the
22 * function can indicate that LUN is removable and/or CD-ROM. (The
23 * later implies read-only access.)
25 * MSF is configured by specifying a fsg_config structure. It has the
28 * nluns Number of LUNs function have (anywhere from 1
29 * to FSG_MAX_LUNS which is 8).
30 * luns An array of LUN configuration values. This
31 * should be filled for each LUN that
32 * function will include (ie. for "nluns"
33 * LUNs). Each element of the array has
34 * the following fields:
35 * ->filename The path to the backing file for the LUN.
36 * Required if LUN is not marked as
38 * ->ro Flag specifying access to the LUN shall be
39 * read-only. This is implied if CD-ROM
40 * emulation is enabled as well as when
41 * it was impossible to open "filename"
43 * ->removable Flag specifying that LUN shall be indicated as
45 * ->cdrom Flag specifying that LUN shall be reported as
48 * lun_name_format A printf-like format for names of the LUN
49 * devices. This determines how the
50 * directory in sysfs will be named.
51 * Unless you are using several MSFs in
52 * a single gadget (as opposed to single
53 * MSF in many configurations) you may
54 * leave it as NULL (in which case
55 * "lun%d" will be used). In the format
56 * you can use "%d" to index LUNs for
57 * MSF's with more than one LUN. (Beware
58 * that there is only one integer given
59 * as an argument for the format and
60 * specifying invalid format may cause
61 * unspecified behaviour.)
62 * thread_name Name of the kernel thread process used by the
63 * MSF. You can safely set it to NULL
64 * (in which case default "file-storage"
69 * release Information used as a reply to INQUIRY
70 * request. To use default set to NULL,
71 * NULL, 0xffff respectively. The first
72 * field should be 8 and the second 16
75 * can_stall Set to permit function to halt bulk endpoints.
76 * Disabled on some USB devices known not
77 * to work correctly. You should set it
80 * If "removable" is not set for a LUN then a backing file must be
81 * specified. If it is set, then NULL filename means the LUN's medium
82 * is not loaded (an empty string as "filename" in the fsg_config
83 * structure causes error). The CD-ROM emulation includes a single
84 * data track and no audio tracks; hence there need be only one
85 * backing file per LUN. Note also that the CD-ROM block length is
86 * set to 512 rather than the more common value 2048.
89 * MSF includes support for module parameters. If gadget using it
90 * decides to use it, the following module parameters will be
93 * file=filename[,filename...]
94 * Names of the files or block devices used for
96 * ro=b[,b...] Default false, boolean for read-only access.
98 * Default true, boolean for removable media.
99 * cdrom=b[,b...] Default false, boolean for whether to emulate
101 * luns=N Default N = number of filenames, number of
103 * stall Default determined according to the type of
104 * USB device controller (usually true),
105 * boolean to permit the driver to halt
108 * The module parameters may be prefixed with some string. You need
109 * to consult gadget's documentation or source to verify whether it is
110 * using those module parameters and if it does what are the prefixes
111 * (look for FSG_MODULE_PARAMETERS() macro usage, what's inside it is
115 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
116 * needed. The memory requirement amounts to two 16K buffers, size
117 * configurable by a parameter. Support is included for both
118 * full-speed and high-speed operation.
120 * Note that the driver is slightly non-portable in that it assumes a
121 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
122 * interrupt-in endpoints. With most device controllers this isn't an
123 * issue, but there may be some with hardware restrictions that prevent
124 * a buffer from being used by more than one endpoint.
127 * The pathnames of the backing files and the ro settings are
128 * available in the attribute files "file" and "ro" in the lun<n> (or
129 * to be more precise in a directory which name comes from
130 * "lun_name_format" option!) subdirectory of the gadget's sysfs
131 * directory. If the "removable" option is set, writing to these
132 * files will simulate ejecting/loading the medium (writing an empty
133 * line means eject) and adjusting a write-enable tab. Changes to the
134 * ro setting are not allowed when the medium is loaded or if CD-ROM
135 * emulation is being used.
137 * When a LUN receive an "eject" SCSI request (Start/Stop Unit),
138 * if the LUN is removable, the backing file is released to simulate
142 * This function is heavily based on "File-backed Storage Gadget" by
143 * Alan Stern which in turn is heavily based on "Gadget Zero" by David
144 * Brownell. The driver's SCSI command interface was based on the
145 * "Information technology - Small Computer System Interface - 2"
146 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
147 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
148 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
149 * was based on the "Universal Serial Bus Mass Storage Class UFI
150 * Command Specification" document, Revision 1.0, December 14, 1998,
152 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
158 * The MSF is fairly straightforward. There is a main kernel
159 * thread that handles most of the work. Interrupt routines field
160 * callbacks from the controller driver: bulk- and interrupt-request
161 * completion notifications, endpoint-0 events, and disconnect events.
162 * Completion events are passed to the main thread by wakeup calls. Many
163 * ep0 requests are handled at interrupt time, but SetInterface,
164 * SetConfiguration, and device reset requests are forwarded to the
165 * thread in the form of "exceptions" using SIGUSR1 signals (since they
166 * should interrupt any ongoing file I/O operations).
168 * The thread's main routine implements the standard command/data/status
169 * parts of a SCSI interaction. It and its subroutines are full of tests
170 * for pending signals/exceptions -- all this polling is necessary since
171 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
172 * indication that the driver really wants to be running in userspace.)
173 * An important point is that so long as the thread is alive it keeps an
174 * open reference to the backing file. This will prevent unmounting
175 * the backing file's underlying filesystem and could cause problems
176 * during system shutdown, for example. To prevent such problems, the
177 * thread catches INT, TERM, and KILL signals and converts them into
180 * In normal operation the main thread is started during the gadget's
181 * fsg_bind() callback and stopped during fsg_unbind(). But it can
182 * also exit when it receives a signal, and there's no point leaving
183 * the gadget running when the thread is dead. At of this moment, MSF
184 * provides no way to deregister the gadget when thread dies -- maybe
185 * a callback functions is needed.
187 * To provide maximum throughput, the driver uses a circular pipeline of
188 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
189 * arbitrarily long; in practice the benefits don't justify having more
190 * than 2 stages (i.e., double buffering). But it helps to think of the
191 * pipeline as being a long one. Each buffer head contains a bulk-in and
192 * a bulk-out request pointer (since the buffer can be used for both
193 * output and input -- directions always are given from the host's
194 * point of view) as well as a pointer to the buffer and various state
197 * Use of the pipeline follows a simple protocol. There is a variable
198 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
199 * At any time that buffer head may still be in use from an earlier
200 * request, so each buffer head has a state variable indicating whether
201 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
202 * buffer head to be EMPTY, filling the buffer either by file I/O or by
203 * USB I/O (during which the buffer head is BUSY), and marking the buffer
204 * head FULL when the I/O is complete. Then the buffer will be emptied
205 * (again possibly by USB I/O, during which it is marked BUSY) and
206 * finally marked EMPTY again (possibly by a completion routine).
208 * A module parameter tells the driver to avoid stalling the bulk
209 * endpoints wherever the transport specification allows. This is
210 * necessary for some UDCs like the SuperH, which cannot reliably clear a
211 * halt on a bulk endpoint. However, under certain circumstances the
212 * Bulk-only specification requires a stall. In such cases the driver
213 * will halt the endpoint and set a flag indicating that it should clear
214 * the halt in software during the next device reset. Hopefully this
215 * will permit everything to work correctly. Furthermore, although the
216 * specification allows the bulk-out endpoint to halt when the host sends
217 * too much data, implementing this would cause an unavoidable race.
218 * The driver will always use the "no-stall" approach for OUT transfers.
220 * One subtle point concerns sending status-stage responses for ep0
221 * requests. Some of these requests, such as device reset, can involve
222 * interrupting an ongoing file I/O operation, which might take an
223 * arbitrarily long time. During that delay the host might give up on
224 * the original ep0 request and issue a new one. When that happens the
225 * driver should not notify the host about completion of the original
226 * request, as the host will no longer be waiting for it. So the driver
227 * assigns to each ep0 request a unique tag, and it keeps track of the
228 * tag value of the request associated with a long-running exception
229 * (device-reset, interface-change, or configuration-change). When the
230 * exception handler is finished, the status-stage response is submitted
231 * only if the current ep0 request tag is equal to the exception request
232 * tag. Thus only the most recently received ep0 request will get a
233 * status-stage response.
235 * Warning: This driver source file is too long. It ought to be split up
236 * into a header file plus about 3 separate .c files, to handle the details
237 * of the Gadget, USB Mass Storage, and SCSI protocols.
240 /* #define VERBOSE_DEBUG */
241 /* #define DUMP_MSGS */
247 #include <linux/err.h>
248 #include <linux/usb/ch9.h>
249 #include <linux/usb/gadget.h>
250 #include <usb_mass_storage.h>
252 #include <asm/unaligned.h>
253 #include <linux/usb/gadget.h>
254 #include <linux/usb/gadget.h>
255 #include <linux/usb/composite.h>
256 #include <usb/lin_gadget_compat.h>
258 /*------------------------------------------------------------------------*/
260 #define FSG_DRIVER_DESC "Mass Storage Function"
261 #define FSG_DRIVER_VERSION "2012/06/5"
263 static const char fsg_string_interface[] = "Mass Storage";
265 #define FSG_NO_INTR_EP 1
266 #define FSG_NO_DEVICE_STRINGS 1
268 #define FSG_NO_INTR_EP 1
270 #include "storage_common.c"
272 /*-------------------------------------------------------------------------*/
274 #define GFP_ATOMIC ((gfp_t) 0)
275 #define PAGE_CACHE_SHIFT 12
276 #define PAGE_CACHE_SIZE (1 << PAGE_CACHE_SHIFT)
277 #define kthread_create(...) __builtin_return_address(0)
278 #define wait_for_completion(...) do {} while (0)
280 struct kref {int x; };
281 struct completion {int x; };
283 inline void set_bit(int nr, volatile void *addr)
286 unsigned int *a = (unsigned int *) addr;
289 mask = 1 << (nr & 0x1f);
293 inline void clear_bit(int nr, volatile void *addr)
296 unsigned int *a = (unsigned int *) addr;
299 mask = 1 << (nr & 0x1f);
306 /* Data shared by all the FSG instances. */
308 struct usb_gadget *gadget;
309 struct fsg_dev *fsg, *new_fsg;
311 struct usb_ep *ep0; /* Copy of gadget->ep0 */
312 struct usb_request *ep0req; /* Copy of cdev->req */
313 unsigned int ep0_req_tag;
315 struct fsg_buffhd *next_buffhd_to_fill;
316 struct fsg_buffhd *next_buffhd_to_drain;
317 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
320 u8 cmnd[MAX_COMMAND_SIZE];
324 struct fsg_lun luns[FSG_MAX_LUNS];
326 unsigned int bulk_out_maxpacket;
327 enum fsg_state state; /* For exception handling */
328 unsigned int exception_req_tag;
330 enum data_direction data_dir;
332 u32 data_size_from_cmnd;
337 unsigned int can_stall:1;
338 unsigned int free_storage_on_release:1;
339 unsigned int phase_error:1;
340 unsigned int short_packet_received:1;
341 unsigned int bad_lun_okay:1;
342 unsigned int running:1;
344 int thread_wakeup_needed;
345 struct completion thread_notifier;
346 struct task_struct *thread_task;
348 /* Callback functions. */
349 const struct fsg_operations *ops;
350 /* Gadget's private data. */
353 const char *vendor_name; /* 8 characters or less */
354 const char *product_name; /* 16 characters or less */
357 /* Vendor (8 chars), product (16 chars), release (4
358 * hexadecimal digits) and NUL byte */
359 char inquiry_string[8 + 16 + 4 + 1];
366 struct fsg_lun_config {
367 const char *filename;
372 } luns[FSG_MAX_LUNS];
374 /* Callback functions. */
375 const struct fsg_operations *ops;
376 /* Gadget's private data. */
379 const char *vendor_name; /* 8 characters or less */
380 const char *product_name; /* 16 characters or less */
386 struct usb_function function;
387 struct usb_gadget *gadget; /* Copy of cdev->gadget */
388 struct fsg_common *common;
390 u16 interface_number;
392 unsigned int bulk_in_enabled:1;
393 unsigned int bulk_out_enabled:1;
395 unsigned long atomic_bitflags;
396 #define IGNORE_BULK_OUT 0
398 struct usb_ep *bulk_in;
399 struct usb_ep *bulk_out;
403 static inline int __fsg_is_set(struct fsg_common *common,
404 const char *func, unsigned line)
408 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
413 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
416 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
418 return container_of(f, struct fsg_dev, function);
422 typedef void (*fsg_routine_t)(struct fsg_dev *);
424 static int exception_in_progress(struct fsg_common *common)
426 return common->state > FSG_STATE_IDLE;
429 /* Make bulk-out requests be divisible by the maxpacket size */
430 static void set_bulk_out_req_length(struct fsg_common *common,
431 struct fsg_buffhd *bh, unsigned int length)
435 bh->bulk_out_intended_length = length;
436 rem = length % common->bulk_out_maxpacket;
438 length += common->bulk_out_maxpacket - rem;
439 bh->outreq->length = length;
442 /*-------------------------------------------------------------------------*/
444 struct ums_board_info *ums_info;
445 struct fsg_common *the_fsg_common;
447 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
451 if (ep == fsg->bulk_in)
453 else if (ep == fsg->bulk_out)
457 DBG(fsg, "%s set halt\n", name);
458 return usb_ep_set_halt(ep);
461 /*-------------------------------------------------------------------------*/
463 /* These routines may be called in process context or in_irq */
465 /* Caller must hold fsg->lock */
466 static void wakeup_thread(struct fsg_common *common)
468 common->thread_wakeup_needed = 1;
471 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
473 /* Do nothing if a higher-priority exception is already in progress.
474 * If a lower-or-equal priority exception is in progress, preempt it
475 * and notify the main thread by sending it a signal. */
476 if (common->state <= new_state) {
477 common->exception_req_tag = common->ep0_req_tag;
478 common->state = new_state;
479 common->thread_wakeup_needed = 1;
483 /*-------------------------------------------------------------------------*/
485 static int ep0_queue(struct fsg_common *common)
489 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
490 common->ep0->driver_data = common;
491 if (rc != 0 && rc != -ESHUTDOWN) {
492 /* We can't do much more than wait for a reset */
493 WARNING(common, "error in submission: %s --> %d\n",
494 common->ep0->name, rc);
499 /*-------------------------------------------------------------------------*/
501 /* Bulk and interrupt endpoint completion handlers.
502 * These always run in_irq. */
504 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
506 struct fsg_common *common = ep->driver_data;
507 struct fsg_buffhd *bh = req->context;
509 if (req->status || req->actual != req->length)
510 DBG(common, "%s --> %d, %u/%u\n", __func__,
511 req->status, req->actual, req->length);
512 if (req->status == -ECONNRESET) /* Request was cancelled */
513 usb_ep_fifo_flush(ep);
515 /* Hold the lock while we update the request and buffer states */
517 bh->state = BUF_STATE_EMPTY;
518 wakeup_thread(common);
521 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
523 struct fsg_common *common = ep->driver_data;
524 struct fsg_buffhd *bh = req->context;
526 dump_msg(common, "bulk-out", req->buf, req->actual);
527 if (req->status || req->actual != bh->bulk_out_intended_length)
528 DBG(common, "%s --> %d, %u/%u\n", __func__,
529 req->status, req->actual,
530 bh->bulk_out_intended_length);
531 if (req->status == -ECONNRESET) /* Request was cancelled */
532 usb_ep_fifo_flush(ep);
534 /* Hold the lock while we update the request and buffer states */
536 bh->state = BUF_STATE_FULL;
537 wakeup_thread(common);
540 /*-------------------------------------------------------------------------*/
542 /* Ep0 class-specific handlers. These always run in_irq. */
544 static int fsg_setup(struct usb_function *f,
545 const struct usb_ctrlrequest *ctrl)
547 struct fsg_dev *fsg = fsg_from_func(f);
548 struct usb_request *req = fsg->common->ep0req;
549 u16 w_index = get_unaligned_le16(&ctrl->wIndex);
550 u16 w_value = get_unaligned_le16(&ctrl->wValue);
551 u16 w_length = get_unaligned_le16(&ctrl->wLength);
553 if (!fsg_is_set(fsg->common))
556 switch (ctrl->bRequest) {
558 case USB_BULK_RESET_REQUEST:
559 if (ctrl->bRequestType !=
560 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
562 if (w_index != fsg->interface_number || w_value != 0)
565 /* Raise an exception to stop the current operation
566 * and reinitialize our state. */
567 DBG(fsg, "bulk reset request\n");
568 raise_exception(fsg->common, FSG_STATE_RESET);
569 return DELAYED_STATUS;
571 case USB_BULK_GET_MAX_LUN_REQUEST:
572 if (ctrl->bRequestType !=
573 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
575 if (w_index != fsg->interface_number || w_value != 0)
577 VDBG(fsg, "get max LUN\n");
578 *(u8 *) req->buf = fsg->common->nluns - 1;
580 /* Respond with data/status */
581 req->length = min((u16)1, w_length);
582 return ep0_queue(fsg->common);
586 "unknown class-specific control req "
587 "%02x.%02x v%04x i%04x l%u\n",
588 ctrl->bRequestType, ctrl->bRequest,
589 get_unaligned_le16(&ctrl->wValue), w_index, w_length);
593 /*-------------------------------------------------------------------------*/
595 /* All the following routines run in process context */
597 /* Use this for bulk or interrupt transfers, not ep0 */
598 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
599 struct usb_request *req, int *pbusy,
600 enum fsg_buffer_state *state)
604 if (ep == fsg->bulk_in)
605 dump_msg(fsg, "bulk-in", req->buf, req->length);
608 *state = BUF_STATE_BUSY;
609 rc = usb_ep_queue(ep, req, GFP_KERNEL);
612 *state = BUF_STATE_EMPTY;
614 /* We can't do much more than wait for a reset */
616 /* Note: currently the net2280 driver fails zero-length
617 * submissions if DMA is enabled. */
618 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
620 WARNING(fsg, "error in submission: %s --> %d\n",
625 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
626 if (fsg_is_set(common)) \
627 start_transfer((common)->fsg, (common)->fsg->ep_name, \
628 req, pbusy, state); \
631 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
632 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
634 static void busy_indicator(void)
662 static int sleep_thread(struct fsg_common *common)
667 /* Wait until a signal arrives or we are woken up */
669 if (common->thread_wakeup_needed)
678 usb_gadget_handle_interrupts();
680 common->thread_wakeup_needed = 0;
684 /*-------------------------------------------------------------------------*/
686 static int do_read(struct fsg_common *common)
688 struct fsg_lun *curlun = &common->luns[common->lun];
690 struct fsg_buffhd *bh;
695 unsigned int partial_page;
698 /* Get the starting Logical Block Address and check that it's
700 if (common->cmnd[0] == SC_READ_6)
701 lba = get_unaligned_be24(&common->cmnd[1]);
703 lba = get_unaligned_be32(&common->cmnd[2]);
705 /* We allow DPO (Disable Page Out = don't save data in the
706 * cache) and FUA (Force Unit Access = don't read from the
707 * cache), but we don't implement them. */
708 if ((common->cmnd[1] & ~0x18) != 0) {
709 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
713 if (lba >= curlun->num_sectors) {
714 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
717 file_offset = ((loff_t) lba) << 9;
719 /* Carry out the file reads */
720 amount_left = common->data_size_from_cmnd;
721 if (unlikely(amount_left == 0))
722 return -EIO; /* No default reply */
726 /* Figure out how much we need to read:
727 * Try to read the remaining amount.
728 * But don't read more than the buffer size.
729 * And don't try to read past the end of the file.
730 * Finally, if we're not at a page boundary, don't read past
732 * If this means reading 0 then we were asked to read past
733 * the end of file. */
734 amount = min(amount_left, FSG_BUFLEN);
735 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
736 if (partial_page > 0)
737 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
740 /* Wait for the next buffer to become available */
741 bh = common->next_buffhd_to_fill;
742 while (bh->state != BUF_STATE_EMPTY) {
743 rc = sleep_thread(common);
748 /* If we were asked to read past the end of file,
749 * end with an empty buffer. */
752 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
753 curlun->info_valid = 1;
754 bh->inreq->length = 0;
755 bh->state = BUF_STATE_FULL;
759 /* Perform the read */
761 rc = ums_info->read_sector(&(ums_info->ums_dev),
762 file_offset / SECTOR_SIZE,
763 amount / SECTOR_SIZE,
764 (char __user *)bh->buf);
769 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
770 (unsigned long long) file_offset,
774 LDBG(curlun, "error in file read: %d\n",
777 } else if (nread < amount) {
778 LDBG(curlun, "partial file read: %d/%u\n",
779 (int) nread, amount);
780 nread -= (nread & 511); /* Round down to a block */
782 file_offset += nread;
783 amount_left -= nread;
784 common->residue -= nread;
785 bh->inreq->length = nread;
786 bh->state = BUF_STATE_FULL;
788 /* If an error occurred, report it and its position */
789 if (nread < amount) {
790 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
791 curlun->info_valid = 1;
795 if (amount_left == 0)
796 break; /* No more left to read */
798 /* Send this buffer and go read some more */
800 START_TRANSFER_OR(common, bulk_in, bh->inreq,
801 &bh->inreq_busy, &bh->state)
802 /* Don't know what to do if
803 * common->fsg is NULL */
805 common->next_buffhd_to_fill = bh->next;
808 return -EIO; /* No default reply */
811 /*-------------------------------------------------------------------------*/
813 static int do_write(struct fsg_common *common)
815 struct fsg_lun *curlun = &common->luns[common->lun];
817 struct fsg_buffhd *bh;
819 u32 amount_left_to_req, amount_left_to_write;
820 loff_t usb_offset, file_offset;
822 unsigned int partial_page;
827 curlun->sense_data = SS_WRITE_PROTECTED;
831 /* Get the starting Logical Block Address and check that it's
833 if (common->cmnd[0] == SC_WRITE_6)
834 lba = get_unaligned_be24(&common->cmnd[1]);
836 lba = get_unaligned_be32(&common->cmnd[2]);
838 /* We allow DPO (Disable Page Out = don't save data in the
839 * cache) and FUA (Force Unit Access = write directly to the
840 * medium). We don't implement DPO; we implement FUA by
841 * performing synchronous output. */
842 if (common->cmnd[1] & ~0x18) {
843 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
847 if (lba >= curlun->num_sectors) {
848 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
852 /* Carry out the file writes */
854 file_offset = usb_offset = ((loff_t) lba) << 9;
855 amount_left_to_req = common->data_size_from_cmnd;
856 amount_left_to_write = common->data_size_from_cmnd;
858 while (amount_left_to_write > 0) {
860 /* Queue a request for more data from the host */
861 bh = common->next_buffhd_to_fill;
862 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
864 /* Figure out how much we want to get:
865 * Try to get the remaining amount.
866 * But don't get more than the buffer size.
867 * And don't try to go past the end of the file.
868 * If we're not at a page boundary,
869 * don't go past the next page.
870 * If this means getting 0, then we were asked
871 * to write past the end of file.
872 * Finally, round down to a block boundary. */
873 amount = min(amount_left_to_req, FSG_BUFLEN);
874 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
875 if (partial_page > 0)
877 (unsigned int) PAGE_CACHE_SIZE - partial_page);
882 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
883 curlun->info_valid = 1;
886 amount -= (amount & 511);
889 /* Why were we were asked to transfer a
895 /* Get the next buffer */
896 usb_offset += amount;
897 common->usb_amount_left -= amount;
898 amount_left_to_req -= amount;
899 if (amount_left_to_req == 0)
902 /* amount is always divisible by 512, hence by
903 * the bulk-out maxpacket size */
904 bh->outreq->length = amount;
905 bh->bulk_out_intended_length = amount;
906 bh->outreq->short_not_ok = 1;
907 START_TRANSFER_OR(common, bulk_out, bh->outreq,
908 &bh->outreq_busy, &bh->state)
909 /* Don't know what to do if
910 * common->fsg is NULL */
912 common->next_buffhd_to_fill = bh->next;
916 /* Write the received data to the backing file */
917 bh = common->next_buffhd_to_drain;
918 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
919 break; /* We stopped early */
920 if (bh->state == BUF_STATE_FULL) {
921 common->next_buffhd_to_drain = bh->next;
922 bh->state = BUF_STATE_EMPTY;
924 /* Did something go wrong with the transfer? */
925 if (bh->outreq->status != 0) {
926 curlun->sense_data = SS_COMMUNICATION_FAILURE;
927 curlun->info_valid = 1;
931 amount = bh->outreq->actual;
933 /* Perform the write */
934 rc = ums_info->write_sector(&(ums_info->ums_dev),
935 file_offset / SECTOR_SIZE,
936 amount / SECTOR_SIZE,
937 (char __user *)bh->buf);
942 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
943 (unsigned long long) file_offset,
947 LDBG(curlun, "error in file write: %d\n",
950 } else if (nwritten < amount) {
951 LDBG(curlun, "partial file write: %d/%u\n",
952 (int) nwritten, amount);
953 nwritten -= (nwritten & 511);
954 /* Round down to a block */
956 file_offset += nwritten;
957 amount_left_to_write -= nwritten;
958 common->residue -= nwritten;
960 /* If an error occurred, report it and its position */
961 if (nwritten < amount) {
962 curlun->sense_data = SS_WRITE_ERROR;
963 curlun->info_valid = 1;
967 /* Did the host decide to stop early? */
968 if (bh->outreq->actual != bh->outreq->length) {
969 common->short_packet_received = 1;
975 /* Wait for something to happen */
976 rc = sleep_thread(common);
981 return -EIO; /* No default reply */
984 /*-------------------------------------------------------------------------*/
986 static int do_synchronize_cache(struct fsg_common *common)
991 /*-------------------------------------------------------------------------*/
993 static int do_verify(struct fsg_common *common)
995 struct fsg_lun *curlun = &common->luns[common->lun];
997 u32 verification_length;
998 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1001 unsigned int amount;
1005 /* Get the starting Logical Block Address and check that it's
1007 lba = get_unaligned_be32(&common->cmnd[2]);
1008 if (lba >= curlun->num_sectors) {
1009 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1013 /* We allow DPO (Disable Page Out = don't save data in the
1014 * cache) but we don't implement it. */
1015 if (common->cmnd[1] & ~0x10) {
1016 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1020 verification_length = get_unaligned_be16(&common->cmnd[7]);
1021 if (unlikely(verification_length == 0))
1022 return -EIO; /* No default reply */
1024 /* Prepare to carry out the file verify */
1025 amount_left = verification_length << 9;
1026 file_offset = ((loff_t) lba) << 9;
1028 /* Write out all the dirty buffers before invalidating them */
1030 /* Just try to read the requested blocks */
1031 while (amount_left > 0) {
1033 /* Figure out how much we need to read:
1034 * Try to read the remaining amount, but not more than
1036 * And don't try to read past the end of the file.
1037 * If this means reading 0 then we were asked to read
1038 * past the end of file. */
1039 amount = min(amount_left, FSG_BUFLEN);
1041 curlun->sense_data =
1042 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1043 curlun->info_valid = 1;
1047 /* Perform the read */
1049 rc = ums_info->read_sector(&(ums_info->ums_dev),
1050 file_offset / SECTOR_SIZE,
1051 amount / SECTOR_SIZE,
1052 (char __user *)bh->buf);
1057 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1058 (unsigned long long) file_offset,
1061 LDBG(curlun, "error in file verify: %d\n",
1064 } else if (nread < amount) {
1065 LDBG(curlun, "partial file verify: %d/%u\n",
1066 (int) nread, amount);
1067 nread -= (nread & 511); /* Round down to a sector */
1070 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1071 curlun->info_valid = 1;
1074 file_offset += nread;
1075 amount_left -= nread;
1080 /*-------------------------------------------------------------------------*/
1082 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1084 struct fsg_lun *curlun = &common->luns[common->lun];
1085 static const char vendor_id[] = "Linux ";
1086 u8 *buf = (u8 *) bh->buf;
1088 if (!curlun) { /* Unsupported LUNs are okay */
1089 common->bad_lun_okay = 1;
1091 buf[0] = 0x7f; /* Unsupported, no device-type */
1092 buf[4] = 31; /* Additional length */
1098 buf[2] = 2; /* ANSI SCSI level 2 */
1099 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1100 buf[4] = 31; /* Additional length */
1101 /* No special options */
1102 sprintf((char *) (buf + 8), "%-8s%-16s%04x", (char*) vendor_id ,
1103 ums_info->name, (u16) 0xffff);
1109 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1111 struct fsg_lun *curlun = &common->luns[common->lun];
1112 u8 *buf = (u8 *) bh->buf;
1117 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1119 * If a REQUEST SENSE command is received from an initiator
1120 * with a pending unit attention condition (before the target
1121 * generates the contingent allegiance condition), then the
1122 * target shall either:
1123 * a) report any pending sense data and preserve the unit
1124 * attention condition on the logical unit, or,
1125 * b) report the unit attention condition, may discard any
1126 * pending sense data, and clear the unit attention
1127 * condition on the logical unit for that initiator.
1129 * FSG normally uses option a); enable this code to use option b).
1132 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1133 curlun->sense_data = curlun->unit_attention_data;
1134 curlun->unit_attention_data = SS_NO_SENSE;
1138 if (!curlun) { /* Unsupported LUNs are okay */
1139 common->bad_lun_okay = 1;
1140 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1144 sd = curlun->sense_data;
1145 valid = curlun->info_valid << 7;
1146 curlun->sense_data = SS_NO_SENSE;
1147 curlun->info_valid = 0;
1151 buf[0] = valid | 0x70; /* Valid, current error */
1153 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1154 buf[7] = 18 - 8; /* Additional sense length */
1160 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1162 struct fsg_lun *curlun = &common->luns[common->lun];
1163 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1164 int pmi = common->cmnd[8];
1165 u8 *buf = (u8 *) bh->buf;
1167 /* Check the PMI and LBA fields */
1168 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1169 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1173 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1174 /* Max logical block */
1175 put_unaligned_be32(512, &buf[4]); /* Block length */
1179 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1181 struct fsg_lun *curlun = &common->luns[common->lun];
1182 int msf = common->cmnd[1] & 0x02;
1183 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1184 u8 *buf = (u8 *) bh->buf;
1186 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1187 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1190 if (lba >= curlun->num_sectors) {
1191 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1196 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1197 store_cdrom_address(&buf[4], msf, lba);
1202 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1204 struct fsg_lun *curlun = &common->luns[common->lun];
1205 int msf = common->cmnd[1] & 0x02;
1206 int start_track = common->cmnd[6];
1207 u8 *buf = (u8 *) bh->buf;
1209 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1211 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1216 buf[1] = (20-2); /* TOC data length */
1217 buf[2] = 1; /* First track number */
1218 buf[3] = 1; /* Last track number */
1219 buf[5] = 0x16; /* Data track, copying allowed */
1220 buf[6] = 0x01; /* Only track is number 1 */
1221 store_cdrom_address(&buf[8], msf, 0);
1223 buf[13] = 0x16; /* Lead-out track is data */
1224 buf[14] = 0xAA; /* Lead-out track number */
1225 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1230 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1232 struct fsg_lun *curlun = &common->luns[common->lun];
1233 int mscmnd = common->cmnd[0];
1234 u8 *buf = (u8 *) bh->buf;
1237 int changeable_values, all_pages;
1241 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1242 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1245 pc = common->cmnd[2] >> 6;
1246 page_code = common->cmnd[2] & 0x3f;
1248 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1251 changeable_values = (pc == 1);
1252 all_pages = (page_code == 0x3f);
1254 /* Write the mode parameter header. Fixed values are: default
1255 * medium type, no cache control (DPOFUA), and no block descriptors.
1256 * The only variable value is the WriteProtect bit. We will fill in
1257 * the mode data length later. */
1259 if (mscmnd == SC_MODE_SENSE_6) {
1260 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1263 } else { /* SC_MODE_SENSE_10 */
1264 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1266 limit = 65535; /* Should really be FSG_BUFLEN */
1269 /* No block descriptors */
1271 /* The mode pages, in numerical order. The only page we support
1272 * is the Caching page. */
1273 if (page_code == 0x08 || all_pages) {
1275 buf[0] = 0x08; /* Page code */
1276 buf[1] = 10; /* Page length */
1277 memset(buf+2, 0, 10); /* None of the fields are changeable */
1279 if (!changeable_values) {
1280 buf[2] = 0x04; /* Write cache enable, */
1281 /* Read cache not disabled */
1282 /* No cache retention priorities */
1283 put_unaligned_be16(0xffff, &buf[4]);
1284 /* Don't disable prefetch */
1285 /* Minimum prefetch = 0 */
1286 put_unaligned_be16(0xffff, &buf[8]);
1287 /* Maximum prefetch */
1288 put_unaligned_be16(0xffff, &buf[10]);
1289 /* Maximum prefetch ceiling */
1294 /* Check that a valid page was requested and the mode data length
1295 * isn't too long. */
1297 if (!valid_page || len > limit) {
1298 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1302 /* Store the mode data length */
1303 if (mscmnd == SC_MODE_SENSE_6)
1306 put_unaligned_be16(len - 2, buf0);
1311 static int do_start_stop(struct fsg_common *common)
1313 struct fsg_lun *curlun = &common->luns[common->lun];
1317 } else if (!curlun->removable) {
1318 curlun->sense_data = SS_INVALID_COMMAND;
1325 static int do_prevent_allow(struct fsg_common *common)
1327 struct fsg_lun *curlun = &common->luns[common->lun];
1330 if (!curlun->removable) {
1331 curlun->sense_data = SS_INVALID_COMMAND;
1335 prevent = common->cmnd[4] & 0x01;
1336 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1337 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1341 if (curlun->prevent_medium_removal && !prevent)
1342 fsg_lun_fsync_sub(curlun);
1343 curlun->prevent_medium_removal = prevent;
1348 static int do_read_format_capacities(struct fsg_common *common,
1349 struct fsg_buffhd *bh)
1351 struct fsg_lun *curlun = &common->luns[common->lun];
1352 u8 *buf = (u8 *) bh->buf;
1354 buf[0] = buf[1] = buf[2] = 0;
1355 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1358 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1359 /* Number of blocks */
1360 put_unaligned_be32(512, &buf[4]); /* Block length */
1361 buf[4] = 0x02; /* Current capacity */
1366 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1368 struct fsg_lun *curlun = &common->luns[common->lun];
1370 /* We don't support MODE SELECT */
1372 curlun->sense_data = SS_INVALID_COMMAND;
1377 /*-------------------------------------------------------------------------*/
1379 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1383 rc = fsg_set_halt(fsg, fsg->bulk_in);
1385 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1387 if (rc != -EAGAIN) {
1388 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1393 rc = usb_ep_set_halt(fsg->bulk_in);
1398 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1402 DBG(fsg, "bulk-in set wedge\n");
1403 rc = 0; /* usb_ep_set_wedge(fsg->bulk_in); */
1405 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1407 if (rc != -EAGAIN) {
1408 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1416 static int pad_with_zeros(struct fsg_dev *fsg)
1418 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1419 u32 nkeep = bh->inreq->length;
1423 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1424 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1425 while (fsg->common->usb_amount_left > 0) {
1427 /* Wait for the next buffer to be free */
1428 while (bh->state != BUF_STATE_EMPTY) {
1429 rc = sleep_thread(fsg->common);
1434 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1435 memset(bh->buf + nkeep, 0, nsend - nkeep);
1436 bh->inreq->length = nsend;
1437 bh->inreq->zero = 0;
1438 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1439 &bh->inreq_busy, &bh->state);
1440 bh = fsg->common->next_buffhd_to_fill = bh->next;
1441 fsg->common->usb_amount_left -= nsend;
1447 static int throw_away_data(struct fsg_common *common)
1449 struct fsg_buffhd *bh;
1453 for (bh = common->next_buffhd_to_drain;
1454 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1455 bh = common->next_buffhd_to_drain) {
1457 /* Throw away the data in a filled buffer */
1458 if (bh->state == BUF_STATE_FULL) {
1459 bh->state = BUF_STATE_EMPTY;
1460 common->next_buffhd_to_drain = bh->next;
1462 /* A short packet or an error ends everything */
1463 if (bh->outreq->actual != bh->outreq->length ||
1464 bh->outreq->status != 0) {
1465 raise_exception(common,
1466 FSG_STATE_ABORT_BULK_OUT);
1472 /* Try to submit another request if we need one */
1473 bh = common->next_buffhd_to_fill;
1474 if (bh->state == BUF_STATE_EMPTY
1475 && common->usb_amount_left > 0) {
1476 amount = min(common->usb_amount_left, FSG_BUFLEN);
1478 /* amount is always divisible by 512, hence by
1479 * the bulk-out maxpacket size */
1480 bh->outreq->length = amount;
1481 bh->bulk_out_intended_length = amount;
1482 bh->outreq->short_not_ok = 1;
1483 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1484 &bh->outreq_busy, &bh->state)
1485 /* Don't know what to do if
1486 * common->fsg is NULL */
1488 common->next_buffhd_to_fill = bh->next;
1489 common->usb_amount_left -= amount;
1493 /* Otherwise wait for something to happen */
1494 rc = sleep_thread(common);
1502 static int finish_reply(struct fsg_common *common)
1504 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1507 switch (common->data_dir) {
1509 break; /* Nothing to send */
1511 /* If we don't know whether the host wants to read or write,
1512 * this must be CB or CBI with an unknown command. We mustn't
1513 * try to send or receive any data. So stall both bulk pipes
1514 * if we can and wait for a reset. */
1515 case DATA_DIR_UNKNOWN:
1516 if (!common->can_stall) {
1518 } else if (fsg_is_set(common)) {
1519 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1520 rc = halt_bulk_in_endpoint(common->fsg);
1522 /* Don't know what to do if common->fsg is NULL */
1527 /* All but the last buffer of data must have already been sent */
1528 case DATA_DIR_TO_HOST:
1529 if (common->data_size == 0) {
1530 /* Nothing to send */
1532 /* If there's no residue, simply send the last buffer */
1533 } else if (common->residue == 0) {
1534 bh->inreq->zero = 0;
1535 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1536 &bh->inreq_busy, &bh->state)
1538 common->next_buffhd_to_fill = bh->next;
1540 /* For Bulk-only, if we're allowed to stall then send the
1541 * short packet and halt the bulk-in endpoint. If we can't
1542 * stall, pad out the remaining data with 0's. */
1543 } else if (common->can_stall) {
1544 bh->inreq->zero = 1;
1545 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1546 &bh->inreq_busy, &bh->state)
1547 /* Don't know what to do if
1548 * common->fsg is NULL */
1550 common->next_buffhd_to_fill = bh->next;
1552 rc = halt_bulk_in_endpoint(common->fsg);
1553 } else if (fsg_is_set(common)) {
1554 rc = pad_with_zeros(common->fsg);
1556 /* Don't know what to do if common->fsg is NULL */
1561 /* We have processed all we want from the data the host has sent.
1562 * There may still be outstanding bulk-out requests. */
1563 case DATA_DIR_FROM_HOST:
1564 if (common->residue == 0) {
1565 /* Nothing to receive */
1567 /* Did the host stop sending unexpectedly early? */
1568 } else if (common->short_packet_received) {
1569 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1572 /* We haven't processed all the incoming data. Even though
1573 * we may be allowed to stall, doing so would cause a race.
1574 * The controller may already have ACK'ed all the remaining
1575 * bulk-out packets, in which case the host wouldn't see a
1576 * STALL. Not realizing the endpoint was halted, it wouldn't
1577 * clear the halt -- leading to problems later on. */
1579 } else if (common->can_stall) {
1580 if (fsg_is_set(common))
1581 fsg_set_halt(common->fsg,
1582 common->fsg->bulk_out);
1583 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1587 /* We can't stall. Read in the excess data and throw it
1590 rc = throw_away_data(common);
1598 static int send_status(struct fsg_common *common)
1600 struct fsg_lun *curlun = &common->luns[common->lun];
1601 struct fsg_buffhd *bh;
1602 struct bulk_cs_wrap *csw;
1604 u8 status = USB_STATUS_PASS;
1607 /* Wait for the next buffer to become available */
1608 bh = common->next_buffhd_to_fill;
1609 while (bh->state != BUF_STATE_EMPTY) {
1610 rc = sleep_thread(common);
1616 sd = curlun->sense_data;
1617 else if (common->bad_lun_okay)
1620 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1622 if (common->phase_error) {
1623 DBG(common, "sending phase-error status\n");
1624 status = USB_STATUS_PHASE_ERROR;
1625 sd = SS_INVALID_COMMAND;
1626 } else if (sd != SS_NO_SENSE) {
1627 DBG(common, "sending command-failure status\n");
1628 status = USB_STATUS_FAIL;
1629 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1631 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1634 /* Store and send the Bulk-only CSW */
1635 csw = (void *)bh->buf;
1637 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1638 csw->Tag = common->tag;
1639 csw->Residue = cpu_to_le32(common->residue);
1640 csw->Status = status;
1642 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1643 bh->inreq->zero = 0;
1644 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1645 &bh->inreq_busy, &bh->state)
1646 /* Don't know what to do if common->fsg is NULL */
1649 common->next_buffhd_to_fill = bh->next;
1654 /*-------------------------------------------------------------------------*/
1656 /* Check whether the command is properly formed and whether its data size
1657 * and direction agree with the values we already have. */
1658 static int check_command(struct fsg_common *common, int cmnd_size,
1659 enum data_direction data_dir, unsigned int mask,
1660 int needs_medium, const char *name)
1663 int lun = common->cmnd[1] >> 5;
1664 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1666 struct fsg_lun *curlun;
1669 if (common->data_dir != DATA_DIR_UNKNOWN)
1670 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1672 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1673 name, cmnd_size, dirletter[(int) data_dir],
1674 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1676 /* We can't reply at all until we know the correct data direction
1678 if (common->data_size_from_cmnd == 0)
1679 data_dir = DATA_DIR_NONE;
1680 if (common->data_size < common->data_size_from_cmnd) {
1681 /* Host data size < Device data size is a phase error.
1682 * Carry out the command, but only transfer as much as
1683 * we are allowed. */
1684 common->data_size_from_cmnd = common->data_size;
1685 common->phase_error = 1;
1687 common->residue = common->data_size;
1688 common->usb_amount_left = common->data_size;
1690 /* Conflicting data directions is a phase error */
1691 if (common->data_dir != data_dir
1692 && common->data_size_from_cmnd > 0) {
1693 common->phase_error = 1;
1697 /* Verify the length of the command itself */
1698 if (cmnd_size != common->cmnd_size) {
1700 /* Special case workaround: There are plenty of buggy SCSI
1701 * implementations. Many have issues with cbw->Length
1702 * field passing a wrong command size. For those cases we
1703 * always try to work around the problem by using the length
1704 * sent by the host side provided it is at least as large
1705 * as the correct command length.
1706 * Examples of such cases would be MS-Windows, which issues
1707 * REQUEST SENSE with cbw->Length == 12 where it should
1708 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1709 * REQUEST SENSE with cbw->Length == 10 where it should
1712 if (cmnd_size <= common->cmnd_size) {
1713 DBG(common, "%s is buggy! Expected length %d "
1714 "but we got %d\n", name,
1715 cmnd_size, common->cmnd_size);
1716 cmnd_size = common->cmnd_size;
1718 common->phase_error = 1;
1723 /* Check that the LUN values are consistent */
1724 if (common->lun != lun)
1725 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1729 if (common->lun >= 0 && common->lun < common->nluns) {
1730 curlun = &common->luns[common->lun];
1731 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1732 curlun->sense_data = SS_NO_SENSE;
1733 curlun->info_valid = 0;
1737 common->bad_lun_okay = 0;
1739 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1740 * to use unsupported LUNs; all others may not. */
1741 if (common->cmnd[0] != SC_INQUIRY &&
1742 common->cmnd[0] != SC_REQUEST_SENSE) {
1743 DBG(common, "unsupported LUN %d\n", common->lun);
1748 /* If a unit attention condition exists, only INQUIRY and
1749 * REQUEST SENSE commands are allowed; anything else must fail. */
1750 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1751 common->cmnd[0] != SC_INQUIRY &&
1752 common->cmnd[0] != SC_REQUEST_SENSE) {
1753 curlun->sense_data = curlun->unit_attention_data;
1754 curlun->unit_attention_data = SS_NO_SENSE;
1758 /* Check that only command bytes listed in the mask are non-zero */
1759 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1760 for (i = 1; i < cmnd_size; ++i) {
1761 if (common->cmnd[i] && !(mask & (1 << i))) {
1763 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1772 static int do_scsi_command(struct fsg_common *common)
1774 struct fsg_buffhd *bh;
1776 int reply = -EINVAL;
1778 static char unknown[16];
1779 struct fsg_lun *curlun = &common->luns[common->lun];
1783 /* Wait for the next buffer to become available for data or status */
1784 bh = common->next_buffhd_to_fill;
1785 common->next_buffhd_to_drain = bh;
1786 while (bh->state != BUF_STATE_EMPTY) {
1787 rc = sleep_thread(common);
1791 common->phase_error = 0;
1792 common->short_packet_received = 0;
1794 down_read(&common->filesem); /* We're using the backing file */
1795 switch (common->cmnd[0]) {
1798 common->data_size_from_cmnd = common->cmnd[4];
1799 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1803 reply = do_inquiry(common, bh);
1806 case SC_MODE_SELECT_6:
1807 common->data_size_from_cmnd = common->cmnd[4];
1808 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1812 reply = do_mode_select(common, bh);
1815 case SC_MODE_SELECT_10:
1816 common->data_size_from_cmnd =
1817 get_unaligned_be16(&common->cmnd[7]);
1818 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1822 reply = do_mode_select(common, bh);
1825 case SC_MODE_SENSE_6:
1826 common->data_size_from_cmnd = common->cmnd[4];
1827 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1828 (1<<1) | (1<<2) | (1<<4), 0,
1831 reply = do_mode_sense(common, bh);
1834 case SC_MODE_SENSE_10:
1835 common->data_size_from_cmnd =
1836 get_unaligned_be16(&common->cmnd[7]);
1837 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1838 (1<<1) | (1<<2) | (3<<7), 0,
1841 reply = do_mode_sense(common, bh);
1844 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1845 common->data_size_from_cmnd = 0;
1846 reply = check_command(common, 6, DATA_DIR_NONE,
1848 "PREVENT-ALLOW MEDIUM REMOVAL");
1850 reply = do_prevent_allow(common);
1854 i = common->cmnd[4];
1855 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1856 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1860 reply = do_read(common);
1864 common->data_size_from_cmnd =
1865 get_unaligned_be16(&common->cmnd[7]) << 9;
1866 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1867 (1<<1) | (0xf<<2) | (3<<7), 1,
1870 reply = do_read(common);
1874 common->data_size_from_cmnd =
1875 get_unaligned_be32(&common->cmnd[6]) << 9;
1876 reply = check_command(common, 12, DATA_DIR_TO_HOST,
1877 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1880 reply = do_read(common);
1883 case SC_READ_CAPACITY:
1884 common->data_size_from_cmnd = 8;
1885 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1886 (0xf<<2) | (1<<8), 1,
1889 reply = do_read_capacity(common, bh);
1892 case SC_READ_HEADER:
1893 if (!common->luns[common->lun].cdrom)
1895 common->data_size_from_cmnd =
1896 get_unaligned_be16(&common->cmnd[7]);
1897 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1898 (3<<7) | (0x1f<<1), 1,
1901 reply = do_read_header(common, bh);
1905 if (!common->luns[common->lun].cdrom)
1907 common->data_size_from_cmnd =
1908 get_unaligned_be16(&common->cmnd[7]);
1909 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1913 reply = do_read_toc(common, bh);
1916 case SC_READ_FORMAT_CAPACITIES:
1917 common->data_size_from_cmnd =
1918 get_unaligned_be16(&common->cmnd[7]);
1919 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1921 "READ FORMAT CAPACITIES");
1923 reply = do_read_format_capacities(common, bh);
1926 case SC_REQUEST_SENSE:
1927 common->data_size_from_cmnd = common->cmnd[4];
1928 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1932 reply = do_request_sense(common, bh);
1935 case SC_START_STOP_UNIT:
1936 common->data_size_from_cmnd = 0;
1937 reply = check_command(common, 6, DATA_DIR_NONE,
1941 reply = do_start_stop(common);
1944 case SC_SYNCHRONIZE_CACHE:
1945 common->data_size_from_cmnd = 0;
1946 reply = check_command(common, 10, DATA_DIR_NONE,
1947 (0xf<<2) | (3<<7), 1,
1948 "SYNCHRONIZE CACHE");
1950 reply = do_synchronize_cache(common);
1953 case SC_TEST_UNIT_READY:
1954 common->data_size_from_cmnd = 0;
1955 reply = check_command(common, 6, DATA_DIR_NONE,
1960 /* Although optional, this command is used by MS-Windows. We
1961 * support a minimal version: BytChk must be 0. */
1963 common->data_size_from_cmnd = 0;
1964 reply = check_command(common, 10, DATA_DIR_NONE,
1965 (1<<1) | (0xf<<2) | (3<<7), 1,
1968 reply = do_verify(common);
1972 i = common->cmnd[4];
1973 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1974 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1978 reply = do_write(common);
1982 common->data_size_from_cmnd =
1983 get_unaligned_be16(&common->cmnd[7]) << 9;
1984 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1985 (1<<1) | (0xf<<2) | (3<<7), 1,
1988 reply = do_write(common);
1992 common->data_size_from_cmnd =
1993 get_unaligned_be32(&common->cmnd[6]) << 9;
1994 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
1995 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1998 reply = do_write(common);
2001 /* Some mandatory commands that we recognize but don't implement.
2002 * They don't mean much in this setting. It's left as an exercise
2003 * for anyone interested to implement RESERVE and RELEASE in terms
2004 * of Posix locks. */
2005 case SC_FORMAT_UNIT:
2008 case SC_SEND_DIAGNOSTIC:
2013 common->data_size_from_cmnd = 0;
2014 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2015 reply = check_command(common, common->cmnd_size,
2016 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2018 curlun->sense_data = SS_INVALID_COMMAND;
2023 up_read(&common->filesem);
2025 if (reply == -EINTR)
2028 /* Set up the single reply buffer for finish_reply() */
2029 if (reply == -EINVAL)
2030 reply = 0; /* Error reply length */
2031 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2032 reply = min((u32) reply, common->data_size_from_cmnd);
2033 bh->inreq->length = reply;
2034 bh->state = BUF_STATE_FULL;
2035 common->residue -= reply;
2036 } /* Otherwise it's already set */
2041 /*-------------------------------------------------------------------------*/
2043 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2045 struct usb_request *req = bh->outreq;
2046 struct fsg_bulk_cb_wrap *cbw = req->buf;
2047 struct fsg_common *common = fsg->common;
2049 /* Was this a real packet? Should it be ignored? */
2050 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2053 /* Is the CBW valid? */
2054 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2055 cbw->Signature != cpu_to_le32(
2057 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2059 le32_to_cpu(cbw->Signature));
2061 /* The Bulk-only spec says we MUST stall the IN endpoint
2062 * (6.6.1), so it's unavoidable. It also says we must
2063 * retain this state until the next reset, but there's
2064 * no way to tell the controller driver it should ignore
2065 * Clear-Feature(HALT) requests.
2067 * We aren't required to halt the OUT endpoint; instead
2068 * we can simply accept and discard any data received
2069 * until the next reset. */
2070 wedge_bulk_in_endpoint(fsg);
2071 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2075 /* Is the CBW meaningful? */
2076 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2077 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2078 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2080 cbw->Lun, cbw->Flags, cbw->Length);
2082 /* We can do anything we want here, so let's stall the
2083 * bulk pipes if we are allowed to. */
2084 if (common->can_stall) {
2085 fsg_set_halt(fsg, fsg->bulk_out);
2086 halt_bulk_in_endpoint(fsg);
2091 /* Save the command for later */
2092 common->cmnd_size = cbw->Length;
2093 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2094 if (cbw->Flags & USB_BULK_IN_FLAG)
2095 common->data_dir = DATA_DIR_TO_HOST;
2097 common->data_dir = DATA_DIR_FROM_HOST;
2098 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2099 if (common->data_size == 0)
2100 common->data_dir = DATA_DIR_NONE;
2101 common->lun = cbw->Lun;
2102 common->tag = cbw->Tag;
2107 static int get_next_command(struct fsg_common *common)
2109 struct fsg_buffhd *bh;
2112 /* Wait for the next buffer to become available */
2113 bh = common->next_buffhd_to_fill;
2114 while (bh->state != BUF_STATE_EMPTY) {
2115 rc = sleep_thread(common);
2120 /* Queue a request to read a Bulk-only CBW */
2121 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2122 bh->outreq->short_not_ok = 1;
2123 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2124 &bh->outreq_busy, &bh->state)
2125 /* Don't know what to do if common->fsg is NULL */
2128 /* We will drain the buffer in software, which means we
2129 * can reuse it for the next filling. No need to advance
2130 * next_buffhd_to_fill. */
2132 /* Wait for the CBW to arrive */
2133 while (bh->state != BUF_STATE_FULL) {
2134 rc = sleep_thread(common);
2139 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2140 bh->state = BUF_STATE_EMPTY;
2146 /*-------------------------------------------------------------------------*/
2148 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2149 const struct usb_endpoint_descriptor *d)
2153 ep->driver_data = common;
2154 rc = usb_ep_enable(ep, d);
2156 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2160 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2161 struct usb_request **preq)
2163 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2166 ERROR(common, "can't allocate request for %s\n", ep->name);
2170 /* Reset interface setting and re-init endpoint state (toggle etc). */
2171 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2173 const struct usb_endpoint_descriptor *d;
2174 struct fsg_dev *fsg;
2177 if (common->running)
2178 DBG(common, "reset interface\n");
2181 /* Deallocate the requests */
2185 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2186 struct fsg_buffhd *bh = &common->buffhds[i];
2189 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2193 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2198 /* Disable the endpoints */
2199 if (fsg->bulk_in_enabled) {
2200 usb_ep_disable(fsg->bulk_in);
2201 fsg->bulk_in_enabled = 0;
2203 if (fsg->bulk_out_enabled) {
2204 usb_ep_disable(fsg->bulk_out);
2205 fsg->bulk_out_enabled = 0;
2209 /* wake_up(&common->fsg_wait); */
2212 common->running = 0;
2216 common->fsg = new_fsg;
2219 /* Enable the endpoints */
2220 d = fsg_ep_desc(common->gadget,
2221 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2222 rc = enable_endpoint(common, fsg->bulk_in, d);
2225 fsg->bulk_in_enabled = 1;
2227 d = fsg_ep_desc(common->gadget,
2228 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2229 rc = enable_endpoint(common, fsg->bulk_out, d);
2232 fsg->bulk_out_enabled = 1;
2233 common->bulk_out_maxpacket =
2234 le16_to_cpu(get_unaligned(&d->wMaxPacketSize));
2235 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2237 /* Allocate the requests */
2238 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2239 struct fsg_buffhd *bh = &common->buffhds[i];
2241 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2244 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2247 bh->inreq->buf = bh->outreq->buf = bh->buf;
2248 bh->inreq->context = bh->outreq->context = bh;
2249 bh->inreq->complete = bulk_in_complete;
2250 bh->outreq->complete = bulk_out_complete;
2253 common->running = 1;
2259 /****************************** ALT CONFIGS ******************************/
2262 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2264 struct fsg_dev *fsg = fsg_from_func(f);
2265 fsg->common->new_fsg = fsg;
2266 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2270 static void fsg_disable(struct usb_function *f)
2272 struct fsg_dev *fsg = fsg_from_func(f);
2273 fsg->common->new_fsg = NULL;
2274 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2277 /*-------------------------------------------------------------------------*/
2279 static void handle_exception(struct fsg_common *common)
2282 struct fsg_buffhd *bh;
2283 enum fsg_state old_state;
2284 struct fsg_lun *curlun;
2285 unsigned int exception_req_tag;
2287 /* Cancel all the pending transfers */
2289 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2290 bh = &common->buffhds[i];
2292 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2293 if (bh->outreq_busy)
2294 usb_ep_dequeue(common->fsg->bulk_out,
2298 /* Wait until everything is idle */
2301 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2302 bh = &common->buffhds[i];
2303 num_active += bh->inreq_busy + bh->outreq_busy;
2305 if (num_active == 0)
2307 if (sleep_thread(common))
2311 /* Clear out the controller's fifos */
2312 if (common->fsg->bulk_in_enabled)
2313 usb_ep_fifo_flush(common->fsg->bulk_in);
2314 if (common->fsg->bulk_out_enabled)
2315 usb_ep_fifo_flush(common->fsg->bulk_out);
2318 /* Reset the I/O buffer states and pointers, the SCSI
2319 * state, and the exception. Then invoke the handler. */
2321 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2322 bh = &common->buffhds[i];
2323 bh->state = BUF_STATE_EMPTY;
2325 common->next_buffhd_to_fill = &common->buffhds[0];
2326 common->next_buffhd_to_drain = &common->buffhds[0];
2327 exception_req_tag = common->exception_req_tag;
2328 old_state = common->state;
2330 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2331 common->state = FSG_STATE_STATUS_PHASE;
2333 for (i = 0; i < common->nluns; ++i) {
2334 curlun = &common->luns[i];
2335 curlun->sense_data = SS_NO_SENSE;
2336 curlun->info_valid = 0;
2338 common->state = FSG_STATE_IDLE;
2341 /* Carry out any extra actions required for the exception */
2342 switch (old_state) {
2343 case FSG_STATE_ABORT_BULK_OUT:
2344 send_status(common);
2346 if (common->state == FSG_STATE_STATUS_PHASE)
2347 common->state = FSG_STATE_IDLE;
2350 case FSG_STATE_RESET:
2351 /* In case we were forced against our will to halt a
2352 * bulk endpoint, clear the halt now. (The SuperH UDC
2353 * requires this.) */
2354 if (!fsg_is_set(common))
2356 if (test_and_clear_bit(IGNORE_BULK_OUT,
2357 &common->fsg->atomic_bitflags))
2358 usb_ep_clear_halt(common->fsg->bulk_in);
2360 if (common->ep0_req_tag == exception_req_tag)
2361 ep0_queue(common); /* Complete the status stage */
2365 case FSG_STATE_CONFIG_CHANGE:
2366 do_set_interface(common, common->new_fsg);
2369 case FSG_STATE_EXIT:
2370 case FSG_STATE_TERMINATED:
2371 do_set_interface(common, NULL); /* Free resources */
2372 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2375 case FSG_STATE_INTERFACE_CHANGE:
2376 case FSG_STATE_DISCONNECT:
2377 case FSG_STATE_COMMAND_PHASE:
2378 case FSG_STATE_DATA_PHASE:
2379 case FSG_STATE_STATUS_PHASE:
2380 case FSG_STATE_IDLE:
2385 /*-------------------------------------------------------------------------*/
2387 int fsg_main_thread(void *common_)
2389 struct fsg_common *common = the_fsg_common;
2392 if (exception_in_progress(common)) {
2393 handle_exception(common);
2397 if (!common->running) {
2398 sleep_thread(common);
2402 if (get_next_command(common))
2405 if (!exception_in_progress(common))
2406 common->state = FSG_STATE_DATA_PHASE;
2408 if (do_scsi_command(common) || finish_reply(common))
2411 if (!exception_in_progress(common))
2412 common->state = FSG_STATE_STATUS_PHASE;
2414 if (send_status(common))
2417 if (!exception_in_progress(common))
2418 common->state = FSG_STATE_IDLE;
2421 common->thread_task = NULL;
2426 static void fsg_common_release(struct kref *ref);
2428 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2429 struct usb_composite_dev *cdev)
2431 struct usb_gadget *gadget = cdev->gadget;
2432 struct fsg_buffhd *bh;
2433 struct fsg_lun *curlun;
2436 /* Find out how many LUNs there should be */
2438 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2439 printf("invalid number of LUNs: %u\n", nluns);
2440 return ERR_PTR(-EINVAL);
2445 common = calloc(sizeof *common, 1);
2447 return ERR_PTR(-ENOMEM);
2448 common->free_storage_on_release = 1;
2450 memset(common, 0, sizeof common);
2451 common->free_storage_on_release = 0;
2455 common->private_data = NULL;
2457 common->gadget = gadget;
2458 common->ep0 = gadget->ep0;
2459 common->ep0req = cdev->req;
2461 /* Maybe allocate device-global string IDs, and patch descriptors */
2462 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2463 rc = usb_string_id(cdev);
2464 if (unlikely(rc < 0))
2466 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2467 fsg_intf_desc.iInterface = rc;
2470 /* Create the LUNs, open their backing files, and register the
2471 * LUN devices in sysfs. */
2472 curlun = calloc(nluns, sizeof *curlun);
2477 common->nluns = nluns;
2479 for (i = 0; i < nluns; i++) {
2480 common->luns[i].removable = 1;
2482 rc = fsg_lun_open(&common->luns[i], "");
2488 /* Data buffers cyclic list */
2489 bh = common->buffhds;
2491 i = FSG_NUM_BUFFERS;
2492 goto buffhds_first_it;
2498 bh->outreq_busy = 0;
2499 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2500 if (unlikely(!bh->buf)) {
2505 bh->next = common->buffhds;
2507 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2510 "File-Store Gadget",
2513 /* Some peripheral controllers are known not to be able to
2514 * halt bulk endpoints correctly. If one of them is present,
2518 /* Tell the thread to start working */
2519 common->thread_task =
2520 kthread_create(fsg_main_thread, common,
2521 OR(cfg->thread_name, "file-storage"));
2522 if (IS_ERR(common->thread_task)) {
2523 rc = PTR_ERR(common->thread_task);
2529 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2530 INFO(common, "Number of LUNs=%d\n", common->nluns);
2535 common->nluns = i + 1;
2537 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2538 /* Call fsg_common_release() directly, ref might be not
2540 fsg_common_release(&common->ref);
2544 static void fsg_common_release(struct kref *ref)
2546 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2548 /* If the thread isn't already dead, tell it to exit now */
2549 if (common->state != FSG_STATE_TERMINATED) {
2550 raise_exception(common, FSG_STATE_EXIT);
2551 wait_for_completion(&common->thread_notifier);
2554 if (likely(common->luns)) {
2555 struct fsg_lun *lun = common->luns;
2556 unsigned i = common->nluns;
2558 /* In error recovery common->nluns may be zero. */
2559 for (; i; --i, ++lun)
2562 kfree(common->luns);
2566 struct fsg_buffhd *bh = common->buffhds;
2567 unsigned i = FSG_NUM_BUFFERS;
2570 } while (++bh, --i);
2573 if (common->free_storage_on_release)
2578 /*-------------------------------------------------------------------------*/
2581 * usb_copy_descriptors - copy a vector of USB descriptors
2582 * @src: null-terminated vector to copy
2583 * Context: initialization code, which may sleep
2585 * This makes a copy of a vector of USB descriptors. Its primary use
2586 * is to support usb_function objects which can have multiple copies,
2587 * each needing different descriptors. Functions may have static
2588 * tables of descriptors, which are used as templates and customized
2589 * with identifiers (for interfaces, strings, endpoints, and more)
2590 * as needed by a given function instance.
2592 struct usb_descriptor_header **
2593 usb_copy_descriptors(struct usb_descriptor_header **src)
2595 struct usb_descriptor_header **tmp;
2599 struct usb_descriptor_header **ret;
2601 /* count descriptors and their sizes; then add vector size */
2602 for (bytes = 0, n_desc = 0, tmp = src; *tmp; tmp++, n_desc++)
2603 bytes += (*tmp)->bLength;
2604 bytes += (n_desc + 1) * sizeof(*tmp);
2606 mem = kmalloc(bytes, GFP_KERNEL);
2610 /* fill in pointers starting at "tmp",
2611 * to descriptors copied starting at "mem";
2616 mem += (n_desc + 1) * sizeof(*tmp);
2618 memcpy(mem, *src, (*src)->bLength);
2621 mem += (*src)->bLength;
2629 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2631 struct fsg_dev *fsg = fsg_from_func(f);
2633 DBG(fsg, "unbind\n");
2634 if (fsg->common->fsg == fsg) {
2635 fsg->common->new_fsg = NULL;
2636 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2639 free(fsg->function.descriptors);
2640 free(fsg->function.hs_descriptors);
2644 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2646 struct fsg_dev *fsg = fsg_from_func(f);
2647 struct usb_gadget *gadget = c->cdev->gadget;
2650 fsg->gadget = gadget;
2653 i = usb_interface_id(c, f);
2656 fsg_intf_desc.bInterfaceNumber = i;
2657 fsg->interface_number = i;
2659 /* Find all the endpoints we will use */
2660 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2663 ep->driver_data = fsg->common; /* claim the endpoint */
2666 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2669 ep->driver_data = fsg->common; /* claim the endpoint */
2672 /* Copy descriptors */
2673 f->descriptors = usb_copy_descriptors(fsg_fs_function);
2674 if (unlikely(!f->descriptors))
2677 if (gadget_is_dualspeed(gadget)) {
2678 /* Assume endpoint addresses are the same for both speeds */
2679 fsg_hs_bulk_in_desc.bEndpointAddress =
2680 fsg_fs_bulk_in_desc.bEndpointAddress;
2681 fsg_hs_bulk_out_desc.bEndpointAddress =
2682 fsg_fs_bulk_out_desc.bEndpointAddress;
2683 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
2684 if (unlikely(!f->hs_descriptors)) {
2685 free(f->descriptors);
2692 ERROR(fsg, "unable to autoconfigure all endpoints\n");
2697 /****************************** ADD FUNCTION ******************************/
2699 static struct usb_gadget_strings *fsg_strings_array[] = {
2704 static int fsg_bind_config(struct usb_composite_dev *cdev,
2705 struct usb_configuration *c,
2706 struct fsg_common *common)
2708 struct fsg_dev *fsg;
2711 fsg = calloc(1, sizeof *fsg);
2714 fsg->function.name = FSG_DRIVER_DESC;
2715 fsg->function.strings = fsg_strings_array;
2716 fsg->function.bind = fsg_bind;
2717 fsg->function.unbind = fsg_unbind;
2718 fsg->function.setup = fsg_setup;
2719 fsg->function.set_alt = fsg_set_alt;
2720 fsg->function.disable = fsg_disable;
2722 fsg->common = common;
2724 /* Our caller holds a reference to common structure so we
2725 * don't have to be worry about it being freed until we return
2726 * from this function. So instead of incrementing counter now
2727 * and decrement in error recovery we increment it only when
2728 * call to usb_add_function() was successful. */
2730 rc = usb_add_function(c, &fsg->function);
2738 int fsg_add(struct usb_configuration *c)
2740 struct fsg_common *fsg_common;
2742 fsg_common = fsg_common_init(NULL, c->cdev);
2744 fsg_common->vendor_name = 0;
2745 fsg_common->product_name = 0;
2746 fsg_common->release = 0xffff;
2748 fsg_common->ops = NULL;
2749 fsg_common->private_data = NULL;
2751 the_fsg_common = fsg_common;
2753 return fsg_bind_config(c->cdev, c, fsg_common);
2756 int fsg_init(struct ums_board_info *ums)