usb: gadget: storage: remove nofua file when unbinding
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / drivers / usb / gadget / f_mass_storage.c
CommitLineData
d5e2b67a 1/*
d26a6aa0 2 * f_mass_storage.c -- Mass Storage USB Composite Function
d5e2b67a
MN
3 *
4 * Copyright (C) 2003-2008 Alan Stern
d26a6aa0
MN
5 * Copyright (C) 2009 Samsung Electronics
6 * Author: Michal Nazarewicz <m.nazarewicz@samsung.com>
d5e2b67a
MN
7 * All rights reserved.
8 *
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.
21 *
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.
26 *
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.
38 */
39
40
41/*
d26a6aa0
MN
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.
d5e2b67a 47 *
d26a6aa0
MN
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.)
53 *
54 * MSF is configured by specifying a fsg_config structure. It has the
55 * following fields:
56 *
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.
76 *
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).
95 *
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.
103 *
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.
108 *
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.
116 *
117 *
118 * MSF includes support for module parameters. If gadget using it
119 * decides to use it, the following module parameters will be
120 * available:
121 *
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.
136 *
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).
d5e2b67a 142 *
d5e2b67a
MN
143 *
144 * Requirements are modest; only a bulk-in and a bulk-out endpoint are
d26a6aa0
MN
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.
d5e2b67a
MN
148 *
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.
154 *
d5e2b67a 155 *
d26a6aa0
MN
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.
d5e2b67a 165 *
31436a1a
FC
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.
169 *
d5e2b67a 170 *
d26a6aa0
MN
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
d5e2b67a
MN
181 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
182 */
183
184
185/*
186 * Driver Design
187 *
d26a6aa0 188 * The MSF is fairly straightforward. There is a main kernel
d5e2b67a
MN
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).
197 *
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.
209 *
210 * In normal operation the main thread is started during the gadget's
d26a6aa0
MN
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.
d5e2b67a
MN
216 *
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.
226 *
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).
237 *
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.
249 *
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.
264 *
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.
268 */
269
270
271/* #define VERBOSE_DEBUG */
272/* #define DUMP_MSGS */
273
274
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>
292
293#include <linux/usb/ch9.h>
294#include <linux/usb/gadget.h>
295
296#include "gadget_chips.h"
297
298
299
e8b6f8c5 300/*------------------------------------------------------------------------*/
d5e2b67a 301
d23b0f08 302#define FSG_DRIVER_DESC "Mass Storage Function"
d26a6aa0 303#define FSG_DRIVER_VERSION "2009/09/11"
d5e2b67a 304
d5e2b67a
MN
305static const char fsg_string_interface[] = "Mass Storage";
306
307
93bcf12e 308#define FSG_NO_INTR_EP 1
d23b0f08
MN
309#define FSG_NO_DEVICE_STRINGS 1
310#define FSG_NO_OTG 1
311#define FSG_NO_INTR_EP 1
93bcf12e 312
d5e2b67a
MN
313#include "storage_common.c"
314
315
d5e2b67a
MN
316/*-------------------------------------------------------------------------*/
317
8ea864cf 318struct fsg_dev;
8876f5e7
MN
319struct fsg_common;
320
321/* FSF callback functions */
322struct 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);
329
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);
339};
8ea864cf 340
d5e2b67a 341
a41ae418
MN
342/* Data shared by all the FSG instances. */
343struct fsg_common {
9c610213 344 struct usb_gadget *gadget;
b894f60a
MN
345 struct fsg_dev *fsg, *new_fsg;
346 wait_queue_head_t fsg_wait;
9c610213 347
a41ae418
MN
348 /* filesem protects: backing files in use */
349 struct rw_semaphore filesem;
350
8ea864cf
MN
351 /* lock protects: state, all the req_busy's */
352 spinlock_t lock;
353
354 struct usb_ep *ep0; /* Copy of gadget->ep0 */
355 struct usb_request *ep0req; /* Copy of cdev->req */
356 unsigned int ep0_req_tag;
8ea864cf 357
a41ae418
MN
358 struct fsg_buffhd *next_buffhd_to_fill;
359 struct fsg_buffhd *next_buffhd_to_drain;
360 struct fsg_buffhd buffhds[FSG_NUM_BUFFERS];
361
362 int cmnd_size;
363 u8 cmnd[MAX_COMMAND_SIZE];
364
365 unsigned int nluns;
366 unsigned int lun;
367 struct fsg_lun *luns;
368 struct fsg_lun *curlun;
9c610213 369
8ea864cf
MN
370 unsigned int bulk_out_maxpacket;
371 enum fsg_state state; /* For exception handling */
372 unsigned int exception_req_tag;
373
8ea864cf
MN
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;
380
481e4929 381 unsigned int can_stall:1;
9c610213 382 unsigned int free_storage_on_release:1;
8ea864cf
MN
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;
9c610213 387
8ea864cf
MN
388 int thread_wakeup_needed;
389 struct completion thread_notifier;
390 struct task_struct *thread_task;
e8b6f8c5 391
8876f5e7
MN
392 /* Callback functions. */
393 const struct fsg_operations *ops;
c85efcb9
MN
394 /* Gadget's private data. */
395 void *private_data;
396
481e4929
MN
397 /* Vendor (8 chars), product (16 chars), release (4
398 * hexadecimal digits) and NUL byte */
399 char inquiry_string[8 + 16 + 4 + 1];
400
9c610213 401 struct kref ref;
a41ae418
MN
402};
403
404
481e4929
MN
405struct 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];
413
e8b6f8c5
MN
414 const char *lun_name_format;
415 const char *thread_name;
416
8876f5e7
MN
417 /* Callback functions. */
418 const struct fsg_operations *ops;
c85efcb9
MN
419 /* Gadget's private data. */
420 void *private_data;
421
481e4929
MN
422 const char *vendor_name; /* 8 characters or less */
423 const char *product_name; /* 16 characters or less */
424 u16 release;
425
426 char can_stall;
427};
428
429
d5e2b67a 430struct fsg_dev {
d23b0f08 431 struct usb_function function;
d23b0f08 432 struct usb_gadget *gadget; /* Copy of cdev->gadget */
a41ae418
MN
433 struct fsg_common *common;
434
d23b0f08
MN
435 u16 interface_number;
436
d26a6aa0
MN
437 unsigned int bulk_in_enabled:1;
438 unsigned int bulk_out_enabled:1;
d5e2b67a
MN
439
440 unsigned long atomic_bitflags;
8ea864cf 441#define IGNORE_BULK_OUT 0
d5e2b67a
MN
442
443 struct usb_ep *bulk_in;
444 struct usb_ep *bulk_out;
8ea864cf 445};
d5e2b67a 446
d5e2b67a 447
8ea864cf
MN
448static inline int __fsg_is_set(struct fsg_common *common,
449 const char *func, unsigned line)
450{
451 if (common->fsg)
452 return 1;
453 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
8876f5e7 454 WARN_ON(1);
8ea864cf
MN
455 return 0;
456}
457
458#define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
d5e2b67a 459
d23b0f08
MN
460
461static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
462{
463 return container_of(f, struct fsg_dev, function);
464}
465
466
d5e2b67a
MN
467typedef void (*fsg_routine_t)(struct fsg_dev *);
468
8ea864cf 469static int exception_in_progress(struct fsg_common *common)
d5e2b67a 470{
8ea864cf 471 return common->state > FSG_STATE_IDLE;
d5e2b67a
MN
472}
473
474/* Make bulk-out requests be divisible by the maxpacket size */
8ea864cf 475static void set_bulk_out_req_length(struct fsg_common *common,
d5e2b67a
MN
476 struct fsg_buffhd *bh, unsigned int length)
477{
478 unsigned int rem;
479
480 bh->bulk_out_intended_length = length;
8ea864cf 481 rem = length % common->bulk_out_maxpacket;
d5e2b67a 482 if (rem > 0)
8ea864cf 483 length += common->bulk_out_maxpacket - rem;
d5e2b67a
MN
484 bh->outreq->length = length;
485}
486
d5e2b67a
MN
487/*-------------------------------------------------------------------------*/
488
489static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
490{
491 const char *name;
492
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);
501}
502
503
d5e2b67a
MN
504/*-------------------------------------------------------------------------*/
505
506/* These routines may be called in process context or in_irq */
507
508/* Caller must hold fsg->lock */
8ea864cf 509static void wakeup_thread(struct fsg_common *common)
d5e2b67a
MN
510{
511 /* Tell the main thread that something has happened */
8ea864cf
MN
512 common->thread_wakeup_needed = 1;
513 if (common->thread_task)
514 wake_up_process(common->thread_task);
d5e2b67a
MN
515}
516
517
8ea864cf 518static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
d5e2b67a
MN
519{
520 unsigned long flags;
521
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. */
8ea864cf
MN
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)
d5e2b67a 530 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
8ea864cf 531 common->thread_task);
d5e2b67a 532 }
8ea864cf 533 spin_unlock_irqrestore(&common->lock, flags);
d5e2b67a
MN
534}
535
536
537/*-------------------------------------------------------------------------*/
538
8ea864cf 539static int ep0_queue(struct fsg_common *common)
d5e2b67a
MN
540{
541 int rc;
542
8ea864cf
MN
543 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
544 common->ep0->driver_data = common;
d5e2b67a 545 if (rc != 0 && rc != -ESHUTDOWN) {
d5e2b67a 546 /* We can't do much more than wait for a reset */
8ea864cf
MN
547 WARNING(common, "error in submission: %s --> %d\n",
548 common->ep0->name, rc);
d5e2b67a
MN
549 }
550 return rc;
551}
552
d5e2b67a
MN
553/*-------------------------------------------------------------------------*/
554
555/* Bulk and interrupt endpoint completion handlers.
556 * These always run in_irq. */
557
558static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
559{
8ea864cf 560 struct fsg_common *common = ep->driver_data;
d5e2b67a
MN
561 struct fsg_buffhd *bh = req->context;
562
563 if (req->status || req->actual != req->length)
8ea864cf 564 DBG(common, "%s --> %d, %u/%u\n", __func__,
d5e2b67a 565 req->status, req->actual, req->length);
d26a6aa0 566 if (req->status == -ECONNRESET) /* Request was cancelled */
d5e2b67a
MN
567 usb_ep_fifo_flush(ep);
568
569 /* Hold the lock while we update the request and buffer states */
570 smp_wmb();
8ea864cf 571 spin_lock(&common->lock);
d5e2b67a
MN
572 bh->inreq_busy = 0;
573 bh->state = BUF_STATE_EMPTY;
8ea864cf
MN
574 wakeup_thread(common);
575 spin_unlock(&common->lock);
d5e2b67a
MN
576}
577
578static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
579{
8ea864cf 580 struct fsg_common *common = ep->driver_data;
d5e2b67a
MN
581 struct fsg_buffhd *bh = req->context;
582
8ea864cf 583 dump_msg(common, "bulk-out", req->buf, req->actual);
d5e2b67a 584 if (req->status || req->actual != bh->bulk_out_intended_length)
8ea864cf 585 DBG(common, "%s --> %d, %u/%u\n", __func__,
d5e2b67a
MN
586 req->status, req->actual,
587 bh->bulk_out_intended_length);
d26a6aa0 588 if (req->status == -ECONNRESET) /* Request was cancelled */
d5e2b67a
MN
589 usb_ep_fifo_flush(ep);
590
591 /* Hold the lock while we update the request and buffer states */
592 smp_wmb();
8ea864cf 593 spin_lock(&common->lock);
d5e2b67a
MN
594 bh->outreq_busy = 0;
595 bh->state = BUF_STATE_FULL;
8ea864cf
MN
596 wakeup_thread(common);
597 spin_unlock(&common->lock);
d5e2b67a
MN
598}
599
600
d5e2b67a
MN
601/*-------------------------------------------------------------------------*/
602
603/* Ep0 class-specific handlers. These always run in_irq. */
604
d23b0f08 605static int fsg_setup(struct usb_function *f,
d5e2b67a
MN
606 const struct usb_ctrlrequest *ctrl)
607{
d23b0f08 608 struct fsg_dev *fsg = fsg_from_func(f);
8ea864cf 609 struct usb_request *req = fsg->common->ep0req;
d5e2b67a 610 u16 w_index = le16_to_cpu(ctrl->wIndex);
93bcf12e 611 u16 w_value = le16_to_cpu(ctrl->wValue);
d5e2b67a
MN
612 u16 w_length = le16_to_cpu(ctrl->wLength);
613
b894f60a 614 if (!fsg_is_set(fsg->common))
93bcf12e 615 return -EOPNOTSUPP;
d5e2b67a 616
93bcf12e 617 switch (ctrl->bRequest) {
d5e2b67a 618
93bcf12e
MN
619 case USB_BULK_RESET_REQUEST:
620 if (ctrl->bRequestType !=
621 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
d5e2b67a 622 break;
d23b0f08 623 if (w_index != fsg->interface_number || w_value != 0)
93bcf12e 624 return -EDOM;
d5e2b67a 625
93bcf12e
MN
626 /* Raise an exception to stop the current operation
627 * and reinitialize our state. */
628 DBG(fsg, "bulk reset request\n");
8ea864cf 629 raise_exception(fsg->common, FSG_STATE_RESET);
93bcf12e 630 return DELAYED_STATUS;
d5e2b67a 631
93bcf12e
MN
632 case USB_BULK_GET_MAX_LUN_REQUEST:
633 if (ctrl->bRequestType !=
634 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
d5e2b67a 635 break;
d23b0f08 636 if (w_index != fsg->interface_number || w_value != 0)
93bcf12e
MN
637 return -EDOM;
638 VDBG(fsg, "get max LUN\n");
a41ae418 639 *(u8 *) req->buf = fsg->common->nluns - 1;
b00ce11f
MN
640
641 /* Respond with data/status */
d7e18a9f 642 req->length = min((u16)1, w_length);
b00ce11f 643 return ep0_queue(fsg->common);
93bcf12e
MN
644 }
645
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;
d5e2b67a
MN
652}
653
654
d5e2b67a
MN
655/*-------------------------------------------------------------------------*/
656
657/* All the following routines run in process context */
658
659
660/* Use this for bulk or interrupt transfers, not ep0 */
661static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
662 struct usb_request *req, int *pbusy,
663 enum fsg_buffer_state *state)
664{
665 int rc;
666
667 if (ep == fsg->bulk_in)
668 dump_msg(fsg, "bulk-in", req->buf, req->length);
d5e2b67a 669
8ea864cf 670 spin_lock_irq(&fsg->common->lock);
d5e2b67a
MN
671 *pbusy = 1;
672 *state = BUF_STATE_BUSY;
8ea864cf 673 spin_unlock_irq(&fsg->common->lock);
d5e2b67a
MN
674 rc = usb_ep_queue(ep, req, GFP_KERNEL);
675 if (rc != 0) {
676 *pbusy = 0;
677 *state = BUF_STATE_EMPTY;
678
679 /* We can't do much more than wait for a reset */
680
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);
687 }
688}
689
8ea864cf
MN
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
695
696#define START_TRANSFER(common, ep_name, req, pbusy, state) \
697 START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
698
699
d5e2b67a 700
8ea864cf 701static int sleep_thread(struct fsg_common *common)
d5e2b67a
MN
702{
703 int rc = 0;
704
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;
712 }
8ea864cf 713 if (common->thread_wakeup_needed)
d5e2b67a
MN
714 break;
715 schedule();
716 }
717 __set_current_state(TASK_RUNNING);
8ea864cf 718 common->thread_wakeup_needed = 0;
d5e2b67a
MN
719 return rc;
720}
721
722
723/*-------------------------------------------------------------------------*/
724
8ea864cf 725static int do_read(struct fsg_common *common)
d5e2b67a 726{
8ea864cf 727 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
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;
736
737 /* Get the starting Logical Block Address and check that it's
738 * not too big */
8ea864cf
MN
739 if (common->cmnd[0] == SC_READ_6)
740 lba = get_unaligned_be24(&common->cmnd[1]);
d5e2b67a 741 else {
8ea864cf 742 lba = get_unaligned_be32(&common->cmnd[2]);
d5e2b67a
MN
743
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. */
8ea864cf 747 if ((common->cmnd[1] & ~0x18) != 0) {
d5e2b67a
MN
748 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
749 return -EINVAL;
750 }
751 }
752 if (lba >= curlun->num_sectors) {
753 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
754 return -EINVAL;
755 }
756 file_offset = ((loff_t) lba) << 9;
757
758 /* Carry out the file reads */
8ea864cf 759 amount_left = common->data_size_from_cmnd;
d5e2b67a 760 if (unlikely(amount_left == 0))
d26a6aa0 761 return -EIO; /* No default reply */
d5e2b67a
MN
762
763 for (;;) {
764
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. */
93bcf12e 773 amount = min(amount_left, FSG_BUFLEN);
d5e2b67a
MN
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);
780
781 /* Wait for the next buffer to become available */
8ea864cf 782 bh = common->next_buffhd_to_fill;
d5e2b67a 783 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 784 rc = sleep_thread(common);
d5e2b67a
MN
785 if (rc)
786 return rc;
787 }
788
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;
799 }
800
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;
811
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);
d26a6aa0 819 nread -= (nread & 511); /* Round down to a block */
d5e2b67a
MN
820 }
821 file_offset += nread;
822 amount_left -= nread;
8ea864cf 823 common->residue -= nread;
d5e2b67a
MN
824 bh->inreq->length = nread;
825 bh->state = BUF_STATE_FULL;
826
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;
833 }
834
835 if (amount_left == 0)
d26a6aa0 836 break; /* No more left to read */
d5e2b67a
MN
837
838 /* Send this buffer and go read some more */
839 bh->inreq->zero = 0;
8ea864cf
MN
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;
d5e2b67a
MN
846 }
847
d26a6aa0 848 return -EIO; /* No default reply */
d5e2b67a
MN
849}
850
851
852/*-------------------------------------------------------------------------*/
853
8ea864cf 854static int do_write(struct fsg_common *common)
d5e2b67a 855{
8ea864cf 856 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
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;
866
867 if (curlun->ro) {
868 curlun->sense_data = SS_WRITE_PROTECTED;
869 return -EINVAL;
870 }
871 spin_lock(&curlun->filp->f_lock);
d26a6aa0 872 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
d5e2b67a
MN
873 spin_unlock(&curlun->filp->f_lock);
874
875 /* Get the starting Logical Block Address and check that it's
876 * not too big */
8ea864cf
MN
877 if (common->cmnd[0] == SC_WRITE_6)
878 lba = get_unaligned_be24(&common->cmnd[1]);
d5e2b67a 879 else {
8ea864cf 880 lba = get_unaligned_be32(&common->cmnd[2]);
d5e2b67a
MN
881
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. */
8ea864cf 886 if (common->cmnd[1] & ~0x18) {
d5e2b67a
MN
887 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
888 return -EINVAL;
889 }
8ea864cf 890 if (common->cmnd[1] & 0x08) { /* FUA */
d5e2b67a
MN
891 spin_lock(&curlun->filp->f_lock);
892 curlun->filp->f_flags |= O_SYNC;
893 spin_unlock(&curlun->filp->f_lock);
894 }
895 }
896 if (lba >= curlun->num_sectors) {
897 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
898 return -EINVAL;
899 }
900
901 /* Carry out the file writes */
902 get_some_more = 1;
903 file_offset = usb_offset = ((loff_t) lba) << 9;
8ea864cf
MN
904 amount_left_to_req = common->data_size_from_cmnd;
905 amount_left_to_write = common->data_size_from_cmnd;
d5e2b67a
MN
906
907 while (amount_left_to_write > 0) {
908
909 /* Queue a request for more data from the host */
8ea864cf 910 bh = common->next_buffhd_to_fill;
d5e2b67a
MN
911 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
912
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. */
93bcf12e 922 amount = min(amount_left_to_req, FSG_BUFLEN);
d5e2b67a
MN
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);
929
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;
937 }
938 amount -= (amount & 511);
939 if (amount == 0) {
940
941 /* Why were we were asked to transfer a
942 * partial block? */
943 get_some_more = 0;
944 continue;
945 }
946
947 /* Get the next buffer */
948 usb_offset += amount;
8ea864cf 949 common->usb_amount_left -= amount;
d5e2b67a
MN
950 amount_left_to_req -= amount;
951 if (amount_left_to_req == 0)
952 get_some_more = 0;
953
954 /* amount is always divisible by 512, hence by
955 * the bulk-out maxpacket size */
d26a6aa0
MN
956 bh->outreq->length = amount;
957 bh->bulk_out_intended_length = amount;
d5e2b67a 958 bh->outreq->short_not_ok = 1;
8ea864cf
MN
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;
d5e2b67a
MN
965 continue;
966 }
967
968 /* Write the received data to the backing file */
8ea864cf 969 bh = common->next_buffhd_to_drain;
d5e2b67a 970 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
d26a6aa0 971 break; /* We stopped early */
d5e2b67a
MN
972 if (bh->state == BUF_STATE_FULL) {
973 smp_rmb();
8ea864cf 974 common->next_buffhd_to_drain = bh->next;
d5e2b67a
MN
975 bh->state = BUF_STATE_EMPTY;
976
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;
983 }
984
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;
992 }
993
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))
d26a6aa0 1003 return -EINTR; /* Interrupted! */
d5e2b67a
MN
1004
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);
d26a6aa0 1013 /* Round down to a block */
d5e2b67a
MN
1014 }
1015 file_offset += nwritten;
1016 amount_left_to_write -= nwritten;
8ea864cf 1017 common->residue -= nwritten;
d5e2b67a
MN
1018
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;
1025 }
1026
1027 /* Did the host decide to stop early? */
1028 if (bh->outreq->actual != bh->outreq->length) {
8ea864cf 1029 common->short_packet_received = 1;
d5e2b67a
MN
1030 break;
1031 }
1032 continue;
1033 }
1034
1035 /* Wait for something to happen */
8ea864cf 1036 rc = sleep_thread(common);
d5e2b67a
MN
1037 if (rc)
1038 return rc;
1039 }
1040
d26a6aa0 1041 return -EIO; /* No default reply */
d5e2b67a
MN
1042}
1043
1044
1045/*-------------------------------------------------------------------------*/
1046
8ea864cf 1047static int do_synchronize_cache(struct fsg_common *common)
d5e2b67a 1048{
8ea864cf 1049 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1050 int rc;
1051
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;
1058}
1059
1060
1061/*-------------------------------------------------------------------------*/
1062
1063static void invalidate_sub(struct fsg_lun *curlun)
1064{
1065 struct file *filp = curlun->filp;
1066 struct inode *inode = filp->f_path.dentry->d_inode;
1067 unsigned long rc;
1068
1069 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
2ecdc82e 1070 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
d5e2b67a
MN
1071}
1072
8ea864cf 1073static int do_verify(struct fsg_common *common)
d5e2b67a 1074{
8ea864cf 1075 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1076 u32 lba;
1077 u32 verification_length;
8ea864cf 1078 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
d5e2b67a
MN
1079 loff_t file_offset, file_offset_tmp;
1080 u32 amount_left;
1081 unsigned int amount;
1082 ssize_t nread;
1083
1084 /* Get the starting Logical Block Address and check that it's
1085 * not too big */
8ea864cf 1086 lba = get_unaligned_be32(&common->cmnd[2]);
d5e2b67a
MN
1087 if (lba >= curlun->num_sectors) {
1088 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1089 return -EINVAL;
1090 }
1091
1092 /* We allow DPO (Disable Page Out = don't save data in the
1093 * cache) but we don't implement it. */
8ea864cf 1094 if (common->cmnd[1] & ~0x10) {
d5e2b67a
MN
1095 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1096 return -EINVAL;
1097 }
1098
8ea864cf 1099 verification_length = get_unaligned_be16(&common->cmnd[7]);
d5e2b67a 1100 if (unlikely(verification_length == 0))
d26a6aa0 1101 return -EIO; /* No default reply */
d5e2b67a
MN
1102
1103 /* Prepare to carry out the file verify */
1104 amount_left = verification_length << 9;
1105 file_offset = ((loff_t) lba) << 9;
1106
1107 /* Write out all the dirty buffers before invalidating them */
1108 fsg_lun_fsync_sub(curlun);
1109 if (signal_pending(current))
1110 return -EINTR;
1111
1112 invalidate_sub(curlun);
1113 if (signal_pending(current))
1114 return -EINTR;
1115
1116 /* Just try to read the requested blocks */
1117 while (amount_left > 0) {
1118
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. */
93bcf12e 1125 amount = min(amount_left, FSG_BUFLEN);
d5e2b67a
MN
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;
1134 }
1135
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;
1146
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);
d26a6aa0 1154 nread -= (nread & 511); /* Round down to a sector */
d5e2b67a
MN
1155 }
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;
1161 }
1162 file_offset += nread;
1163 amount_left -= nread;
1164 }
1165 return 0;
1166}
1167
1168
1169/*-------------------------------------------------------------------------*/
1170
8ea864cf 1171static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1172{
8ea864cf 1173 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1174 u8 *buf = (u8 *) bh->buf;
1175
481e4929 1176 if (!curlun) { /* Unsupported LUNs are okay */
8ea864cf 1177 common->bad_lun_okay = 1;
d5e2b67a 1178 memset(buf, 0, 36);
d26a6aa0
MN
1179 buf[0] = 0x7f; /* Unsupported, no device-type */
1180 buf[4] = 31; /* Additional length */
d5e2b67a
MN
1181 return 36;
1182 }
1183
481e4929
MN
1184 buf[0] = curlun->cdrom ? TYPE_CDROM : TYPE_DISK;
1185 buf[1] = curlun->removable ? 0x80 : 0;
d26a6aa0
MN
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 */
481e4929
MN
1190 buf[6] = 0;
1191 buf[7] = 0;
8ea864cf 1192 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
d5e2b67a
MN
1193 return 36;
1194}
1195
1196
8ea864cf 1197static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1198{
8ea864cf 1199 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1200 u8 *buf = (u8 *) bh->buf;
1201 u32 sd, sdinfo;
1202 int valid;
1203
1204 /*
1205 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1206 *
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.
1216 *
1217 * FSG normally uses option a); enable this code to use option b).
1218 */
1219#if 0
1220 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1221 curlun->sense_data = curlun->unit_attention_data;
1222 curlun->unit_attention_data = SS_NO_SENSE;
1223 }
1224#endif
1225
d26a6aa0 1226 if (!curlun) { /* Unsupported LUNs are okay */
8ea864cf 1227 common->bad_lun_okay = 1;
d5e2b67a
MN
1228 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1229 sdinfo = 0;
1230 valid = 0;
1231 } else {
1232 sd = curlun->sense_data;
1233 sdinfo = curlun->sense_data_info;
1234 valid = curlun->info_valid << 7;
1235 curlun->sense_data = SS_NO_SENSE;
1236 curlun->sense_data_info = 0;
1237 curlun->info_valid = 0;
1238 }
1239
1240 memset(buf, 0, 18);
d26a6aa0 1241 buf[0] = valid | 0x70; /* Valid, current error */
d5e2b67a
MN
1242 buf[2] = SK(sd);
1243 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
d26a6aa0 1244 buf[7] = 18 - 8; /* Additional sense length */
d5e2b67a
MN
1245 buf[12] = ASC(sd);
1246 buf[13] = ASCQ(sd);
1247 return 18;
1248}
1249
1250
8ea864cf 1251static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1252{
8ea864cf
MN
1253 struct fsg_lun *curlun = common->curlun;
1254 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1255 int pmi = common->cmnd[8];
d5e2b67a
MN
1256 u8 *buf = (u8 *) bh->buf;
1257
1258 /* Check the PMI and LBA fields */
1259 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1260 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1261 return -EINVAL;
1262 }
1263
1264 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1265 /* Max logical block */
1266 put_unaligned_be32(512, &buf[4]); /* Block length */
1267 return 8;
1268}
1269
1270
8ea864cf 1271static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1272{
8ea864cf
MN
1273 struct fsg_lun *curlun = common->curlun;
1274 int msf = common->cmnd[1] & 0x02;
1275 u32 lba = get_unaligned_be32(&common->cmnd[2]);
d5e2b67a
MN
1276 u8 *buf = (u8 *) bh->buf;
1277
8ea864cf 1278 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
d5e2b67a
MN
1279 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1280 return -EINVAL;
1281 }
1282 if (lba >= curlun->num_sectors) {
1283 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1284 return -EINVAL;
1285 }
1286
1287 memset(buf, 0, 8);
1288 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1289 store_cdrom_address(&buf[4], msf, lba);
1290 return 8;
1291}
1292
1293
8ea864cf 1294static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1295{
8ea864cf
MN
1296 struct fsg_lun *curlun = common->curlun;
1297 int msf = common->cmnd[1] & 0x02;
1298 int start_track = common->cmnd[6];
d5e2b67a
MN
1299 u8 *buf = (u8 *) bh->buf;
1300
8ea864cf 1301 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
d5e2b67a
MN
1302 start_track > 1) {
1303 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1304 return -EINVAL;
1305 }
1306
1307 memset(buf, 0, 20);
1308 buf[1] = (20-2); /* TOC data length */
1309 buf[2] = 1; /* First track number */
1310 buf[3] = 1; /* Last track number */
1311 buf[5] = 0x16; /* Data track, copying allowed */
1312 buf[6] = 0x01; /* Only track is number 1 */
1313 store_cdrom_address(&buf[8], msf, 0);
1314
1315 buf[13] = 0x16; /* Lead-out track is data */
1316 buf[14] = 0xAA; /* Lead-out track number */
1317 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1318 return 20;
1319}
1320
1321
8ea864cf 1322static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1323{
8ea864cf
MN
1324 struct fsg_lun *curlun = common->curlun;
1325 int mscmnd = common->cmnd[0];
d5e2b67a
MN
1326 u8 *buf = (u8 *) bh->buf;
1327 u8 *buf0 = buf;
1328 int pc, page_code;
1329 int changeable_values, all_pages;
1330 int valid_page = 0;
1331 int len, limit;
1332
8ea864cf 1333 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
d5e2b67a
MN
1334 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1335 return -EINVAL;
1336 }
8ea864cf
MN
1337 pc = common->cmnd[2] >> 6;
1338 page_code = common->cmnd[2] & 0x3f;
d5e2b67a
MN
1339 if (pc == 3) {
1340 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1341 return -EINVAL;
1342 }
1343 changeable_values = (pc == 1);
1344 all_pages = (page_code == 0x3f);
1345
1346 /* Write the mode parameter header. Fixed values are: default
1347 * medium type, no cache control (DPOFUA), and no block descriptors.
1348 * The only variable value is the WriteProtect bit. We will fill in
1349 * the mode data length later. */
1350 memset(buf, 0, 8);
1351 if (mscmnd == SC_MODE_SENSE_6) {
d26a6aa0 1352 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
d5e2b67a
MN
1353 buf += 4;
1354 limit = 255;
d26a6aa0
MN
1355 } else { /* SC_MODE_SENSE_10 */
1356 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
d5e2b67a 1357 buf += 8;
d26a6aa0 1358 limit = 65535; /* Should really be FSG_BUFLEN */
d5e2b67a
MN
1359 }
1360
1361 /* No block descriptors */
1362
1363 /* The mode pages, in numerical order. The only page we support
1364 * is the Caching page. */
1365 if (page_code == 0x08 || all_pages) {
1366 valid_page = 1;
d26a6aa0
MN
1367 buf[0] = 0x08; /* Page code */
1368 buf[1] = 10; /* Page length */
1369 memset(buf+2, 0, 10); /* None of the fields are changeable */
d5e2b67a
MN
1370
1371 if (!changeable_values) {
d26a6aa0
MN
1372 buf[2] = 0x04; /* Write cache enable, */
1373 /* Read cache not disabled */
1374 /* No cache retention priorities */
d5e2b67a
MN
1375 put_unaligned_be16(0xffff, &buf[4]);
1376 /* Don't disable prefetch */
1377 /* Minimum prefetch = 0 */
1378 put_unaligned_be16(0xffff, &buf[8]);
1379 /* Maximum prefetch */
1380 put_unaligned_be16(0xffff, &buf[10]);
1381 /* Maximum prefetch ceiling */
1382 }
1383 buf += 12;
1384 }
1385
1386 /* Check that a valid page was requested and the mode data length
1387 * isn't too long. */
1388 len = buf - buf0;
1389 if (!valid_page || len > limit) {
1390 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1391 return -EINVAL;
1392 }
1393
1394 /* Store the mode data length */
1395 if (mscmnd == SC_MODE_SENSE_6)
1396 buf0[0] = len - 1;
1397 else
1398 put_unaligned_be16(len - 2, buf0);
1399 return len;
1400}
1401
1402
8ea864cf 1403static int do_start_stop(struct fsg_common *common)
d5e2b67a 1404{
31436a1a
FC
1405 struct fsg_lun *curlun = common->curlun;
1406 int loej, start;
1407
1408 if (!curlun) {
481e4929 1409 return -EINVAL;
31436a1a
FC
1410 } else if (!curlun->removable) {
1411 curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a 1412 return -EINVAL;
8876f5e7
MN
1413 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1414 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
31436a1a
FC
1415 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1416 return -EINVAL;
1417 }
1418
8876f5e7
MN
1419 loej = common->cmnd[4] & 0x02;
1420 start = common->cmnd[4] & 0x01;
31436a1a 1421
8876f5e7
MN
1422 /* Our emulation doesn't support mounting; the medium is
1423 * available for use as soon as it is loaded. */
1424 if (start) {
31436a1a
FC
1425 if (!fsg_lun_is_open(curlun)) {
1426 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1427 return -EINVAL;
1428 }
8876f5e7 1429 return 0;
31436a1a 1430 }
8876f5e7
MN
1431
1432 /* Are we allowed to unload the media? */
1433 if (curlun->prevent_medium_removal) {
1434 LDBG(curlun, "unload attempt prevented\n");
1435 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1436 return -EINVAL;
1437 }
1438
1439 if (!loej)
1440 return 0;
1441
1442 /* Simulate an unload/eject */
1443 if (common->ops && common->ops->pre_eject) {
1444 int r = common->ops->pre_eject(common, curlun,
1445 curlun - common->luns);
1446 if (unlikely(r < 0))
1447 return r;
1448 else if (r)
1449 return 0;
1450 }
1451
1452 up_read(&common->filesem);
1453 down_write(&common->filesem);
1454 fsg_lun_close(curlun);
1455 up_write(&common->filesem);
1456 down_read(&common->filesem);
1457
1458 return common->ops && common->ops->post_eject
1459 ? min(0, common->ops->post_eject(common, curlun,
1460 curlun - common->luns))
1461 : 0;
d5e2b67a
MN
1462}
1463
1464
8ea864cf 1465static int do_prevent_allow(struct fsg_common *common)
d5e2b67a 1466{
8ea864cf 1467 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1468 int prevent;
1469
8ea864cf 1470 if (!common->curlun) {
481e4929 1471 return -EINVAL;
8ea864cf
MN
1472 } else if (!common->curlun->removable) {
1473 common->curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
1474 return -EINVAL;
1475 }
1476
8ea864cf
MN
1477 prevent = common->cmnd[4] & 0x01;
1478 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
d5e2b67a
MN
1479 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1480 return -EINVAL;
1481 }
1482
1483 if (curlun->prevent_medium_removal && !prevent)
1484 fsg_lun_fsync_sub(curlun);
1485 curlun->prevent_medium_removal = prevent;
1486 return 0;
1487}
1488
1489
8ea864cf 1490static int do_read_format_capacities(struct fsg_common *common,
d5e2b67a
MN
1491 struct fsg_buffhd *bh)
1492{
8ea864cf 1493 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1494 u8 *buf = (u8 *) bh->buf;
1495
1496 buf[0] = buf[1] = buf[2] = 0;
d26a6aa0 1497 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
d5e2b67a
MN
1498 buf += 4;
1499
1500 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1501 /* Number of blocks */
1502 put_unaligned_be32(512, &buf[4]); /* Block length */
1503 buf[4] = 0x02; /* Current capacity */
1504 return 12;
1505}
1506
1507
8ea864cf 1508static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1509{
8ea864cf 1510 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1511
1512 /* We don't support MODE SELECT */
8ea864cf
MN
1513 if (curlun)
1514 curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
1515 return -EINVAL;
1516}
1517
1518
1519/*-------------------------------------------------------------------------*/
1520
1521static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1522{
1523 int rc;
1524
1525 rc = fsg_set_halt(fsg, fsg->bulk_in);
1526 if (rc == -EAGAIN)
1527 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1528 while (rc != 0) {
1529 if (rc != -EAGAIN) {
1530 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1531 rc = 0;
1532 break;
1533 }
1534
1535 /* Wait for a short time and then try again */
1536 if (msleep_interruptible(100) != 0)
1537 return -EINTR;
1538 rc = usb_ep_set_halt(fsg->bulk_in);
1539 }
1540 return rc;
1541}
1542
1543static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1544{
1545 int rc;
1546
1547 DBG(fsg, "bulk-in set wedge\n");
1548 rc = usb_ep_set_wedge(fsg->bulk_in);
1549 if (rc == -EAGAIN)
1550 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1551 while (rc != 0) {
1552 if (rc != -EAGAIN) {
1553 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1554 rc = 0;
1555 break;
1556 }
1557
1558 /* Wait for a short time and then try again */
1559 if (msleep_interruptible(100) != 0)
1560 return -EINTR;
1561 rc = usb_ep_set_wedge(fsg->bulk_in);
1562 }
1563 return rc;
1564}
1565
1566static int pad_with_zeros(struct fsg_dev *fsg)
1567{
a41ae418 1568 struct fsg_buffhd *bh = fsg->common->next_buffhd_to_fill;
d5e2b67a
MN
1569 u32 nkeep = bh->inreq->length;
1570 u32 nsend;
1571 int rc;
1572
d26a6aa0 1573 bh->state = BUF_STATE_EMPTY; /* For the first iteration */
8ea864cf
MN
1574 fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1575 while (fsg->common->usb_amount_left > 0) {
d5e2b67a
MN
1576
1577 /* Wait for the next buffer to be free */
1578 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 1579 rc = sleep_thread(fsg->common);
d5e2b67a
MN
1580 if (rc)
1581 return rc;
1582 }
1583
8ea864cf 1584 nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
d5e2b67a
MN
1585 memset(bh->buf + nkeep, 0, nsend - nkeep);
1586 bh->inreq->length = nsend;
1587 bh->inreq->zero = 0;
1588 start_transfer(fsg, fsg->bulk_in, bh->inreq,
1589 &bh->inreq_busy, &bh->state);
a41ae418 1590 bh = fsg->common->next_buffhd_to_fill = bh->next;
8ea864cf 1591 fsg->common->usb_amount_left -= nsend;
d5e2b67a
MN
1592 nkeep = 0;
1593 }
1594 return 0;
1595}
1596
8ea864cf 1597static int throw_away_data(struct fsg_common *common)
d5e2b67a
MN
1598{
1599 struct fsg_buffhd *bh;
1600 u32 amount;
1601 int rc;
1602
8ea864cf
MN
1603 for (bh = common->next_buffhd_to_drain;
1604 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1605 bh = common->next_buffhd_to_drain) {
d5e2b67a
MN
1606
1607 /* Throw away the data in a filled buffer */
1608 if (bh->state == BUF_STATE_FULL) {
1609 smp_rmb();
1610 bh->state = BUF_STATE_EMPTY;
8ea864cf 1611 common->next_buffhd_to_drain = bh->next;
d5e2b67a
MN
1612
1613 /* A short packet or an error ends everything */
1614 if (bh->outreq->actual != bh->outreq->length ||
1615 bh->outreq->status != 0) {
8ea864cf
MN
1616 raise_exception(common,
1617 FSG_STATE_ABORT_BULK_OUT);
d5e2b67a
MN
1618 return -EINTR;
1619 }
1620 continue;
1621 }
1622
1623 /* Try to submit another request if we need one */
8ea864cf
MN
1624 bh = common->next_buffhd_to_fill;
1625 if (bh->state == BUF_STATE_EMPTY
1626 && common->usb_amount_left > 0) {
1627 amount = min(common->usb_amount_left, FSG_BUFLEN);
d5e2b67a
MN
1628
1629 /* amount is always divisible by 512, hence by
1630 * the bulk-out maxpacket size */
d26a6aa0
MN
1631 bh->outreq->length = amount;
1632 bh->bulk_out_intended_length = amount;
d5e2b67a 1633 bh->outreq->short_not_ok = 1;
8ea864cf
MN
1634 START_TRANSFER_OR(common, bulk_out, bh->outreq,
1635 &bh->outreq_busy, &bh->state)
1636 /* Don't know what to do if
1637 * common->fsg is NULL */
1638 return -EIO;
1639 common->next_buffhd_to_fill = bh->next;
1640 common->usb_amount_left -= amount;
d5e2b67a
MN
1641 continue;
1642 }
1643
1644 /* Otherwise wait for something to happen */
8ea864cf 1645 rc = sleep_thread(common);
d5e2b67a
MN
1646 if (rc)
1647 return rc;
1648 }
1649 return 0;
1650}
1651
1652
8ea864cf 1653static int finish_reply(struct fsg_common *common)
d5e2b67a 1654{
8ea864cf 1655 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
d5e2b67a
MN
1656 int rc = 0;
1657
8ea864cf 1658 switch (common->data_dir) {
d5e2b67a 1659 case DATA_DIR_NONE:
d26a6aa0 1660 break; /* Nothing to send */
d5e2b67a
MN
1661
1662 /* If we don't know whether the host wants to read or write,
1663 * this must be CB or CBI with an unknown command. We mustn't
1664 * try to send or receive any data. So stall both bulk pipes
1665 * if we can and wait for a reset. */
1666 case DATA_DIR_UNKNOWN:
8ea864cf
MN
1667 if (!common->can_stall) {
1668 /* Nothing */
1669 } else if (fsg_is_set(common)) {
1670 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1671 rc = halt_bulk_in_endpoint(common->fsg);
1672 } else {
1673 /* Don't know what to do if common->fsg is NULL */
1674 rc = -EIO;
d5e2b67a
MN
1675 }
1676 break;
1677
1678 /* All but the last buffer of data must have already been sent */
1679 case DATA_DIR_TO_HOST:
8ea864cf 1680 if (common->data_size == 0) {
93bcf12e 1681 /* Nothing to send */
d5e2b67a
MN
1682
1683 /* If there's no residue, simply send the last buffer */
8ea864cf 1684 } else if (common->residue == 0) {
d5e2b67a 1685 bh->inreq->zero = 0;
8ea864cf
MN
1686 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1687 &bh->inreq_busy, &bh->state)
1688 return -EIO;
1689 common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1690
1691 /* For Bulk-only, if we're allowed to stall then send the
1692 * short packet and halt the bulk-in endpoint. If we can't
1693 * stall, pad out the remaining data with 0's. */
8ea864cf 1694 } else if (common->can_stall) {
93bcf12e 1695 bh->inreq->zero = 1;
8ea864cf
MN
1696 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1697 &bh->inreq_busy, &bh->state)
1698 /* Don't know what to do if
1699 * common->fsg is NULL */
1700 rc = -EIO;
1701 common->next_buffhd_to_fill = bh->next;
1702 if (common->fsg)
1703 rc = halt_bulk_in_endpoint(common->fsg);
1704 } else if (fsg_is_set(common)) {
1705 rc = pad_with_zeros(common->fsg);
93bcf12e 1706 } else {
8ea864cf
MN
1707 /* Don't know what to do if common->fsg is NULL */
1708 rc = -EIO;
d5e2b67a
MN
1709 }
1710 break;
1711
1712 /* We have processed all we want from the data the host has sent.
1713 * There may still be outstanding bulk-out requests. */
1714 case DATA_DIR_FROM_HOST:
8ea864cf 1715 if (common->residue == 0) {
d26a6aa0 1716 /* Nothing to receive */
d5e2b67a
MN
1717
1718 /* Did the host stop sending unexpectedly early? */
8ea864cf
MN
1719 } else if (common->short_packet_received) {
1720 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
d5e2b67a 1721 rc = -EINTR;
d5e2b67a
MN
1722
1723 /* We haven't processed all the incoming data. Even though
1724 * we may be allowed to stall, doing so would cause a race.
1725 * The controller may already have ACK'ed all the remaining
1726 * bulk-out packets, in which case the host wouldn't see a
1727 * STALL. Not realizing the endpoint was halted, it wouldn't
1728 * clear the halt -- leading to problems later on. */
1729#if 0
8ea864cf
MN
1730 } else if (common->can_stall) {
1731 if (fsg_is_set(common))
1732 fsg_set_halt(common->fsg,
1733 common->fsg->bulk_out);
1734 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
d5e2b67a 1735 rc = -EINTR;
d5e2b67a
MN
1736#endif
1737
1738 /* We can't stall. Read in the excess data and throw it
1739 * all away. */
d26a6aa0 1740 } else {
8ea864cf 1741 rc = throw_away_data(common);
d26a6aa0 1742 }
d5e2b67a
MN
1743 break;
1744 }
1745 return rc;
1746}
1747
1748
8ea864cf 1749static int send_status(struct fsg_common *common)
d5e2b67a 1750{
8ea864cf 1751 struct fsg_lun *curlun = common->curlun;
d5e2b67a 1752 struct fsg_buffhd *bh;
93bcf12e 1753 struct bulk_cs_wrap *csw;
d5e2b67a
MN
1754 int rc;
1755 u8 status = USB_STATUS_PASS;
1756 u32 sd, sdinfo = 0;
1757
1758 /* Wait for the next buffer to become available */
8ea864cf 1759 bh = common->next_buffhd_to_fill;
d5e2b67a 1760 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 1761 rc = sleep_thread(common);
d5e2b67a
MN
1762 if (rc)
1763 return rc;
1764 }
1765
1766 if (curlun) {
1767 sd = curlun->sense_data;
1768 sdinfo = curlun->sense_data_info;
8ea864cf 1769 } else if (common->bad_lun_okay)
d5e2b67a
MN
1770 sd = SS_NO_SENSE;
1771 else
1772 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1773
8ea864cf
MN
1774 if (common->phase_error) {
1775 DBG(common, "sending phase-error status\n");
d5e2b67a
MN
1776 status = USB_STATUS_PHASE_ERROR;
1777 sd = SS_INVALID_COMMAND;
1778 } else if (sd != SS_NO_SENSE) {
8ea864cf 1779 DBG(common, "sending command-failure status\n");
d5e2b67a 1780 status = USB_STATUS_FAIL;
8ea864cf 1781 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
d5e2b67a
MN
1782 " info x%x\n",
1783 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1784 }
1785
93bcf12e 1786 /* Store and send the Bulk-only CSW */
d26a6aa0 1787 csw = (void *)bh->buf;
d5e2b67a 1788
93bcf12e 1789 csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
8ea864cf
MN
1790 csw->Tag = common->tag;
1791 csw->Residue = cpu_to_le32(common->residue);
93bcf12e 1792 csw->Status = status;
d5e2b67a 1793
93bcf12e
MN
1794 bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1795 bh->inreq->zero = 0;
8ea864cf
MN
1796 START_TRANSFER_OR(common, bulk_in, bh->inreq,
1797 &bh->inreq_busy, &bh->state)
1798 /* Don't know what to do if common->fsg is NULL */
1799 return -EIO;
d5e2b67a 1800
8ea864cf 1801 common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1802 return 0;
1803}
1804
1805
1806/*-------------------------------------------------------------------------*/
1807
1808/* Check whether the command is properly formed and whether its data size
1809 * and direction agree with the values we already have. */
8ea864cf 1810static int check_command(struct fsg_common *common, int cmnd_size,
d5e2b67a
MN
1811 enum data_direction data_dir, unsigned int mask,
1812 int needs_medium, const char *name)
1813{
1814 int i;
8ea864cf 1815 int lun = common->cmnd[1] >> 5;
d5e2b67a
MN
1816 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1817 char hdlen[20];
1818 struct fsg_lun *curlun;
1819
d5e2b67a 1820 hdlen[0] = 0;
8ea864cf
MN
1821 if (common->data_dir != DATA_DIR_UNKNOWN)
1822 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1823 common->data_size);
1824 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
d26a6aa0 1825 name, cmnd_size, dirletter[(int) data_dir],
8ea864cf 1826 common->data_size_from_cmnd, common->cmnd_size, hdlen);
d5e2b67a
MN
1827
1828 /* We can't reply at all until we know the correct data direction
1829 * and size. */
8ea864cf 1830 if (common->data_size_from_cmnd == 0)
d5e2b67a 1831 data_dir = DATA_DIR_NONE;
8ea864cf
MN
1832 if (common->data_size < common->data_size_from_cmnd) {
1833 /* Host data size < Device data size is a phase error.
1834 * Carry out the command, but only transfer as much as
1835 * we are allowed. */
1836 common->data_size_from_cmnd = common->data_size;
1837 common->phase_error = 1;
d5e2b67a 1838 }
8ea864cf
MN
1839 common->residue = common->data_size;
1840 common->usb_amount_left = common->data_size;
d5e2b67a
MN
1841
1842 /* Conflicting data directions is a phase error */
8ea864cf
MN
1843 if (common->data_dir != data_dir
1844 && common->data_size_from_cmnd > 0) {
1845 common->phase_error = 1;
d5e2b67a
MN
1846 return -EINVAL;
1847 }
1848
1849 /* Verify the length of the command itself */
8ea864cf 1850 if (cmnd_size != common->cmnd_size) {
d5e2b67a
MN
1851
1852 /* Special case workaround: There are plenty of buggy SCSI
1853 * implementations. Many have issues with cbw->Length
1854 * field passing a wrong command size. For those cases we
1855 * always try to work around the problem by using the length
1856 * sent by the host side provided it is at least as large
1857 * as the correct command length.
1858 * Examples of such cases would be MS-Windows, which issues
1859 * REQUEST SENSE with cbw->Length == 12 where it should
1860 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1861 * REQUEST SENSE with cbw->Length == 10 where it should
1862 * be 6 as well.
1863 */
8ea864cf
MN
1864 if (cmnd_size <= common->cmnd_size) {
1865 DBG(common, "%s is buggy! Expected length %d "
a41ae418 1866 "but we got %d\n", name,
8ea864cf
MN
1867 cmnd_size, common->cmnd_size);
1868 cmnd_size = common->cmnd_size;
d5e2b67a 1869 } else {
8ea864cf 1870 common->phase_error = 1;
d5e2b67a
MN
1871 return -EINVAL;
1872 }
1873 }
1874
1875 /* Check that the LUN values are consistent */
8ea864cf
MN
1876 if (common->lun != lun)
1877 DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1878 common->lun, lun);
d5e2b67a
MN
1879
1880 /* Check the LUN */
8ea864cf
MN
1881 if (common->lun >= 0 && common->lun < common->nluns) {
1882 curlun = &common->luns[common->lun];
1883 common->curlun = curlun;
1884 if (common->cmnd[0] != SC_REQUEST_SENSE) {
d5e2b67a
MN
1885 curlun->sense_data = SS_NO_SENSE;
1886 curlun->sense_data_info = 0;
1887 curlun->info_valid = 0;
1888 }
1889 } else {
8ea864cf
MN
1890 common->curlun = NULL;
1891 curlun = NULL;
1892 common->bad_lun_okay = 0;
d5e2b67a
MN
1893
1894 /* INQUIRY and REQUEST SENSE commands are explicitly allowed
1895 * to use unsupported LUNs; all others may not. */
8ea864cf
MN
1896 if (common->cmnd[0] != SC_INQUIRY &&
1897 common->cmnd[0] != SC_REQUEST_SENSE) {
1898 DBG(common, "unsupported LUN %d\n", common->lun);
d5e2b67a
MN
1899 return -EINVAL;
1900 }
1901 }
1902
1903 /* If a unit attention condition exists, only INQUIRY and
1904 * REQUEST SENSE commands are allowed; anything else must fail. */
1905 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
8ea864cf
MN
1906 common->cmnd[0] != SC_INQUIRY &&
1907 common->cmnd[0] != SC_REQUEST_SENSE) {
d5e2b67a
MN
1908 curlun->sense_data = curlun->unit_attention_data;
1909 curlun->unit_attention_data = SS_NO_SENSE;
1910 return -EINVAL;
1911 }
1912
1913 /* Check that only command bytes listed in the mask are non-zero */
8ea864cf 1914 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
d5e2b67a 1915 for (i = 1; i < cmnd_size; ++i) {
8ea864cf 1916 if (common->cmnd[i] && !(mask & (1 << i))) {
d5e2b67a
MN
1917 if (curlun)
1918 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1919 return -EINVAL;
1920 }
1921 }
1922
1923 /* If the medium isn't mounted and the command needs to access
1924 * it, return an error. */
1925 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1926 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1927 return -EINVAL;
1928 }
1929
1930 return 0;
1931}
1932
1933
8ea864cf 1934static int do_scsi_command(struct fsg_common *common)
d5e2b67a
MN
1935{
1936 struct fsg_buffhd *bh;
1937 int rc;
1938 int reply = -EINVAL;
1939 int i;
1940 static char unknown[16];
1941
8ea864cf 1942 dump_cdb(common);
d5e2b67a
MN
1943
1944 /* Wait for the next buffer to become available for data or status */
8ea864cf
MN
1945 bh = common->next_buffhd_to_fill;
1946 common->next_buffhd_to_drain = bh;
d5e2b67a 1947 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 1948 rc = sleep_thread(common);
d5e2b67a
MN
1949 if (rc)
1950 return rc;
1951 }
8ea864cf
MN
1952 common->phase_error = 0;
1953 common->short_packet_received = 0;
d5e2b67a 1954
8ea864cf
MN
1955 down_read(&common->filesem); /* We're using the backing file */
1956 switch (common->cmnd[0]) {
d5e2b67a
MN
1957
1958 case SC_INQUIRY:
8ea864cf
MN
1959 common->data_size_from_cmnd = common->cmnd[4];
1960 reply = check_command(common, 6, DATA_DIR_TO_HOST,
d26a6aa0
MN
1961 (1<<4), 0,
1962 "INQUIRY");
1963 if (reply == 0)
8ea864cf 1964 reply = do_inquiry(common, bh);
d5e2b67a
MN
1965 break;
1966
1967 case SC_MODE_SELECT_6:
8ea864cf
MN
1968 common->data_size_from_cmnd = common->cmnd[4];
1969 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
d26a6aa0
MN
1970 (1<<1) | (1<<4), 0,
1971 "MODE SELECT(6)");
1972 if (reply == 0)
8ea864cf 1973 reply = do_mode_select(common, bh);
d5e2b67a
MN
1974 break;
1975
1976 case SC_MODE_SELECT_10:
8ea864cf
MN
1977 common->data_size_from_cmnd =
1978 get_unaligned_be16(&common->cmnd[7]);
1979 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
d26a6aa0
MN
1980 (1<<1) | (3<<7), 0,
1981 "MODE SELECT(10)");
1982 if (reply == 0)
8ea864cf 1983 reply = do_mode_select(common, bh);
d5e2b67a
MN
1984 break;
1985
1986 case SC_MODE_SENSE_6:
8ea864cf
MN
1987 common->data_size_from_cmnd = common->cmnd[4];
1988 reply = check_command(common, 6, DATA_DIR_TO_HOST,
d26a6aa0
MN
1989 (1<<1) | (1<<2) | (1<<4), 0,
1990 "MODE SENSE(6)");
1991 if (reply == 0)
8ea864cf 1992 reply = do_mode_sense(common, bh);
d5e2b67a
MN
1993 break;
1994
1995 case SC_MODE_SENSE_10:
8ea864cf
MN
1996 common->data_size_from_cmnd =
1997 get_unaligned_be16(&common->cmnd[7]);
1998 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
1999 (1<<1) | (1<<2) | (3<<7), 0,
2000 "MODE SENSE(10)");
2001 if (reply == 0)
8ea864cf 2002 reply = do_mode_sense(common, bh);
d5e2b67a
MN
2003 break;
2004
2005 case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
8ea864cf
MN
2006 common->data_size_from_cmnd = 0;
2007 reply = check_command(common, 6, DATA_DIR_NONE,
d26a6aa0
MN
2008 (1<<4), 0,
2009 "PREVENT-ALLOW MEDIUM REMOVAL");
2010 if (reply == 0)
8ea864cf 2011 reply = do_prevent_allow(common);
d5e2b67a
MN
2012 break;
2013
2014 case SC_READ_6:
8ea864cf
MN
2015 i = common->cmnd[4];
2016 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2017 reply = check_command(common, 6, DATA_DIR_TO_HOST,
d26a6aa0
MN
2018 (7<<1) | (1<<4), 1,
2019 "READ(6)");
2020 if (reply == 0)
8ea864cf 2021 reply = do_read(common);
d5e2b67a
MN
2022 break;
2023
2024 case SC_READ_10:
8ea864cf
MN
2025 common->data_size_from_cmnd =
2026 get_unaligned_be16(&common->cmnd[7]) << 9;
2027 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
2028 (1<<1) | (0xf<<2) | (3<<7), 1,
2029 "READ(10)");
2030 if (reply == 0)
8ea864cf 2031 reply = do_read(common);
d5e2b67a
MN
2032 break;
2033
2034 case SC_READ_12:
8ea864cf
MN
2035 common->data_size_from_cmnd =
2036 get_unaligned_be32(&common->cmnd[6]) << 9;
2037 reply = check_command(common, 12, DATA_DIR_TO_HOST,
d26a6aa0
MN
2038 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2039 "READ(12)");
2040 if (reply == 0)
8ea864cf 2041 reply = do_read(common);
d5e2b67a
MN
2042 break;
2043
2044 case SC_READ_CAPACITY:
8ea864cf
MN
2045 common->data_size_from_cmnd = 8;
2046 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
2047 (0xf<<2) | (1<<8), 1,
2048 "READ CAPACITY");
2049 if (reply == 0)
8ea864cf 2050 reply = do_read_capacity(common, bh);
d5e2b67a
MN
2051 break;
2052
2053 case SC_READ_HEADER:
8ea864cf 2054 if (!common->curlun || !common->curlun->cdrom)
d5e2b67a 2055 goto unknown_cmnd;
8ea864cf
MN
2056 common->data_size_from_cmnd =
2057 get_unaligned_be16(&common->cmnd[7]);
2058 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
2059 (3<<7) | (0x1f<<1), 1,
2060 "READ HEADER");
2061 if (reply == 0)
8ea864cf 2062 reply = do_read_header(common, bh);
d5e2b67a
MN
2063 break;
2064
2065 case SC_READ_TOC:
8ea864cf 2066 if (!common->curlun || !common->curlun->cdrom)
d5e2b67a 2067 goto unknown_cmnd;
8ea864cf
MN
2068 common->data_size_from_cmnd =
2069 get_unaligned_be16(&common->cmnd[7]);
2070 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
2071 (7<<6) | (1<<1), 1,
2072 "READ TOC");
2073 if (reply == 0)
8ea864cf 2074 reply = do_read_toc(common, bh);
d5e2b67a
MN
2075 break;
2076
2077 case SC_READ_FORMAT_CAPACITIES:
8ea864cf
MN
2078 common->data_size_from_cmnd =
2079 get_unaligned_be16(&common->cmnd[7]);
2080 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
2081 (3<<7), 1,
2082 "READ FORMAT CAPACITIES");
2083 if (reply == 0)
8ea864cf 2084 reply = do_read_format_capacities(common, bh);
d5e2b67a
MN
2085 break;
2086
2087 case SC_REQUEST_SENSE:
8ea864cf
MN
2088 common->data_size_from_cmnd = common->cmnd[4];
2089 reply = check_command(common, 6, DATA_DIR_TO_HOST,
d26a6aa0
MN
2090 (1<<4), 0,
2091 "REQUEST SENSE");
2092 if (reply == 0)
8ea864cf 2093 reply = do_request_sense(common, bh);
d5e2b67a
MN
2094 break;
2095
2096 case SC_START_STOP_UNIT:
8ea864cf
MN
2097 common->data_size_from_cmnd = 0;
2098 reply = check_command(common, 6, DATA_DIR_NONE,
d26a6aa0
MN
2099 (1<<1) | (1<<4), 0,
2100 "START-STOP UNIT");
2101 if (reply == 0)
8ea864cf 2102 reply = do_start_stop(common);
d5e2b67a
MN
2103 break;
2104
2105 case SC_SYNCHRONIZE_CACHE:
8ea864cf
MN
2106 common->data_size_from_cmnd = 0;
2107 reply = check_command(common, 10, DATA_DIR_NONE,
d26a6aa0
MN
2108 (0xf<<2) | (3<<7), 1,
2109 "SYNCHRONIZE CACHE");
2110 if (reply == 0)
8ea864cf 2111 reply = do_synchronize_cache(common);
d5e2b67a
MN
2112 break;
2113
2114 case SC_TEST_UNIT_READY:
8ea864cf
MN
2115 common->data_size_from_cmnd = 0;
2116 reply = check_command(common, 6, DATA_DIR_NONE,
d5e2b67a
MN
2117 0, 1,
2118 "TEST UNIT READY");
2119 break;
2120
2121 /* Although optional, this command is used by MS-Windows. We
2122 * support a minimal version: BytChk must be 0. */
2123 case SC_VERIFY:
8ea864cf
MN
2124 common->data_size_from_cmnd = 0;
2125 reply = check_command(common, 10, DATA_DIR_NONE,
d26a6aa0
MN
2126 (1<<1) | (0xf<<2) | (3<<7), 1,
2127 "VERIFY");
2128 if (reply == 0)
8ea864cf 2129 reply = do_verify(common);
d5e2b67a
MN
2130 break;
2131
2132 case SC_WRITE_6:
8ea864cf
MN
2133 i = common->cmnd[4];
2134 common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
2135 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
d26a6aa0
MN
2136 (7<<1) | (1<<4), 1,
2137 "WRITE(6)");
2138 if (reply == 0)
8ea864cf 2139 reply = do_write(common);
d5e2b67a
MN
2140 break;
2141
2142 case SC_WRITE_10:
8ea864cf
MN
2143 common->data_size_from_cmnd =
2144 get_unaligned_be16(&common->cmnd[7]) << 9;
2145 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
d26a6aa0
MN
2146 (1<<1) | (0xf<<2) | (3<<7), 1,
2147 "WRITE(10)");
2148 if (reply == 0)
8ea864cf 2149 reply = do_write(common);
d5e2b67a
MN
2150 break;
2151
2152 case SC_WRITE_12:
8ea864cf
MN
2153 common->data_size_from_cmnd =
2154 get_unaligned_be32(&common->cmnd[6]) << 9;
2155 reply = check_command(common, 12, DATA_DIR_FROM_HOST,
d26a6aa0
MN
2156 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2157 "WRITE(12)");
2158 if (reply == 0)
8ea864cf 2159 reply = do_write(common);
d5e2b67a
MN
2160 break;
2161
2162 /* Some mandatory commands that we recognize but don't implement.
2163 * They don't mean much in this setting. It's left as an exercise
2164 * for anyone interested to implement RESERVE and RELEASE in terms
2165 * of Posix locks. */
2166 case SC_FORMAT_UNIT:
2167 case SC_RELEASE:
2168 case SC_RESERVE:
2169 case SC_SEND_DIAGNOSTIC:
d26a6aa0 2170 /* Fall through */
d5e2b67a
MN
2171
2172 default:
d26a6aa0 2173unknown_cmnd:
8ea864cf
MN
2174 common->data_size_from_cmnd = 0;
2175 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2176 reply = check_command(common, common->cmnd_size,
d26a6aa0
MN
2177 DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2178 if (reply == 0) {
8ea864cf 2179 common->curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
2180 reply = -EINVAL;
2181 }
2182 break;
2183 }
8ea864cf 2184 up_read(&common->filesem);
d5e2b67a
MN
2185
2186 if (reply == -EINTR || signal_pending(current))
2187 return -EINTR;
2188
2189 /* Set up the single reply buffer for finish_reply() */
2190 if (reply == -EINVAL)
d26a6aa0 2191 reply = 0; /* Error reply length */
8ea864cf
MN
2192 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2193 reply = min((u32) reply, common->data_size_from_cmnd);
d5e2b67a
MN
2194 bh->inreq->length = reply;
2195 bh->state = BUF_STATE_FULL;
8ea864cf 2196 common->residue -= reply;
d26a6aa0 2197 } /* Otherwise it's already set */
d5e2b67a
MN
2198
2199 return 0;
2200}
2201
2202
2203/*-------------------------------------------------------------------------*/
2204
2205static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2206{
8ea864cf 2207 struct usb_request *req = bh->outreq;
d5e2b67a 2208 struct fsg_bulk_cb_wrap *cbw = req->buf;
8ea864cf 2209 struct fsg_common *common = fsg->common;
d5e2b67a
MN
2210
2211 /* Was this a real packet? Should it be ignored? */
2212 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2213 return -EINVAL;
2214
2215 /* Is the CBW valid? */
2216 if (req->actual != USB_BULK_CB_WRAP_LEN ||
2217 cbw->Signature != cpu_to_le32(
2218 USB_BULK_CB_SIG)) {
2219 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2220 req->actual,
2221 le32_to_cpu(cbw->Signature));
2222
2223 /* The Bulk-only spec says we MUST stall the IN endpoint
2224 * (6.6.1), so it's unavoidable. It also says we must
2225 * retain this state until the next reset, but there's
2226 * no way to tell the controller driver it should ignore
2227 * Clear-Feature(HALT) requests.
2228 *
2229 * We aren't required to halt the OUT endpoint; instead
2230 * we can simply accept and discard any data received
2231 * until the next reset. */
2232 wedge_bulk_in_endpoint(fsg);
2233 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2234 return -EINVAL;
2235 }
2236
2237 /* Is the CBW meaningful? */
2238 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2239 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2240 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2241 "cmdlen %u\n",
2242 cbw->Lun, cbw->Flags, cbw->Length);
2243
2244 /* We can do anything we want here, so let's stall the
2245 * bulk pipes if we are allowed to. */
8ea864cf 2246 if (common->can_stall) {
d5e2b67a
MN
2247 fsg_set_halt(fsg, fsg->bulk_out);
2248 halt_bulk_in_endpoint(fsg);
2249 }
2250 return -EINVAL;
2251 }
2252
2253 /* Save the command for later */
8ea864cf
MN
2254 common->cmnd_size = cbw->Length;
2255 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
d5e2b67a 2256 if (cbw->Flags & USB_BULK_IN_FLAG)
8ea864cf 2257 common->data_dir = DATA_DIR_TO_HOST;
d5e2b67a 2258 else
8ea864cf
MN
2259 common->data_dir = DATA_DIR_FROM_HOST;
2260 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2261 if (common->data_size == 0)
2262 common->data_dir = DATA_DIR_NONE;
2263 common->lun = cbw->Lun;
2264 common->tag = cbw->Tag;
d5e2b67a
MN
2265 return 0;
2266}
2267
2268
8ea864cf 2269static int get_next_command(struct fsg_common *common)
d5e2b67a
MN
2270{
2271 struct fsg_buffhd *bh;
2272 int rc = 0;
2273
93bcf12e 2274 /* Wait for the next buffer to become available */
8ea864cf 2275 bh = common->next_buffhd_to_fill;
93bcf12e 2276 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 2277 rc = sleep_thread(common);
93bcf12e
MN
2278 if (rc)
2279 return rc;
2280 }
d5e2b67a 2281
93bcf12e 2282 /* Queue a request to read a Bulk-only CBW */
8ea864cf 2283 set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
93bcf12e 2284 bh->outreq->short_not_ok = 1;
8ea864cf
MN
2285 START_TRANSFER_OR(common, bulk_out, bh->outreq,
2286 &bh->outreq_busy, &bh->state)
2287 /* Don't know what to do if common->fsg is NULL */
2288 return -EIO;
d5e2b67a 2289
93bcf12e
MN
2290 /* We will drain the buffer in software, which means we
2291 * can reuse it for the next filling. No need to advance
2292 * next_buffhd_to_fill. */
d5e2b67a 2293
93bcf12e
MN
2294 /* Wait for the CBW to arrive */
2295 while (bh->state != BUF_STATE_FULL) {
8ea864cf 2296 rc = sleep_thread(common);
93bcf12e
MN
2297 if (rc)
2298 return rc;
d5e2b67a 2299 }
93bcf12e 2300 smp_rmb();
8ea864cf 2301 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
93bcf12e
MN
2302 bh->state = BUF_STATE_EMPTY;
2303
d5e2b67a
MN
2304 return rc;
2305}
2306
2307
2308/*-------------------------------------------------------------------------*/
2309
8ea864cf 2310static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
d5e2b67a
MN
2311 const struct usb_endpoint_descriptor *d)
2312{
2313 int rc;
2314
8ea864cf 2315 ep->driver_data = common;
d5e2b67a
MN
2316 rc = usb_ep_enable(ep, d);
2317 if (rc)
8ea864cf 2318 ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
d5e2b67a
MN
2319 return rc;
2320}
2321
8ea864cf 2322static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
d5e2b67a
MN
2323 struct usb_request **preq)
2324{
2325 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2326 if (*preq)
2327 return 0;
8ea864cf 2328 ERROR(common, "can't allocate request for %s\n", ep->name);
d5e2b67a
MN
2329 return -ENOMEM;
2330}
2331
b894f60a
MN
2332/* Reset interface setting and re-init endpoint state (toggle etc). */
2333static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
d5e2b67a 2334{
b894f60a
MN
2335 const struct usb_endpoint_descriptor *d;
2336 struct fsg_dev *fsg;
2337 int i, rc = 0;
d5e2b67a 2338
8ea864cf
MN
2339 if (common->running)
2340 DBG(common, "reset interface\n");
d5e2b67a
MN
2341
2342reset:
2343 /* Deallocate the requests */
b894f60a
MN
2344 if (common->fsg) {
2345 fsg = common->fsg;
8ea864cf
MN
2346
2347 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2348 struct fsg_buffhd *bh = &common->buffhds[i];
d5e2b67a 2349
8ea864cf
MN
2350 if (bh->inreq) {
2351 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2352 bh->inreq = NULL;
2353 }
2354 if (bh->outreq) {
2355 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2356 bh->outreq = NULL;
2357 }
d5e2b67a 2358 }
8ea864cf
MN
2359
2360 /* Disable the endpoints */
2361 if (fsg->bulk_in_enabled) {
2362 usb_ep_disable(fsg->bulk_in);
2363 fsg->bulk_in_enabled = 0;
2364 }
2365 if (fsg->bulk_out_enabled) {
2366 usb_ep_disable(fsg->bulk_out);
2367 fsg->bulk_out_enabled = 0;
d5e2b67a 2368 }
d5e2b67a 2369
b894f60a
MN
2370 common->fsg = NULL;
2371 wake_up(&common->fsg_wait);
d5e2b67a 2372 }
d5e2b67a 2373
8ea864cf 2374 common->running = 0;
b894f60a 2375 if (!new_fsg || rc)
d5e2b67a
MN
2376 return rc;
2377
b894f60a
MN
2378 common->fsg = new_fsg;
2379 fsg = common->fsg;
d5e2b67a 2380
b894f60a
MN
2381 /* Enable the endpoints */
2382 d = fsg_ep_desc(common->gadget,
2383 &fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc);
2384 rc = enable_endpoint(common, fsg->bulk_in, d);
2385 if (rc)
2386 goto reset;
2387 fsg->bulk_in_enabled = 1;
8ea864cf 2388
b894f60a
MN
2389 d = fsg_ep_desc(common->gadget,
2390 &fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc);
2391 rc = enable_endpoint(common, fsg->bulk_out, d);
2392 if (rc)
2393 goto reset;
2394 fsg->bulk_out_enabled = 1;
2395 common->bulk_out_maxpacket = le16_to_cpu(d->wMaxPacketSize);
2396 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2397
2398 /* Allocate the requests */
2399 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2400 struct fsg_buffhd *bh = &common->buffhds[i];
2401
2402 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
8ea864cf 2403 if (rc)
d5e2b67a 2404 goto reset;
b894f60a 2405 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
8ea864cf 2406 if (rc)
d5e2b67a 2407 goto reset;
b894f60a
MN
2408 bh->inreq->buf = bh->outreq->buf = bh->buf;
2409 bh->inreq->context = bh->outreq->context = bh;
2410 bh->inreq->complete = bulk_in_complete;
2411 bh->outreq->complete = bulk_out_complete;
8ea864cf 2412 }
d5e2b67a 2413
b894f60a
MN
2414 common->running = 1;
2415 for (i = 0; i < common->nluns; ++i)
2416 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
d5e2b67a
MN
2417 return rc;
2418}
2419
2420
d23b0f08
MN
2421/****************************** ALT CONFIGS ******************************/
2422
2423
2424static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2425{
2426 struct fsg_dev *fsg = fsg_from_func(f);
b894f60a 2427 fsg->common->new_fsg = fsg;
8ea864cf 2428 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
d23b0f08
MN
2429 return 0;
2430}
2431
2432static void fsg_disable(struct usb_function *f)
2433{
2434 struct fsg_dev *fsg = fsg_from_func(f);
b894f60a 2435 fsg->common->new_fsg = NULL;
8ea864cf 2436 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
d23b0f08
MN
2437}
2438
2439
d5e2b67a
MN
2440/*-------------------------------------------------------------------------*/
2441
8ea864cf 2442static void handle_exception(struct fsg_common *common)
d5e2b67a
MN
2443{
2444 siginfo_t info;
d5e2b67a 2445 int i;
d5e2b67a
MN
2446 struct fsg_buffhd *bh;
2447 enum fsg_state old_state;
d5e2b67a
MN
2448 struct fsg_lun *curlun;
2449 unsigned int exception_req_tag;
d5e2b67a
MN
2450
2451 /* Clear the existing signals. Anything but SIGUSR1 is converted
2452 * into a high-priority EXIT exception. */
2453 for (;;) {
b894f60a
MN
2454 int sig =
2455 dequeue_signal_lock(current, &current->blocked, &info);
d5e2b67a
MN
2456 if (!sig)
2457 break;
2458 if (sig != SIGUSR1) {
8ea864cf
MN
2459 if (common->state < FSG_STATE_EXIT)
2460 DBG(common, "Main thread exiting on signal\n");
2461 raise_exception(common, FSG_STATE_EXIT);
d5e2b67a
MN
2462 }
2463 }
2464
2465 /* Cancel all the pending transfers */
b894f60a 2466 if (likely(common->fsg)) {
d5e2b67a 2467 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
8ea864cf
MN
2468 bh = &common->buffhds[i];
2469 if (bh->inreq_busy)
2470 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2471 if (bh->outreq_busy)
2472 usb_ep_dequeue(common->fsg->bulk_out,
2473 bh->outreq);
d5e2b67a 2474 }
d5e2b67a 2475
8ea864cf
MN
2476 /* Wait until everything is idle */
2477 for (;;) {
2478 int num_active = 0;
2479 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2480 bh = &common->buffhds[i];
2481 num_active += bh->inreq_busy + bh->outreq_busy;
2482 }
2483 if (num_active == 0)
2484 break;
2485 if (sleep_thread(common))
2486 return;
2487 }
2488
2489 /* Clear out the controller's fifos */
2490 if (common->fsg->bulk_in_enabled)
2491 usb_ep_fifo_flush(common->fsg->bulk_in);
2492 if (common->fsg->bulk_out_enabled)
2493 usb_ep_fifo_flush(common->fsg->bulk_out);
2494 }
d5e2b67a
MN
2495
2496 /* Reset the I/O buffer states and pointers, the SCSI
2497 * state, and the exception. Then invoke the handler. */
8ea864cf 2498 spin_lock_irq(&common->lock);
d5e2b67a
MN
2499
2500 for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
8ea864cf 2501 bh = &common->buffhds[i];
d5e2b67a
MN
2502 bh->state = BUF_STATE_EMPTY;
2503 }
8ea864cf
MN
2504 common->next_buffhd_to_fill = &common->buffhds[0];
2505 common->next_buffhd_to_drain = &common->buffhds[0];
2506 exception_req_tag = common->exception_req_tag;
8ea864cf 2507 old_state = common->state;
d5e2b67a
MN
2508
2509 if (old_state == FSG_STATE_ABORT_BULK_OUT)
8ea864cf 2510 common->state = FSG_STATE_STATUS_PHASE;
d5e2b67a 2511 else {
8ea864cf
MN
2512 for (i = 0; i < common->nluns; ++i) {
2513 curlun = &common->luns[i];
d5e2b67a 2514 curlun->prevent_medium_removal = 0;
d26a6aa0
MN
2515 curlun->sense_data = SS_NO_SENSE;
2516 curlun->unit_attention_data = SS_NO_SENSE;
d5e2b67a
MN
2517 curlun->sense_data_info = 0;
2518 curlun->info_valid = 0;
2519 }
8ea864cf 2520 common->state = FSG_STATE_IDLE;
d5e2b67a 2521 }
8ea864cf 2522 spin_unlock_irq(&common->lock);
d5e2b67a
MN
2523
2524 /* Carry out any extra actions required for the exception */
2525 switch (old_state) {
d5e2b67a 2526 case FSG_STATE_ABORT_BULK_OUT:
8ea864cf
MN
2527 send_status(common);
2528 spin_lock_irq(&common->lock);
2529 if (common->state == FSG_STATE_STATUS_PHASE)
2530 common->state = FSG_STATE_IDLE;
2531 spin_unlock_irq(&common->lock);
d5e2b67a
MN
2532 break;
2533
2534 case FSG_STATE_RESET:
2535 /* In case we were forced against our will to halt a
2536 * bulk endpoint, clear the halt now. (The SuperH UDC
2537 * requires this.) */
8ea864cf
MN
2538 if (!fsg_is_set(common))
2539 break;
2540 if (test_and_clear_bit(IGNORE_BULK_OUT,
2541 &common->fsg->atomic_bitflags))
2542 usb_ep_clear_halt(common->fsg->bulk_in);
d5e2b67a 2543
8ea864cf
MN
2544 if (common->ep0_req_tag == exception_req_tag)
2545 ep0_queue(common); /* Complete the status stage */
d5e2b67a
MN
2546
2547 /* Technically this should go here, but it would only be
2548 * a waste of time. Ditto for the INTERFACE_CHANGE and
2549 * CONFIG_CHANGE cases. */
8ea864cf
MN
2550 /* for (i = 0; i < common->nluns; ++i) */
2551 /* common->luns[i].unit_attention_data = */
d26a6aa0 2552 /* SS_RESET_OCCURRED; */
d5e2b67a
MN
2553 break;
2554
d5e2b67a 2555 case FSG_STATE_CONFIG_CHANGE:
b894f60a 2556 do_set_interface(common, common->new_fsg);
d5e2b67a
MN
2557 break;
2558
d5e2b67a
MN
2559 case FSG_STATE_EXIT:
2560 case FSG_STATE_TERMINATED:
b894f60a 2561 do_set_interface(common, NULL); /* Free resources */
8ea864cf
MN
2562 spin_lock_irq(&common->lock);
2563 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2564 spin_unlock_irq(&common->lock);
d5e2b67a 2565 break;
d23b0f08
MN
2566
2567 case FSG_STATE_INTERFACE_CHANGE:
2568 case FSG_STATE_DISCONNECT:
2569 case FSG_STATE_COMMAND_PHASE:
2570 case FSG_STATE_DATA_PHASE:
2571 case FSG_STATE_STATUS_PHASE:
2572 case FSG_STATE_IDLE:
2573 break;
d5e2b67a
MN
2574 }
2575}
2576
2577
2578/*-------------------------------------------------------------------------*/
2579
8ea864cf 2580static int fsg_main_thread(void *common_)
d5e2b67a 2581{
8ea864cf 2582 struct fsg_common *common = common_;
d5e2b67a
MN
2583
2584 /* Allow the thread to be killed by a signal, but set the signal mask
2585 * to block everything but INT, TERM, KILL, and USR1. */
2586 allow_signal(SIGINT);
2587 allow_signal(SIGTERM);
2588 allow_signal(SIGKILL);
2589 allow_signal(SIGUSR1);
2590
2591 /* Allow the thread to be frozen */
2592 set_freezable();
2593
2594 /* Arrange for userspace references to be interpreted as kernel
2595 * pointers. That way we can pass a kernel pointer to a routine
2596 * that expects a __user pointer and it will work okay. */
2597 set_fs(get_ds());
2598
2599 /* The main loop */
8ea864cf
MN
2600 while (common->state != FSG_STATE_TERMINATED) {
2601 if (exception_in_progress(common) || signal_pending(current)) {
2602 handle_exception(common);
d5e2b67a
MN
2603 continue;
2604 }
2605
8ea864cf
MN
2606 if (!common->running) {
2607 sleep_thread(common);
d5e2b67a
MN
2608 continue;
2609 }
2610
8ea864cf 2611 if (get_next_command(common))
d5e2b67a
MN
2612 continue;
2613
8ea864cf
MN
2614 spin_lock_irq(&common->lock);
2615 if (!exception_in_progress(common))
2616 common->state = FSG_STATE_DATA_PHASE;
2617 spin_unlock_irq(&common->lock);
d5e2b67a 2618
8ea864cf 2619 if (do_scsi_command(common) || finish_reply(common))
d5e2b67a
MN
2620 continue;
2621
8ea864cf
MN
2622 spin_lock_irq(&common->lock);
2623 if (!exception_in_progress(common))
2624 common->state = FSG_STATE_STATUS_PHASE;
2625 spin_unlock_irq(&common->lock);
d5e2b67a 2626
8ea864cf 2627 if (send_status(common))
d5e2b67a
MN
2628 continue;
2629
8ea864cf
MN
2630 spin_lock_irq(&common->lock);
2631 if (!exception_in_progress(common))
2632 common->state = FSG_STATE_IDLE;
2633 spin_unlock_irq(&common->lock);
d23b0f08 2634 }
d5e2b67a 2635
8ea864cf
MN
2636 spin_lock_irq(&common->lock);
2637 common->thread_task = NULL;
2638 spin_unlock_irq(&common->lock);
d5e2b67a 2639
8876f5e7
MN
2640 if (!common->ops || !common->ops->thread_exits
2641 || common->ops->thread_exits(common) < 0) {
7f1ee826
MN
2642 struct fsg_lun *curlun = common->luns;
2643 unsigned i = common->nluns;
2644
2645 down_write(&common->filesem);
2646 for (; i--; ++curlun) {
2647 if (!fsg_lun_is_open(curlun))
2648 continue;
2649
2650 fsg_lun_close(curlun);
2651 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2652 }
2653 up_write(&common->filesem);
2654 }
d5e2b67a
MN
2655
2656 /* Let the unbind and cleanup routines know the thread has exited */
8ea864cf 2657 complete_and_exit(&common->thread_notifier, 0);
d5e2b67a
MN
2658}
2659
2660
9c610213 2661/*************************** DEVICE ATTRIBUTES ***************************/
d5e2b67a 2662
d23b0f08
MN
2663/* Write permission is checked per LUN in store_*() functions. */
2664static DEVICE_ATTR(ro, 0644, fsg_show_ro, fsg_store_ro);
2665static DEVICE_ATTR(file, 0644, fsg_show_file, fsg_store_file);
d5e2b67a
MN
2666
2667
9c610213
MN
2668/****************************** FSG COMMON ******************************/
2669
2670static void fsg_common_release(struct kref *ref);
d5e2b67a 2671
9c610213 2672static void fsg_lun_release(struct device *dev)
d5e2b67a 2673{
9c610213 2674 /* Nothing needs to be done */
d5e2b67a
MN
2675}
2676
9c610213 2677static inline void fsg_common_get(struct fsg_common *common)
d5e2b67a 2678{
9c610213 2679 kref_get(&common->ref);
d5e2b67a
MN
2680}
2681
9c610213
MN
2682static inline void fsg_common_put(struct fsg_common *common)
2683{
2684 kref_put(&common->ref, fsg_common_release);
2685}
2686
2687
2688static struct fsg_common *fsg_common_init(struct fsg_common *common,
481e4929
MN
2689 struct usb_composite_dev *cdev,
2690 struct fsg_config *cfg)
9c610213 2691{
d23b0f08 2692 struct usb_gadget *gadget = cdev->gadget;
9c610213
MN
2693 struct fsg_buffhd *bh;
2694 struct fsg_lun *curlun;
481e4929 2695 struct fsg_lun_config *lcfg;
9c610213 2696 int nluns, i, rc;
d23b0f08 2697 char *pathbuf;
9c610213
MN
2698
2699 /* Find out how many LUNs there should be */
481e4929 2700 nluns = cfg->nluns;
9c610213
MN
2701 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2702 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2703 return ERR_PTR(-EINVAL);
2704 }
2705
2706 /* Allocate? */
2707 if (!common) {
2708 common = kzalloc(sizeof *common, GFP_KERNEL);
2709 if (!common)
2710 return ERR_PTR(-ENOMEM);
2711 common->free_storage_on_release = 1;
2712 } else {
2713 memset(common, 0, sizeof common);
2714 common->free_storage_on_release = 0;
2715 }
8ea864cf 2716
8876f5e7 2717 common->ops = cfg->ops;
c85efcb9
MN
2718 common->private_data = cfg->private_data;
2719
9c610213 2720 common->gadget = gadget;
8ea864cf
MN
2721 common->ep0 = gadget->ep0;
2722 common->ep0req = cdev->req;
2723
2724 /* Maybe allocate device-global string IDs, and patch descriptors */
2725 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2726 rc = usb_string_id(cdev);
b9e00088
MN
2727 if (unlikely(rc < 0))
2728 goto error_release;
8ea864cf
MN
2729 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2730 fsg_intf_desc.iInterface = rc;
2731 }
9c610213
MN
2732
2733 /* Create the LUNs, open their backing files, and register the
2734 * LUN devices in sysfs. */
2735 curlun = kzalloc(nluns * sizeof *curlun, GFP_KERNEL);
b9e00088
MN
2736 if (unlikely(!curlun)) {
2737 rc = -ENOMEM;
2738 goto error_release;
9c610213
MN
2739 }
2740 common->luns = curlun;
2741
2742 init_rwsem(&common->filesem);
2743
481e4929
MN
2744 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2745 curlun->cdrom = !!lcfg->cdrom;
2746 curlun->ro = lcfg->cdrom || lcfg->ro;
2747 curlun->removable = lcfg->removable;
9c610213
MN
2748 curlun->dev.release = fsg_lun_release;
2749 curlun->dev.parent = &gadget->dev;
d23b0f08 2750 /* curlun->dev.driver = &fsg_driver.driver; XXX */
9c610213 2751 dev_set_drvdata(&curlun->dev, &common->filesem);
e8b6f8c5
MN
2752 dev_set_name(&curlun->dev,
2753 cfg->lun_name_format
2754 ? cfg->lun_name_format
2755 : "lun%d",
2756 i);
9c610213
MN
2757
2758 rc = device_register(&curlun->dev);
2759 if (rc) {
2760 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2761 common->nluns = i;
2762 goto error_release;
2763 }
2764
2765 rc = device_create_file(&curlun->dev, &dev_attr_ro);
2766 if (rc)
2767 goto error_luns;
2768 rc = device_create_file(&curlun->dev, &dev_attr_file);
2769 if (rc)
2770 goto error_luns;
2771
481e4929
MN
2772 if (lcfg->filename) {
2773 rc = fsg_lun_open(curlun, lcfg->filename);
9c610213
MN
2774 if (rc)
2775 goto error_luns;
481e4929 2776 } else if (!curlun->removable) {
9c610213
MN
2777 ERROR(common, "no file given for LUN%d\n", i);
2778 rc = -EINVAL;
2779 goto error_luns;
2780 }
2781 }
2782 common->nluns = nluns;
2783
2784
2785 /* Data buffers cyclic list */
9c610213 2786 bh = common->buffhds;
aae86e8a
MN
2787 i = FSG_NUM_BUFFERS;
2788 goto buffhds_first_it;
9c610213
MN
2789 do {
2790 bh->next = bh + 1;
aae86e8a
MN
2791 ++bh;
2792buffhds_first_it:
2793 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2794 if (unlikely(!bh->buf)) {
2795 rc = -ENOMEM;
2796 goto error_release;
2797 }
2798 } while (--i);
9c610213
MN
2799 bh->next = common->buffhds;
2800
2801
481e4929
MN
2802 /* Prepare inquiryString */
2803 if (cfg->release != 0xffff) {
2804 i = cfg->release;
2805 } else {
90f79768 2806 i = usb_gadget_controller_number(gadget);
481e4929
MN
2807 if (i >= 0) {
2808 i = 0x0300 + i;
2809 } else {
9c610213
MN
2810 WARNING(common, "controller '%s' not recognized\n",
2811 gadget->name);
481e4929 2812 i = 0x0399;
9c610213
MN
2813 }
2814 }
481e4929
MN
2815#define OR(x, y) ((x) ? (x) : (y))
2816 snprintf(common->inquiry_string, sizeof common->inquiry_string,
2817 "%-8s%-16s%04x",
2818 OR(cfg->vendor_name, "Linux "),
2819 /* Assume product name dependent on the first LUN */
2820 OR(cfg->product_name, common->luns->cdrom
2821 ? "File-Stor Gadget"
2822 : "File-CD Gadget "),
2823 i);
9c610213
MN
2824
2825
2826 /* Some peripheral controllers are known not to be able to
2827 * halt bulk endpoints correctly. If one of them is present,
2828 * disable stalls.
2829 */
481e4929 2830 common->can_stall = cfg->can_stall &&
90f79768 2831 !(gadget_is_at91(common->gadget));
9c610213
MN
2832
2833
8ea864cf 2834 spin_lock_init(&common->lock);
9c610213 2835 kref_init(&common->ref);
8ea864cf
MN
2836
2837
2838 /* Tell the thread to start working */
2839 common->thread_task =
2840 kthread_create(fsg_main_thread, common,
2841 OR(cfg->thread_name, "file-storage"));
2842 if (IS_ERR(common->thread_task)) {
2843 rc = PTR_ERR(common->thread_task);
2844 goto error_release;
2845 }
2846 init_completion(&common->thread_notifier);
b894f60a 2847 init_waitqueue_head(&common->fsg_wait);
e8b6f8c5
MN
2848#undef OR
2849
d23b0f08
MN
2850
2851 /* Information */
2852 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2853 INFO(common, "Number of LUNs=%d\n", common->nluns);
2854
2855 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2856 for (i = 0, nluns = common->nluns, curlun = common->luns;
2857 i < nluns;
2858 ++curlun, ++i) {
2859 char *p = "(no medium)";
2860 if (fsg_lun_is_open(curlun)) {
2861 p = "(error)";
2862 if (pathbuf) {
2863 p = d_path(&curlun->filp->f_path,
2864 pathbuf, PATH_MAX);
2865 if (IS_ERR(p))
2866 p = "(error)";
2867 }
2868 }
2869 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
2870 curlun->removable ? "removable " : "",
2871 curlun->ro ? "read only " : "",
2872 curlun->cdrom ? "CD-ROM " : "",
2873 p);
2874 }
2875 kfree(pathbuf);
2876
8ea864cf
MN
2877 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
2878
2879 wake_up_process(common->thread_task);
2880
9c610213
MN
2881 return common;
2882
2883
2884error_luns:
2885 common->nluns = i + 1;
2886error_release:
8ea864cf 2887 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
d26a6aa0
MN
2888 /* Call fsg_common_release() directly, ref might be not
2889 * initialised */
9c610213
MN
2890 fsg_common_release(&common->ref);
2891 return ERR_PTR(rc);
2892}
2893
2894
2895static void fsg_common_release(struct kref *ref)
2896{
b9e00088 2897 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
9c610213 2898
8ea864cf
MN
2899 /* If the thread isn't already dead, tell it to exit now */
2900 if (common->state != FSG_STATE_TERMINATED) {
2901 raise_exception(common, FSG_STATE_EXIT);
2902 wait_for_completion(&common->thread_notifier);
2903
2904 /* The cleanup routine waits for this completion also */
2905 complete(&common->thread_notifier);
2906 }
2907
b9e00088
MN
2908 if (likely(common->luns)) {
2909 struct fsg_lun *lun = common->luns;
2910 unsigned i = common->nluns;
2911
2912 /* In error recovery common->nluns may be zero. */
2913 for (; i; --i, ++lun) {
2914 device_remove_file(&lun->dev, &dev_attr_ro);
2915 device_remove_file(&lun->dev, &dev_attr_file);
2916 fsg_lun_close(lun);
2917 device_unregister(&lun->dev);
2918 }
9c610213 2919
b9e00088 2920 kfree(common->luns);
9c610213
MN
2921 }
2922
b9e00088
MN
2923 {
2924 struct fsg_buffhd *bh = common->buffhds;
2925 unsigned i = FSG_NUM_BUFFERS;
2926 do {
2927 kfree(bh->buf);
2928 } while (++bh, --i);
2929 }
aae86e8a 2930
9c610213
MN
2931 if (common->free_storage_on_release)
2932 kfree(common);
2933}
2934
2935
2936/*-------------------------------------------------------------------------*/
2937
2938
d23b0f08 2939static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
d5e2b67a 2940{
d23b0f08 2941 struct fsg_dev *fsg = fsg_from_func(f);
b894f60a 2942 struct fsg_common *common = fsg->common;
d5e2b67a
MN
2943
2944 DBG(fsg, "unbind\n");
b894f60a
MN
2945 if (fsg->common->fsg == fsg) {
2946 fsg->common->new_fsg = NULL;
2947 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2948 /* FIXME: make interruptible or killable somehow? */
2949 wait_event(common->fsg_wait, common->fsg != fsg);
2950 }
2951
2952 fsg_common_put(common);
0fb2c2a1
MN
2953 usb_free_descriptors(fsg->function.descriptors);
2954 usb_free_descriptors(fsg->function.hs_descriptors);
9c610213 2955 kfree(fsg);
d5e2b67a
MN
2956}
2957
2958
28824b18 2959static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
d5e2b67a 2960{
d23b0f08
MN
2961 struct fsg_dev *fsg = fsg_from_func(f);
2962 struct usb_gadget *gadget = c->cdev->gadget;
d5e2b67a 2963 int i;
d5e2b67a 2964 struct usb_ep *ep;
d5e2b67a
MN
2965
2966 fsg->gadget = gadget;
d5e2b67a 2967
d23b0f08
MN
2968 /* New interface */
2969 i = usb_interface_id(c, f);
2970 if (i < 0)
2971 return i;
2972 fsg_intf_desc.bInterfaceNumber = i;
2973 fsg->interface_number = i;
d5e2b67a 2974
d5e2b67a 2975 /* Find all the endpoints we will use */
d5e2b67a
MN
2976 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2977 if (!ep)
2978 goto autoconf_fail;
8ea864cf 2979 ep->driver_data = fsg->common; /* claim the endpoint */
d5e2b67a
MN
2980 fsg->bulk_in = ep;
2981
2982 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2983 if (!ep)
2984 goto autoconf_fail;
8ea864cf 2985 ep->driver_data = fsg->common; /* claim the endpoint */
d5e2b67a
MN
2986 fsg->bulk_out = ep;
2987
e5fd39d9
MN
2988 /* Copy descriptors */
2989 f->descriptors = usb_copy_descriptors(fsg_fs_function);
2990 if (unlikely(!f->descriptors))
2991 return -ENOMEM;
2992
d5e2b67a 2993 if (gadget_is_dualspeed(gadget)) {
d5e2b67a
MN
2994 /* Assume endpoint addresses are the same for both speeds */
2995 fsg_hs_bulk_in_desc.bEndpointAddress =
2996 fsg_fs_bulk_in_desc.bEndpointAddress;
2997 fsg_hs_bulk_out_desc.bEndpointAddress =
2998 fsg_fs_bulk_out_desc.bEndpointAddress;
0fb2c2a1 2999 f->hs_descriptors = usb_copy_descriptors(fsg_hs_function);
e5fd39d9
MN
3000 if (unlikely(!f->hs_descriptors)) {
3001 usb_free_descriptors(f->descriptors);
0fb2c2a1 3002 return -ENOMEM;
e5fd39d9 3003 }
d5e2b67a
MN
3004 }
3005
d5e2b67a
MN
3006 return 0;
3007
3008autoconf_fail:
3009 ERROR(fsg, "unable to autoconfigure all endpoints\n");
e5fd39d9 3010 return -ENOTSUPP;
d5e2b67a
MN
3011}
3012
3013
d23b0f08 3014/****************************** ADD FUNCTION ******************************/
d5e2b67a 3015
d23b0f08
MN
3016static struct usb_gadget_strings *fsg_strings_array[] = {
3017 &fsg_stringtab,
3018 NULL,
d5e2b67a
MN
3019};
3020
1dc90985
MN
3021static int fsg_bind_config(struct usb_composite_dev *cdev,
3022 struct usb_configuration *c,
3023 struct fsg_common *common)
d5e2b67a 3024{
d23b0f08
MN
3025 struct fsg_dev *fsg;
3026 int rc;
3027
3028 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3029 if (unlikely(!fsg))
3030 return -ENOMEM;
d5e2b67a 3031
d23b0f08
MN
3032 fsg->function.name = FSG_DRIVER_DESC;
3033 fsg->function.strings = fsg_strings_array;
d23b0f08
MN
3034 fsg->function.bind = fsg_bind;
3035 fsg->function.unbind = fsg_unbind;
3036 fsg->function.setup = fsg_setup;
3037 fsg->function.set_alt = fsg_set_alt;
3038 fsg->function.disable = fsg_disable;
3039
3040 fsg->common = common;
3041 /* Our caller holds a reference to common structure so we
3042 * don't have to be worry about it being freed until we return
3043 * from this function. So instead of incrementing counter now
3044 * and decrement in error recovery we increment it only when
3045 * call to usb_add_function() was successful. */
3046
3047 rc = usb_add_function(c, &fsg->function);
0fb2c2a1 3048 if (unlikely(rc))
e5fd39d9
MN
3049 kfree(fsg);
3050 else
3051 fsg_common_get(fsg->common);
d23b0f08 3052 return rc;
d5e2b67a 3053}
481e4929 3054
1dc90985
MN
3055static inline int __deprecated __maybe_unused
3056fsg_add(struct usb_composite_dev *cdev,
3057 struct usb_configuration *c,
3058 struct fsg_common *common)
3059{
3060 return fsg_bind_config(cdev, c, common);
3061}
481e4929
MN
3062
3063
3064/************************* Module parameters *************************/
3065
3066
3067struct fsg_module_parameters {
3068 char *file[FSG_MAX_LUNS];
3069 int ro[FSG_MAX_LUNS];
3070 int removable[FSG_MAX_LUNS];
3071 int cdrom[FSG_MAX_LUNS];
3072
3073 unsigned int file_count, ro_count, removable_count, cdrom_count;
3074 unsigned int luns; /* nluns */
3075 int stall; /* can_stall */
3076};
3077
3078
3079#define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3080 module_param_array_named(prefix ## name, params.name, type, \
3081 &prefix ## params.name ## _count, \
3082 S_IRUGO); \
3083 MODULE_PARM_DESC(prefix ## name, desc)
3084
3085#define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3086 module_param_named(prefix ## name, params.name, type, \
3087 S_IRUGO); \
3088 MODULE_PARM_DESC(prefix ## name, desc)
3089
3090#define FSG_MODULE_PARAMETERS(prefix, params) \
3091 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3092 "names of backing files or devices"); \
3093 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3094 "true to force read-only"); \
3095 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3096 "true to simulate removable media"); \
3097 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3098 "true to simulate CD-ROM instead of disk"); \
3099 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3100 "number of LUNs"); \
3101 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3102 "false to prevent bulk stalls")
3103
3104
3105static void
3106fsg_config_from_params(struct fsg_config *cfg,
3107 const struct fsg_module_parameters *params)
3108{
3109 struct fsg_lun_config *lun;
d26a6aa0 3110 unsigned i;
481e4929
MN
3111
3112 /* Configure LUNs */
d26a6aa0
MN
3113 cfg->nluns =
3114 min(params->luns ?: (params->file_count ?: 1u),
3115 (unsigned)FSG_MAX_LUNS);
3116 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
481e4929
MN
3117 lun->ro = !!params->ro[i];
3118 lun->cdrom = !!params->cdrom[i];
d26a6aa0 3119 lun->removable = /* Removable by default */
481e4929
MN
3120 params->removable_count <= i || params->removable[i];
3121 lun->filename =
3122 params->file_count > i && params->file[i][0]
3123 ? params->file[i]
3124 : 0;
3125 }
3126
d26a6aa0 3127 /* Let MSF use defaults */
e8b6f8c5
MN
3128 cfg->lun_name_format = 0;
3129 cfg->thread_name = 0;
481e4929
MN
3130 cfg->vendor_name = 0;
3131 cfg->product_name = 0;
3132 cfg->release = 0xffff;
3133
8876f5e7
MN
3134 cfg->ops = NULL;
3135 cfg->private_data = NULL;
c85efcb9 3136
481e4929
MN
3137 /* Finalise */
3138 cfg->can_stall = params->stall;
3139}
3140
3141static inline struct fsg_common *
3142fsg_common_from_params(struct fsg_common *common,
3143 struct usb_composite_dev *cdev,
3144 const struct fsg_module_parameters *params)
3145 __attribute__((unused));
3146static inline struct fsg_common *
3147fsg_common_from_params(struct fsg_common *common,
3148 struct usb_composite_dev *cdev,
3149 const struct fsg_module_parameters *params)
3150{
3151 struct fsg_config cfg;
3152 fsg_config_from_params(&cfg, params);
3153 return fsg_common_init(common, cdev, &cfg);
3154}
3155