GUI: Fix Tomato RAF theme for all builds. Compilation typo.
[tomato.git] / release / src-rt-6.x.4708 / linux / linux-2.6.36 / drivers / usb / gadget / f_mass_storage.c
blob28974d0cfad3a6498f0247ecfee81248ddb0d5b6
1 /*
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>
7 * All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions, and the following disclaimer,
14 * without modification.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. The names of the above-listed copyright holders may not be used
19 * to endorse or promote products derived from this software without
20 * specific prior written permission.
22 * ALTERNATIVELY, this software may be distributed under the terms of the
23 * GNU General Public License ("GPL") as published by the Free Software
24 * Foundation, either version 2 of that License or (at your option) any
25 * later version.
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
28 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
31 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
33 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
34 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
35 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
36 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
37 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 * The Mass Storage Function acts as a USB Mass Storage device,
43 * appearing to the host as a disk drive or as a CD-ROM drive. In
44 * addition to providing an example of a genuinely useful composite
45 * function for a USB device, it also illustrates a technique of
46 * double-buffering for increased throughput.
48 * Function supports multiple logical units (LUNs). Backing storage
49 * for each LUN is provided by a regular file or a block device.
50 * Access for each LUN can be limited to read-only. Moreover, the
51 * function can indicate that LUN is removable and/or CD-ROM. (The
52 * later implies read-only access.)
54 * MSF is configured by specifying a fsg_config structure. It has the
55 * following fields:
57 * nluns Number of LUNs function have (anywhere from 1
58 * to FSG_MAX_LUNS which is 8).
59 * luns An array of LUN configuration values. This
60 * should be filled for each LUN that
61 * function will include (ie. for "nluns"
62 * LUNs). Each element of the array has
63 * the following fields:
64 * ->filename The path to the backing file for the LUN.
65 * Required if LUN is not marked as
66 * removable.
67 * ->ro Flag specifying access to the LUN shall be
68 * read-only. This is implied if CD-ROM
69 * emulation is enabled as well as when
70 * it was impossible to open "filename"
71 * in R/W mode.
72 * ->removable Flag specifying that LUN shall be indicated as
73 * being removable.
74 * ->cdrom Flag specifying that LUN shall be reported as
75 * being a CD-ROM.
77 * lun_name_format A printf-like format for names of the LUN
78 * devices. This determines how the
79 * directory in sysfs will be named.
80 * Unless you are using several MSFs in
81 * a single gadget (as opposed to single
82 * MSF in many configurations) you may
83 * leave it as NULL (in which case
84 * "lun%d" will be used). In the format
85 * you can use "%d" to index LUNs for
86 * MSF's with more than one LUN. (Beware
87 * that there is only one integer given
88 * as an argument for the format and
89 * specifying invalid format may cause
90 * unspecified behaviour.)
91 * thread_name Name of the kernel thread process used by the
92 * MSF. You can safely set it to NULL
93 * (in which case default "file-storage"
94 * will be used).
96 * vendor_name
97 * product_name
98 * release Information used as a reply to INQUIRY
99 * request. To use default set to NULL,
100 * NULL, 0xffff respectively. The first
101 * field should be 8 and the second 16
102 * characters or less.
104 * can_stall Set to permit function to halt bulk endpoints.
105 * Disabled on some USB devices known not
106 * to work correctly. You should set it
107 * to true.
109 * If "removable" is not set for a LUN then a backing file must be
110 * specified. If it is set, then NULL filename means the LUN's medium
111 * is not loaded (an empty string as "filename" in the fsg_config
112 * structure causes error). The CD-ROM emulation includes a single
113 * data track and no audio tracks; hence there need be only one
114 * backing file per LUN. Note also that the CD-ROM block length is
115 * set to 512 rather than the more common value 2048.
118 * MSF includes support for module parameters. If gadget using it
119 * decides to use it, the following module parameters will be
120 * available:
122 * file=filename[,filename...]
123 * Names of the files or block devices used for
124 * backing storage.
125 * ro=b[,b...] Default false, boolean for read-only access.
126 * removable=b[,b...]
127 * Default true, boolean for removable media.
128 * cdrom=b[,b...] Default false, boolean for whether to emulate
129 * a CD-ROM drive.
130 * luns=N Default N = number of filenames, number of
131 * LUNs to support.
132 * stall Default determined according to the type of
133 * USB device controller (usually true),
134 * boolean to permit the driver to halt
135 * bulk endpoints.
137 * The module parameters may be prefixed with some string. You need
138 * to consult gadget's documentation or source to verify whether it is
139 * using those module parameters and if it does what are the prefixes
140 * (look for FSG_MODULE_PARAMETERS() macro usage, what's inside it is
141 * the prefix).
144 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
145 * needed. The memory requirement amounts to two 16K buffers, size
146 * configurable by a parameter. Support is included for both
147 * full-speed and high-speed operation.
149 * Note that the driver is slightly non-portable in that it assumes a
150 * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
151 * interrupt-in endpoints. With most device controllers this isn't an
152 * issue, but there may be some with hardware restrictions that prevent
153 * a buffer from being used by more than one endpoint.
156 * The pathnames of the backing files and the ro settings are
157 * available in the attribute files "file" and "ro" in the lun<n> (or
158 * to be more precise in a directory which name comes from
159 * "lun_name_format" option!) subdirectory of the gadget's sysfs
160 * directory. If the "removable" option is set, writing to these
161 * files will simulate ejecting/loading the medium (writing an empty
162 * line means eject) and adjusting a write-enable tab. Changes to the
163 * ro setting are not allowed when the medium is loaded or if CD-ROM
164 * emulation is being used.
166 * When a LUN receive an "eject" SCSI request (Start/Stop Unit),
167 * if the LUN is removable, the backing file is released to simulate
168 * ejection.
171 * This function is heavily based on "File-backed Storage Gadget" by
172 * Alan Stern which in turn is heavily based on "Gadget Zero" by David
173 * Brownell. The driver's SCSI command interface was based on the
174 * "Information technology - Small Computer System Interface - 2"
175 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
176 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
177 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
178 * was based on the "Universal Serial Bus Mass Storage Class UFI
179 * Command Specification" document, Revision 1.0, December 14, 1998,
180 * available at
181 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
186 * Driver Design
188 * The MSF is fairly straightforward. There is a main kernel
189 * thread that handles most of the work. Interrupt routines field
190 * callbacks from the controller driver: bulk- and interrupt-request
191 * completion notifications, endpoint-0 events, and disconnect events.
192 * Completion events are passed to the main thread by wakeup calls. Many
193 * ep0 requests are handled at interrupt time, but SetInterface,
194 * SetConfiguration, and device reset requests are forwarded to the
195 * thread in the form of "exceptions" using SIGUSR1 signals (since they
196 * should interrupt any ongoing file I/O operations).
198 * The thread's main routine implements the standard command/data/status
199 * parts of a SCSI interaction. It and its subroutines are full of tests
200 * for pending signals/exceptions -- all this polling is necessary since
201 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
202 * indication that the driver really wants to be running in userspace.)
203 * An important point is that so long as the thread is alive it keeps an
204 * open reference to the backing file. This will prevent unmounting
205 * the backing file's underlying filesystem and could cause problems
206 * during system shutdown, for example. To prevent such problems, the
207 * thread catches INT, TERM, and KILL signals and converts them into
208 * an EXIT exception.
210 * In normal operation the main thread is started during the gadget's
211 * fsg_bind() callback and stopped during fsg_unbind(). But it can
212 * also exit when it receives a signal, and there's no point leaving
213 * the gadget running when the thread is dead. At of this moment, MSF
214 * provides no way to deregister the gadget when thread dies -- maybe
215 * a callback functions is needed.
217 * To provide maximum throughput, the driver uses a circular pipeline of
218 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
219 * arbitrarily long; in practice the benefits don't justify having more
220 * than 2 stages (i.e., double buffering). But it helps to think of the
221 * pipeline as being a long one. Each buffer head contains a bulk-in and
222 * a bulk-out request pointer (since the buffer can be used for both
223 * output and input -- directions always are given from the host's
224 * point of view) as well as a pointer to the buffer and various state
225 * variables.
227 * Use of the pipeline follows a simple protocol. There is a variable
228 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
229 * At any time that buffer head may still be in use from an earlier
230 * request, so each buffer head has a state variable indicating whether
231 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
232 * buffer head to be EMPTY, filling the buffer either by file I/O or by
233 * USB I/O (during which the buffer head is BUSY), and marking the buffer
234 * head FULL when the I/O is complete. Then the buffer will be emptied
235 * (again possibly by USB I/O, during which it is marked BUSY) and
236 * finally marked EMPTY again (possibly by a completion routine).
238 * A module parameter tells the driver to avoid stalling the bulk
239 * endpoints wherever the transport specification allows. This is
240 * necessary for some UDCs like the SuperH, which cannot reliably clear a
241 * halt on a bulk endpoint. However, under certain circumstances the
242 * Bulk-only specification requires a stall. In such cases the driver
243 * will halt the endpoint and set a flag indicating that it should clear
244 * the halt in software during the next device reset. Hopefully this
245 * will permit everything to work correctly. Furthermore, although the
246 * specification allows the bulk-out endpoint to halt when the host sends
247 * too much data, implementing this would cause an unavoidable race.
248 * The driver will always use the "no-stall" approach for OUT transfers.
250 * One subtle point concerns sending status-stage responses for ep0
251 * requests. Some of these requests, such as device reset, can involve
252 * interrupting an ongoing file I/O operation, which might take an
253 * arbitrarily long time. During that delay the host might give up on
254 * the original ep0 request and issue a new one. When that happens the
255 * driver should not notify the host about completion of the original
256 * request, as the host will no longer be waiting for it. So the driver
257 * assigns to each ep0 request a unique tag, and it keeps track of the
258 * tag value of the request associated with a long-running exception
259 * (device-reset, interface-change, or configuration-change). When the
260 * exception handler is finished, the status-stage response is submitted
261 * only if the current ep0 request tag is equal to the exception request
262 * tag. Thus only the most recently received ep0 request will get a
263 * status-stage response.
265 * Warning: This driver source file is too long. It ought to be split up
266 * into a header file plus about 3 separate .c files, to handle the details
267 * of the Gadget, USB Mass Storage, and SCSI protocols.
271 /* #define VERBOSE_DEBUG */
272 /* #define DUMP_MSGS */
275 #include <linux/blkdev.h>
276 #include <linux/completion.h>
277 #include <linux/dcache.h>
278 #include <linux/delay.h>
279 #include <linux/device.h>
280 #include <linux/fcntl.h>
281 #include <linux/file.h>
282 #include <linux/fs.h>
283 #include <linux/kref.h>
284 #include <linux/kthread.h>
285 #include <linux/limits.h>
286 #include <linux/rwsem.h>
287 #include <linux/slab.h>
288 #include <linux/spinlock.h>
289 #include <linux/string.h>
290 #include <linux/freezer.h>
291 #include <linux/utsname.h>
293 #include <linux/usb/ch9.h>
294 #include <linux/usb/gadget.h>
296 #include "gadget_chips.h"
300 /*------------------------------------------------------------------------*/
302 #define FSG_DRIVER_DESC "Mass Storage Function"
303 #define FSG_DRIVER_VERSION "2009/09/11"
305 static const char fsg_string_interface[] = "Mass Storage";
308 #define FSG_NO_INTR_EP 1
309 #define FSG_NO_DEVICE_STRINGS 1
310 #define FSG_NO_OTG 1
311 #define FSG_NO_INTR_EP 1
313 #include "storage_common.c"
316 /*-------------------------------------------------------------------------*/
318 struct fsg_dev;
319 struct fsg_common;
321 /* FSF callback functions */
322 struct fsg_operations {
323 /* Callback function to call when thread exits. If no
324 * callback is set or it returns value lower then zero MSF
325 * will force eject all LUNs it operates on (including those
326 * marked as non-removable or with prevent_medium_removal flag
327 * set). */
328 int (*thread_exits)(struct fsg_common *common);
330 /* Called prior to ejection. Negative return means error,
331 * zero means to continue with ejection, positive means not to
332 * eject. */
333 int (*pre_eject)(struct fsg_common *common,
334 struct fsg_lun *lun, int num);
335 /* Called after ejection. Negative return means error, zero
336 * or positive is just a success. */
337 int (*post_eject)(struct fsg_common *common,
338 struct fsg_lun *lun, int num);
342 /* Data shared by all the FSG instances. */
343 struct fsg_common {
344 struct usb_gadget *gadget;
345 struct fsg_dev *fsg, *new_fsg;
346 wait_queue_head_t fsg_wait;
348 /* filesem protects: backing files in use */
349 struct rw_semaphore filesem;
351 /* lock protects: state, all the req_busy's */
352 spinlock_t lock;
354 struct usb_ep *ep0; /* Copy of gadget->ep0 */
355 struct usb_request *ep0req; /* Copy of cdev->req */
356 unsigned int ep0_req_tag;
358 struct fsg_buffhd *next_buffhd_to_fill;
359 struct fsg_buffhd *next_buffhd_to_drain;
360 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
362 int cmnd_size;
363 u8 cmnd[MAX_COMMAND_SIZE];
365 unsigned int nluns;
366 unsigned int lun;
367 struct fsg_lun *luns;
368 struct fsg_lun *curlun;
370 unsigned int bulk_out_maxpacket;
371 enum fsg_state state; /* For exception handling */
372 unsigned int exception_req_tag;
374 enum data_direction data_dir;
375 u32 data_size;
376 u32 data_size_from_cmnd;
377 u32 tag;
378 u32 residue;
379 u32 usb_amount_left;
381 unsigned int can_stall:1;
382 unsigned int free_storage_on_release:1;
383 unsigned int phase_error:1;
384 unsigned int short_packet_received:1;
385 unsigned int bad_lun_okay:1;
386 unsigned int running:1;
388 int thread_wakeup_needed;
389 struct completion thread_notifier;
390 struct task_struct *thread_task;
392 /* Callback functions. */
393 const struct fsg_operations *ops;
394 /* Gadget's private data. */
395 void *private_data;
397 /* Vendor (8 chars), product (16 chars), release (4
398 * hexadecimal digits) and NUL byte */
399 char inquiry_string[8 + 16 + 4 + 1];
401 struct kref ref;
405 struct fsg_config {
406 unsigned nluns;
407 struct fsg_lun_config {
408 const char *filename;
409 char ro;
410 char removable;
411 char cdrom;
412 } luns[FSG_MAX_LUNS];
414 const char *lun_name_format;
415 const char *thread_name;
417 /* Callback functions. */
418 const struct fsg_operations *ops;
419 /* Gadget's private data. */
420 void *private_data;
422 const char *vendor_name; /* 8 characters or less */
423 const char *product_name; /* 16 characters or less */
424 u16 release;
426 char can_stall;
430 struct fsg_dev {
431 struct usb_function function;
432 struct usb_gadget *gadget; /* Copy of cdev->gadget */
433 struct fsg_common *common;
435 u16 interface_number;
437 unsigned int bulk_in_enabled:1;
438 unsigned int bulk_out_enabled:1;
440 unsigned long atomic_bitflags;
441 #define IGNORE_BULK_OUT 0
443 struct usb_ep *bulk_in;
444 struct usb_ep *bulk_out;
448 static inline int __fsg_is_set(struct fsg_common *common,
449 const char *func, unsigned line)
451 if (common->fsg)
452 return 1;
453 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
454 WARN_ON(1);
455 return 0;
458 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
461 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
463 return container_of(f, struct fsg_dev, function);
467 typedef void (*fsg_routine_t)(struct fsg_dev *);
469 static int exception_in_progress(struct fsg_common *common)
471 return common->state > FSG_STATE_IDLE;
474 /* Make bulk-out requests be divisible by the maxpacket size */
475 static void set_bulk_out_req_length(struct fsg_common *common,
476 struct fsg_buffhd *bh, unsigned int length)
478 unsigned int rem;
480 bh->bulk_out_intended_length = length;
481 rem = length % common->bulk_out_maxpacket;
482 if (rem > 0)
483 length += common->bulk_out_maxpacket - rem;
484 bh->outreq->length = length;
487 /*-------------------------------------------------------------------------*/
489 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
491 const char *name;
493 if (ep == fsg->bulk_in)
494 name = "bulk-in";
495 else if (ep == fsg->bulk_out)
496 name = "bulk-out";
497 else
498 name = ep->name;
499 DBG(fsg, "%s set halt\n", name);
500 return usb_ep_set_halt(ep);
504 /*-------------------------------------------------------------------------*/
506 /* These routines may be called in process context or in_irq */
508 /* Caller must hold fsg->lock */
509 static void wakeup_thread(struct fsg_common *common)
511 /* Tell the main thread that something has happened */
512 common->thread_wakeup_needed = 1;
513 if (common->thread_task)
514 wake_up_process(common->thread_task);
518 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
520 unsigned long flags;
522 /* Do nothing if a higher-priority exception is already in progress.
523 * If a lower-or-equal priority exception is in progress, preempt it
524 * and notify the main thread by sending it a signal. */
525 spin_lock_irqsave(&common->lock, flags);
526 if (common->state <= new_state) {
527 common->exception_req_tag = common->ep0_req_tag;
528 common->state = new_state;
529 if (common->thread_task)
530 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
531 common->thread_task);
533 spin_unlock_irqrestore(&common->lock, flags);
537 /*-------------------------------------------------------------------------*/
539 static int ep0_queue(struct fsg_common *common)
541 int rc;
543 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
544 common->ep0->driver_data = common;
545 if (rc != 0 && rc != -ESHUTDOWN) {
546 /* We can't do much more than wait for a reset */
547 WARNING(common, "error in submission: %s --> %d\n",
548 common->ep0->name, rc);
550 return rc;
553 /*-------------------------------------------------------------------------*/
555 /* Bulk and interrupt endpoint completion handlers.
556 * These always run in_irq. */
558 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
560 struct fsg_common *common = ep->driver_data;
561 struct fsg_buffhd *bh = req->context;
563 if (req->status || req->actual != req->length)
564 DBG(common, "%s --> %d, %u/%u\n", __func__,
565 req->status, req->actual, req->length);
566 if (req->status == -ECONNRESET) /* Request was cancelled */
567 usb_ep_fifo_flush(ep);
569 /* Hold the lock while we update the request and buffer states */
570 smp_wmb();
571 spin_lock(&common->lock);
572 bh->inreq_busy = 0;
573 bh->state = BUF_STATE_EMPTY;
574 wakeup_thread(common);
575 spin_unlock(&common->lock);
578 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
580 struct fsg_common *common = ep->driver_data;
581 struct fsg_buffhd *bh = req->context;
583 dump_msg(common, "bulk-out", req->buf, req->actual);
584 if (req->status || req->actual != bh->bulk_out_intended_length)
585 DBG(common, "%s --> %d, %u/%u\n", __func__,
586 req->status, req->actual,
587 bh->bulk_out_intended_length);
588 if (req->status == -ECONNRESET) /* Request was cancelled */
589 usb_ep_fifo_flush(ep);
591 /* Hold the lock while we update the request and buffer states */
592 smp_wmb();
593 spin_lock(&common->lock);
594 bh->outreq_busy = 0;
595 bh->state = BUF_STATE_FULL;
596 wakeup_thread(common);
597 spin_unlock(&common->lock);
601 /*-------------------------------------------------------------------------*/
603 /* Ep0 class-specific handlers. These always run in_irq. */
605 static int fsg_setup(struct usb_function *f,
606 const struct usb_ctrlrequest *ctrl)
608 struct fsg_dev *fsg = fsg_from_func(f);
609 struct usb_request *req = fsg->common->ep0req;
610 u16 w_index = le16_to_cpu(ctrl->wIndex);
611 u16 w_value = le16_to_cpu(ctrl->wValue);
612 u16 w_length = le16_to_cpu(ctrl->wLength);
614 if (!fsg_is_set(fsg->common))
615 return -EOPNOTSUPP;
617 switch (ctrl->bRequest) {
619 case USB_BULK_RESET_REQUEST:
620 if (ctrl->bRequestType !=
621 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
622 break;
623 if (w_index != fsg->interface_number || w_value != 0)
624 return -EDOM;
626 /* Raise an exception to stop the current operation
627 * and reinitialize our state. */
628 DBG(fsg, "bulk reset request\n");
629 raise_exception(fsg->common, FSG_STATE_RESET);
630 return DELAYED_STATUS;
632 case USB_BULK_GET_MAX_LUN_REQUEST:
633 if (ctrl->bRequestType !=
634 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
635 break;
636 if (w_index != fsg->interface_number || w_value != 0)
637 return -EDOM;
638 VDBG(fsg, "get max LUN\n");
639 *(u8 *) req->buf = fsg->common->nluns - 1;
641 /* Respond with data/status */
642 req->length = min((u16)1, w_length);
643 return ep0_queue(fsg->common);
646 VDBG(fsg,
647 "unknown class-specific control req "
648 "%02x.%02x v%04x i%04x l%u\n",
649 ctrl->bRequestType, ctrl->bRequest,
650 le16_to_cpu(ctrl->wValue), w_index, w_length);
651 return -EOPNOTSUPP;
655 /*-------------------------------------------------------------------------*/
657 /* All the following routines run in process context */
660 /* Use this for bulk or interrupt transfers, not ep0 */
661 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
662 struct usb_request *req, int *pbusy,
663 enum fsg_buffer_state *state)
665 int rc;
667 if (ep == fsg->bulk_in)
668 dump_msg(fsg, "bulk-in", req->buf, req->length);
670 spin_lock_irq(&fsg->common->lock);
671 *pbusy = 1;
672 *state = BUF_STATE_BUSY;
673 spin_unlock_irq(&fsg->common->lock);
674 rc = usb_ep_queue(ep, req, GFP_KERNEL);
675 if (rc != 0) {
676 *pbusy = 0;
677 *state = BUF_STATE_EMPTY;
679 /* We can't do much more than wait for a reset */
681 /* Note: currently the net2280 driver fails zero-length
682 * submissions if DMA is enabled. */
683 if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
684 req->length == 0))
685 WARNING(fsg, "error in submission: %s --> %d\n",
686 ep->name, rc);
690 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state) \
691 if (fsg_is_set(common)) \
692 start_transfer((common)->fsg, (common)->fsg->ep_name, \
693 req, pbusy, state); \
694 else
696 #define START_TRANSFER(common, ep_name, req, pbusy, state) \
697 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
701 static int sleep_thread(struct fsg_common *common)
703 int rc = 0;
705 /* Wait until a signal arrives or we are woken up */
706 for (;;) {
707 try_to_freeze();
708 set_current_state(TASK_INTERRUPTIBLE);
709 if (signal_pending(current)) {
710 rc = -EINTR;
711 break;
713 if (common->thread_wakeup_needed)
714 break;
715 schedule();
717 __set_current_state(TASK_RUNNING);
718 common->thread_wakeup_needed = 0;
719 return rc;
723 /*-------------------------------------------------------------------------*/
725 static int do_read(struct fsg_common *common)
727 struct fsg_lun *curlun = common->curlun;
728 u32 lba;
729 struct fsg_buffhd *bh;
730 int rc;
731 u32 amount_left;
732 loff_t file_offset, file_offset_tmp;
733 unsigned int amount;
734 unsigned int partial_page;
735 ssize_t nread;
737 /* Get the starting Logical Block Address and check that it's
738 * not too big */
739 if (common->cmnd[0] == SC_READ_6)
740 lba = get_unaligned_be24(&common->cmnd[1]);
741 else {
742 lba = get_unaligned_be32(&common->cmnd[2]);
744 /* We allow DPO (Disable Page Out = don't save data in the
745 * cache) and FUA (Force Unit Access = don't read from the
746 * cache), but we don't implement them. */
747 if ((common->cmnd[1] & ~0x18) != 0) {
748 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
749 return -EINVAL;
752 if (lba >= curlun->num_sectors) {
753 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
754 return -EINVAL;
756 file_offset = ((loff_t) lba) << 9;
758 /* Carry out the file reads */
759 amount_left = common->data_size_from_cmnd;
760 if (unlikely(amount_left == 0))
761 return -EIO; /* No default reply */
763 for (;;) {
765 /* Figure out how much we need to read:
766 * Try to read the remaining amount.
767 * But don't read more than the buffer size.
768 * And don't try to read past the end of the file.
769 * Finally, if we're not at a page boundary, don't read past
770 * the next page.
771 * If this means reading 0 then we were asked to read past
772 * the end of file. */
773 amount = min(amount_left, FSG_BUFLEN);
774 amount = min((loff_t) amount,
775 curlun->file_length - file_offset);
776 partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
777 if (partial_page > 0)
778 amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
779 partial_page);
781 /* Wait for the next buffer to become available */
782 bh = common->next_buffhd_to_fill;
783 while (bh->state != BUF_STATE_EMPTY) {
784 rc = sleep_thread(common);
785 if (rc)
786 return rc;
789 /* If we were asked to read past the end of file,
790 * end with an empty buffer. */
791 if (amount == 0) {
792 curlun->sense_data =
793 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
794 curlun->sense_data_info = file_offset >> 9;
795 curlun->info_valid = 1;
796 bh->inreq->length = 0;
797 bh->state = BUF_STATE_FULL;
798 break;
801 /* Perform the read */
802 file_offset_tmp = file_offset;
803 nread = vfs_read(curlun->filp,
804 (char __user *) bh->buf,
805 amount, &file_offset_tmp);
806 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
807 (unsigned long long) file_offset,
808 (int) nread);
809 if (signal_pending(current))
810 return -EINTR;
812 if (nread < 0) {
813 LDBG(curlun, "error in file read: %d\n",
814 (int) nread);
815 nread = 0;
816 } else if (nread < amount) {
817 LDBG(curlun, "partial file read: %d/%u\n",
818 (int) nread, amount);
819 nread -= (nread & 511); /* Round down to a block */
821 file_offset += nread;
822 amount_left -= nread;
823 common->residue -= nread;
824 bh->inreq->length = nread;
825 bh->state = BUF_STATE_FULL;
827 /* If an error occurred, report it and its position */
828 if (nread < amount) {
829 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
830 curlun->sense_data_info = file_offset >> 9;
831 curlun->info_valid = 1;
832 break;
835 if (amount_left == 0)
836 break; /* No more left to read */
838 /* Send this buffer and go read some more */
839 bh->inreq->zero = 0;
840 START_TRANSFER_OR(common, bulk_in, bh->inreq,
841 &bh->inreq_busy, &bh->state)
842 /* Don't know what to do if
843 * common->fsg is NULL */
844 return -EIO;
845 common->next_buffhd_to_fill = bh->next;
848 return -EIO; /* No default reply */
852 /*-------------------------------------------------------------------------*/
854 static int do_write(struct fsg_common *common)
856 struct fsg_lun *curlun = common->curlun;
857 u32 lba;
858 struct fsg_buffhd *bh;
859 int get_some_more;
860 u32 amount_left_to_req, amount_left_to_write;
861 loff_t usb_offset, file_offset, file_offset_tmp;
862 unsigned int amount;
863 unsigned int partial_page;
864 ssize_t nwritten;
865 int rc;
867 if (curlun->ro) {
868 curlun->sense_data = SS_WRITE_PROTECTED;
869 return -EINVAL;
871 spin_lock(&curlun->filp->f_lock);
872 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
873 spin_unlock(&curlun->filp->f_lock);
875 /* Get the starting Logical Block Address and check that it's
876 * not too big */
877 if (common->cmnd[0] == SC_WRITE_6)
878 lba = get_unaligned_be24(&common->cmnd[1]);
879 else {
880 lba = get_unaligned_be32(&common->cmnd[2]);
882 /* We allow DPO (Disable Page Out = don't save data in the
883 * cache) and FUA (Force Unit Access = write directly to the
884 * medium). We don't implement DPO; we implement FUA by
885 * performing synchronous output. */
886 if (common->cmnd[1] & ~0x18) {
887 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
888 return -EINVAL;
890 if (common->cmnd[1] & 0x08) { /* FUA */
891 spin_lock(&curlun->filp->f_lock);
892 curlun->filp->f_flags |= O_SYNC;
893 spin_unlock(&curlun->filp->f_lock);
896 if (lba >= curlun->num_sectors) {
897 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
898 return -EINVAL;
901 /* Carry out the file writes */
902 get_some_more = 1;
903 file_offset = usb_offset = ((loff_t) lba) << 9;
904 amount_left_to_req = common->data_size_from_cmnd;
905 amount_left_to_write = common->data_size_from_cmnd;
907 while (amount_left_to_write > 0) {
909 /* Queue a request for more data from the host */
910 bh = common->next_buffhd_to_fill;
911 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
913 /* Figure out how much we want to get:
914 * Try to get the remaining amount.
915 * But don't get more than the buffer size.
916 * And don't try to go past the end of the file.
917 * If we're not at a page boundary,
918 * don't go past the next page.
919 * If this means getting 0, then we were asked
920 * to write past the end of file.
921 * Finally, round down to a block boundary. */
922 amount = min(amount_left_to_req, FSG_BUFLEN);
923 amount = min((loff_t) amount, curlun->file_length -
924 usb_offset);
925 partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
926 if (partial_page > 0)
927 amount = min(amount,
928 (unsigned int) PAGE_CACHE_SIZE - partial_page);
930 if (amount == 0) {
931 get_some_more = 0;
932 curlun->sense_data =
933 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
934 curlun->sense_data_info = usb_offset >> 9;
935 curlun->info_valid = 1;
936 continue;
938 amount -= (amount & 511);
939 if (amount == 0) {
941 /* Why were we were asked to transfer a
942 * partial block? */
943 get_some_more = 0;
944 continue;
947 /* Get the next buffer */
948 usb_offset += amount;
949 common->usb_amount_left -= amount;
950 amount_left_to_req -= amount;
951 if (amount_left_to_req == 0)
952 get_some_more = 0;
954 /* amount is always divisible by 512, hence by
955 * the bulk-out maxpacket size */
956 bh->outreq->length = amount;
957 bh->bulk_out_intended_length = amount;
958 bh->outreq->short_not_ok = 1;
959 START_TRANSFER_OR(common, bulk_out, bh->outreq,
960 &bh->outreq_busy, &bh->state)
961 /* Don't know what to do if
962 * common->fsg is NULL */
963 return -EIO;
964 common->next_buffhd_to_fill = bh->next;
965 continue;
968 /* Write the received data to the backing file */
969 bh = common->next_buffhd_to_drain;
970 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
971 break; /* We stopped early */
972 if (bh->state == BUF_STATE_FULL) {
973 smp_rmb();
974 common->next_buffhd_to_drain = bh->next;
975 bh->state = BUF_STATE_EMPTY;
977 /* Did something go wrong with the transfer? */
978 if (bh->outreq->status != 0) {
979 curlun->sense_data = SS_COMMUNICATION_FAILURE;
980 curlun->sense_data_info = file_offset >> 9;
981 curlun->info_valid = 1;
982 break;
985 amount = bh->outreq->actual;
986 if (curlun->file_length - file_offset < amount) {
987 LERROR(curlun,
988 "write %u @ %llu beyond end %llu\n",
989 amount, (unsigned long long) file_offset,
990 (unsigned long long) curlun->file_length);
991 amount = curlun->file_length - file_offset;
994 /* Perform the write */
995 file_offset_tmp = file_offset;
996 nwritten = vfs_write(curlun->filp,
997 (char __user *) bh->buf,
998 amount, &file_offset_tmp);
999 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
1000 (unsigned long long) file_offset,
1001 (int) nwritten);
1002 if (signal_pending(current))
1003 return -EINTR; /* Interrupted! */
1005 if (nwritten < 0) {
1006 LDBG(curlun, "error in file write: %d\n",
1007 (int) nwritten);
1008 nwritten = 0;
1009 } else if (nwritten < amount) {
1010 LDBG(curlun, "partial file write: %d/%u\n",
1011 (int) nwritten, amount);
1012 nwritten -= (nwritten & 511);
1013 /* Round down to a block */
1015 file_offset += nwritten;
1016 amount_left_to_write -= nwritten;
1017 common->residue -= nwritten;
1019 /* If an error occurred, report it and its position */
1020 if (nwritten < amount) {
1021 curlun->sense_data = SS_WRITE_ERROR;
1022 curlun->sense_data_info = file_offset >> 9;
1023 curlun->info_valid = 1;
1024 break;
1027 /* Did the host decide to stop early? */
1028 if (bh->outreq->actual != bh->outreq->length) {
1029 common->short_packet_received = 1;
1030 break;
1032 continue;
1035 /* Wait for something to happen */
1036 rc = sleep_thread(common);
1037 if (rc)
1038 return rc;
1041 return -EIO; /* No default reply */
1045 /*-------------------------------------------------------------------------*/
1047 static int do_synchronize_cache(struct fsg_common *common)
1049 struct fsg_lun *curlun = common->curlun;
1050 int rc;
1052 /* We ignore the requested LBA and write out all file's
1053 * dirty data buffers. */
1054 rc = fsg_lun_fsync_sub(curlun);
1055 if (rc)
1056 curlun->sense_data = SS_WRITE_ERROR;
1057 return 0;
1061 /*-------------------------------------------------------------------------*/
1063 static void invalidate_sub(struct fsg_lun *curlun)
1065 struct file *filp = curlun->filp;
1066 struct inode *inode = filp->f_path.dentry->d_inode;
1067 unsigned long rc;
1069 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
1070 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
1073 static int do_verify(struct fsg_common *common)
1075 struct fsg_lun *curlun = common->curlun;
1076 u32 lba;
1077 u32 verification_length;
1078 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1079 loff_t file_offset, file_offset_tmp;
1080 u32 amount_left;
1081 unsigned int amount;
1082 ssize_t nread;
1084 /* Get the starting Logical Block Address and check that it's
1085 * not too big */
1086 lba = get_unaligned_be32(&common->cmnd[2]);
1087 if (lba >= curlun->num_sectors) {
1088 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1089 return -EINVAL;
1092 /* We allow DPO (Disable Page Out = don't save data in the
1093 * cache) but we don't implement it. */
1094 if (common->cmnd[1] & ~0x10) {
1095 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1096 return -EINVAL;
1099 verification_length = get_unaligned_be16(&common->cmnd[7]);
1100 if (unlikely(verification_length == 0))
1101 return -EIO; /* No default reply */
1103 /* Prepare to carry out the file verify */
1104 amount_left = verification_length << 9;
1105 file_offset = ((loff_t) lba) << 9;
1107 /* Write out all the dirty buffers before invalidating them */
1108 fsg_lun_fsync_sub(curlun);
1109 if (signal_pending(current))
1110 return -EINTR;
1112 invalidate_sub(curlun);
1113 if (signal_pending(current))
1114 return -EINTR;
1116 /* Just try to read the requested blocks */
1117 while (amount_left > 0) {
1119 /* Figure out how much we need to read:
1120 * Try to read the remaining amount, but not more than
1121 * the buffer size.
1122 * And don't try to read past the end of the file.
1123 * If this means reading 0 then we were asked to read
1124 * past the end of file. */
1125 amount = min(amount_left, FSG_BUFLEN);
1126 amount = min((loff_t) amount,
1127 curlun->file_length - file_offset);
1128 if (amount == 0) {
1129 curlun->sense_data =
1130 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1131 curlun->sense_data_info = file_offset >> 9;
1132 curlun->info_valid = 1;
1133 break;
1136 /* Perform the read */
1137 file_offset_tmp = file_offset;
1138 nread = vfs_read(curlun->filp,
1139 (char __user *) bh->buf,
1140 amount, &file_offset_tmp);
1141 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1142 (unsigned long long) file_offset,
1143 (int) nread);
1144 if (signal_pending(current))
1145 return -EINTR;
1147 if (nread < 0) {
1148 LDBG(curlun, "error in file verify: %d\n",
1149 (int) nread);
1150 nread = 0;
1151 } else if (nread < amount) {
1152 LDBG(curlun, "partial file verify: %d/%u\n",
1153 (int) nread, amount);
1154 nread -= (nread & 511); /* Round down to a sector */
1156 if (nread == 0) {
1157 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1158 curlun->sense_data_info = file_offset >> 9;
1159 curlun->info_valid = 1;
1160 break;
1162 file_offset += nread;
1163 amount_left -= nread;
1165 return 0;
1169 /*-------------------------------------------------------------------------*/
1171 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1173 struct fsg_lun *curlun = common->curlun;
1174 u8 *buf = (u8 *) bh->buf;
1176 if (!curlun) { /* Unsupported LUNs are okay */
1177 common->bad_lun_okay = 1;
1178 memset(buf, 0, 36);
1179 buf[0] = 0x7f; /* Unsupported, no device-type */
1180 buf[4] = 31; /* Additional length */
1181 return 36;
1184 buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1185 buf[1] = curlun->removable ? 0x80 : 0;
1186 buf[2] = 2; /* ANSI SCSI level 2 */
1187 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1188 buf[4] = 31; /* Additional length */
1189 buf[5] = 0; /* No special options */
1190 buf[6] = 0;
1191 buf[7] = 0;
1192 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1193 return 36;
1197 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1199 struct fsg_lun *curlun = common->curlun;
1200 u8 *buf = (u8 *) bh->buf;
1201 u32 sd, sdinfo;
1202 int valid;
1205 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1207 * If a REQUEST SENSE command is received from an initiator
1208 * with a pending unit attention condition (before the target
1209 * generates the contingent allegiance condition), then the
1210 * target shall either:
1211 * a) report any pending sense data and preserve the unit
1212 * attention condition on the logical unit, or,
1213 * b) report the unit attention condition, may discard any
1214 * pending sense data, and clear the unit attention
1215 * condition on the logical unit for that initiator.
1217 * FSG normally uses option a); enable this code to use option b).
1220 if (!curlun) { /* Unsupported LUNs are okay */
1221 common->bad_lun_okay = 1;
1222 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1223 sdinfo = 0;
1224 valid = 0;
1225 } else {
1226 sd = curlun->sense_data;
1227 sdinfo = curlun->sense_data_info;
1228 valid = curlun->info_valid << 7;
1229 curlun->sense_data = SS_NO_SENSE;
1230 curlun->sense_data_info = 0;
1231 curlun->info_valid = 0;
1234 memset(buf, 0, 18);
1235 buf[0] = valid | 0x70; /* Valid, current error */
1236 buf[2] = SK(sd);
1237 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1238 buf[7] = 18 - 8; /* Additional sense length */
1239 buf[12] = ASC(sd);
1240 buf[13] = ASCQ(sd);
1241 return 18;
1245 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1247 struct fsg_lun *curlun = common->curlun;
1248 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1249 int pmi = common->cmnd[8];
1250 u8 *buf = (u8 *) bh->buf;
1252 /* Check the PMI and LBA fields */
1253 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1254 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1255 return -EINVAL;
1258 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1259 /* Max logical block */
1260 put_unaligned_be32(512, &buf[4]); /* Block length */
1261 return 8;
1265 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1267 struct fsg_lun *curlun = common->curlun;
1268 int msf = common->cmnd[1] & 0x02;
1269 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1270 u8 *buf = (u8 *) bh->buf;
1272 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1273 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1274 return -EINVAL;
1276 if (lba >= curlun->num_sectors) {
1277 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1278 return -EINVAL;
1281 memset(buf, 0, 8);
1282 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1283 store_cdrom_address(&buf[4], msf, lba);
1284 return 8;
1288 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1290 struct fsg_lun *curlun = common->curlun;
1291 int msf = common->cmnd[1] & 0x02;
1292 int start_track = common->cmnd[6];
1293 u8 *buf = (u8 *) bh->buf;
1295 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1296 start_track > 1) {
1297 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1298 return -EINVAL;
1301 memset(buf, 0, 20);
1302 buf[1] = (20-2); /* TOC data length */
1303 buf[2] = 1; /* First track number */
1304 buf[3] = 1; /* Last track number */
1305 buf[5] = 0x16; /* Data track, copying allowed */
1306 buf[6] = 0x01; /* Only track is number 1 */
1307 store_cdrom_address(&buf[8], msf, 0);
1309 buf[13] = 0x16; /* Lead-out track is data */
1310 buf[14] = 0xAA; /* Lead-out track number */
1311 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1312 return 20;
1316 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1318 struct fsg_lun *curlun = common->curlun;
1319 int mscmnd = common->cmnd[0];
1320 u8 *buf = (u8 *) bh->buf;
1321 u8 *buf0 = buf;
1322 int pc, page_code;
1323 int changeable_values, all_pages;
1324 int valid_page = 0;
1325 int len, limit;
1327 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1328 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1329 return -EINVAL;
1331 pc = common->cmnd[2] >> 6;
1332 page_code = common->cmnd[2] & 0x3f;
1333 if (pc == 3) {
1334 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1335 return -EINVAL;
1337 changeable_values = (pc == 1);
1338 all_pages = (page_code == 0x3f);
1340 /* Write the mode parameter header. Fixed values are: default
1341 * medium type, no cache control (DPOFUA), and no block descriptors.
1342 * The only variable value is the WriteProtect bit. We will fill in
1343 * the mode data length later. */
1344 memset(buf, 0, 8);
1345 if (mscmnd == SC_MODE_SENSE_6) {
1346 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1347 buf += 4;
1348 limit = 255;
1349 } else { /* SC_MODE_SENSE_10 */
1350 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1351 buf += 8;
1352 limit = 65535; /* Should really be FSG_BUFLEN */
1355 /* No block descriptors */
1357 /* The mode pages, in numerical order. The only page we support
1358 * is the Caching page. */
1359 if (page_code == 0x08 || all_pages) {
1360 valid_page = 1;
1361 buf[0] = 0x08; /* Page code */
1362 buf[1] = 10; /* Page length */
1363 memset(buf+2, 0, 10); /* None of the fields are changeable */
1365 if (!changeable_values) {
1366 buf[2] = 0x04; /* Write cache enable, */
1367 /* Read cache not disabled */
1368 /* No cache retention priorities */
1369 put_unaligned_be16(0xffff, &buf[4]);
1370 /* Don't disable prefetch */
1371 /* Minimum prefetch = 0 */
1372 put_unaligned_be16(0xffff, &buf[8]);
1373 /* Maximum prefetch */
1374 put_unaligned_be16(0xffff, &buf[10]);
1375 /* Maximum prefetch ceiling */
1377 buf += 12;
1380 /* Check that a valid page was requested and the mode data length
1381 * isn't too long. */
1382 len = buf - buf0;
1383 if (!valid_page || len > limit) {
1384 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1385 return -EINVAL;
1388 /* Store the mode data length */
1389 if (mscmnd == SC_MODE_SENSE_6)
1390 buf0[0] = len - 1;
1391 else
1392 put_unaligned_be16(len - 2, buf0);
1393 return len;
1397 static int do_start_stop(struct fsg_common *common)
1399 struct fsg_lun *curlun = common->curlun;
1400 int loej, start;
1402 if (!curlun) {
1403 return -EINVAL;
1404 } else if (!curlun->removable) {
1405 curlun->sense_data = SS_INVALID_COMMAND;
1406 return -EINVAL;
1407 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1408 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1409 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1410 return -EINVAL;
1413 loej = common->cmnd[4] & 0x02;
1414 start = common->cmnd[4] & 0x01;
1416 /* Our emulation doesn't support mounting; the medium is
1417 * available for use as soon as it is loaded. */
1418 if (start) {
1419 if (!fsg_lun_is_open(curlun)) {
1420 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1421 return -EINVAL;
1423 return 0;
1426 /* Are we allowed to unload the media? */
1427 if (curlun->prevent_medium_removal) {
1428 LDBG(curlun, "unload attempt prevented\n");
1429 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1430 return -EINVAL;
1433 if (!loej)
1434 return 0;
1436 /* Simulate an unload/eject */
1437 if (common->ops && common->ops->pre_eject) {
1438 int r = common->ops->pre_eject(common, curlun,
1439 curlun - common->luns);
1440 if (unlikely(r < 0))
1441 return r;
1442 else if (r)
1443 return 0;
1446 up_read(&common->filesem);
1447 down_write(&common->filesem);
1448 fsg_lun_close(curlun);
1449 up_write(&common->filesem);
1450 down_read(&common->filesem);
1452 return common->ops && common->ops->post_eject
1453 ? min(0, common->ops->post_eject(common, curlun,
1454 curlun - common->luns))
1455 : 0;
1459 static int do_prevent_allow(struct fsg_common *common)
1461 struct fsg_lun *curlun = common->curlun;
1462 int prevent;
1464 if (!common->curlun) {
1465 return -EINVAL;
1466 } else if (!common->curlun->removable) {
1467 common->curlun->sense_data = SS_INVALID_COMMAND;
1468 return -EINVAL;
1471 prevent = common->cmnd[4] & 0x01;
1472 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1473 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1474 return -EINVAL;
1477 if (curlun->prevent_medium_removal && !prevent)
1478 fsg_lun_fsync_sub(curlun);
1479 curlun->prevent_medium_removal = prevent;
1480 return 0;
1484 static int do_read_format_capacities(struct fsg_common *common,
1485 struct fsg_buffhd *bh)
1487 struct fsg_lun *curlun = common->curlun;
1488 u8 *buf = (u8 *) bh->buf;
1490 buf[0] = buf[1] = buf[2] = 0;
1491 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1492 buf += 4;
1494 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1495 /* Number of blocks */
1496 put_unaligned_be32(512, &buf[4]); /* Block length */
1497 buf[4] = 0x02; /* Current capacity */
1498 return 12;
1502 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1504 struct fsg_lun *curlun = common->curlun;
1506 /* We don't support MODE SELECT */
1507 if (curlun)
1508 curlun->sense_data = SS_INVALID_COMMAND;
1509 return -EINVAL;
1513 /*-------------------------------------------------------------------------*/
1515 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1517 int rc;
1519 rc = fsg_set_halt(fsg, fsg->bulk_in);
1520 if (rc == -EAGAIN)
1521 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1522 while (rc != 0) {
1523 if (rc != -EAGAIN) {
1524 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1525 rc = 0;
1526 break;
1529 /* Wait for a short time and then try again */
1530 if (msleep_interruptible(100) != 0)
1531 return -EINTR;
1532 rc = usb_ep_set_halt(fsg->bulk_in);
1534 return rc;
1537 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1539 int rc;
1541 DBG(fsg, "bulk-in set wedge\n");
1542 rc = usb_ep_set_wedge(fsg->bulk_in);
1543 if (rc == -EAGAIN)
1544 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1545 while (rc != 0) {
1546 if (rc != -EAGAIN) {
1547 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1548 rc = 0;
1549 break;
1552 /* Wait for a short time and then try again */
1553 if (msleep_interruptible(100) != 0)
1554 return -EINTR;
1555 rc = usb_ep_set_wedge(fsg->bulk_in);
1557 return rc;
1560 static int pad_with_zeros(struct fsg_dev *fsg)
1562 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
1563 u32 nkeep = bh->inreq->length;
1564 u32 nsend;
1565 int rc;
1567 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
1568 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1569 while (fsg->common->usb_amount_left > 0) {
1571 /* Wait for the next buffer to be free */
1572 while (bh->state != BUF_STATE_EMPTY) {
1573 rc = sleep_thread(fsg->common);
1574 if (rc)
1575 return rc;
1578 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1579 memset(bh->buf + nkeep, 0, nsend - nkeep);
1580 bh->inreq->length = nsend;
1581 bh->inreq->zero = 0;
1582 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1583 &bh->inreq_busy, &bh->state);
1584 bh = fsg->common->next_buffhd_to_fill = bh->next;
1585 fsg->common->usb_amount_left -= nsend;
1586 nkeep = 0;
1588 return 0;
1591 static int throw_away_data(struct fsg_common *common)
1593 struct fsg_buffhd *bh;
1594 u32 amount;
1595 int rc;
1597 for (bh = common->next_buffhd_to_drain;
1598 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1599 bh = common->next_buffhd_to_drain) {
1601 /* Throw away the data in a filled buffer */
1602 if (bh->state == BUF_STATE_FULL) {
1603 smp_rmb();
1604 bh->state = BUF_STATE_EMPTY;
1605 common->next_buffhd_to_drain = bh->next;
1607 /* A short packet or an error ends everything */
1608 if (bh->outreq->actual != bh->outreq->length ||
1609 bh->outreq->status != 0) {
1610 raise_exception(common,
1611 FSG_STATE_ABORT_BULK_OUT);
1612 return -EINTR;
1614 continue;
1617 /* Try to submit another request if we need one */
1618 bh = common->next_buffhd_to_fill;
1619 if (bh->state == BUF_STATE_EMPTY
1620 && common->usb_amount_left > 0) {
1621 amount = min(common->usb_amount_left, FSG_BUFLEN);
1623 /* amount is always divisible by 512, hence by
1624 * the bulk-out maxpacket size */
1625 bh->outreq->length = amount;
1626 bh->bulk_out_intended_length = amount;
1627 bh->outreq->short_not_ok = 1;
1628 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1629 &bh->outreq_busy, &bh->state)
1630 /* Don't know what to do if
1631 * common->fsg is NULL */
1632 return -EIO;
1633 common->next_buffhd_to_fill = bh->next;
1634 common->usb_amount_left -= amount;
1635 continue;
1638 /* Otherwise wait for something to happen */
1639 rc = sleep_thread(common);
1640 if (rc)
1641 return rc;
1643 return 0;
1647 static int finish_reply(struct fsg_common *common)
1649 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1650 int rc = 0;
1652 switch (common->data_dir) {
1653 case DATA_DIR_NONE:
1654 break; /* Nothing to send */
1656 /* If we don't know whether the host wants to read or write,
1657 * this must be CB or CBI with an unknown command. We mustn't
1658 * try to send or receive any data. So stall both bulk pipes
1659 * if we can and wait for a reset. */
1660 case DATA_DIR_UNKNOWN:
1661 if (!common->can_stall) {
1662 /* Nothing */
1663 } else if (fsg_is_set(common)) {
1664 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1665 rc = halt_bulk_in_endpoint(common->fsg);
1666 } else {
1667 /* Don't know what to do if common->fsg is NULL */
1668 rc = -EIO;
1670 break;
1672 /* All but the last buffer of data must have already been sent */
1673 case DATA_DIR_TO_HOST:
1674 if (common->data_size == 0) {
1675 /* Nothing to send */
1677 /* If there's no residue, simply send the last buffer */
1678 } else if (common->residue == 0) {
1679 bh->inreq->zero = 0;
1680 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1681 &bh->inreq_busy, &bh->state)
1682 return -EIO;
1683 common->next_buffhd_to_fill = bh->next;
1685 /* For Bulk-only, if we're allowed to stall then send the
1686 * short packet and halt the bulk-in endpoint. If we can't
1687 * stall, pad out the remaining data with 0's. */
1688 } else if (common->can_stall) {
1689 bh->inreq->zero = 1;
1690 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1691 &bh->inreq_busy, &bh->state)
1692 /* Don't know what to do if
1693 * common->fsg is NULL */
1694 rc = -EIO;
1695 common->next_buffhd_to_fill = bh->next;
1696 if (common->fsg)
1697 rc = halt_bulk_in_endpoint(common->fsg);
1698 } else if (fsg_is_set(common)) {
1699 rc = pad_with_zeros(common->fsg);
1700 } else {
1701 /* Don't know what to do if common->fsg is NULL */
1702 rc = -EIO;
1704 break;
1706 /* We have processed all we want from the data the host has sent.
1707 * There may still be outstanding bulk-out requests. */
1708 case DATA_DIR_FROM_HOST:
1709 if (common->residue == 0) {
1710 /* Nothing to receive */
1712 /* Did the host stop sending unexpectedly early? */
1713 } else if (common->short_packet_received) {
1714 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1715 rc = -EINTR;
1717 /* We haven't processed all the incoming data. Even though
1718 * we may be allowed to stall, doing so would cause a race.
1719 * The controller may already have ACK'ed all the remaining
1720 * bulk-out packets, in which case the host wouldn't see a
1721 * STALL. Not realizing the endpoint was halted, it wouldn't
1722 * clear the halt -- leading to problems later on. */
1724 /* We can't stall. Read in the excess data and throw it
1725 * all away. */
1726 } else {
1727 rc = throw_away_data(common);
1729 break;
1731 return rc;
1735 static int send_status(struct fsg_common *common)
1737 struct fsg_lun *curlun = common->curlun;
1738 struct fsg_buffhd *bh;
1739 struct bulk_cs_wrap *csw;
1740 int rc;
1741 u8 status = USB_STATUS_PASS;
1742 u32 sd, sdinfo = 0;
1744 /* Wait for the next buffer to become available */
1745 bh = common->next_buffhd_to_fill;
1746 while (bh->state != BUF_STATE_EMPTY) {
1747 rc = sleep_thread(common);
1748 if (rc)
1749 return rc;
1752 if (curlun) {
1753 sd = curlun->sense_data;
1754 sdinfo = curlun->sense_data_info;
1755 } else if (common->bad_lun_okay)
1756 sd = SS_NO_SENSE;
1757 else
1758 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1760 if (common->phase_error) {
1761 DBG(common, "sending phase-error status\n");
1762 status = USB_STATUS_PHASE_ERROR;
1763 sd = SS_INVALID_COMMAND;
1764 } else if (sd != SS_NO_SENSE) {
1765 DBG(common, "sending command-failure status\n");
1766 status = USB_STATUS_FAIL;
1767 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1768 " info x%x\n",
1769 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1772 /* Store and send the Bulk-only CSW */
1773 csw = (void *)bh->buf;
1775 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1776 csw->Tag = common->tag;
1777 csw->Residue = cpu_to_le32(common->residue);
1778 csw->Status = status;
1780 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1781 bh->inreq->zero = 0;
1782 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1783 &bh->inreq_busy, &bh->state)
1784 /* Don't know what to do if common->fsg is NULL */
1785 return -EIO;
1787 common->next_buffhd_to_fill = bh->next;
1788 return 0;
1792 /*-------------------------------------------------------------------------*/
1794 /* Check whether the command is properly formed and whether its data size
1795 * and direction agree with the values we already have. */
1796 static int check_command(struct fsg_common *common, int cmnd_size,
1797 enum data_direction data_dir, unsigned int mask,
1798 int needs_medium, const char *name)
1800 int i;
1801 int lun = common->cmnd[1] >> 5;
1802 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1803 char hdlen[20];
1804 struct fsg_lun *curlun;
1806 hdlen[0] = 0;
1807 if (common->data_dir != DATA_DIR_UNKNOWN)
1808 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1809 common->data_size);
1810 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1811 name, cmnd_size, dirletter[(int) data_dir],
1812 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1814 /* We can't reply at all until we know the correct data direction
1815 * and size. */
1816 if (common->data_size_from_cmnd == 0)
1817 data_dir = DATA_DIR_NONE;
1818 if (common->data_size < common->data_size_from_cmnd) {
1819 /* Host data size < Device data size is a phase error.
1820 * Carry out the command, but only transfer as much as
1821 * we are allowed. */
1822 common->data_size_from_cmnd = common->data_size;
1823 common->phase_error = 1;
1825 common->residue = common->data_size;
1826 common->usb_amount_left = common->data_size;
1828 /* Conflicting data directions is a phase error */
1829 if (common->data_dir != data_dir
1830 && common->data_size_from_cmnd > 0) {
1831 common->phase_error = 1;
1832 return -EINVAL;
1835 /* Verify the length of the command itself */
1836 if (cmnd_size != common->cmnd_size) {
1838 if (cmnd_size <= common->cmnd_size) {
1839 DBG(common, "%s is buggy! Expected length %d "
1840 "but we got %d\n", name,
1841 cmnd_size, common->cmnd_size);
1842 cmnd_size = common->cmnd_size;
1843 } else {
1844 common->phase_error = 1;
1845 return -EINVAL;
1849 /* Check that the LUN values are consistent */
1850 if (common->lun != lun)
1851 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1852 common->lun, lun);
1854 /* Check the LUN */
1855 if (common->lun >= 0 && common->lun < common->nluns) {
1856 curlun = &common->luns[common->lun];
1857 common->curlun = curlun;
1858 if (common->cmnd[0] != SC_REQUEST_SENSE) {
1859 curlun->sense_data = SS_NO_SENSE;
1860 curlun->sense_data_info = 0;
1861 curlun->info_valid = 0;
1863 } else {
1864 common->curlun = NULL;
1865 curlun = NULL;
1866 common->bad_lun_okay = 0;
1868 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1869 * to use unsupported LUNs; all others may not. */
1870 if (common->cmnd[0] != SC_INQUIRY &&
1871 common->cmnd[0] != SC_REQUEST_SENSE) {
1872 DBG(common, "unsupported LUN %d\n", common->lun);
1873 return -EINVAL;
1877 /* If a unit attention condition exists, only INQUIRY and
1878 * REQUEST SENSE commands are allowed; anything else must fail. */
1879 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1880 common->cmnd[0] != SC_INQUIRY &&
1881 common->cmnd[0] != SC_REQUEST_SENSE) {
1882 curlun->sense_data = curlun->unit_attention_data;
1883 curlun->unit_attention_data = SS_NO_SENSE;
1884 return -EINVAL;
1887 /* Check that only command bytes listed in the mask are non-zero */
1888 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1889 for (i = 1; i < cmnd_size; ++i) {
1890 if (common->cmnd[i] && !(mask & (1 << i))) {
1891 if (curlun)
1892 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1893 return -EINVAL;
1897 /* If the medium isn't mounted and the command needs to access
1898 * it, return an error. */
1899 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1900 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1901 return -EINVAL;
1904 return 0;
1908 static int do_scsi_command(struct fsg_common *common)
1910 struct fsg_buffhd *bh;
1911 int rc;
1912 int reply = -EINVAL;
1913 int i;
1914 static char unknown[16];
1916 dump_cdb(common);
1918 /* Wait for the next buffer to become available for data or status */
1919 bh = common->next_buffhd_to_fill;
1920 common->next_buffhd_to_drain = bh;
1921 while (bh->state != BUF_STATE_EMPTY) {
1922 rc = sleep_thread(common);
1923 if (rc)
1924 return rc;
1926 common->phase_error = 0;
1927 common->short_packet_received = 0;
1929 down_read(&common->filesem); /* We're using the backing file */
1930 switch (common->cmnd[0]) {
1932 case SC_INQUIRY:
1933 common->data_size_from_cmnd = common->cmnd[4];
1934 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1935 (1<<4), 0,
1936 "INQUIRY");
1937 if (reply == 0)
1938 reply = do_inquiry(common, bh);
1939 break;
1941 case SC_MODE_SELECT_6:
1942 common->data_size_from_cmnd = common->cmnd[4];
1943 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1944 (1<<1) | (1<<4), 0,
1945 "MODE SELECT(6)");
1946 if (reply == 0)
1947 reply = do_mode_select(common, bh);
1948 break;
1950 case SC_MODE_SELECT_10:
1951 common->data_size_from_cmnd =
1952 get_unaligned_be16(&common->cmnd[7]);
1953 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1954 (1<<1) | (3<<7), 0,
1955 "MODE SELECT(10)");
1956 if (reply == 0)
1957 reply = do_mode_select(common, bh);
1958 break;
1960 case SC_MODE_SENSE_6:
1961 common->data_size_from_cmnd = common->cmnd[4];
1962 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1963 (1<<1) | (1<<2) | (1<<4), 0,
1964 "MODE SENSE(6)");
1965 if (reply == 0)
1966 reply = do_mode_sense(common, bh);
1967 break;
1969 case SC_MODE_SENSE_10:
1970 common->data_size_from_cmnd =
1971 get_unaligned_be16(&common->cmnd[7]);
1972 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1973 (1<<1) | (1<<2) | (3<<7), 0,
1974 "MODE SENSE(10)");
1975 if (reply == 0)
1976 reply = do_mode_sense(common, bh);
1977 break;
1979 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1980 common->data_size_from_cmnd = 0;
1981 reply = check_command(common, 6, DATA_DIR_NONE,
1982 (1<<4), 0,
1983 "PREVENT-ALLOW MEDIUM REMOVAL");
1984 if (reply == 0)
1985 reply = do_prevent_allow(common);
1986 break;
1988 case SC_READ_6:
1989 i = common->cmnd[4];
1990 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1991 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1992 (7<<1) | (1<<4), 1,
1993 "READ(6)");
1994 if (reply == 0)
1995 reply = do_read(common);
1996 break;
1998 case SC_READ_10:
1999 common->data_size_from_cmnd =
2000 get_unaligned_be16(&common->cmnd[7]) << 9;
2001 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2002 (1<<1) | (0xf<<2) | (3<<7), 1,
2003 "READ(10)");
2004 if (reply == 0)
2005 reply = do_read(common);
2006 break;
2008 case SC_READ_12:
2009 common->data_size_from_cmnd =
2010 get_unaligned_be32(&common->cmnd[6]) << 9;
2011 reply = check_command(common, 12, DATA_DIR_TO_HOST,
2012 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2013 "READ(12)");
2014 if (reply == 0)
2015 reply = do_read(common);
2016 break;
2018 case SC_READ_CAPACITY:
2019 common->data_size_from_cmnd = 8;
2020 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2021 (0xf<<2) | (1<<8), 1,
2022 "READ CAPACITY");
2023 if (reply == 0)
2024 reply = do_read_capacity(common, bh);
2025 break;
2027 case SC_READ_HEADER:
2028 if (!common->curlun || !common->curlun->cdrom)
2029 goto unknown_cmnd;
2030 common->data_size_from_cmnd =
2031 get_unaligned_be16(&common->cmnd[7]);
2032 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2033 (3<<7) | (0x1f<<1), 1,
2034 "READ HEADER");
2035 if (reply == 0)
2036 reply = do_read_header(common, bh);
2037 break;
2039 case SC_READ_TOC:
2040 if (!common->curlun || !common->curlun->cdrom)
2041 goto unknown_cmnd;
2042 common->data_size_from_cmnd =
2043 get_unaligned_be16(&common->cmnd[7]);
2044 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2045 (7<<6) | (1<<1), 1,
2046 "READ TOC");
2047 if (reply == 0)
2048 reply = do_read_toc(common, bh);
2049 break;
2051 case SC_READ_FORMAT_CAPACITIES:
2052 common->data_size_from_cmnd =
2053 get_unaligned_be16(&common->cmnd[7]);
2054 reply = check_command(common, 10, DATA_DIR_TO_HOST,
2055 (3<<7), 1,
2056 "READ FORMAT CAPACITIES");
2057 if (reply == 0)
2058 reply = do_read_format_capacities(common, bh);
2059 break;
2061 case SC_REQUEST_SENSE:
2062 common->data_size_from_cmnd = common->cmnd[4];
2063 reply = check_command(common, 6, DATA_DIR_TO_HOST,
2064 (1<<4), 0,
2065 "REQUEST SENSE");
2066 if (reply == 0)
2067 reply = do_request_sense(common, bh);
2068 break;
2070 case SC_START_STOP_UNIT:
2071 common->data_size_from_cmnd = 0;
2072 reply = check_command(common, 6, DATA_DIR_NONE,
2073 (1<<1) | (1<<4), 0,
2074 "START-STOP UNIT");
2075 if (reply == 0)
2076 reply = do_start_stop(common);
2077 break;
2079 case SC_SYNCHRONIZE_CACHE:
2080 common->data_size_from_cmnd = 0;
2081 reply = check_command(common, 10, DATA_DIR_NONE,
2082 (0xf<<2) | (3<<7), 1,
2083 "SYNCHRONIZE CACHE");
2084 if (reply == 0)
2085 reply = do_synchronize_cache(common);
2086 break;
2088 case SC_TEST_UNIT_READY:
2089 common->data_size_from_cmnd = 0;
2090 reply = check_command(common, 6, DATA_DIR_NONE,
2091 0, 1,
2092 "TEST UNIT READY");
2093 break;
2095 /* Although optional, this command is used by MS-Windows. We
2096 * support a minimal version: BytChk must be 0. */
2097 case SC_VERIFY:
2098 common->data_size_from_cmnd = 0;
2099 reply = check_command(common, 10, DATA_DIR_NONE,
2100 (1<<1) | (0xf<<2) | (3<<7), 1,
2101 "VERIFY");
2102 if (reply == 0)
2103 reply = do_verify(common);
2104 break;
2106 case SC_WRITE_6:
2107 i = common->cmnd[4];
2108 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2109 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2110 (7<<1) | (1<<4), 1,
2111 "WRITE(6)");
2112 if (reply == 0)
2113 reply = do_write(common);
2114 break;
2116 case SC_WRITE_10:
2117 common->data_size_from_cmnd =
2118 get_unaligned_be16(&common->cmnd[7]) << 9;
2119 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2120 (1<<1) | (0xf<<2) | (3<<7), 1,
2121 "WRITE(10)");
2122 if (reply == 0)
2123 reply = do_write(common);
2124 break;
2126 case SC_WRITE_12:
2127 common->data_size_from_cmnd =
2128 get_unaligned_be32(&common->cmnd[6]) << 9;
2129 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2130 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2131 "WRITE(12)");
2132 if (reply == 0)
2133 reply = do_write(common);
2134 break;
2136 /* Some mandatory commands that we recognize but don't implement.
2137 * They don't mean much in this setting. It's left as an exercise
2138 * for anyone interested to implement RESERVE and RELEASE in terms
2139 * of Posix locks. */
2140 case SC_FORMAT_UNIT:
2141 case SC_RELEASE:
2142 case SC_RESERVE:
2143 case SC_SEND_DIAGNOSTIC:
2144 /* Fall through */
2146 default:
2147 unknown_cmnd:
2148 common->data_size_from_cmnd = 0;
2149 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2150 reply = check_command(common, common->cmnd_size,
2151 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2152 if (reply == 0) {
2153 common->curlun->sense_data = SS_INVALID_COMMAND;
2154 reply = -EINVAL;
2156 break;
2158 up_read(&common->filesem);
2160 if (reply == -EINTR || signal_pending(current))
2161 return -EINTR;
2163 /* Set up the single reply buffer for finish_reply() */
2164 if (reply == -EINVAL)
2165 reply = 0; /* Error reply length */
2166 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2167 reply = min((u32) reply, common->data_size_from_cmnd);
2168 bh->inreq->length = reply;
2169 bh->state = BUF_STATE_FULL;
2170 common->residue -= reply;
2171 } /* Otherwise it's already set */
2173 return 0;
2177 /*-------------------------------------------------------------------------*/
2179 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2181 struct usb_request *req = bh->outreq;
2182 struct fsg_bulk_cb_wrap *cbw = req->buf;
2183 struct fsg_common *common = fsg->common;
2185 /* Was this a real packet? Should it be ignored? */
2186 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2187 return -EINVAL;
2189 /* Is the CBW valid? */
2190 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2191 cbw->Signature != cpu_to_le32(
2192 USB_BULK_CB_SIG)) {
2193 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2194 req->actual,
2195 le32_to_cpu(cbw->Signature));
2197 /* The Bulk-only spec says we MUST stall the IN endpoint
2198 * (6.6.1), so it's unavoidable. It also says we must
2199 * retain this state until the next reset, but there's
2200 * no way to tell the controller driver it should ignore
2201 * Clear-Feature(HALT) requests.
2203 * We aren't required to halt the OUT endpoint; instead
2204 * we can simply accept and discard any data received
2205 * until the next reset. */
2206 wedge_bulk_in_endpoint(fsg);
2207 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2208 return -EINVAL;
2211 /* Is the CBW meaningful? */
2212 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2213 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2214 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2215 "cmdlen %u\n",
2216 cbw->Lun, cbw->Flags, cbw->Length);
2218 /* We can do anything we want here, so let's stall the
2219 * bulk pipes if we are allowed to. */
2220 if (common->can_stall) {
2221 fsg_set_halt(fsg, fsg->bulk_out);
2222 halt_bulk_in_endpoint(fsg);
2224 return -EINVAL;
2227 /* Save the command for later */
2228 common->cmnd_size = cbw->Length;
2229 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2230 if (cbw->Flags & USB_BULK_IN_FLAG)
2231 common->data_dir = DATA_DIR_TO_HOST;
2232 else
2233 common->data_dir = DATA_DIR_FROM_HOST;
2234 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2235 if (common->data_size == 0)
2236 common->data_dir = DATA_DIR_NONE;
2237 common->lun = cbw->Lun;
2238 common->tag = cbw->Tag;
2239 return 0;
2243 static int get_next_command(struct fsg_common *common)
2245 struct fsg_buffhd *bh;
2246 int rc = 0;
2248 /* Wait for the next buffer to become available */
2249 bh = common->next_buffhd_to_fill;
2250 while (bh->state != BUF_STATE_EMPTY) {
2251 rc = sleep_thread(common);
2252 if (rc)
2253 return rc;
2256 /* Queue a request to read a Bulk-only CBW */
2257 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2258 bh->outreq->short_not_ok = 1;
2259 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2260 &bh->outreq_busy, &bh->state)
2261 /* Don't know what to do if common->fsg is NULL */
2262 return -EIO;
2264 /* We will drain the buffer in software, which means we
2265 * can reuse it for the next filling. No need to advance
2266 * next_buffhd_to_fill. */
2268 /* Wait for the CBW to arrive */
2269 while (bh->state != BUF_STATE_FULL) {
2270 rc = sleep_thread(common);
2271 if (rc)
2272 return rc;
2274 smp_rmb();
2275 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2276 bh->state = BUF_STATE_EMPTY;
2278 return rc;
2282 /*-------------------------------------------------------------------------*/
2284 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2285 const struct usb_endpoint_descriptor *d)
2287 int rc;
2289 ep->driver_data = common;
2290 rc = usb_ep_enable(ep, d);
2291 if (rc)
2292 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2293 return rc;
2296 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2297 struct usb_request **preq)
2299 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2300 if (*preq)
2301 return 0;
2302 ERROR(common, "can't allocate request for %s\n", ep->name);
2303 return -ENOMEM;
2306 /* Reset interface setting and re-init endpoint state (toggle etc). */
2307 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2309 const struct usb_endpoint_descriptor *d;
2310 struct fsg_dev *fsg;
2311 int i, rc = 0;
2313 if (common->running)
2314 DBG(common, "reset interface\n");
2316 reset:
2317 /* Deallocate the requests */
2318 if (common->fsg) {
2319 fsg = common->fsg;
2321 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2322 struct fsg_buffhd *bh = &common->buffhds[i];
2324 if (bh->inreq) {
2325 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2326 bh->inreq = NULL;
2328 if (bh->outreq) {
2329 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2330 bh->outreq = NULL;
2334 /* Disable the endpoints */
2335 if (fsg->bulk_in_enabled) {
2336 usb_ep_disable(fsg->bulk_in);
2337 fsg->bulk_in_enabled = 0;
2339 if (fsg->bulk_out_enabled) {
2340 usb_ep_disable(fsg->bulk_out);
2341 fsg->bulk_out_enabled = 0;
2344 common->fsg = NULL;
2345 wake_up(&common->fsg_wait);
2348 common->running = 0;
2349 if (!new_fsg || rc)
2350 return rc;
2352 common->fsg = new_fsg;
2353 fsg = common->fsg;
2355 /* Enable the endpoints */
2356 d = fsg_ep_desc(common->gadget,
2357 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2358 rc = enable_endpoint(common, fsg->bulk_in, d);
2359 if (rc)
2360 goto reset;
2361 fsg->bulk_in_enabled = 1;
2363 d = fsg_ep_desc(common->gadget,
2364 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2365 rc = enable_endpoint(common, fsg->bulk_out, d);
2366 if (rc)
2367 goto reset;
2368 fsg->bulk_out_enabled = 1;
2369 common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2370 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2372 /* Allocate the requests */
2373 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2374 struct fsg_buffhd *bh = &common->buffhds[i];
2376 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2377 if (rc)
2378 goto reset;
2379 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2380 if (rc)
2381 goto reset;
2382 bh->inreq->buf = bh->outreq->buf = bh->buf;
2383 bh->inreq->context = bh->outreq->context = bh;
2384 bh->inreq->complete = bulk_in_complete;
2385 bh->outreq->complete = bulk_out_complete;
2388 common->running = 1;
2389 for (i = 0; i < common->nluns; ++i)
2390 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
2391 return rc;
2395 /****************************** ALT CONFIGS ******************************/
2398 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2400 struct fsg_dev *fsg = fsg_from_func(f);
2401 fsg->common->new_fsg = fsg;
2402 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2403 return 0;
2406 static void fsg_disable(struct usb_function *f)
2408 struct fsg_dev *fsg = fsg_from_func(f);
2409 fsg->common->new_fsg = NULL;
2410 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2414 /*-------------------------------------------------------------------------*/
2416 static void handle_exception(struct fsg_common *common)
2418 siginfo_t info;
2419 int i;
2420 struct fsg_buffhd *bh;
2421 enum fsg_state old_state;
2422 struct fsg_lun *curlun;
2423 unsigned int exception_req_tag;
2425 /* Clear the existing signals. Anything but SIGUSR1 is converted
2426 * into a high-priority EXIT exception. */
2427 for (;;) {
2428 int sig =
2429 dequeue_signal_lock(current, &current->blocked, &info);
2430 if (!sig)
2431 break;
2432 if (sig != SIGUSR1) {
2433 if (common->state < FSG_STATE_EXIT)
2434 DBG(common, "Main thread exiting on signal\n");
2435 raise_exception(common, FSG_STATE_EXIT);
2439 /* Cancel all the pending transfers */
2440 if (likely(common->fsg)) {
2441 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2442 bh = &common->buffhds[i];
2443 if (bh->inreq_busy)
2444 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2445 if (bh->outreq_busy)
2446 usb_ep_dequeue(common->fsg->bulk_out,
2447 bh->outreq);
2450 /* Wait until everything is idle */
2451 for (;;) {
2452 int num_active = 0;
2453 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2454 bh = &common->buffhds[i];
2455 num_active += bh->inreq_busy + bh->outreq_busy;
2457 if (num_active == 0)
2458 break;
2459 if (sleep_thread(common))
2460 return;
2463 /* Clear out the controller's fifos */
2464 if (common->fsg->bulk_in_enabled)
2465 usb_ep_fifo_flush(common->fsg->bulk_in);
2466 if (common->fsg->bulk_out_enabled)
2467 usb_ep_fifo_flush(common->fsg->bulk_out);
2470 /* Reset the I/O buffer states and pointers, the SCSI
2471 * state, and the exception. Then invoke the handler. */
2472 spin_lock_irq(&common->lock);
2474 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2475 bh = &common->buffhds[i];
2476 bh->state = BUF_STATE_EMPTY;
2478 common->next_buffhd_to_fill = &common->buffhds[0];
2479 common->next_buffhd_to_drain = &common->buffhds[0];
2480 exception_req_tag = common->exception_req_tag;
2481 old_state = common->state;
2483 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2484 common->state = FSG_STATE_STATUS_PHASE;
2485 else {
2486 for (i = 0; i < common->nluns; ++i) {
2487 curlun = &common->luns[i];
2488 curlun->prevent_medium_removal = 0;
2489 curlun->sense_data = SS_NO_SENSE;
2490 curlun->unit_attention_data = SS_NO_SENSE;
2491 curlun->sense_data_info = 0;
2492 curlun->info_valid = 0;
2494 common->state = FSG_STATE_IDLE;
2496 spin_unlock_irq(&common->lock);
2498 /* Carry out any extra actions required for the exception */
2499 switch (old_state) {
2500 case FSG_STATE_ABORT_BULK_OUT:
2501 send_status(common);
2502 spin_lock_irq(&common->lock);
2503 if (common->state == FSG_STATE_STATUS_PHASE)
2504 common->state = FSG_STATE_IDLE;
2505 spin_unlock_irq(&common->lock);
2506 break;
2508 case FSG_STATE_RESET:
2509 /* In case we were forced against our will to halt a
2510 * bulk endpoint, clear the halt now. (The SuperH UDC
2511 * requires this.) */
2512 if (!fsg_is_set(common))
2513 break;
2514 if (test_and_clear_bit(IGNORE_BULK_OUT,
2515 &common->fsg->atomic_bitflags))
2516 usb_ep_clear_halt(common->fsg->bulk_in);
2518 if (common->ep0_req_tag == exception_req_tag)
2519 ep0_queue(common); /* Complete the status stage */
2521 /* Technically this should go here, but it would only be
2522 * a waste of time. Ditto for the INTERFACE_CHANGE and
2523 * CONFIG_CHANGE cases. */
2524 /* for (i = 0; i < common->nluns; ++i) */
2525 /* common->luns[i].unit_attention_data = */
2526 /* SS_RESET_OCCURRED; */
2527 break;
2529 case FSG_STATE_CONFIG_CHANGE:
2530 do_set_interface(common, common->new_fsg);
2531 break;
2533 case FSG_STATE_EXIT:
2534 case FSG_STATE_TERMINATED:
2535 do_set_interface(common, NULL); /* Free resources */
2536 spin_lock_irq(&common->lock);
2537 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2538 spin_unlock_irq(&common->lock);
2539 break;
2541 case FSG_STATE_INTERFACE_CHANGE:
2542 case FSG_STATE_DISCONNECT:
2543 case FSG_STATE_COMMAND_PHASE:
2544 case FSG_STATE_DATA_PHASE:
2545 case FSG_STATE_STATUS_PHASE:
2546 case FSG_STATE_IDLE:
2547 break;
2552 /*-------------------------------------------------------------------------*/
2554 static int fsg_main_thread(void *common_)
2556 struct fsg_common *common = common_;
2558 /* Allow the thread to be killed by a signal, but set the signal mask
2559 * to block everything but INT, TERM, KILL, and USR1. */
2560 allow_signal(SIGINT);
2561 allow_signal(SIGTERM);
2562 allow_signal(SIGKILL);
2563 allow_signal(SIGUSR1);
2565 /* Allow the thread to be frozen */
2566 set_freezable();
2568 /* Arrange for userspace references to be interpreted as kernel
2569 * pointers. That way we can pass a kernel pointer to a routine
2570 * that expects a __user pointer and it will work okay. */
2571 set_fs(get_ds());
2573 /* The main loop */
2574 while (common->state != FSG_STATE_TERMINATED) {
2575 if (exception_in_progress(common) || signal_pending(current)) {
2576 handle_exception(common);
2577 continue;
2580 if (!common->running) {
2581 sleep_thread(common);
2582 continue;
2585 if (get_next_command(common))
2586 continue;
2588 spin_lock_irq(&common->lock);
2589 if (!exception_in_progress(common))
2590 common->state = FSG_STATE_DATA_PHASE;
2591 spin_unlock_irq(&common->lock);
2593 if (do_scsi_command(common) || finish_reply(common))
2594 continue;
2596 spin_lock_irq(&common->lock);
2597 if (!exception_in_progress(common))
2598 common->state = FSG_STATE_STATUS_PHASE;
2599 spin_unlock_irq(&common->lock);
2601 if (send_status(common))
2602 continue;
2604 spin_lock_irq(&common->lock);
2605 if (!exception_in_progress(common))
2606 common->state = FSG_STATE_IDLE;
2607 spin_unlock_irq(&common->lock);
2610 spin_lock_irq(&common->lock);
2611 common->thread_task = NULL;
2612 spin_unlock_irq(&common->lock);
2614 if (!common->ops || !common->ops->thread_exits
2615 || common->ops->thread_exits(common) < 0) {
2616 struct fsg_lun *curlun = common->luns;
2617 unsigned i = common->nluns;
2619 down_write(&common->filesem);
2620 for (; i--; ++curlun) {
2621 if (!fsg_lun_is_open(curlun))
2622 continue;
2624 fsg_lun_close(curlun);
2625 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2627 up_write(&common->filesem);
2630 /* Let the unbind and cleanup routines know the thread has exited */
2631 complete_and_exit(&common->thread_notifier, 0);
2635 /*************************** DEVICE ATTRIBUTES ***************************/
2637 /* Write permission is checked per LUN in store_*() functions. */
2638 static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2639 static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
2642 /****************************** FSG COMMON ******************************/
2644 static void fsg_common_release(struct kref *ref);
2646 static void fsg_lun_release(struct device *dev)
2648 /* Nothing needs to be done */
2651 static inline void fsg_common_get(struct fsg_common *common)
2653 kref_get(&common->ref);
2656 static inline void fsg_common_put(struct fsg_common *common)
2658 kref_put(&common->ref, fsg_common_release);
2662 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2663 struct usb_composite_dev *cdev,
2664 struct fsg_config *cfg)
2666 struct usb_gadget *gadget = cdev->gadget;
2667 struct fsg_buffhd *bh;
2668 struct fsg_lun *curlun;
2669 struct fsg_lun_config *lcfg;
2670 int nluns, i, rc;
2671 char *pathbuf;
2673 /* Find out how many LUNs there should be */
2674 nluns = cfg->nluns;
2675 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2676 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2677 return ERR_PTR(-EINVAL);
2680 /* Allocate? */
2681 if (!common) {
2682 common = kzalloc(sizeof *common, GFP_KERNEL);
2683 if (!common)
2684 return ERR_PTR(-ENOMEM);
2685 common->free_storage_on_release = 1;
2686 } else {
2687 memset(common, 0, sizeof common);
2688 common->free_storage_on_release = 0;
2691 common->ops = cfg->ops;
2692 common->private_data = cfg->private_data;
2694 common->gadget = gadget;
2695 common->ep0 = gadget->ep0;
2696 common->ep0req = cdev->req;
2698 /* Maybe allocate device-global string IDs, and patch descriptors */
2699 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2700 rc = usb_string_id(cdev);
2701 if (unlikely(rc < 0))
2702 goto error_release;
2703 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2704 fsg_intf_desc.iInterface = rc;
2707 /* Create the LUNs, open their backing files, and register the
2708 * LUN devices in sysfs. */
2709 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
2710 if (unlikely(!curlun)) {
2711 rc = -ENOMEM;
2712 goto error_release;
2714 common->luns = curlun;
2716 init_rwsem(&common->filesem);
2718 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2719 curlun->cdrom = !!lcfg->cdrom;
2720 curlun->ro = lcfg->cdrom || lcfg->ro;
2721 curlun->removable = lcfg->removable;
2722 curlun->dev.release = fsg_lun_release;
2723 curlun->dev.parent = &gadget->dev;
2724 dev_set_drvdata(&curlun->dev, &common->filesem);
2725 dev_set_name(&curlun->dev,
2726 cfg->lun_name_format
2727 ? cfg->lun_name_format
2728 : "lun%d",
2731 rc = device_register(&curlun->dev);
2732 if (rc) {
2733 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2734 common->nluns = i;
2735 goto error_release;
2738 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2739 if (rc)
2740 goto error_luns;
2741 rc = device_create_file(&curlun->dev, &dev_attr_file);
2742 if (rc)
2743 goto error_luns;
2745 if (lcfg->filename) {
2746 rc = fsg_lun_open(curlun, lcfg->filename);
2747 if (rc)
2748 goto error_luns;
2749 } else if (!curlun->removable) {
2750 ERROR(common, "no file given for LUN%d\n", i);
2751 rc = -EINVAL;
2752 goto error_luns;
2755 common->nluns = nluns;
2758 /* Data buffers cyclic list */
2759 bh = common->buffhds;
2760 i = FSG_NUM_BUFFERS;
2761 goto buffhds_first_it;
2762 do {
2763 bh->next = bh + 1;
2764 ++bh;
2765 buffhds_first_it:
2766 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2767 if (unlikely(!bh->buf)) {
2768 rc = -ENOMEM;
2769 goto error_release;
2771 } while (--i);
2772 bh->next = common->buffhds;
2775 /* Prepare inquiryString */
2776 if (cfg->release != 0xffff) {
2777 i = cfg->release;
2778 } else {
2779 i = usb_gadget_controller_number(gadget);
2780 if (i >= 0) {
2781 i = 0x0300 + i;
2782 } else {
2783 WARNING(common, "controller '%s' not recognized\n",
2784 gadget->name);
2785 i = 0x0399;
2788 #define OR(x, y) ((x) ? (x) : (y))
2789 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2790 "%-8s%-16s%04x",
2791 OR(cfg->vendor_name, "Linux "),
2792 /* Assume product name dependent on the first LUN */
2793 OR(cfg->product_name, common->luns->cdrom
2794 ? "File-Stor Gadget"
2795 : "File-CD Gadget "),
2799 /* Some peripheral controllers are known not to be able to
2800 * halt bulk endpoints correctly. If one of them is present,
2801 * disable stalls.
2803 common->can_stall = cfg->can_stall &&
2804 !(gadget_is_at91(common->gadget));
2807 spin_lock_init(&common->lock);
2808 kref_init(&common->ref);
2811 /* Tell the thread to start working */
2812 common->thread_task =
2813 kthread_create(fsg_main_thread, common,
2814 OR(cfg->thread_name, "file-storage"));
2815 if (IS_ERR(common->thread_task)) {
2816 rc = PTR_ERR(common->thread_task);
2817 goto error_release;
2819 init_completion(&common->thread_notifier);
2820 init_waitqueue_head(&common->fsg_wait);
2821 #undef OR
2824 /* Information */
2825 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2826 INFO(common, "Number of LUNs=%d\n", common->nluns);
2828 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2829 for (i = 0, nluns = common->nluns, curlun = common->luns;
2830 i < nluns;
2831 ++curlun, ++i) {
2832 char *p = "(no medium)";
2833 if (fsg_lun_is_open(curlun)) {
2834 p = "(error)";
2835 if (pathbuf) {
2836 p = d_path(&curlun->filp->f_path,
2837 pathbuf, PATH_MAX);
2838 if (IS_ERR(p))
2839 p = "(error)";
2842 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
2843 curlun->removable ? "removable " : "",
2844 curlun->ro ? "read only " : "",
2845 curlun->cdrom ? "CD-ROM " : "",
2848 kfree(pathbuf);
2850 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
2852 wake_up_process(common->thread_task);
2854 return common;
2857 error_luns:
2858 common->nluns = i + 1;
2859 error_release:
2860 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
2861 /* Call fsg_common_release() directly, ref might be not
2862 * initialised */
2863 fsg_common_release(&common->ref);
2864 return ERR_PTR(rc);
2868 static void fsg_common_release(struct kref *ref)
2870 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2872 /* If the thread isn't already dead, tell it to exit now */
2873 if (common->state != FSG_STATE_TERMINATED) {
2874 raise_exception(common, FSG_STATE_EXIT);
2875 wait_for_completion(&common->thread_notifier);
2877 /* The cleanup routine waits for this completion also */
2878 complete(&common->thread_notifier);
2881 if (likely(common->luns)) {
2882 struct fsg_lun *lun = common->luns;
2883 unsigned i = common->nluns;
2885 /* In error recovery common->nluns may be zero. */
2886 for (; i; --i, ++lun) {
2887 device_remove_file(&lun->dev, &dev_attr_ro);
2888 device_remove_file(&lun->dev, &dev_attr_file);
2889 fsg_lun_close(lun);
2890 device_unregister(&lun->dev);
2893 kfree(common->luns);
2897 struct fsg_buffhd *bh = common->buffhds;
2898 unsigned i = FSG_NUM_BUFFERS;
2899 do {
2900 kfree(bh->buf);
2901 } while (++bh, --i);
2904 if (common->free_storage_on_release)
2905 kfree(common);
2909 /*-------------------------------------------------------------------------*/
2912 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2914 struct fsg_dev *fsg = fsg_from_func(f);
2915 struct fsg_common *common = fsg->common;
2917 DBG(fsg, "unbind\n");
2918 if (fsg->common->fsg == fsg) {
2919 fsg->common->new_fsg = NULL;
2920 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2921 wait_event(common->fsg_wait, common->fsg != fsg);
2924 fsg_common_put(common);
2925 usb_free_descriptors(fsg->function.descriptors);
2926 usb_free_descriptors(fsg->function.hs_descriptors);
2927 kfree(fsg);
2931 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2933 struct fsg_dev *fsg = fsg_from_func(f);
2934 struct usb_gadget *gadget = c->cdev->gadget;
2935 int i;
2936 struct usb_ep *ep;
2938 fsg->gadget = gadget;
2940 /* New interface */
2941 i = usb_interface_id(c, f);
2942 if (i < 0)
2943 return i;
2944 fsg_intf_desc.bInterfaceNumber = i;
2945 fsg->interface_number = i;
2947 /* Find all the endpoints we will use */
2948 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2949 if (!ep)
2950 goto autoconf_fail;
2951 ep->driver_data = fsg->common; /* claim the endpoint */
2952 fsg->bulk_in = ep;
2954 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2955 if (!ep)
2956 goto autoconf_fail;
2957 ep->driver_data = fsg->common; /* claim the endpoint */
2958 fsg->bulk_out = ep;
2960 /* Copy descriptors */
2961 f->descriptors = usb_copy_descriptors(fsg_fs_function);
2962 if (unlikely(!f->descriptors))
2963 return -ENOMEM;
2965 if (gadget_is_dualspeed(gadget)) {
2966 /* Assume endpoint addresses are the same for both speeds */
2967 fsg_hs_bulk_in_desc.bEndpointAddress =
2968 fsg_fs_bulk_in_desc.bEndpointAddress;
2969 fsg_hs_bulk_out_desc.bEndpointAddress =
2970 fsg_fs_bulk_out_desc.bEndpointAddress;
2971 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
2972 if (unlikely(!f->hs_descriptors)) {
2973 usb_free_descriptors(f->descriptors);
2974 return -ENOMEM;
2978 return 0;
2980 autoconf_fail:
2981 ERROR(fsg, "unable to autoconfigure all endpoints\n");
2982 return -ENOTSUPP;
2986 /****************************** ADD FUNCTION ******************************/
2988 static struct usb_gadget_strings *fsg_strings_array[] = {
2989 &fsg_stringtab,
2990 NULL,
2993 static int fsg_bind_config(struct usb_composite_dev *cdev,
2994 struct usb_configuration *c,
2995 struct fsg_common *common)
2997 struct fsg_dev *fsg;
2998 int rc;
3000 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3001 if (unlikely(!fsg))
3002 return -ENOMEM;
3004 fsg->function.name = FSG_DRIVER_DESC;
3005 fsg->function.strings = fsg_strings_array;
3006 fsg->function.bind = fsg_bind;
3007 fsg->function.unbind = fsg_unbind;
3008 fsg->function.setup = fsg_setup;
3009 fsg->function.set_alt = fsg_set_alt;
3010 fsg->function.disable = fsg_disable;
3012 fsg->common = common;
3013 /* Our caller holds a reference to common structure so we
3014 * don't have to be worry about it being freed until we return
3015 * from this function. So instead of incrementing counter now
3016 * and decrement in error recovery we increment it only when
3017 * call to usb_add_function() was successful. */
3019 rc = usb_add_function(c, &fsg->function);
3020 if (unlikely(rc))
3021 kfree(fsg);
3022 else
3023 fsg_common_get(fsg->common);
3024 return rc;
3027 static inline int __deprecated __maybe_unused
3028 fsg_add(struct usb_composite_dev *cdev,
3029 struct usb_configuration *c,
3030 struct fsg_common *common)
3032 return fsg_bind_config(cdev, c, common);
3036 /************************* Module parameters *************************/
3039 struct fsg_module_parameters {
3040 char *file[FSG_MAX_LUNS];
3041 int ro[FSG_MAX_LUNS];
3042 int removable[FSG_MAX_LUNS];
3043 int cdrom[FSG_MAX_LUNS];
3045 unsigned int file_count, ro_count, removable_count, cdrom_count;
3046 unsigned int luns; /* nluns */
3047 int stall; /* can_stall */
3051 #define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3052 module_param_array_named(prefix ## name, params.name, type, \
3053 &prefix ## params.name ## _count, \
3054 S_IRUGO); \
3055 MODULE_PARM_DESC(prefix ## name, desc)
3057 #define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3058 module_param_named(prefix ## name, params.name, type, \
3059 S_IRUGO); \
3060 MODULE_PARM_DESC(prefix ## name, desc)
3062 #define FSG_MODULE_PARAMETERS(prefix, params) \
3063 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3064 "names of backing files or devices"); \
3065 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3066 "true to force read-only"); \
3067 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3068 "true to simulate removable media"); \
3069 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3070 "true to simulate CD-ROM instead of disk"); \
3071 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3072 "number of LUNs"); \
3073 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3074 "false to prevent bulk stalls")
3077 static void
3078 fsg_config_from_params(struct fsg_config *cfg,
3079 const struct fsg_module_parameters *params)
3081 struct fsg_lun_config *lun;
3082 unsigned i;
3084 /* Configure LUNs */
3085 cfg->nluns =
3086 min(params->luns ?: (params->file_count ?: 1u),
3087 (unsigned)FSG_MAX_LUNS);
3088 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3089 lun->ro = !!params->ro[i];
3090 lun->cdrom = !!params->cdrom[i];
3091 lun->removable = /* Removable by default */
3092 params->removable_count <= i || params->removable[i];
3093 lun->filename =
3094 params->file_count > i && params->file[i][0]
3095 ? params->file[i]
3096 : 0;
3099 /* Let MSF use defaults */
3100 cfg->lun_name_format = 0;
3101 cfg->thread_name = 0;
3102 cfg->vendor_name = 0;
3103 cfg->product_name = 0;
3104 cfg->release = 0xffff;
3106 cfg->ops = NULL;
3107 cfg->private_data = NULL;
3109 /* Finalise */
3110 cfg->can_stall = params->stall;
3113 static inline struct fsg_common *
3114 fsg_common_from_params(struct fsg_common *common,
3115 struct usb_composite_dev *cdev,
3116 const struct fsg_module_parameters *params)
3117 __attribute__((unused));
3118 static inline struct fsg_common *
3119 fsg_common_from_params(struct fsg_common *common,
3120 struct usb_composite_dev *cdev,
3121 const struct fsg_module_parameters *params)
3123 struct fsg_config cfg;
3124 fsg_config_from_params(&cfg, params);
3125 return fsg_common_init(common, cdev, &cfg);