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 */
249 #include <linux/err.h>
250 #include <linux/usb/ch9.h>
251 #include <linux/usb/gadget.h>
252 #include <usb_mass_storage.h>
254 #include <asm/unaligned.h>
255 #include <linux/usb/gadget.h>
256 #include <linux/usb/gadget.h>
257 #include <linux/usb/composite.h>
258 #include <usb/lin_gadget_compat.h>
261 /*------------------------------------------------------------------------*/
263 #define FSG_DRIVER_DESC "Mass Storage Function"
264 #define FSG_DRIVER_VERSION "2012/06/5"
266 static const char fsg_string_interface[] = "Mass Storage";
268 #define FSG_NO_INTR_EP 1
269 #define FSG_NO_DEVICE_STRINGS 1
271 #define FSG_NO_INTR_EP 1
273 #include "storage_common.c"
275 /*-------------------------------------------------------------------------*/
277 #define GFP_ATOMIC ((gfp_t) 0)
278 #define PAGE_CACHE_SHIFT 12
279 #define PAGE_CACHE_SIZE (1 << PAGE_CACHE_SHIFT)
280 #define kthread_create(...) __builtin_return_address(0)
281 #define wait_for_completion(...) do {} while (0)
283 struct kref {int x; };
284 struct completion {int x; };
286 inline void set_bit(int nr, volatile void *addr)
289 unsigned int *a = (unsigned int *) addr;
292 mask = 1 << (nr & 0x1f);
296 inline void clear_bit(int nr, volatile void *addr)
299 unsigned int *a = (unsigned int *) addr;
302 mask = 1 << (nr & 0x1f);
309 /* Data shared by all the FSG instances. */
311 struct usb_gadget *gadget;
312 struct fsg_dev *fsg, *new_fsg;
314 struct usb_ep *ep0; /* Copy of gadget->ep0 */
315 struct usb_request *ep0req; /* Copy of cdev->req */
316 unsigned int ep0_req_tag;
318 struct fsg_buffhd *next_buffhd_to_fill;
319 struct fsg_buffhd *next_buffhd_to_drain;
320 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
323 u8 cmnd[MAX_COMMAND_SIZE];
327 struct fsg_lun luns[FSG_MAX_LUNS];
329 unsigned int bulk_out_maxpacket;
330 enum fsg_state state; /* For exception handling */
331 unsigned int exception_req_tag;
333 enum data_direction data_dir;
335 u32 data_size_from_cmnd;
340 unsigned int can_stall:1;
341 unsigned int free_storage_on_release:1;
342 unsigned int phase_error:1;
343 unsigned int short_packet_received:1;
344 unsigned int bad_lun_okay:1;
345 unsigned int running:1;
347 int thread_wakeup_needed;
348 struct completion thread_notifier;
349 struct task_struct *thread_task;
351 /* Callback functions. */
352 const struct fsg_operations *ops;
353 /* Gadget's private data. */
356 const char *vendor_name; /* 8 characters or less */
357 const char *product_name; /* 16 characters or less */
360 /* Vendor (8 chars), product (16 chars), release (4
361 * hexadecimal digits) and NUL byte */
362 char inquiry_string[8 + 16 + 4 + 1];
369 struct fsg_lun_config {
370 const char *filename;
375 } luns[FSG_MAX_LUNS];
377 /* Callback functions. */
378 const struct fsg_operations *ops;
379 /* Gadget's private data. */
382 const char *vendor_name; /* 8 characters or less */
383 const char *product_name; /* 16 characters or less */
389 struct usb_function function;
390 struct usb_gadget *gadget; /* Copy of cdev->gadget */
391 struct fsg_common *common;
393 u16 interface_number;
395 unsigned int bulk_in_enabled:1;
396 unsigned int bulk_out_enabled:1;
398 unsigned long atomic_bitflags;
399 #define IGNORE_BULK_OUT 0
401 struct usb_ep *bulk_in;
402 struct usb_ep *bulk_out;
406 static inline int __fsg_is_set(struct fsg_common *common,
407 const char *func, unsigned line)
411 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
416 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
419 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
421 return container_of(f, struct fsg_dev, function);
425 typedef void (*fsg_routine_t)(struct fsg_dev *);
427 static int exception_in_progress(struct fsg_common *common)
429 return common->state > FSG_STATE_IDLE;
432 /* Make bulk-out requests be divisible by the maxpacket size */
433 static void set_bulk_out_req_length(struct fsg_common *common,
434 struct fsg_buffhd *bh, unsigned int length)
438 bh->bulk_out_intended_length = length;
439 rem = length % common->bulk_out_maxpacket;
441 length += common->bulk_out_maxpacket - rem;
442 bh->outreq->length = length;
445 /*-------------------------------------------------------------------------*/
447 static struct ums *ums;
448 static int ums_count;
449 static struct fsg_common *the_fsg_common;
451 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
455 if (ep == fsg->bulk_in)
457 else if (ep == fsg->bulk_out)
461 DBG(fsg, "%s set halt\n", name);
462 return usb_ep_set_halt(ep);
465 /*-------------------------------------------------------------------------*/
467 /* These routines may be called in process context or in_irq */
469 /* Caller must hold fsg->lock */
470 static void wakeup_thread(struct fsg_common *common)
472 common->thread_wakeup_needed = 1;
475 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
477 /* Do nothing if a higher-priority exception is already in progress.
478 * If a lower-or-equal priority exception is in progress, preempt it
479 * and notify the main thread by sending it a signal. */
480 if (common->state <= new_state) {
481 common->exception_req_tag = common->ep0_req_tag;
482 common->state = new_state;
483 common->thread_wakeup_needed = 1;
487 /*-------------------------------------------------------------------------*/
489 static int ep0_queue(struct fsg_common *common)
493 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
494 common->ep0->driver_data = common;
495 if (rc != 0 && rc != -ESHUTDOWN) {
496 /* We can't do much more than wait for a reset */
497 WARNING(common, "error in submission: %s --> %d\n",
498 common->ep0->name, rc);
503 /*-------------------------------------------------------------------------*/
505 /* Bulk and interrupt endpoint completion handlers.
506 * These always run in_irq. */
508 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
510 struct fsg_common *common = ep->driver_data;
511 struct fsg_buffhd *bh = req->context;
513 if (req->status || req->actual != req->length)
514 DBG(common, "%s --> %d, %u/%u\n", __func__,
515 req->status, req->actual, req->length);
516 if (req->status == -ECONNRESET) /* Request was cancelled */
517 usb_ep_fifo_flush(ep);
519 /* Hold the lock while we update the request and buffer states */
521 bh->state = BUF_STATE_EMPTY;
522 wakeup_thread(common);
525 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
527 struct fsg_common *common = ep->driver_data;
528 struct fsg_buffhd *bh = req->context;
530 dump_msg(common, "bulk-out", req->buf, req->actual);
531 if (req->status || req->actual != bh->bulk_out_intended_length)
532 DBG(common, "%s --> %d, %u/%u\n", __func__,
533 req->status, req->actual,
534 bh->bulk_out_intended_length);
535 if (req->status == -ECONNRESET) /* Request was cancelled */
536 usb_ep_fifo_flush(ep);
538 /* Hold the lock while we update the request and buffer states */
540 bh->state = BUF_STATE_FULL;
541 wakeup_thread(common);
544 /*-------------------------------------------------------------------------*/
546 /* Ep0 class-specific handlers. These always run in_irq. */
548 static int fsg_setup(struct usb_function *f,
549 const struct usb_ctrlrequest *ctrl)
551 struct fsg_dev *fsg = fsg_from_func(f);
552 struct usb_request *req = fsg->common->ep0req;
553 u16 w_index = get_unaligned_le16(&ctrl->wIndex);
554 u16 w_value = get_unaligned_le16(&ctrl->wValue);
555 u16 w_length = get_unaligned_le16(&ctrl->wLength);
557 if (!fsg_is_set(fsg->common))
560 switch (ctrl->bRequest) {
562 case USB_BULK_RESET_REQUEST:
563 if (ctrl->bRequestType !=
564 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
566 if (w_index != fsg->interface_number || w_value != 0)
569 /* Raise an exception to stop the current operation
570 * and reinitialize our state. */
571 DBG(fsg, "bulk reset request\n");
572 raise_exception(fsg->common, FSG_STATE_RESET);
573 return DELAYED_STATUS;
575 case USB_BULK_GET_MAX_LUN_REQUEST:
576 if (ctrl->bRequestType !=
577 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
579 if (w_index != fsg->interface_number || w_value != 0)
581 VDBG(fsg, "get max LUN\n");
582 *(u8 *) req->buf = fsg->common->nluns - 1;
584 /* Respond with data/status */
585 req->length = min((u16)1, w_length);
586 return ep0_queue(fsg->common);
590 "unknown class-specific control req "
591 "%02x.%02x v%04x i%04x l%u\n",
592 ctrl->bRequestType, ctrl->bRequest,
593 get_unaligned_le16(&ctrl->wValue), w_index, w_length);
597 /*-------------------------------------------------------------------------*/
599 /* All the following routines run in process context */
601 /* Use this for bulk or interrupt transfers, not ep0 */
602 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
603 struct usb_request *req, int *pbusy,
604 enum fsg_buffer_state *state)
608 if (ep == fsg->bulk_in)
609 dump_msg(fsg, "bulk-in", req->buf, req->length);
612 *state = BUF_STATE_BUSY;
613 rc = usb_ep_queue(ep, req, GFP_KERNEL);
616 *state = BUF_STATE_EMPTY;
618 /* We can't do much more than wait for a reset */
620 /* Note: currently the net2280 driver fails zero-length
621 * submissions if DMA is enabled. */
622 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
624 WARNING(fsg, "error in submission: %s --> %d\n",
629 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
630 if (fsg_is_set(common)) \
631 start_transfer((common)->fsg, (common)->fsg->ep_name, \
632 req, pbusy, state); \
635 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
636 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
638 static void busy_indicator(void)
666 static int sleep_thread(struct fsg_common *common)
671 /* Wait until a signal arrives or we are woken up */
673 if (common->thread_wakeup_needed)
687 /* Check cable connection */
688 if (!g_dnl_board_usb_cable_connected())
694 usb_gadget_handle_interrupts(0);
696 common->thread_wakeup_needed = 0;
700 /*-------------------------------------------------------------------------*/
702 static int do_read(struct fsg_common *common)
704 struct fsg_lun *curlun = &common->luns[common->lun];
706 struct fsg_buffhd *bh;
711 unsigned int partial_page;
714 /* Get the starting Logical Block Address and check that it's
716 if (common->cmnd[0] == SC_READ_6)
717 lba = get_unaligned_be24(&common->cmnd[1]);
719 lba = get_unaligned_be32(&common->cmnd[2]);
721 /* We allow DPO (Disable Page Out = don't save data in the
722 * cache) and FUA (Force Unit Access = don't read from the
723 * cache), but we don't implement them. */
724 if ((common->cmnd[1] & ~0x18) != 0) {
725 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
729 if (lba >= curlun->num_sectors) {
730 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
733 file_offset = ((loff_t) lba) << 9;
735 /* Carry out the file reads */
736 amount_left = common->data_size_from_cmnd;
737 if (unlikely(amount_left == 0))
738 return -EIO; /* No default reply */
742 /* Figure out how much we need to read:
743 * Try to read the remaining amount.
744 * But don't read more than the buffer size.
745 * And don't try to read past the end of the file.
746 * Finally, if we're not at a page boundary, don't read past
748 * If this means reading 0 then we were asked to read past
749 * the end of file. */
750 amount = min(amount_left, FSG_BUFLEN);
751 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
752 if (partial_page > 0)
753 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
756 /* Wait for the next buffer to become available */
757 bh = common->next_buffhd_to_fill;
758 while (bh->state != BUF_STATE_EMPTY) {
759 rc = sleep_thread(common);
764 /* If we were asked to read past the end of file,
765 * end with an empty buffer. */
768 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
769 curlun->info_valid = 1;
770 bh->inreq->length = 0;
771 bh->state = BUF_STATE_FULL;
775 /* Perform the read */
776 rc = ums[common->lun].read_sector(&ums[common->lun],
777 file_offset / SECTOR_SIZE,
778 amount / SECTOR_SIZE,
779 (char __user *)bh->buf);
783 nread = rc * SECTOR_SIZE;
785 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
786 (unsigned long long) file_offset,
790 LDBG(curlun, "error in file read: %d\n",
793 } else if (nread < amount) {
794 LDBG(curlun, "partial file read: %d/%u\n",
795 (int) nread, amount);
796 nread -= (nread & 511); /* Round down to a block */
798 file_offset += nread;
799 amount_left -= nread;
800 common->residue -= nread;
801 bh->inreq->length = nread;
802 bh->state = BUF_STATE_FULL;
804 /* If an error occurred, report it and its position */
805 if (nread < amount) {
806 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
807 curlun->info_valid = 1;
811 if (amount_left == 0)
812 break; /* No more left to read */
814 /* Send this buffer and go read some more */
816 START_TRANSFER_OR(common, bulk_in, bh->inreq,
817 &bh->inreq_busy, &bh->state)
818 /* Don't know what to do if
819 * common->fsg is NULL */
821 common->next_buffhd_to_fill = bh->next;
824 return -EIO; /* No default reply */
827 /*-------------------------------------------------------------------------*/
829 static int do_write(struct fsg_common *common)
831 struct fsg_lun *curlun = &common->luns[common->lun];
833 struct fsg_buffhd *bh;
835 u32 amount_left_to_req, amount_left_to_write;
836 loff_t usb_offset, file_offset;
838 unsigned int partial_page;
843 curlun->sense_data = SS_WRITE_PROTECTED;
847 /* Get the starting Logical Block Address and check that it's
849 if (common->cmnd[0] == SC_WRITE_6)
850 lba = get_unaligned_be24(&common->cmnd[1]);
852 lba = get_unaligned_be32(&common->cmnd[2]);
854 /* We allow DPO (Disable Page Out = don't save data in the
855 * cache) and FUA (Force Unit Access = write directly to the
856 * medium). We don't implement DPO; we implement FUA by
857 * performing synchronous output. */
858 if (common->cmnd[1] & ~0x18) {
859 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
863 if (lba >= curlun->num_sectors) {
864 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
868 /* Carry out the file writes */
870 file_offset = usb_offset = ((loff_t) lba) << 9;
871 amount_left_to_req = common->data_size_from_cmnd;
872 amount_left_to_write = common->data_size_from_cmnd;
874 while (amount_left_to_write > 0) {
876 /* Queue a request for more data from the host */
877 bh = common->next_buffhd_to_fill;
878 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
880 /* Figure out how much we want to get:
881 * Try to get the remaining amount.
882 * But don't get more than the buffer size.
883 * And don't try to go past the end of the file.
884 * If we're not at a page boundary,
885 * don't go past the next page.
886 * If this means getting 0, then we were asked
887 * to write past the end of file.
888 * Finally, round down to a block boundary. */
889 amount = min(amount_left_to_req, FSG_BUFLEN);
890 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
891 if (partial_page > 0)
893 (unsigned int) PAGE_CACHE_SIZE - partial_page);
898 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
899 curlun->info_valid = 1;
902 amount -= (amount & 511);
905 /* Why were we were asked to transfer a
911 /* Get the next buffer */
912 usb_offset += amount;
913 common->usb_amount_left -= amount;
914 amount_left_to_req -= amount;
915 if (amount_left_to_req == 0)
918 /* amount is always divisible by 512, hence by
919 * the bulk-out maxpacket size */
920 bh->outreq->length = amount;
921 bh->bulk_out_intended_length = amount;
922 bh->outreq->short_not_ok = 1;
923 START_TRANSFER_OR(common, bulk_out, bh->outreq,
924 &bh->outreq_busy, &bh->state)
925 /* Don't know what to do if
926 * common->fsg is NULL */
928 common->next_buffhd_to_fill = bh->next;
932 /* Write the received data to the backing file */
933 bh = common->next_buffhd_to_drain;
934 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
935 break; /* We stopped early */
936 if (bh->state == BUF_STATE_FULL) {
937 common->next_buffhd_to_drain = bh->next;
938 bh->state = BUF_STATE_EMPTY;
940 /* Did something go wrong with the transfer? */
941 if (bh->outreq->status != 0) {
942 curlun->sense_data = SS_COMMUNICATION_FAILURE;
943 curlun->info_valid = 1;
947 amount = bh->outreq->actual;
949 /* Perform the write */
950 rc = ums[common->lun].write_sector(&ums[common->lun],
951 file_offset / SECTOR_SIZE,
952 amount / SECTOR_SIZE,
953 (char __user *)bh->buf);
956 nwritten = rc * SECTOR_SIZE;
958 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
959 (unsigned long long) file_offset,
963 LDBG(curlun, "error in file write: %d\n",
966 } else if (nwritten < amount) {
967 LDBG(curlun, "partial file write: %d/%u\n",
968 (int) nwritten, amount);
969 nwritten -= (nwritten & 511);
970 /* Round down to a block */
972 file_offset += nwritten;
973 amount_left_to_write -= nwritten;
974 common->residue -= nwritten;
976 /* If an error occurred, report it and its position */
977 if (nwritten < amount) {
978 printf("nwritten:%zd amount:%u\n", nwritten,
980 curlun->sense_data = SS_WRITE_ERROR;
981 curlun->info_valid = 1;
985 /* Did the host decide to stop early? */
986 if (bh->outreq->actual != bh->outreq->length) {
987 common->short_packet_received = 1;
993 /* Wait for something to happen */
994 rc = sleep_thread(common);
999 return -EIO; /* No default reply */
1002 /*-------------------------------------------------------------------------*/
1004 static int do_synchronize_cache(struct fsg_common *common)
1009 /*-------------------------------------------------------------------------*/
1011 static int do_verify(struct fsg_common *common)
1013 struct fsg_lun *curlun = &common->luns[common->lun];
1015 u32 verification_length;
1016 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1019 unsigned int amount;
1023 /* Get the starting Logical Block Address and check that it's
1025 lba = get_unaligned_be32(&common->cmnd[2]);
1026 if (lba >= curlun->num_sectors) {
1027 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1031 /* We allow DPO (Disable Page Out = don't save data in the
1032 * cache) but we don't implement it. */
1033 if (common->cmnd[1] & ~0x10) {
1034 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1038 verification_length = get_unaligned_be16(&common->cmnd[7]);
1039 if (unlikely(verification_length == 0))
1040 return -EIO; /* No default reply */
1042 /* Prepare to carry out the file verify */
1043 amount_left = verification_length << 9;
1044 file_offset = ((loff_t) lba) << 9;
1046 /* Write out all the dirty buffers before invalidating them */
1048 /* Just try to read the requested blocks */
1049 while (amount_left > 0) {
1051 /* Figure out how much we need to read:
1052 * Try to read the remaining amount, but not more than
1054 * And don't try to read past the end of the file.
1055 * If this means reading 0 then we were asked to read
1056 * past the end of file. */
1057 amount = min(amount_left, FSG_BUFLEN);
1059 curlun->sense_data =
1060 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1061 curlun->info_valid = 1;
1065 /* Perform the read */
1066 rc = ums[common->lun].read_sector(&ums[common->lun],
1067 file_offset / SECTOR_SIZE,
1068 amount / SECTOR_SIZE,
1069 (char __user *)bh->buf);
1072 nread = rc * SECTOR_SIZE;
1074 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1075 (unsigned long long) file_offset,
1078 LDBG(curlun, "error in file verify: %d\n",
1081 } else if (nread < amount) {
1082 LDBG(curlun, "partial file verify: %d/%u\n",
1083 (int) nread, amount);
1084 nread -= (nread & 511); /* Round down to a sector */
1087 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1088 curlun->info_valid = 1;
1091 file_offset += nread;
1092 amount_left -= nread;
1097 /*-------------------------------------------------------------------------*/
1099 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1101 struct fsg_lun *curlun = &common->luns[common->lun];
1102 static const char vendor_id[] = "Linux ";
1103 u8 *buf = (u8 *) bh->buf;
1105 if (!curlun) { /* Unsupported LUNs are okay */
1106 common->bad_lun_okay = 1;
1108 buf[0] = 0x7f; /* Unsupported, no device-type */
1109 buf[4] = 31; /* Additional length */
1115 buf[1] = curlun->removable ? 0x80 : 0;
1116 buf[2] = 2; /* ANSI SCSI level 2 */
1117 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1118 buf[4] = 31; /* Additional length */
1119 /* No special options */
1120 sprintf((char *) (buf + 8), "%-8s%-16s%04x", (char*) vendor_id ,
1121 ums[common->lun].name, (u16) 0xffff);
1127 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1129 struct fsg_lun *curlun = &common->luns[common->lun];
1130 u8 *buf = (u8 *) bh->buf;
1135 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1137 * If a REQUEST SENSE command is received from an initiator
1138 * with a pending unit attention condition (before the target
1139 * generates the contingent allegiance condition), then the
1140 * target shall either:
1141 * a) report any pending sense data and preserve the unit
1142 * attention condition on the logical unit, or,
1143 * b) report the unit attention condition, may discard any
1144 * pending sense data, and clear the unit attention
1145 * condition on the logical unit for that initiator.
1147 * FSG normally uses option a); enable this code to use option b).
1150 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1151 curlun->sense_data = curlun->unit_attention_data;
1152 curlun->unit_attention_data = SS_NO_SENSE;
1156 if (!curlun) { /* Unsupported LUNs are okay */
1157 common->bad_lun_okay = 1;
1158 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1162 sd = curlun->sense_data;
1163 valid = curlun->info_valid << 7;
1164 curlun->sense_data = SS_NO_SENSE;
1165 curlun->info_valid = 0;
1169 buf[0] = valid | 0x70; /* Valid, current error */
1171 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1172 buf[7] = 18 - 8; /* Additional sense length */
1178 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1180 struct fsg_lun *curlun = &common->luns[common->lun];
1181 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1182 int pmi = common->cmnd[8];
1183 u8 *buf = (u8 *) bh->buf;
1185 /* Check the PMI and LBA fields */
1186 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1187 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1191 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1192 /* Max logical block */
1193 put_unaligned_be32(512, &buf[4]); /* Block length */
1197 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1199 struct fsg_lun *curlun = &common->luns[common->lun];
1200 int msf = common->cmnd[1] & 0x02;
1201 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1202 u8 *buf = (u8 *) bh->buf;
1204 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1205 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1208 if (lba >= curlun->num_sectors) {
1209 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1214 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1215 store_cdrom_address(&buf[4], msf, lba);
1220 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1222 struct fsg_lun *curlun = &common->luns[common->lun];
1223 int msf = common->cmnd[1] & 0x02;
1224 int start_track = common->cmnd[6];
1225 u8 *buf = (u8 *) bh->buf;
1227 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1229 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1234 buf[1] = (20-2); /* TOC data length */
1235 buf[2] = 1; /* First track number */
1236 buf[3] = 1; /* Last track number */
1237 buf[5] = 0x16; /* Data track, copying allowed */
1238 buf[6] = 0x01; /* Only track is number 1 */
1239 store_cdrom_address(&buf[8], msf, 0);
1241 buf[13] = 0x16; /* Lead-out track is data */
1242 buf[14] = 0xAA; /* Lead-out track number */
1243 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1248 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1250 struct fsg_lun *curlun = &common->luns[common->lun];
1251 int mscmnd = common->cmnd[0];
1252 u8 *buf = (u8 *) bh->buf;
1255 int changeable_values, all_pages;
1259 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1260 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1263 pc = common->cmnd[2] >> 6;
1264 page_code = common->cmnd[2] & 0x3f;
1266 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1269 changeable_values = (pc == 1);
1270 all_pages = (page_code == 0x3f);
1272 /* Write the mode parameter header. Fixed values are: default
1273 * medium type, no cache control (DPOFUA), and no block descriptors.
1274 * The only variable value is the WriteProtect bit. We will fill in
1275 * the mode data length later. */
1277 if (mscmnd == SC_MODE_SENSE_6) {
1278 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1281 } else { /* SC_MODE_SENSE_10 */
1282 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1284 limit = 65535; /* Should really be FSG_BUFLEN */
1287 /* No block descriptors */
1289 /* The mode pages, in numerical order. The only page we support
1290 * is the Caching page. */
1291 if (page_code == 0x08 || all_pages) {
1293 buf[0] = 0x08; /* Page code */
1294 buf[1] = 10; /* Page length */
1295 memset(buf+2, 0, 10); /* None of the fields are changeable */
1297 if (!changeable_values) {
1298 buf[2] = 0x04; /* Write cache enable, */
1299 /* Read cache not disabled */
1300 /* No cache retention priorities */
1301 put_unaligned_be16(0xffff, &buf[4]);
1302 /* Don't disable prefetch */
1303 /* Minimum prefetch = 0 */
1304 put_unaligned_be16(0xffff, &buf[8]);
1305 /* Maximum prefetch */
1306 put_unaligned_be16(0xffff, &buf[10]);
1307 /* Maximum prefetch ceiling */
1312 /* Check that a valid page was requested and the mode data length
1313 * isn't too long. */
1315 if (!valid_page || len > limit) {
1316 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1320 /* Store the mode data length */
1321 if (mscmnd == SC_MODE_SENSE_6)
1324 put_unaligned_be16(len - 2, buf0);
1329 static int do_start_stop(struct fsg_common *common)
1331 struct fsg_lun *curlun = &common->luns[common->lun];
1335 } else if (!curlun->removable) {
1336 curlun->sense_data = SS_INVALID_COMMAND;
1343 static int do_prevent_allow(struct fsg_common *common)
1345 struct fsg_lun *curlun = &common->luns[common->lun];
1348 if (!curlun->removable) {
1349 curlun->sense_data = SS_INVALID_COMMAND;
1353 prevent = common->cmnd[4] & 0x01;
1354 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1355 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1359 if (curlun->prevent_medium_removal && !prevent)
1360 fsg_lun_fsync_sub(curlun);
1361 curlun->prevent_medium_removal = prevent;
1366 static int do_read_format_capacities(struct fsg_common *common,
1367 struct fsg_buffhd *bh)
1369 struct fsg_lun *curlun = &common->luns[common->lun];
1370 u8 *buf = (u8 *) bh->buf;
1372 buf[0] = buf[1] = buf[2] = 0;
1373 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1376 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1377 /* Number of blocks */
1378 put_unaligned_be32(512, &buf[4]); /* Block length */
1379 buf[4] = 0x02; /* Current capacity */
1384 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1386 struct fsg_lun *curlun = &common->luns[common->lun];
1388 /* We don't support MODE SELECT */
1390 curlun->sense_data = SS_INVALID_COMMAND;
1395 /*-------------------------------------------------------------------------*/
1397 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1401 rc = fsg_set_halt(fsg, fsg->bulk_in);
1403 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1405 if (rc != -EAGAIN) {
1406 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1411 rc = usb_ep_set_halt(fsg->bulk_in);
1416 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1420 DBG(fsg, "bulk-in set wedge\n");
1421 rc = 0; /* usb_ep_set_wedge(fsg->bulk_in); */
1423 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1425 if (rc != -EAGAIN) {
1426 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1434 static int pad_with_zeros(struct fsg_dev *fsg)
1436 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1437 u32 nkeep = bh->inreq->length;
1441 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1442 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1443 while (fsg->common->usb_amount_left > 0) {
1445 /* Wait for the next buffer to be free */
1446 while (bh->state != BUF_STATE_EMPTY) {
1447 rc = sleep_thread(fsg->common);
1452 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1453 memset(bh->buf + nkeep, 0, nsend - nkeep);
1454 bh->inreq->length = nsend;
1455 bh->inreq->zero = 0;
1456 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1457 &bh->inreq_busy, &bh->state);
1458 bh = fsg->common->next_buffhd_to_fill = bh->next;
1459 fsg->common->usb_amount_left -= nsend;
1465 static int throw_away_data(struct fsg_common *common)
1467 struct fsg_buffhd *bh;
1471 for (bh = common->next_buffhd_to_drain;
1472 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1473 bh = common->next_buffhd_to_drain) {
1475 /* Throw away the data in a filled buffer */
1476 if (bh->state == BUF_STATE_FULL) {
1477 bh->state = BUF_STATE_EMPTY;
1478 common->next_buffhd_to_drain = bh->next;
1480 /* A short packet or an error ends everything */
1481 if (bh->outreq->actual != bh->outreq->length ||
1482 bh->outreq->status != 0) {
1483 raise_exception(common,
1484 FSG_STATE_ABORT_BULK_OUT);
1490 /* Try to submit another request if we need one */
1491 bh = common->next_buffhd_to_fill;
1492 if (bh->state == BUF_STATE_EMPTY
1493 && common->usb_amount_left > 0) {
1494 amount = min(common->usb_amount_left, FSG_BUFLEN);
1496 /* amount is always divisible by 512, hence by
1497 * the bulk-out maxpacket size */
1498 bh->outreq->length = amount;
1499 bh->bulk_out_intended_length = amount;
1500 bh->outreq->short_not_ok = 1;
1501 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1502 &bh->outreq_busy, &bh->state)
1503 /* Don't know what to do if
1504 * common->fsg is NULL */
1506 common->next_buffhd_to_fill = bh->next;
1507 common->usb_amount_left -= amount;
1511 /* Otherwise wait for something to happen */
1512 rc = sleep_thread(common);
1520 static int finish_reply(struct fsg_common *common)
1522 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1525 switch (common->data_dir) {
1527 break; /* Nothing to send */
1529 /* If we don't know whether the host wants to read or write,
1530 * this must be CB or CBI with an unknown command. We mustn't
1531 * try to send or receive any data. So stall both bulk pipes
1532 * if we can and wait for a reset. */
1533 case DATA_DIR_UNKNOWN:
1534 if (!common->can_stall) {
1536 } else if (fsg_is_set(common)) {
1537 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1538 rc = halt_bulk_in_endpoint(common->fsg);
1540 /* Don't know what to do if common->fsg is NULL */
1545 /* All but the last buffer of data must have already been sent */
1546 case DATA_DIR_TO_HOST:
1547 if (common->data_size == 0) {
1548 /* Nothing to send */
1550 /* If there's no residue, simply send the last buffer */
1551 } else if (common->residue == 0) {
1552 bh->inreq->zero = 0;
1553 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1554 &bh->inreq_busy, &bh->state)
1556 common->next_buffhd_to_fill = bh->next;
1558 /* For Bulk-only, if we're allowed to stall then send the
1559 * short packet and halt the bulk-in endpoint. If we can't
1560 * stall, pad out the remaining data with 0's. */
1561 } else if (common->can_stall) {
1562 bh->inreq->zero = 1;
1563 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1564 &bh->inreq_busy, &bh->state)
1565 /* Don't know what to do if
1566 * common->fsg is NULL */
1568 common->next_buffhd_to_fill = bh->next;
1570 rc = halt_bulk_in_endpoint(common->fsg);
1571 } else if (fsg_is_set(common)) {
1572 rc = pad_with_zeros(common->fsg);
1574 /* Don't know what to do if common->fsg is NULL */
1579 /* We have processed all we want from the data the host has sent.
1580 * There may still be outstanding bulk-out requests. */
1581 case DATA_DIR_FROM_HOST:
1582 if (common->residue == 0) {
1583 /* Nothing to receive */
1585 /* Did the host stop sending unexpectedly early? */
1586 } else if (common->short_packet_received) {
1587 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1590 /* We haven't processed all the incoming data. Even though
1591 * we may be allowed to stall, doing so would cause a race.
1592 * The controller may already have ACK'ed all the remaining
1593 * bulk-out packets, in which case the host wouldn't see a
1594 * STALL. Not realizing the endpoint was halted, it wouldn't
1595 * clear the halt -- leading to problems later on. */
1597 } else if (common->can_stall) {
1598 if (fsg_is_set(common))
1599 fsg_set_halt(common->fsg,
1600 common->fsg->bulk_out);
1601 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1605 /* We can't stall. Read in the excess data and throw it
1608 rc = throw_away_data(common);
1616 static int send_status(struct fsg_common *common)
1618 struct fsg_lun *curlun = &common->luns[common->lun];
1619 struct fsg_buffhd *bh;
1620 struct bulk_cs_wrap *csw;
1622 u8 status = USB_STATUS_PASS;
1625 /* Wait for the next buffer to become available */
1626 bh = common->next_buffhd_to_fill;
1627 while (bh->state != BUF_STATE_EMPTY) {
1628 rc = sleep_thread(common);
1634 sd = curlun->sense_data;
1635 else if (common->bad_lun_okay)
1638 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1640 if (common->phase_error) {
1641 DBG(common, "sending phase-error status\n");
1642 status = USB_STATUS_PHASE_ERROR;
1643 sd = SS_INVALID_COMMAND;
1644 } else if (sd != SS_NO_SENSE) {
1645 DBG(common, "sending command-failure status\n");
1646 status = USB_STATUS_FAIL;
1647 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1649 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1652 /* Store and send the Bulk-only CSW */
1653 csw = (void *)bh->buf;
1655 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1656 csw->Tag = common->tag;
1657 csw->Residue = cpu_to_le32(common->residue);
1658 csw->Status = status;
1660 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1661 bh->inreq->zero = 0;
1662 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1663 &bh->inreq_busy, &bh->state)
1664 /* Don't know what to do if common->fsg is NULL */
1667 common->next_buffhd_to_fill = bh->next;
1672 /*-------------------------------------------------------------------------*/
1674 /* Check whether the command is properly formed and whether its data size
1675 * and direction agree with the values we already have. */
1676 static int check_command(struct fsg_common *common, int cmnd_size,
1677 enum data_direction data_dir, unsigned int mask,
1678 int needs_medium, const char *name)
1681 int lun = common->cmnd[1] >> 5;
1682 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1684 struct fsg_lun *curlun;
1687 if (common->data_dir != DATA_DIR_UNKNOWN)
1688 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1690 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1691 name, cmnd_size, dirletter[(int) data_dir],
1692 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1694 /* We can't reply at all until we know the correct data direction
1696 if (common->data_size_from_cmnd == 0)
1697 data_dir = DATA_DIR_NONE;
1698 if (common->data_size < common->data_size_from_cmnd) {
1699 /* Host data size < Device data size is a phase error.
1700 * Carry out the command, but only transfer as much as
1701 * we are allowed. */
1702 common->data_size_from_cmnd = common->data_size;
1703 common->phase_error = 1;
1705 common->residue = common->data_size;
1706 common->usb_amount_left = common->data_size;
1708 /* Conflicting data directions is a phase error */
1709 if (common->data_dir != data_dir
1710 && common->data_size_from_cmnd > 0) {
1711 common->phase_error = 1;
1715 /* Verify the length of the command itself */
1716 if (cmnd_size != common->cmnd_size) {
1718 /* Special case workaround: There are plenty of buggy SCSI
1719 * implementations. Many have issues with cbw->Length
1720 * field passing a wrong command size. For those cases we
1721 * always try to work around the problem by using the length
1722 * sent by the host side provided it is at least as large
1723 * as the correct command length.
1724 * Examples of such cases would be MS-Windows, which issues
1725 * REQUEST SENSE with cbw->Length == 12 where it should
1726 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1727 * REQUEST SENSE with cbw->Length == 10 where it should
1730 if (cmnd_size <= common->cmnd_size) {
1731 DBG(common, "%s is buggy! Expected length %d "
1732 "but we got %d\n", name,
1733 cmnd_size, common->cmnd_size);
1734 cmnd_size = common->cmnd_size;
1736 common->phase_error = 1;
1741 /* Check that the LUN values are consistent */
1742 if (common->lun != lun)
1743 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1747 if (common->lun >= 0 && common->lun < common->nluns) {
1748 curlun = &common->luns[common->lun];
1749 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1750 curlun->sense_data = SS_NO_SENSE;
1751 curlun->info_valid = 0;
1755 common->bad_lun_okay = 0;
1757 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1758 * to use unsupported LUNs; all others may not. */
1759 if (common->cmnd[0] != SC_INQUIRY &&
1760 common->cmnd[0] != SC_REQUEST_SENSE) {
1761 DBG(common, "unsupported LUN %d\n", common->lun);
1766 /* If a unit attention condition exists, only INQUIRY and
1767 * REQUEST SENSE commands are allowed; anything else must fail. */
1768 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1769 common->cmnd[0] != SC_INQUIRY &&
1770 common->cmnd[0] != SC_REQUEST_SENSE) {
1771 curlun->sense_data = curlun->unit_attention_data;
1772 curlun->unit_attention_data = SS_NO_SENSE;
1776 /* Check that only command bytes listed in the mask are non-zero */
1777 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1778 for (i = 1; i < cmnd_size; ++i) {
1779 if (common->cmnd[i] && !(mask & (1 << i))) {
1781 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1790 static int do_scsi_command(struct fsg_common *common)
1792 struct fsg_buffhd *bh;
1794 int reply = -EINVAL;
1796 static char unknown[16];
1797 struct fsg_lun *curlun = &common->luns[common->lun];
1801 /* Wait for the next buffer to become available for data or status */
1802 bh = common->next_buffhd_to_fill;
1803 common->next_buffhd_to_drain = bh;
1804 while (bh->state != BUF_STATE_EMPTY) {
1805 rc = sleep_thread(common);
1809 common->phase_error = 0;
1810 common->short_packet_received = 0;
1812 down_read(&common->filesem); /* We're using the backing file */
1813 switch (common->cmnd[0]) {
1816 common->data_size_from_cmnd = common->cmnd[4];
1817 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1821 reply = do_inquiry(common, bh);
1824 case SC_MODE_SELECT_6:
1825 common->data_size_from_cmnd = common->cmnd[4];
1826 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1830 reply = do_mode_select(common, bh);
1833 case SC_MODE_SELECT_10:
1834 common->data_size_from_cmnd =
1835 get_unaligned_be16(&common->cmnd[7]);
1836 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1840 reply = do_mode_select(common, bh);
1843 case SC_MODE_SENSE_6:
1844 common->data_size_from_cmnd = common->cmnd[4];
1845 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1846 (1<<1) | (1<<2) | (1<<4), 0,
1849 reply = do_mode_sense(common, bh);
1852 case SC_MODE_SENSE_10:
1853 common->data_size_from_cmnd =
1854 get_unaligned_be16(&common->cmnd[7]);
1855 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1856 (1<<1) | (1<<2) | (3<<7), 0,
1859 reply = do_mode_sense(common, bh);
1862 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1863 common->data_size_from_cmnd = 0;
1864 reply = check_command(common, 6, DATA_DIR_NONE,
1866 "PREVENT-ALLOW MEDIUM REMOVAL");
1868 reply = do_prevent_allow(common);
1872 i = common->cmnd[4];
1873 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1874 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1878 reply = do_read(common);
1882 common->data_size_from_cmnd =
1883 get_unaligned_be16(&common->cmnd[7]) << 9;
1884 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1885 (1<<1) | (0xf<<2) | (3<<7), 1,
1888 reply = do_read(common);
1892 common->data_size_from_cmnd =
1893 get_unaligned_be32(&common->cmnd[6]) << 9;
1894 reply = check_command(common, 12, DATA_DIR_TO_HOST,
1895 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1898 reply = do_read(common);
1901 case SC_READ_CAPACITY:
1902 common->data_size_from_cmnd = 8;
1903 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1904 (0xf<<2) | (1<<8), 1,
1907 reply = do_read_capacity(common, bh);
1910 case SC_READ_HEADER:
1911 if (!common->luns[common->lun].cdrom)
1913 common->data_size_from_cmnd =
1914 get_unaligned_be16(&common->cmnd[7]);
1915 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1916 (3<<7) | (0x1f<<1), 1,
1919 reply = do_read_header(common, bh);
1923 if (!common->luns[common->lun].cdrom)
1925 common->data_size_from_cmnd =
1926 get_unaligned_be16(&common->cmnd[7]);
1927 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1931 reply = do_read_toc(common, bh);
1934 case SC_READ_FORMAT_CAPACITIES:
1935 common->data_size_from_cmnd =
1936 get_unaligned_be16(&common->cmnd[7]);
1937 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1939 "READ FORMAT CAPACITIES");
1941 reply = do_read_format_capacities(common, bh);
1944 case SC_REQUEST_SENSE:
1945 common->data_size_from_cmnd = common->cmnd[4];
1946 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1950 reply = do_request_sense(common, bh);
1953 case SC_START_STOP_UNIT:
1954 common->data_size_from_cmnd = 0;
1955 reply = check_command(common, 6, DATA_DIR_NONE,
1959 reply = do_start_stop(common);
1962 case SC_SYNCHRONIZE_CACHE:
1963 common->data_size_from_cmnd = 0;
1964 reply = check_command(common, 10, DATA_DIR_NONE,
1965 (0xf<<2) | (3<<7), 1,
1966 "SYNCHRONIZE CACHE");
1968 reply = do_synchronize_cache(common);
1971 case SC_TEST_UNIT_READY:
1972 common->data_size_from_cmnd = 0;
1973 reply = check_command(common, 6, DATA_DIR_NONE,
1978 /* Although optional, this command is used by MS-Windows. We
1979 * support a minimal version: BytChk must be 0. */
1981 common->data_size_from_cmnd = 0;
1982 reply = check_command(common, 10, DATA_DIR_NONE,
1983 (1<<1) | (0xf<<2) | (3<<7), 1,
1986 reply = do_verify(common);
1990 i = common->cmnd[4];
1991 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1992 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1996 reply = do_write(common);
2000 common->data_size_from_cmnd =
2001 get_unaligned_be16(&common->cmnd[7]) << 9;
2002 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2003 (1<<1) | (0xf<<2) | (3<<7), 1,
2006 reply = do_write(common);
2010 common->data_size_from_cmnd =
2011 get_unaligned_be32(&common->cmnd[6]) << 9;
2012 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2013 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2016 reply = do_write(common);
2019 /* Some mandatory commands that we recognize but don't implement.
2020 * They don't mean much in this setting. It's left as an exercise
2021 * for anyone interested to implement RESERVE and RELEASE in terms
2022 * of Posix locks. */
2023 case SC_FORMAT_UNIT:
2026 case SC_SEND_DIAGNOSTIC:
2031 common->data_size_from_cmnd = 0;
2032 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2033 reply = check_command(common, common->cmnd_size,
2034 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2036 curlun->sense_data = SS_INVALID_COMMAND;
2041 up_read(&common->filesem);
2043 if (reply == -EINTR)
2046 /* Set up the single reply buffer for finish_reply() */
2047 if (reply == -EINVAL)
2048 reply = 0; /* Error reply length */
2049 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2050 reply = min((u32) reply, common->data_size_from_cmnd);
2051 bh->inreq->length = reply;
2052 bh->state = BUF_STATE_FULL;
2053 common->residue -= reply;
2054 } /* Otherwise it's already set */
2059 /*-------------------------------------------------------------------------*/
2061 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2063 struct usb_request *req = bh->outreq;
2064 struct fsg_bulk_cb_wrap *cbw = req->buf;
2065 struct fsg_common *common = fsg->common;
2067 /* Was this a real packet? Should it be ignored? */
2068 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2071 /* Is the CBW valid? */
2072 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2073 cbw->Signature != cpu_to_le32(
2075 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2077 le32_to_cpu(cbw->Signature));
2079 /* The Bulk-only spec says we MUST stall the IN endpoint
2080 * (6.6.1), so it's unavoidable. It also says we must
2081 * retain this state until the next reset, but there's
2082 * no way to tell the controller driver it should ignore
2083 * Clear-Feature(HALT) requests.
2085 * We aren't required to halt the OUT endpoint; instead
2086 * we can simply accept and discard any data received
2087 * until the next reset. */
2088 wedge_bulk_in_endpoint(fsg);
2089 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2093 /* Is the CBW meaningful? */
2094 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2095 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2096 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2098 cbw->Lun, cbw->Flags, cbw->Length);
2100 /* We can do anything we want here, so let's stall the
2101 * bulk pipes if we are allowed to. */
2102 if (common->can_stall) {
2103 fsg_set_halt(fsg, fsg->bulk_out);
2104 halt_bulk_in_endpoint(fsg);
2109 /* Save the command for later */
2110 common->cmnd_size = cbw->Length;
2111 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2112 if (cbw->Flags & USB_BULK_IN_FLAG)
2113 common->data_dir = DATA_DIR_TO_HOST;
2115 common->data_dir = DATA_DIR_FROM_HOST;
2116 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2117 if (common->data_size == 0)
2118 common->data_dir = DATA_DIR_NONE;
2119 common->lun = cbw->Lun;
2120 common->tag = cbw->Tag;
2125 static int get_next_command(struct fsg_common *common)
2127 struct fsg_buffhd *bh;
2130 /* Wait for the next buffer to become available */
2131 bh = common->next_buffhd_to_fill;
2132 while (bh->state != BUF_STATE_EMPTY) {
2133 rc = sleep_thread(common);
2138 /* Queue a request to read a Bulk-only CBW */
2139 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2140 bh->outreq->short_not_ok = 1;
2141 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2142 &bh->outreq_busy, &bh->state)
2143 /* Don't know what to do if common->fsg is NULL */
2146 /* We will drain the buffer in software, which means we
2147 * can reuse it for the next filling. No need to advance
2148 * next_buffhd_to_fill. */
2150 /* Wait for the CBW to arrive */
2151 while (bh->state != BUF_STATE_FULL) {
2152 rc = sleep_thread(common);
2157 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2158 bh->state = BUF_STATE_EMPTY;
2164 /*-------------------------------------------------------------------------*/
2166 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2167 const struct usb_endpoint_descriptor *d)
2171 ep->driver_data = common;
2172 rc = usb_ep_enable(ep, d);
2174 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2178 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2179 struct usb_request **preq)
2181 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2184 ERROR(common, "can't allocate request for %s\n", ep->name);
2188 /* Reset interface setting and re-init endpoint state (toggle etc). */
2189 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2191 const struct usb_endpoint_descriptor *d;
2192 struct fsg_dev *fsg;
2195 if (common->running)
2196 DBG(common, "reset interface\n");
2199 /* Deallocate the requests */
2203 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2204 struct fsg_buffhd *bh = &common->buffhds[i];
2207 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2211 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2216 /* Disable the endpoints */
2217 if (fsg->bulk_in_enabled) {
2218 usb_ep_disable(fsg->bulk_in);
2219 fsg->bulk_in_enabled = 0;
2221 if (fsg->bulk_out_enabled) {
2222 usb_ep_disable(fsg->bulk_out);
2223 fsg->bulk_out_enabled = 0;
2227 /* wake_up(&common->fsg_wait); */
2230 common->running = 0;
2234 common->fsg = new_fsg;
2237 /* Enable the endpoints */
2238 d = fsg_ep_desc(common->gadget,
2239 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2240 rc = enable_endpoint(common, fsg->bulk_in, d);
2243 fsg->bulk_in_enabled = 1;
2245 d = fsg_ep_desc(common->gadget,
2246 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2247 rc = enable_endpoint(common, fsg->bulk_out, d);
2250 fsg->bulk_out_enabled = 1;
2251 common->bulk_out_maxpacket =
2252 le16_to_cpu(get_unaligned(&d->wMaxPacketSize));
2253 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2255 /* Allocate the requests */
2256 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2257 struct fsg_buffhd *bh = &common->buffhds[i];
2259 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2262 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2265 bh->inreq->buf = bh->outreq->buf = bh->buf;
2266 bh->inreq->context = bh->outreq->context = bh;
2267 bh->inreq->complete = bulk_in_complete;
2268 bh->outreq->complete = bulk_out_complete;
2271 common->running = 1;
2277 /****************************** ALT CONFIGS ******************************/
2280 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2282 struct fsg_dev *fsg = fsg_from_func(f);
2283 fsg->common->new_fsg = fsg;
2284 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2288 static void fsg_disable(struct usb_function *f)
2290 struct fsg_dev *fsg = fsg_from_func(f);
2291 fsg->common->new_fsg = NULL;
2292 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2295 /*-------------------------------------------------------------------------*/
2297 static void handle_exception(struct fsg_common *common)
2300 struct fsg_buffhd *bh;
2301 enum fsg_state old_state;
2302 struct fsg_lun *curlun;
2303 unsigned int exception_req_tag;
2305 /* Cancel all the pending transfers */
2307 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2308 bh = &common->buffhds[i];
2310 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2311 if (bh->outreq_busy)
2312 usb_ep_dequeue(common->fsg->bulk_out,
2316 /* Wait until everything is idle */
2319 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2320 bh = &common->buffhds[i];
2321 num_active += bh->inreq_busy + bh->outreq_busy;
2323 if (num_active == 0)
2325 if (sleep_thread(common))
2329 /* Clear out the controller's fifos */
2330 if (common->fsg->bulk_in_enabled)
2331 usb_ep_fifo_flush(common->fsg->bulk_in);
2332 if (common->fsg->bulk_out_enabled)
2333 usb_ep_fifo_flush(common->fsg->bulk_out);
2336 /* Reset the I/O buffer states and pointers, the SCSI
2337 * state, and the exception. Then invoke the handler. */
2339 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2340 bh = &common->buffhds[i];
2341 bh->state = BUF_STATE_EMPTY;
2343 common->next_buffhd_to_fill = &common->buffhds[0];
2344 common->next_buffhd_to_drain = &common->buffhds[0];
2345 exception_req_tag = common->exception_req_tag;
2346 old_state = common->state;
2348 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2349 common->state = FSG_STATE_STATUS_PHASE;
2351 for (i = 0; i < common->nluns; ++i) {
2352 curlun = &common->luns[i];
2353 curlun->sense_data = SS_NO_SENSE;
2354 curlun->info_valid = 0;
2356 common->state = FSG_STATE_IDLE;
2359 /* Carry out any extra actions required for the exception */
2360 switch (old_state) {
2361 case FSG_STATE_ABORT_BULK_OUT:
2362 send_status(common);
2364 if (common->state == FSG_STATE_STATUS_PHASE)
2365 common->state = FSG_STATE_IDLE;
2368 case FSG_STATE_RESET:
2369 /* In case we were forced against our will to halt a
2370 * bulk endpoint, clear the halt now. (The SuperH UDC
2371 * requires this.) */
2372 if (!fsg_is_set(common))
2374 if (test_and_clear_bit(IGNORE_BULK_OUT,
2375 &common->fsg->atomic_bitflags))
2376 usb_ep_clear_halt(common->fsg->bulk_in);
2378 if (common->ep0_req_tag == exception_req_tag)
2379 ep0_queue(common); /* Complete the status stage */
2383 case FSG_STATE_CONFIG_CHANGE:
2384 do_set_interface(common, common->new_fsg);
2387 case FSG_STATE_EXIT:
2388 case FSG_STATE_TERMINATED:
2389 do_set_interface(common, NULL); /* Free resources */
2390 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2393 case FSG_STATE_INTERFACE_CHANGE:
2394 case FSG_STATE_DISCONNECT:
2395 case FSG_STATE_COMMAND_PHASE:
2396 case FSG_STATE_DATA_PHASE:
2397 case FSG_STATE_STATUS_PHASE:
2398 case FSG_STATE_IDLE:
2403 /*-------------------------------------------------------------------------*/
2405 int fsg_main_thread(void *common_)
2408 struct fsg_common *common = the_fsg_common;
2411 if (exception_in_progress(common)) {
2412 handle_exception(common);
2416 if (!common->running) {
2417 ret = sleep_thread(common);
2424 ret = get_next_command(common);
2428 if (!exception_in_progress(common))
2429 common->state = FSG_STATE_DATA_PHASE;
2431 if (do_scsi_command(common) || finish_reply(common))
2434 if (!exception_in_progress(common))
2435 common->state = FSG_STATE_STATUS_PHASE;
2437 if (send_status(common))
2440 if (!exception_in_progress(common))
2441 common->state = FSG_STATE_IDLE;
2444 common->thread_task = NULL;
2449 static void fsg_common_release(struct kref *ref);
2451 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2452 struct usb_composite_dev *cdev)
2454 struct usb_gadget *gadget = cdev->gadget;
2455 struct fsg_buffhd *bh;
2456 struct fsg_lun *curlun;
2459 /* Find out how many LUNs there should be */
2461 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2462 printf("invalid number of LUNs: %u\n", nluns);
2463 return ERR_PTR(-EINVAL);
2468 common = calloc(sizeof(*common), 1);
2470 return ERR_PTR(-ENOMEM);
2471 common->free_storage_on_release = 1;
2473 memset(common, 0, sizeof(*common));
2474 common->free_storage_on_release = 0;
2478 common->private_data = NULL;
2480 common->gadget = gadget;
2481 common->ep0 = gadget->ep0;
2482 common->ep0req = cdev->req;
2484 /* Maybe allocate device-global string IDs, and patch descriptors */
2485 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2486 rc = usb_string_id(cdev);
2487 if (unlikely(rc < 0))
2489 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2490 fsg_intf_desc.iInterface = rc;
2493 /* Create the LUNs, open their backing files, and register the
2494 * LUN devices in sysfs. */
2495 curlun = calloc(nluns, sizeof *curlun);
2500 common->nluns = nluns;
2502 for (i = 0; i < nluns; i++) {
2503 common->luns[i].removable = 1;
2505 rc = fsg_lun_open(&common->luns[i], ums[i].num_sectors, "");
2511 /* Data buffers cyclic list */
2512 bh = common->buffhds;
2514 i = FSG_NUM_BUFFERS;
2515 goto buffhds_first_it;
2521 bh->outreq_busy = 0;
2522 bh->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, FSG_BUFLEN);
2523 if (unlikely(!bh->buf)) {
2528 bh->next = common->buffhds;
2530 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2533 "File-Store Gadget",
2536 /* Some peripheral controllers are known not to be able to
2537 * halt bulk endpoints correctly. If one of them is present,
2541 /* Tell the thread to start working */
2542 common->thread_task =
2543 kthread_create(fsg_main_thread, common,
2544 OR(cfg->thread_name, "file-storage"));
2545 if (IS_ERR(common->thread_task)) {
2546 rc = PTR_ERR(common->thread_task);
2552 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2553 INFO(common, "Number of LUNs=%d\n", common->nluns);
2558 common->nluns = i + 1;
2560 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2561 /* Call fsg_common_release() directly, ref might be not
2563 fsg_common_release(&common->ref);
2567 static void fsg_common_release(struct kref *ref)
2569 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2571 /* If the thread isn't already dead, tell it to exit now */
2572 if (common->state != FSG_STATE_TERMINATED) {
2573 raise_exception(common, FSG_STATE_EXIT);
2574 wait_for_completion(&common->thread_notifier);
2577 if (likely(common->luns)) {
2578 struct fsg_lun *lun = common->luns;
2579 unsigned i = common->nluns;
2581 /* In error recovery common->nluns may be zero. */
2582 for (; i; --i, ++lun)
2585 kfree(common->luns);
2589 struct fsg_buffhd *bh = common->buffhds;
2590 unsigned i = FSG_NUM_BUFFERS;
2593 } while (++bh, --i);
2596 if (common->free_storage_on_release)
2601 /*-------------------------------------------------------------------------*/
2604 * usb_copy_descriptors - copy a vector of USB descriptors
2605 * @src: null-terminated vector to copy
2606 * Context: initialization code, which may sleep
2608 * This makes a copy of a vector of USB descriptors. Its primary use
2609 * is to support usb_function objects which can have multiple copies,
2610 * each needing different descriptors. Functions may have static
2611 * tables of descriptors, which are used as templates and customized
2612 * with identifiers (for interfaces, strings, endpoints, and more)
2613 * as needed by a given function instance.
2615 struct usb_descriptor_header **
2616 usb_copy_descriptors(struct usb_descriptor_header **src)
2618 struct usb_descriptor_header **tmp;
2622 struct usb_descriptor_header **ret;
2624 /* count descriptors and their sizes; then add vector size */
2625 for (bytes = 0, n_desc = 0, tmp = src; *tmp; tmp++, n_desc++)
2626 bytes += (*tmp)->bLength;
2627 bytes += (n_desc + 1) * sizeof(*tmp);
2629 mem = memalign(CONFIG_SYS_CACHELINE_SIZE, bytes);
2633 /* fill in pointers starting at "tmp",
2634 * to descriptors copied starting at "mem";
2639 mem += (n_desc + 1) * sizeof(*tmp);
2641 memcpy(mem, *src, (*src)->bLength);
2644 mem += (*src)->bLength;
2652 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2654 struct fsg_dev *fsg = fsg_from_func(f);
2656 DBG(fsg, "unbind\n");
2657 if (fsg->common->fsg == fsg) {
2658 fsg->common->new_fsg = NULL;
2659 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2662 free(fsg->function.descriptors);
2663 free(fsg->function.hs_descriptors);
2667 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2669 struct fsg_dev *fsg = fsg_from_func(f);
2670 struct usb_gadget *gadget = c->cdev->gadget;
2673 fsg->gadget = gadget;
2676 i = usb_interface_id(c, f);
2679 fsg_intf_desc.bInterfaceNumber = i;
2680 fsg->interface_number = i;
2682 /* Find all the endpoints we will use */
2683 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2686 ep->driver_data = fsg->common; /* claim the endpoint */
2689 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2692 ep->driver_data = fsg->common; /* claim the endpoint */
2695 /* Copy descriptors */
2696 f->descriptors = usb_copy_descriptors(fsg_fs_function);
2697 if (unlikely(!f->descriptors))
2700 if (gadget_is_dualspeed(gadget)) {
2701 /* Assume endpoint addresses are the same for both speeds */
2702 fsg_hs_bulk_in_desc.bEndpointAddress =
2703 fsg_fs_bulk_in_desc.bEndpointAddress;
2704 fsg_hs_bulk_out_desc.bEndpointAddress =
2705 fsg_fs_bulk_out_desc.bEndpointAddress;
2706 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
2707 if (unlikely(!f->hs_descriptors)) {
2708 free(f->descriptors);
2715 ERROR(fsg, "unable to autoconfigure all endpoints\n");
2720 /****************************** ADD FUNCTION ******************************/
2722 static struct usb_gadget_strings *fsg_strings_array[] = {
2727 static int fsg_bind_config(struct usb_composite_dev *cdev,
2728 struct usb_configuration *c,
2729 struct fsg_common *common)
2731 struct fsg_dev *fsg;
2734 fsg = calloc(1, sizeof *fsg);
2737 fsg->function.name = FSG_DRIVER_DESC;
2738 fsg->function.strings = fsg_strings_array;
2739 fsg->function.bind = fsg_bind;
2740 fsg->function.unbind = fsg_unbind;
2741 fsg->function.setup = fsg_setup;
2742 fsg->function.set_alt = fsg_set_alt;
2743 fsg->function.disable = fsg_disable;
2745 fsg->common = common;
2747 /* Our caller holds a reference to common structure so we
2748 * don't have to be worry about it being freed until we return
2749 * from this function. So instead of incrementing counter now
2750 * and decrement in error recovery we increment it only when
2751 * call to usb_add_function() was successful. */
2753 rc = usb_add_function(c, &fsg->function);
2761 int fsg_add(struct usb_configuration *c)
2763 struct fsg_common *fsg_common;
2765 fsg_common = fsg_common_init(NULL, c->cdev);
2767 fsg_common->vendor_name = 0;
2768 fsg_common->product_name = 0;
2769 fsg_common->release = 0xffff;
2771 fsg_common->ops = NULL;
2772 fsg_common->private_data = NULL;
2774 the_fsg_common = fsg_common;
2776 return fsg_bind_config(c->cdev, c, fsg_common);
2779 int fsg_init(struct ums *ums_devs, int count)
2787 DECLARE_GADGET_BIND_CALLBACK(usb_dnl_ums, fsg_add);