usb: gadget: create a utility module for mass_storage
[deliverable/linux.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 5 * Copyright (C) 2009 Samsung Electronics
54b8360f 6 * Author: Michal Nazarewicz <mina86@mina86.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
d5e2b67a 40/*
d26a6aa0
MN
41 * The Mass Storage Function acts as a USB Mass Storage device,
42 * appearing to the host as a disk drive or as a CD-ROM drive. In
43 * addition to providing an example of a genuinely useful composite
44 * function for a USB device, it also illustrates a technique of
45 * double-buffering for increased throughput.
d5e2b67a 46 *
a8287a4e
MN
47 * For more information about MSF and in particular its module
48 * parameters and sysfs interface read the
49 * <Documentation/usb/mass-storage.txt> file.
50 */
51
52/*
d26a6aa0
MN
53 * MSF is configured by specifying a fsg_config structure. It has the
54 * following fields:
55 *
56 * nluns Number of LUNs function have (anywhere from 1
57 * to FSG_MAX_LUNS which is 8).
58 * luns An array of LUN configuration values. This
59 * should be filled for each LUN that
60 * function will include (ie. for "nluns"
61 * LUNs). Each element of the array has
62 * the following fields:
63 * ->filename The path to the backing file for the LUN.
64 * Required if LUN is not marked as
65 * removable.
66 * ->ro Flag specifying access to the LUN shall be
67 * read-only. This is implied if CD-ROM
68 * emulation is enabled as well as when
69 * it was impossible to open "filename"
70 * in R/W mode.
71 * ->removable Flag specifying that LUN shall be indicated as
72 * being removable.
73 * ->cdrom Flag specifying that LUN shall be reported as
74 * being a CD-ROM.
9cfe745e
MN
75 * ->nofua Flag specifying that FUA flag in SCSI WRITE(10,12)
76 * commands for this LUN shall be ignored.
d26a6aa0 77 *
d26a6aa0
MN
78 * vendor_name
79 * product_name
80 * release Information used as a reply to INQUIRY
81 * request. To use default set to NULL,
82 * NULL, 0xffff respectively. The first
83 * field should be 8 and the second 16
84 * characters or less.
85 *
86 * can_stall Set to permit function to halt bulk endpoints.
87 * Disabled on some USB devices known not
88 * to work correctly. You should set it
89 * to true.
90 *
91 * If "removable" is not set for a LUN then a backing file must be
92 * specified. If it is set, then NULL filename means the LUN's medium
93 * is not loaded (an empty string as "filename" in the fsg_config
94 * structure causes error). The CD-ROM emulation includes a single
95 * data track and no audio tracks; hence there need be only one
3f565a36 96 * backing file per LUN.
d26a6aa0 97 *
d26a6aa0
MN
98 * This function is heavily based on "File-backed Storage Gadget" by
99 * Alan Stern which in turn is heavily based on "Gadget Zero" by David
100 * Brownell. The driver's SCSI command interface was based on the
101 * "Information technology - Small Computer System Interface - 2"
102 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
103 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
104 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
105 * was based on the "Universal Serial Bus Mass Storage Class UFI
106 * Command Specification" document, Revision 1.0, December 14, 1998,
107 * available at
d5e2b67a
MN
108 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
109 */
110
d5e2b67a
MN
111/*
112 * Driver Design
113 *
d26a6aa0 114 * The MSF is fairly straightforward. There is a main kernel
d5e2b67a
MN
115 * thread that handles most of the work. Interrupt routines field
116 * callbacks from the controller driver: bulk- and interrupt-request
117 * completion notifications, endpoint-0 events, and disconnect events.
118 * Completion events are passed to the main thread by wakeup calls. Many
119 * ep0 requests are handled at interrupt time, but SetInterface,
120 * SetConfiguration, and device reset requests are forwarded to the
121 * thread in the form of "exceptions" using SIGUSR1 signals (since they
122 * should interrupt any ongoing file I/O operations).
123 *
124 * The thread's main routine implements the standard command/data/status
125 * parts of a SCSI interaction. It and its subroutines are full of tests
126 * for pending signals/exceptions -- all this polling is necessary since
127 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
128 * indication that the driver really wants to be running in userspace.)
129 * An important point is that so long as the thread is alive it keeps an
130 * open reference to the backing file. This will prevent unmounting
131 * the backing file's underlying filesystem and could cause problems
132 * during system shutdown, for example. To prevent such problems, the
133 * thread catches INT, TERM, and KILL signals and converts them into
134 * an EXIT exception.
135 *
136 * In normal operation the main thread is started during the gadget's
d26a6aa0
MN
137 * fsg_bind() callback and stopped during fsg_unbind(). But it can
138 * also exit when it receives a signal, and there's no point leaving
a8287a4e 139 * the gadget running when the thread is dead. As of this moment, MSF
d26a6aa0
MN
140 * provides no way to deregister the gadget when thread dies -- maybe
141 * a callback functions is needed.
d5e2b67a
MN
142 *
143 * To provide maximum throughput, the driver uses a circular pipeline of
144 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
145 * arbitrarily long; in practice the benefits don't justify having more
146 * than 2 stages (i.e., double buffering). But it helps to think of the
147 * pipeline as being a long one. Each buffer head contains a bulk-in and
148 * a bulk-out request pointer (since the buffer can be used for both
149 * output and input -- directions always are given from the host's
150 * point of view) as well as a pointer to the buffer and various state
151 * variables.
152 *
153 * Use of the pipeline follows a simple protocol. There is a variable
154 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
155 * At any time that buffer head may still be in use from an earlier
156 * request, so each buffer head has a state variable indicating whether
157 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
158 * buffer head to be EMPTY, filling the buffer either by file I/O or by
159 * USB I/O (during which the buffer head is BUSY), and marking the buffer
160 * head FULL when the I/O is complete. Then the buffer will be emptied
161 * (again possibly by USB I/O, during which it is marked BUSY) and
162 * finally marked EMPTY again (possibly by a completion routine).
163 *
164 * A module parameter tells the driver to avoid stalling the bulk
165 * endpoints wherever the transport specification allows. This is
166 * necessary for some UDCs like the SuperH, which cannot reliably clear a
167 * halt on a bulk endpoint. However, under certain circumstances the
168 * Bulk-only specification requires a stall. In such cases the driver
169 * will halt the endpoint and set a flag indicating that it should clear
170 * the halt in software during the next device reset. Hopefully this
171 * will permit everything to work correctly. Furthermore, although the
172 * specification allows the bulk-out endpoint to halt when the host sends
173 * too much data, implementing this would cause an unavoidable race.
174 * The driver will always use the "no-stall" approach for OUT transfers.
175 *
176 * One subtle point concerns sending status-stage responses for ep0
177 * requests. Some of these requests, such as device reset, can involve
178 * interrupting an ongoing file I/O operation, which might take an
179 * arbitrarily long time. During that delay the host might give up on
180 * the original ep0 request and issue a new one. When that happens the
181 * driver should not notify the host about completion of the original
182 * request, as the host will no longer be waiting for it. So the driver
183 * assigns to each ep0 request a unique tag, and it keeps track of the
184 * tag value of the request associated with a long-running exception
185 * (device-reset, interface-change, or configuration-change). When the
186 * exception handler is finished, the status-stage response is submitted
187 * only if the current ep0 request tag is equal to the exception request
188 * tag. Thus only the most recently received ep0 request will get a
189 * status-stage response.
190 *
191 * Warning: This driver source file is too long. It ought to be split up
192 * into a header file plus about 3 separate .c files, to handle the details
193 * of the Gadget, USB Mass Storage, and SCSI protocols.
194 */
195
196
197/* #define VERBOSE_DEBUG */
198/* #define DUMP_MSGS */
199
d5e2b67a
MN
200#include <linux/blkdev.h>
201#include <linux/completion.h>
202#include <linux/dcache.h>
203#include <linux/delay.h>
204#include <linux/device.h>
205#include <linux/fcntl.h>
206#include <linux/file.h>
207#include <linux/fs.h>
208#include <linux/kref.h>
209#include <linux/kthread.h>
210#include <linux/limits.h>
211#include <linux/rwsem.h>
212#include <linux/slab.h>
213#include <linux/spinlock.h>
214#include <linux/string.h>
215#include <linux/freezer.h>
d5e2b67a
MN
216
217#include <linux/usb/ch9.h>
218#include <linux/usb/gadget.h>
a283c03a 219#include <linux/usb/composite.h>
d5e2b67a
MN
220
221#include "gadget_chips.h"
222
223
e8b6f8c5 224/*------------------------------------------------------------------------*/
d5e2b67a 225
d23b0f08 226#define FSG_DRIVER_DESC "Mass Storage Function"
d26a6aa0 227#define FSG_DRIVER_VERSION "2009/09/11"
d5e2b67a 228
d5e2b67a
MN
229static const char fsg_string_interface[] = "Mass Storage";
230
6fdc5dd2 231#include "storage_common.h"
d5e2b67a 232
6fdc5dd2
AP
233/* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
234static struct usb_string fsg_strings[] = {
235 {FSG_STRING_INTERFACE, fsg_string_interface},
236 {}
237};
238
239static struct usb_gadget_strings fsg_stringtab = {
240 .language = 0x0409, /* en-us */
241 .strings = fsg_strings,
242};
d5e2b67a 243
d5e2b67a
MN
244/*-------------------------------------------------------------------------*/
245
8ea864cf 246struct fsg_dev;
8876f5e7
MN
247struct fsg_common;
248
249/* FSF callback functions */
250struct fsg_operations {
b73af61e
MN
251 /*
252 * Callback function to call when thread exits. If no
8876f5e7
MN
253 * callback is set or it returns value lower then zero MSF
254 * will force eject all LUNs it operates on (including those
255 * marked as non-removable or with prevent_medium_removal flag
b73af61e
MN
256 * set).
257 */
8876f5e7 258 int (*thread_exits)(struct fsg_common *common);
8876f5e7 259};
8ea864cf 260
a41ae418
MN
261/* Data shared by all the FSG instances. */
262struct fsg_common {
9c610213 263 struct usb_gadget *gadget;
95ed3236 264 struct usb_composite_dev *cdev;
b894f60a
MN
265 struct fsg_dev *fsg, *new_fsg;
266 wait_queue_head_t fsg_wait;
9c610213 267
a41ae418
MN
268 /* filesem protects: backing files in use */
269 struct rw_semaphore filesem;
270
8ea864cf
MN
271 /* lock protects: state, all the req_busy's */
272 spinlock_t lock;
273
274 struct usb_ep *ep0; /* Copy of gadget->ep0 */
275 struct usb_request *ep0req; /* Copy of cdev->req */
276 unsigned int ep0_req_tag;
8ea864cf 277
a41ae418
MN
278 struct fsg_buffhd *next_buffhd_to_fill;
279 struct fsg_buffhd *next_buffhd_to_drain;
6532c7fd 280 struct fsg_buffhd *buffhds;
6fdc5dd2 281 unsigned int fsg_num_buffers;
a41ae418
MN
282
283 int cmnd_size;
284 u8 cmnd[MAX_COMMAND_SIZE];
285
286 unsigned int nluns;
287 unsigned int lun;
288 struct fsg_lun *luns;
289 struct fsg_lun *curlun;
9c610213 290
8ea864cf
MN
291 unsigned int bulk_out_maxpacket;
292 enum fsg_state state; /* For exception handling */
293 unsigned int exception_req_tag;
294
8ea864cf
MN
295 enum data_direction data_dir;
296 u32 data_size;
297 u32 data_size_from_cmnd;
298 u32 tag;
299 u32 residue;
300 u32 usb_amount_left;
301
481e4929 302 unsigned int can_stall:1;
9c610213 303 unsigned int free_storage_on_release:1;
8ea864cf
MN
304 unsigned int phase_error:1;
305 unsigned int short_packet_received:1;
306 unsigned int bad_lun_okay:1;
307 unsigned int running:1;
9c610213 308
8ea864cf
MN
309 int thread_wakeup_needed;
310 struct completion thread_notifier;
311 struct task_struct *thread_task;
e8b6f8c5 312
8876f5e7
MN
313 /* Callback functions. */
314 const struct fsg_operations *ops;
c85efcb9
MN
315 /* Gadget's private data. */
316 void *private_data;
317
b73af61e
MN
318 /*
319 * Vendor (8 chars), product (16 chars), release (4
320 * hexadecimal digits) and NUL byte
321 */
481e4929
MN
322 char inquiry_string[8 + 16 + 4 + 1];
323
9c610213 324 struct kref ref;
a41ae418
MN
325};
326
481e4929
MN
327struct fsg_config {
328 unsigned nluns;
329 struct fsg_lun_config {
330 const char *filename;
331 char ro;
332 char removable;
333 char cdrom;
9cfe745e 334 char nofua;
481e4929
MN
335 } luns[FSG_MAX_LUNS];
336
8876f5e7
MN
337 /* Callback functions. */
338 const struct fsg_operations *ops;
c85efcb9
MN
339 /* Gadget's private data. */
340 void *private_data;
341
481e4929
MN
342 const char *vendor_name; /* 8 characters or less */
343 const char *product_name; /* 16 characters or less */
481e4929
MN
344
345 char can_stall;
6fdc5dd2 346 unsigned int fsg_num_buffers;
481e4929
MN
347};
348
d5e2b67a 349struct fsg_dev {
d23b0f08 350 struct usb_function function;
d23b0f08 351 struct usb_gadget *gadget; /* Copy of cdev->gadget */
a41ae418
MN
352 struct fsg_common *common;
353
d23b0f08
MN
354 u16 interface_number;
355
d26a6aa0
MN
356 unsigned int bulk_in_enabled:1;
357 unsigned int bulk_out_enabled:1;
d5e2b67a
MN
358
359 unsigned long atomic_bitflags;
8ea864cf 360#define IGNORE_BULK_OUT 0
d5e2b67a
MN
361
362 struct usb_ep *bulk_in;
363 struct usb_ep *bulk_out;
8ea864cf 364};
d5e2b67a 365
8ea864cf
MN
366static inline int __fsg_is_set(struct fsg_common *common,
367 const char *func, unsigned line)
368{
369 if (common->fsg)
370 return 1;
371 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
8876f5e7 372 WARN_ON(1);
8ea864cf
MN
373 return 0;
374}
375
376#define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
d5e2b67a 377
d23b0f08
MN
378static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
379{
380 return container_of(f, struct fsg_dev, function);
381}
382
d5e2b67a
MN
383typedef void (*fsg_routine_t)(struct fsg_dev *);
384
8ea864cf 385static int exception_in_progress(struct fsg_common *common)
d5e2b67a 386{
8ea864cf 387 return common->state > FSG_STATE_IDLE;
d5e2b67a
MN
388}
389
98346f7d
GKH
390/* Make bulk-out requests be divisible by the maxpacket size */
391static void set_bulk_out_req_length(struct fsg_common *common,
392 struct fsg_buffhd *bh, unsigned int length)
393{
394 unsigned int rem;
395
396 bh->bulk_out_intended_length = length;
397 rem = length % common->bulk_out_maxpacket;
398 if (rem > 0)
399 length += common->bulk_out_maxpacket - rem;
400 bh->outreq->length = length;
401}
402
403
d5e2b67a
MN
404/*-------------------------------------------------------------------------*/
405
406static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
407{
408 const char *name;
409
410 if (ep == fsg->bulk_in)
411 name = "bulk-in";
412 else if (ep == fsg->bulk_out)
413 name = "bulk-out";
414 else
415 name = ep->name;
416 DBG(fsg, "%s set halt\n", name);
417 return usb_ep_set_halt(ep);
418}
419
420
d5e2b67a
MN
421/*-------------------------------------------------------------------------*/
422
423/* These routines may be called in process context or in_irq */
424
425/* Caller must hold fsg->lock */
8ea864cf 426static void wakeup_thread(struct fsg_common *common)
d5e2b67a 427{
d68c277b 428 smp_wmb(); /* ensure the write of bh->state is complete */
d5e2b67a 429 /* Tell the main thread that something has happened */
8ea864cf
MN
430 common->thread_wakeup_needed = 1;
431 if (common->thread_task)
432 wake_up_process(common->thread_task);
d5e2b67a
MN
433}
434
8ea864cf 435static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
d5e2b67a
MN
436{
437 unsigned long flags;
438
b73af61e
MN
439 /*
440 * Do nothing if a higher-priority exception is already in progress.
d5e2b67a 441 * If a lower-or-equal priority exception is in progress, preempt it
b73af61e
MN
442 * and notify the main thread by sending it a signal.
443 */
8ea864cf
MN
444 spin_lock_irqsave(&common->lock, flags);
445 if (common->state <= new_state) {
446 common->exception_req_tag = common->ep0_req_tag;
447 common->state = new_state;
448 if (common->thread_task)
d5e2b67a 449 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
8ea864cf 450 common->thread_task);
d5e2b67a 451 }
8ea864cf 452 spin_unlock_irqrestore(&common->lock, flags);
d5e2b67a
MN
453}
454
455
456/*-------------------------------------------------------------------------*/
457
8ea864cf 458static int ep0_queue(struct fsg_common *common)
d5e2b67a
MN
459{
460 int rc;
461
8ea864cf
MN
462 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
463 common->ep0->driver_data = common;
d5e2b67a 464 if (rc != 0 && rc != -ESHUTDOWN) {
d5e2b67a 465 /* We can't do much more than wait for a reset */
8ea864cf
MN
466 WARNING(common, "error in submission: %s --> %d\n",
467 common->ep0->name, rc);
d5e2b67a
MN
468 }
469 return rc;
470}
471
b73af61e 472
d5e2b67a
MN
473/*-------------------------------------------------------------------------*/
474
b73af61e 475/* Completion handlers. These always run in_irq. */
d5e2b67a
MN
476
477static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
478{
8ea864cf 479 struct fsg_common *common = ep->driver_data;
d5e2b67a
MN
480 struct fsg_buffhd *bh = req->context;
481
482 if (req->status || req->actual != req->length)
8ea864cf 483 DBG(common, "%s --> %d, %u/%u\n", __func__,
b73af61e 484 req->status, req->actual, req->length);
d26a6aa0 485 if (req->status == -ECONNRESET) /* Request was cancelled */
d5e2b67a
MN
486 usb_ep_fifo_flush(ep);
487
488 /* Hold the lock while we update the request and buffer states */
489 smp_wmb();
8ea864cf 490 spin_lock(&common->lock);
d5e2b67a
MN
491 bh->inreq_busy = 0;
492 bh->state = BUF_STATE_EMPTY;
8ea864cf
MN
493 wakeup_thread(common);
494 spin_unlock(&common->lock);
d5e2b67a
MN
495}
496
497static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
498{
8ea864cf 499 struct fsg_common *common = ep->driver_data;
d5e2b67a
MN
500 struct fsg_buffhd *bh = req->context;
501
8ea864cf 502 dump_msg(common, "bulk-out", req->buf, req->actual);
98346f7d 503 if (req->status || req->actual != bh->bulk_out_intended_length)
8ea864cf 504 DBG(common, "%s --> %d, %u/%u\n", __func__,
98346f7d 505 req->status, req->actual, bh->bulk_out_intended_length);
d26a6aa0 506 if (req->status == -ECONNRESET) /* Request was cancelled */
d5e2b67a
MN
507 usb_ep_fifo_flush(ep);
508
509 /* Hold the lock while we update the request and buffer states */
510 smp_wmb();
8ea864cf 511 spin_lock(&common->lock);
d5e2b67a
MN
512 bh->outreq_busy = 0;
513 bh->state = BUF_STATE_FULL;
8ea864cf
MN
514 wakeup_thread(common);
515 spin_unlock(&common->lock);
d5e2b67a
MN
516}
517
d23b0f08 518static int fsg_setup(struct usb_function *f,
b73af61e 519 const struct usb_ctrlrequest *ctrl)
d5e2b67a 520{
d23b0f08 521 struct fsg_dev *fsg = fsg_from_func(f);
8ea864cf 522 struct usb_request *req = fsg->common->ep0req;
d5e2b67a 523 u16 w_index = le16_to_cpu(ctrl->wIndex);
93bcf12e 524 u16 w_value = le16_to_cpu(ctrl->wValue);
d5e2b67a
MN
525 u16 w_length = le16_to_cpu(ctrl->wLength);
526
b894f60a 527 if (!fsg_is_set(fsg->common))
93bcf12e 528 return -EOPNOTSUPP;
d5e2b67a 529
73ee4da9
RQ
530 ++fsg->common->ep0_req_tag; /* Record arrival of a new request */
531 req->context = NULL;
532 req->length = 0;
533 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
534
93bcf12e 535 switch (ctrl->bRequest) {
d5e2b67a 536
775dafdc 537 case US_BULK_RESET_REQUEST:
93bcf12e
MN
538 if (ctrl->bRequestType !=
539 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
d5e2b67a 540 break;
ce7b6121
PZ
541 if (w_index != fsg->interface_number || w_value != 0 ||
542 w_length != 0)
93bcf12e 543 return -EDOM;
d5e2b67a 544
b73af61e
MN
545 /*
546 * Raise an exception to stop the current operation
547 * and reinitialize our state.
548 */
93bcf12e 549 DBG(fsg, "bulk reset request\n");
8ea864cf 550 raise_exception(fsg->common, FSG_STATE_RESET);
93bcf12e 551 return DELAYED_STATUS;
d5e2b67a 552
775dafdc 553 case US_BULK_GET_MAX_LUN:
93bcf12e
MN
554 if (ctrl->bRequestType !=
555 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
d5e2b67a 556 break;
db332bc9
PZ
557 if (w_index != fsg->interface_number || w_value != 0 ||
558 w_length != 1)
93bcf12e
MN
559 return -EDOM;
560 VDBG(fsg, "get max LUN\n");
b73af61e 561 *(u8 *)req->buf = fsg->common->nluns - 1;
b00ce11f
MN
562
563 /* Respond with data/status */
d7e18a9f 564 req->length = min((u16)1, w_length);
b00ce11f 565 return ep0_queue(fsg->common);
93bcf12e
MN
566 }
567
568 VDBG(fsg,
b73af61e 569 "unknown class-specific control req %02x.%02x v%04x i%04x l%u\n",
93bcf12e
MN
570 ctrl->bRequestType, ctrl->bRequest,
571 le16_to_cpu(ctrl->wValue), w_index, w_length);
572 return -EOPNOTSUPP;
d5e2b67a
MN
573}
574
575
d5e2b67a
MN
576/*-------------------------------------------------------------------------*/
577
578/* All the following routines run in process context */
579
d5e2b67a
MN
580/* Use this for bulk or interrupt transfers, not ep0 */
581static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
b73af61e
MN
582 struct usb_request *req, int *pbusy,
583 enum fsg_buffer_state *state)
d5e2b67a
MN
584{
585 int rc;
586
587 if (ep == fsg->bulk_in)
588 dump_msg(fsg, "bulk-in", req->buf, req->length);
d5e2b67a 589
8ea864cf 590 spin_lock_irq(&fsg->common->lock);
d5e2b67a
MN
591 *pbusy = 1;
592 *state = BUF_STATE_BUSY;
8ea864cf 593 spin_unlock_irq(&fsg->common->lock);
d5e2b67a
MN
594 rc = usb_ep_queue(ep, req, GFP_KERNEL);
595 if (rc != 0) {
596 *pbusy = 0;
597 *state = BUF_STATE_EMPTY;
598
599 /* We can't do much more than wait for a reset */
600
b73af61e
MN
601 /*
602 * Note: currently the net2280 driver fails zero-length
603 * submissions if DMA is enabled.
604 */
605 if (rc != -ESHUTDOWN &&
606 !(rc == -EOPNOTSUPP && req->length == 0))
d5e2b67a 607 WARNING(fsg, "error in submission: %s --> %d\n",
b73af61e 608 ep->name, rc);
d5e2b67a
MN
609 }
610}
611
fe52f792
MN
612static bool start_in_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
613{
614 if (!fsg_is_set(common))
615 return false;
616 start_transfer(common->fsg, common->fsg->bulk_in,
617 bh->inreq, &bh->inreq_busy, &bh->state);
618 return true;
619}
8ea864cf 620
fe52f792
MN
621static bool start_out_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
622{
623 if (!fsg_is_set(common))
624 return false;
625 start_transfer(common->fsg, common->fsg->bulk_out,
626 bh->outreq, &bh->outreq_busy, &bh->state);
627 return true;
628}
d5e2b67a 629
8ea864cf 630static int sleep_thread(struct fsg_common *common)
d5e2b67a
MN
631{
632 int rc = 0;
633
634 /* Wait until a signal arrives or we are woken up */
635 for (;;) {
636 try_to_freeze();
637 set_current_state(TASK_INTERRUPTIBLE);
638 if (signal_pending(current)) {
639 rc = -EINTR;
640 break;
641 }
8ea864cf 642 if (common->thread_wakeup_needed)
d5e2b67a
MN
643 break;
644 schedule();
645 }
646 __set_current_state(TASK_RUNNING);
8ea864cf 647 common->thread_wakeup_needed = 0;
d68c277b 648 smp_rmb(); /* ensure the latest bh->state is visible */
d5e2b67a
MN
649 return rc;
650}
651
652
653/*-------------------------------------------------------------------------*/
654
8ea864cf 655static int do_read(struct fsg_common *common)
d5e2b67a 656{
8ea864cf 657 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
658 u32 lba;
659 struct fsg_buffhd *bh;
660 int rc;
661 u32 amount_left;
662 loff_t file_offset, file_offset_tmp;
663 unsigned int amount;
d5e2b67a
MN
664 ssize_t nread;
665
b73af61e
MN
666 /*
667 * Get the starting Logical Block Address and check that it's
668 * not too big.
669 */
0a6a717c 670 if (common->cmnd[0] == READ_6)
8ea864cf 671 lba = get_unaligned_be24(&common->cmnd[1]);
d5e2b67a 672 else {
8ea864cf 673 lba = get_unaligned_be32(&common->cmnd[2]);
d5e2b67a 674
b73af61e
MN
675 /*
676 * We allow DPO (Disable Page Out = don't save data in the
d5e2b67a 677 * cache) and FUA (Force Unit Access = don't read from the
b73af61e
MN
678 * cache), but we don't implement them.
679 */
8ea864cf 680 if ((common->cmnd[1] & ~0x18) != 0) {
d5e2b67a
MN
681 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
682 return -EINVAL;
683 }
684 }
685 if (lba >= curlun->num_sectors) {
686 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
687 return -EINVAL;
688 }
3f565a36 689 file_offset = ((loff_t) lba) << curlun->blkbits;
d5e2b67a
MN
690
691 /* Carry out the file reads */
8ea864cf 692 amount_left = common->data_size_from_cmnd;
d5e2b67a 693 if (unlikely(amount_left == 0))
d26a6aa0 694 return -EIO; /* No default reply */
d5e2b67a
MN
695
696 for (;;) {
b73af61e
MN
697 /*
698 * Figure out how much we need to read:
d5e2b67a
MN
699 * Try to read the remaining amount.
700 * But don't read more than the buffer size.
701 * And don't try to read past the end of the file.
b73af61e 702 */
93bcf12e 703 amount = min(amount_left, FSG_BUFLEN);
b73af61e
MN
704 amount = min((loff_t)amount,
705 curlun->file_length - file_offset);
d5e2b67a
MN
706
707 /* Wait for the next buffer to become available */
8ea864cf 708 bh = common->next_buffhd_to_fill;
d5e2b67a 709 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 710 rc = sleep_thread(common);
d5e2b67a
MN
711 if (rc)
712 return rc;
713 }
714
b73af61e
MN
715 /*
716 * If we were asked to read past the end of file,
717 * end with an empty buffer.
718 */
d5e2b67a
MN
719 if (amount == 0) {
720 curlun->sense_data =
721 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
3f565a36
PL
722 curlun->sense_data_info =
723 file_offset >> curlun->blkbits;
d5e2b67a
MN
724 curlun->info_valid = 1;
725 bh->inreq->length = 0;
726 bh->state = BUF_STATE_FULL;
727 break;
728 }
729
730 /* Perform the read */
731 file_offset_tmp = file_offset;
732 nread = vfs_read(curlun->filp,
b73af61e
MN
733 (char __user *)bh->buf,
734 amount, &file_offset_tmp);
d5e2b67a 735 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
b73af61e 736 (unsigned long long)file_offset, (int)nread);
d5e2b67a
MN
737 if (signal_pending(current))
738 return -EINTR;
739
740 if (nread < 0) {
b73af61e 741 LDBG(curlun, "error in file read: %d\n", (int)nread);
d5e2b67a
MN
742 nread = 0;
743 } else if (nread < amount) {
744 LDBG(curlun, "partial file read: %d/%u\n",
b73af61e 745 (int)nread, amount);
3f565a36 746 nread = round_down(nread, curlun->blksize);
d5e2b67a
MN
747 }
748 file_offset += nread;
749 amount_left -= nread;
8ea864cf 750 common->residue -= nread;
04eee25b
AS
751
752 /*
753 * Except at the end of the transfer, nread will be
754 * equal to the buffer size, which is divisible by the
755 * bulk-in maxpacket size.
756 */
d5e2b67a
MN
757 bh->inreq->length = nread;
758 bh->state = BUF_STATE_FULL;
759
760 /* If an error occurred, report it and its position */
761 if (nread < amount) {
762 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
3f565a36
PL
763 curlun->sense_data_info =
764 file_offset >> curlun->blkbits;
d5e2b67a
MN
765 curlun->info_valid = 1;
766 break;
767 }
768
769 if (amount_left == 0)
d26a6aa0 770 break; /* No more left to read */
d5e2b67a
MN
771
772 /* Send this buffer and go read some more */
773 bh->inreq->zero = 0;
fe52f792
MN
774 if (!start_in_transfer(common, bh))
775 /* Don't know what to do if common->fsg is NULL */
8ea864cf
MN
776 return -EIO;
777 common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
778 }
779
d26a6aa0 780 return -EIO; /* No default reply */
d5e2b67a
MN
781}
782
783
784/*-------------------------------------------------------------------------*/
785
8ea864cf 786static int do_write(struct fsg_common *common)
d5e2b67a 787{
8ea864cf 788 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
789 u32 lba;
790 struct fsg_buffhd *bh;
791 int get_some_more;
792 u32 amount_left_to_req, amount_left_to_write;
793 loff_t usb_offset, file_offset, file_offset_tmp;
794 unsigned int amount;
d5e2b67a
MN
795 ssize_t nwritten;
796 int rc;
797
798 if (curlun->ro) {
799 curlun->sense_data = SS_WRITE_PROTECTED;
800 return -EINVAL;
801 }
802 spin_lock(&curlun->filp->f_lock);
d26a6aa0 803 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
d5e2b67a
MN
804 spin_unlock(&curlun->filp->f_lock);
805
b73af61e
MN
806 /*
807 * Get the starting Logical Block Address and check that it's
808 * not too big
809 */
0a6a717c 810 if (common->cmnd[0] == WRITE_6)
8ea864cf 811 lba = get_unaligned_be24(&common->cmnd[1]);
d5e2b67a 812 else {
8ea864cf 813 lba = get_unaligned_be32(&common->cmnd[2]);
d5e2b67a 814
b73af61e
MN
815 /*
816 * We allow DPO (Disable Page Out = don't save data in the
d5e2b67a
MN
817 * cache) and FUA (Force Unit Access = write directly to the
818 * medium). We don't implement DPO; we implement FUA by
b73af61e
MN
819 * performing synchronous output.
820 */
8ea864cf 821 if (common->cmnd[1] & ~0x18) {
d5e2b67a
MN
822 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
823 return -EINVAL;
824 }
9cfe745e 825 if (!curlun->nofua && (common->cmnd[1] & 0x08)) { /* FUA */
d5e2b67a
MN
826 spin_lock(&curlun->filp->f_lock);
827 curlun->filp->f_flags |= O_SYNC;
828 spin_unlock(&curlun->filp->f_lock);
829 }
830 }
831 if (lba >= curlun->num_sectors) {
832 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
833 return -EINVAL;
834 }
835
836 /* Carry out the file writes */
837 get_some_more = 1;
3f565a36 838 file_offset = usb_offset = ((loff_t) lba) << curlun->blkbits;
8ea864cf
MN
839 amount_left_to_req = common->data_size_from_cmnd;
840 amount_left_to_write = common->data_size_from_cmnd;
d5e2b67a
MN
841
842 while (amount_left_to_write > 0) {
843
844 /* Queue a request for more data from the host */
8ea864cf 845 bh = common->next_buffhd_to_fill;
d5e2b67a
MN
846 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
847
b73af61e
MN
848 /*
849 * Figure out how much we want to get:
04eee25b
AS
850 * Try to get the remaining amount,
851 * but not more than the buffer size.
b73af61e 852 */
93bcf12e 853 amount = min(amount_left_to_req, FSG_BUFLEN);
04eee25b
AS
854
855 /* Beyond the end of the backing file? */
856 if (usb_offset >= curlun->file_length) {
d5e2b67a
MN
857 get_some_more = 0;
858 curlun->sense_data =
859 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
3f565a36
PL
860 curlun->sense_data_info =
861 usb_offset >> curlun->blkbits;
d5e2b67a
MN
862 curlun->info_valid = 1;
863 continue;
864 }
d5e2b67a
MN
865
866 /* Get the next buffer */
867 usb_offset += amount;
8ea864cf 868 common->usb_amount_left -= amount;
d5e2b67a
MN
869 amount_left_to_req -= amount;
870 if (amount_left_to_req == 0)
871 get_some_more = 0;
872
b73af61e 873 /*
04eee25b
AS
874 * Except at the end of the transfer, amount will be
875 * equal to the buffer size, which is divisible by
876 * the bulk-out maxpacket size.
b73af61e 877 */
fe696765 878 set_bulk_out_req_length(common, bh, amount);
fe52f792 879 if (!start_out_transfer(common, bh))
b73af61e 880 /* Dunno what to do if common->fsg is NULL */
8ea864cf
MN
881 return -EIO;
882 common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
883 continue;
884 }
885
886 /* Write the received data to the backing file */
8ea864cf 887 bh = common->next_buffhd_to_drain;
d5e2b67a 888 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
d26a6aa0 889 break; /* We stopped early */
d5e2b67a
MN
890 if (bh->state == BUF_STATE_FULL) {
891 smp_rmb();
8ea864cf 892 common->next_buffhd_to_drain = bh->next;
d5e2b67a
MN
893 bh->state = BUF_STATE_EMPTY;
894
895 /* Did something go wrong with the transfer? */
896 if (bh->outreq->status != 0) {
897 curlun->sense_data = SS_COMMUNICATION_FAILURE;
3f565a36
PL
898 curlun->sense_data_info =
899 file_offset >> curlun->blkbits;
d5e2b67a
MN
900 curlun->info_valid = 1;
901 break;
902 }
903
904 amount = bh->outreq->actual;
905 if (curlun->file_length - file_offset < amount) {
906 LERROR(curlun,
b73af61e
MN
907 "write %u @ %llu beyond end %llu\n",
908 amount, (unsigned long long)file_offset,
909 (unsigned long long)curlun->file_length);
d5e2b67a
MN
910 amount = curlun->file_length - file_offset;
911 }
912
fe696765
PZ
913 /* Don't accept excess data. The spec doesn't say
914 * what to do in this case. We'll ignore the error.
915 */
916 amount = min(amount, bh->bulk_out_intended_length);
917
04eee25b
AS
918 /* Don't write a partial block */
919 amount = round_down(amount, curlun->blksize);
920 if (amount == 0)
921 goto empty_write;
922
d5e2b67a
MN
923 /* Perform the write */
924 file_offset_tmp = file_offset;
925 nwritten = vfs_write(curlun->filp,
b73af61e
MN
926 (char __user *)bh->buf,
927 amount, &file_offset_tmp);
d5e2b67a 928 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
b73af61e 929 (unsigned long long)file_offset, (int)nwritten);
d5e2b67a 930 if (signal_pending(current))
d26a6aa0 931 return -EINTR; /* Interrupted! */
d5e2b67a
MN
932
933 if (nwritten < 0) {
934 LDBG(curlun, "error in file write: %d\n",
b73af61e 935 (int)nwritten);
d5e2b67a
MN
936 nwritten = 0;
937 } else if (nwritten < amount) {
938 LDBG(curlun, "partial file write: %d/%u\n",
b73af61e 939 (int)nwritten, amount);
3f565a36 940 nwritten = round_down(nwritten, curlun->blksize);
d5e2b67a
MN
941 }
942 file_offset += nwritten;
943 amount_left_to_write -= nwritten;
8ea864cf 944 common->residue -= nwritten;
d5e2b67a
MN
945
946 /* If an error occurred, report it and its position */
947 if (nwritten < amount) {
948 curlun->sense_data = SS_WRITE_ERROR;
3f565a36
PL
949 curlun->sense_data_info =
950 file_offset >> curlun->blkbits;
d5e2b67a
MN
951 curlun->info_valid = 1;
952 break;
953 }
954
04eee25b 955 empty_write:
d5e2b67a 956 /* Did the host decide to stop early? */
fe696765 957 if (bh->outreq->actual < bh->bulk_out_intended_length) {
8ea864cf 958 common->short_packet_received = 1;
d5e2b67a
MN
959 break;
960 }
961 continue;
962 }
963
964 /* Wait for something to happen */
8ea864cf 965 rc = sleep_thread(common);
d5e2b67a
MN
966 if (rc)
967 return rc;
968 }
969
d26a6aa0 970 return -EIO; /* No default reply */
d5e2b67a
MN
971}
972
973
974/*-------------------------------------------------------------------------*/
975
8ea864cf 976static int do_synchronize_cache(struct fsg_common *common)
d5e2b67a 977{
8ea864cf 978 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
979 int rc;
980
981 /* We ignore the requested LBA and write out all file's
982 * dirty data buffers. */
983 rc = fsg_lun_fsync_sub(curlun);
984 if (rc)
985 curlun->sense_data = SS_WRITE_ERROR;
986 return 0;
987}
988
989
990/*-------------------------------------------------------------------------*/
991
992static void invalidate_sub(struct fsg_lun *curlun)
993{
994 struct file *filp = curlun->filp;
496ad9aa 995 struct inode *inode = file_inode(filp);
d5e2b67a
MN
996 unsigned long rc;
997
998 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
2ecdc82e 999 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
d5e2b67a
MN
1000}
1001
8ea864cf 1002static int do_verify(struct fsg_common *common)
d5e2b67a 1003{
8ea864cf 1004 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1005 u32 lba;
1006 u32 verification_length;
8ea864cf 1007 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
d5e2b67a
MN
1008 loff_t file_offset, file_offset_tmp;
1009 u32 amount_left;
1010 unsigned int amount;
1011 ssize_t nread;
1012
b73af61e
MN
1013 /*
1014 * Get the starting Logical Block Address and check that it's
1015 * not too big.
1016 */
8ea864cf 1017 lba = get_unaligned_be32(&common->cmnd[2]);
d5e2b67a
MN
1018 if (lba >= curlun->num_sectors) {
1019 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1020 return -EINVAL;
1021 }
1022
b73af61e
MN
1023 /*
1024 * We allow DPO (Disable Page Out = don't save data in the
1025 * cache) but we don't implement it.
1026 */
8ea864cf 1027 if (common->cmnd[1] & ~0x10) {
d5e2b67a
MN
1028 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1029 return -EINVAL;
1030 }
1031
8ea864cf 1032 verification_length = get_unaligned_be16(&common->cmnd[7]);
d5e2b67a 1033 if (unlikely(verification_length == 0))
d26a6aa0 1034 return -EIO; /* No default reply */
d5e2b67a
MN
1035
1036 /* Prepare to carry out the file verify */
3f565a36
PL
1037 amount_left = verification_length << curlun->blkbits;
1038 file_offset = ((loff_t) lba) << curlun->blkbits;
d5e2b67a
MN
1039
1040 /* Write out all the dirty buffers before invalidating them */
1041 fsg_lun_fsync_sub(curlun);
1042 if (signal_pending(current))
1043 return -EINTR;
1044
1045 invalidate_sub(curlun);
1046 if (signal_pending(current))
1047 return -EINTR;
1048
1049 /* Just try to read the requested blocks */
1050 while (amount_left > 0) {
b73af61e
MN
1051 /*
1052 * Figure out how much we need to read:
d5e2b67a
MN
1053 * Try to read the remaining amount, but not more than
1054 * the buffer size.
1055 * And don't try to read past the end of the file.
b73af61e 1056 */
93bcf12e 1057 amount = min(amount_left, FSG_BUFLEN);
b73af61e
MN
1058 amount = min((loff_t)amount,
1059 curlun->file_length - file_offset);
d5e2b67a
MN
1060 if (amount == 0) {
1061 curlun->sense_data =
1062 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
3f565a36
PL
1063 curlun->sense_data_info =
1064 file_offset >> curlun->blkbits;
d5e2b67a
MN
1065 curlun->info_valid = 1;
1066 break;
1067 }
1068
1069 /* Perform the read */
1070 file_offset_tmp = file_offset;
1071 nread = vfs_read(curlun->filp,
1072 (char __user *) bh->buf,
1073 amount, &file_offset_tmp);
1074 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1075 (unsigned long long) file_offset,
1076 (int) nread);
1077 if (signal_pending(current))
1078 return -EINTR;
1079
1080 if (nread < 0) {
b73af61e 1081 LDBG(curlun, "error in file verify: %d\n", (int)nread);
d5e2b67a
MN
1082 nread = 0;
1083 } else if (nread < amount) {
1084 LDBG(curlun, "partial file verify: %d/%u\n",
b73af61e 1085 (int)nread, amount);
3f565a36 1086 nread = round_down(nread, curlun->blksize);
d5e2b67a
MN
1087 }
1088 if (nread == 0) {
1089 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
3f565a36
PL
1090 curlun->sense_data_info =
1091 file_offset >> curlun->blkbits;
d5e2b67a
MN
1092 curlun->info_valid = 1;
1093 break;
1094 }
1095 file_offset += nread;
1096 amount_left -= nread;
1097 }
1098 return 0;
1099}
1100
1101
1102/*-------------------------------------------------------------------------*/
1103
8ea864cf 1104static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1105{
8ea864cf 1106 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1107 u8 *buf = (u8 *) bh->buf;
1108
481e4929 1109 if (!curlun) { /* Unsupported LUNs are okay */
8ea864cf 1110 common->bad_lun_okay = 1;
d5e2b67a 1111 memset(buf, 0, 36);
d26a6aa0
MN
1112 buf[0] = 0x7f; /* Unsupported, no device-type */
1113 buf[4] = 31; /* Additional length */
d5e2b67a
MN
1114 return 36;
1115 }
1116
0a6a717c 1117 buf[0] = curlun->cdrom ? TYPE_ROM : TYPE_DISK;
481e4929 1118 buf[1] = curlun->removable ? 0x80 : 0;
d26a6aa0
MN
1119 buf[2] = 2; /* ANSI SCSI level 2 */
1120 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1121 buf[4] = 31; /* Additional length */
1122 buf[5] = 0; /* No special options */
481e4929
MN
1123 buf[6] = 0;
1124 buf[7] = 0;
8ea864cf 1125 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
d5e2b67a
MN
1126 return 36;
1127}
1128
8ea864cf 1129static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1130{
8ea864cf 1131 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1132 u8 *buf = (u8 *) bh->buf;
1133 u32 sd, sdinfo;
1134 int valid;
1135
1136 /*
1137 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1138 *
1139 * If a REQUEST SENSE command is received from an initiator
1140 * with a pending unit attention condition (before the target
1141 * generates the contingent allegiance condition), then the
1142 * target shall either:
1143 * a) report any pending sense data and preserve the unit
1144 * attention condition on the logical unit, or,
1145 * b) report the unit attention condition, may discard any
1146 * pending sense data, and clear the unit attention
1147 * condition on the logical unit for that initiator.
1148 *
1149 * FSG normally uses option a); enable this code to use option b).
1150 */
1151#if 0
1152 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1153 curlun->sense_data = curlun->unit_attention_data;
1154 curlun->unit_attention_data = SS_NO_SENSE;
1155 }
1156#endif
1157
d26a6aa0 1158 if (!curlun) { /* Unsupported LUNs are okay */
8ea864cf 1159 common->bad_lun_okay = 1;
d5e2b67a
MN
1160 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1161 sdinfo = 0;
1162 valid = 0;
1163 } else {
1164 sd = curlun->sense_data;
1165 sdinfo = curlun->sense_data_info;
1166 valid = curlun->info_valid << 7;
1167 curlun->sense_data = SS_NO_SENSE;
1168 curlun->sense_data_info = 0;
1169 curlun->info_valid = 0;
1170 }
1171
1172 memset(buf, 0, 18);
d26a6aa0 1173 buf[0] = valid | 0x70; /* Valid, current error */
d5e2b67a
MN
1174 buf[2] = SK(sd);
1175 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
d26a6aa0 1176 buf[7] = 18 - 8; /* Additional sense length */
d5e2b67a
MN
1177 buf[12] = ASC(sd);
1178 buf[13] = ASCQ(sd);
1179 return 18;
1180}
1181
8ea864cf 1182static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1183{
8ea864cf
MN
1184 struct fsg_lun *curlun = common->curlun;
1185 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1186 int pmi = common->cmnd[8];
b73af61e 1187 u8 *buf = (u8 *)bh->buf;
d5e2b67a
MN
1188
1189 /* Check the PMI and LBA fields */
1190 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1191 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1192 return -EINVAL;
1193 }
1194
1195 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1196 /* Max logical block */
3f565a36 1197 put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */
d5e2b67a
MN
1198 return 8;
1199}
1200
8ea864cf 1201static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1202{
8ea864cf
MN
1203 struct fsg_lun *curlun = common->curlun;
1204 int msf = common->cmnd[1] & 0x02;
1205 u32 lba = get_unaligned_be32(&common->cmnd[2]);
b73af61e 1206 u8 *buf = (u8 *)bh->buf;
d5e2b67a 1207
8ea864cf 1208 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
d5e2b67a
MN
1209 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1210 return -EINVAL;
1211 }
1212 if (lba >= curlun->num_sectors) {
1213 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1214 return -EINVAL;
1215 }
1216
1217 memset(buf, 0, 8);
1218 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1219 store_cdrom_address(&buf[4], msf, lba);
1220 return 8;
1221}
1222
8ea864cf 1223static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1224{
8ea864cf
MN
1225 struct fsg_lun *curlun = common->curlun;
1226 int msf = common->cmnd[1] & 0x02;
1227 int start_track = common->cmnd[6];
b73af61e 1228 u8 *buf = (u8 *)bh->buf;
d5e2b67a 1229
8ea864cf 1230 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
d5e2b67a
MN
1231 start_track > 1) {
1232 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1233 return -EINVAL;
1234 }
1235
1236 memset(buf, 0, 20);
1237 buf[1] = (20-2); /* TOC data length */
1238 buf[2] = 1; /* First track number */
1239 buf[3] = 1; /* Last track number */
1240 buf[5] = 0x16; /* Data track, copying allowed */
1241 buf[6] = 0x01; /* Only track is number 1 */
1242 store_cdrom_address(&buf[8], msf, 0);
1243
1244 buf[13] = 0x16; /* Lead-out track is data */
1245 buf[14] = 0xAA; /* Lead-out track number */
1246 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1247 return 20;
1248}
1249
8ea864cf 1250static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1251{
8ea864cf
MN
1252 struct fsg_lun *curlun = common->curlun;
1253 int mscmnd = common->cmnd[0];
d5e2b67a
MN
1254 u8 *buf = (u8 *) bh->buf;
1255 u8 *buf0 = buf;
1256 int pc, page_code;
1257 int changeable_values, all_pages;
1258 int valid_page = 0;
1259 int len, limit;
1260
8ea864cf 1261 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
d5e2b67a
MN
1262 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1263 return -EINVAL;
1264 }
8ea864cf
MN
1265 pc = common->cmnd[2] >> 6;
1266 page_code = common->cmnd[2] & 0x3f;
d5e2b67a
MN
1267 if (pc == 3) {
1268 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1269 return -EINVAL;
1270 }
1271 changeable_values = (pc == 1);
1272 all_pages = (page_code == 0x3f);
1273
b73af61e
MN
1274 /*
1275 * Write the mode parameter header. Fixed values are: default
d5e2b67a
MN
1276 * medium type, no cache control (DPOFUA), and no block descriptors.
1277 * The only variable value is the WriteProtect bit. We will fill in
b73af61e
MN
1278 * the mode data length later.
1279 */
d5e2b67a 1280 memset(buf, 0, 8);
0a6a717c 1281 if (mscmnd == MODE_SENSE) {
d26a6aa0 1282 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
d5e2b67a
MN
1283 buf += 4;
1284 limit = 255;
0a6a717c 1285 } else { /* MODE_SENSE_10 */
d26a6aa0 1286 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
d5e2b67a 1287 buf += 8;
d26a6aa0 1288 limit = 65535; /* Should really be FSG_BUFLEN */
d5e2b67a
MN
1289 }
1290
1291 /* No block descriptors */
1292
b73af61e
MN
1293 /*
1294 * The mode pages, in numerical order. The only page we support
1295 * is the Caching page.
1296 */
d5e2b67a
MN
1297 if (page_code == 0x08 || all_pages) {
1298 valid_page = 1;
d26a6aa0
MN
1299 buf[0] = 0x08; /* Page code */
1300 buf[1] = 10; /* Page length */
1301 memset(buf+2, 0, 10); /* None of the fields are changeable */
d5e2b67a
MN
1302
1303 if (!changeable_values) {
d26a6aa0
MN
1304 buf[2] = 0x04; /* Write cache enable, */
1305 /* Read cache not disabled */
1306 /* No cache retention priorities */
d5e2b67a
MN
1307 put_unaligned_be16(0xffff, &buf[4]);
1308 /* Don't disable prefetch */
1309 /* Minimum prefetch = 0 */
1310 put_unaligned_be16(0xffff, &buf[8]);
1311 /* Maximum prefetch */
1312 put_unaligned_be16(0xffff, &buf[10]);
1313 /* Maximum prefetch ceiling */
1314 }
1315 buf += 12;
1316 }
1317
b73af61e
MN
1318 /*
1319 * Check that a valid page was requested and the mode data length
1320 * isn't too long.
1321 */
d5e2b67a
MN
1322 len = buf - buf0;
1323 if (!valid_page || len > limit) {
1324 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1325 return -EINVAL;
1326 }
1327
1328 /* Store the mode data length */
0a6a717c 1329 if (mscmnd == MODE_SENSE)
d5e2b67a
MN
1330 buf0[0] = len - 1;
1331 else
1332 put_unaligned_be16(len - 2, buf0);
1333 return len;
1334}
1335
8ea864cf 1336static int do_start_stop(struct fsg_common *common)
d5e2b67a 1337{
31436a1a
FC
1338 struct fsg_lun *curlun = common->curlun;
1339 int loej, start;
1340
1341 if (!curlun) {
481e4929 1342 return -EINVAL;
31436a1a
FC
1343 } else if (!curlun->removable) {
1344 curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a 1345 return -EINVAL;
8876f5e7
MN
1346 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1347 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
31436a1a
FC
1348 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1349 return -EINVAL;
1350 }
1351
8876f5e7
MN
1352 loej = common->cmnd[4] & 0x02;
1353 start = common->cmnd[4] & 0x01;
31436a1a 1354
b73af61e
MN
1355 /*
1356 * Our emulation doesn't support mounting; the medium is
1357 * available for use as soon as it is loaded.
1358 */
8876f5e7 1359 if (start) {
31436a1a
FC
1360 if (!fsg_lun_is_open(curlun)) {
1361 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1362 return -EINVAL;
1363 }
8876f5e7 1364 return 0;
31436a1a 1365 }
8876f5e7
MN
1366
1367 /* Are we allowed to unload the media? */
1368 if (curlun->prevent_medium_removal) {
1369 LDBG(curlun, "unload attempt prevented\n");
1370 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1371 return -EINVAL;
1372 }
1373
1374 if (!loej)
1375 return 0;
1376
8876f5e7
MN
1377 up_read(&common->filesem);
1378 down_write(&common->filesem);
1379 fsg_lun_close(curlun);
1380 up_write(&common->filesem);
1381 down_read(&common->filesem);
1382
2b508002 1383 return 0;
d5e2b67a
MN
1384}
1385
8ea864cf 1386static int do_prevent_allow(struct fsg_common *common)
d5e2b67a 1387{
8ea864cf 1388 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1389 int prevent;
1390
8ea864cf 1391 if (!common->curlun) {
481e4929 1392 return -EINVAL;
8ea864cf
MN
1393 } else if (!common->curlun->removable) {
1394 common->curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
1395 return -EINVAL;
1396 }
1397
8ea864cf
MN
1398 prevent = common->cmnd[4] & 0x01;
1399 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
d5e2b67a
MN
1400 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1401 return -EINVAL;
1402 }
1403
1404 if (curlun->prevent_medium_removal && !prevent)
1405 fsg_lun_fsync_sub(curlun);
1406 curlun->prevent_medium_removal = prevent;
1407 return 0;
1408}
1409
8ea864cf 1410static int do_read_format_capacities(struct fsg_common *common,
d5e2b67a
MN
1411 struct fsg_buffhd *bh)
1412{
8ea864cf 1413 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1414 u8 *buf = (u8 *) bh->buf;
1415
1416 buf[0] = buf[1] = buf[2] = 0;
d26a6aa0 1417 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
d5e2b67a
MN
1418 buf += 4;
1419
1420 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1421 /* Number of blocks */
3f565a36 1422 put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */
d5e2b67a
MN
1423 buf[4] = 0x02; /* Current capacity */
1424 return 12;
1425}
1426
8ea864cf 1427static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
d5e2b67a 1428{
8ea864cf 1429 struct fsg_lun *curlun = common->curlun;
d5e2b67a
MN
1430
1431 /* We don't support MODE SELECT */
8ea864cf
MN
1432 if (curlun)
1433 curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
1434 return -EINVAL;
1435}
1436
1437
1438/*-------------------------------------------------------------------------*/
1439
1440static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1441{
1442 int rc;
1443
1444 rc = fsg_set_halt(fsg, fsg->bulk_in);
1445 if (rc == -EAGAIN)
1446 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1447 while (rc != 0) {
1448 if (rc != -EAGAIN) {
1449 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1450 rc = 0;
1451 break;
1452 }
1453
1454 /* Wait for a short time and then try again */
1455 if (msleep_interruptible(100) != 0)
1456 return -EINTR;
1457 rc = usb_ep_set_halt(fsg->bulk_in);
1458 }
1459 return rc;
1460}
1461
1462static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1463{
1464 int rc;
1465
1466 DBG(fsg, "bulk-in set wedge\n");
1467 rc = usb_ep_set_wedge(fsg->bulk_in);
1468 if (rc == -EAGAIN)
1469 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1470 while (rc != 0) {
1471 if (rc != -EAGAIN) {
1472 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1473 rc = 0;
1474 break;
1475 }
1476
1477 /* Wait for a short time and then try again */
1478 if (msleep_interruptible(100) != 0)
1479 return -EINTR;
1480 rc = usb_ep_set_wedge(fsg->bulk_in);
1481 }
1482 return rc;
1483}
1484
8ea864cf 1485static int throw_away_data(struct fsg_common *common)
d5e2b67a
MN
1486{
1487 struct fsg_buffhd *bh;
1488 u32 amount;
1489 int rc;
1490
8ea864cf
MN
1491 for (bh = common->next_buffhd_to_drain;
1492 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1493 bh = common->next_buffhd_to_drain) {
d5e2b67a
MN
1494
1495 /* Throw away the data in a filled buffer */
1496 if (bh->state == BUF_STATE_FULL) {
1497 smp_rmb();
1498 bh->state = BUF_STATE_EMPTY;
8ea864cf 1499 common->next_buffhd_to_drain = bh->next;
d5e2b67a
MN
1500
1501 /* A short packet or an error ends everything */
fe696765 1502 if (bh->outreq->actual < bh->bulk_out_intended_length ||
b73af61e 1503 bh->outreq->status != 0) {
8ea864cf
MN
1504 raise_exception(common,
1505 FSG_STATE_ABORT_BULK_OUT);
d5e2b67a
MN
1506 return -EINTR;
1507 }
1508 continue;
1509 }
1510
1511 /* Try to submit another request if we need one */
8ea864cf
MN
1512 bh = common->next_buffhd_to_fill;
1513 if (bh->state == BUF_STATE_EMPTY
1514 && common->usb_amount_left > 0) {
1515 amount = min(common->usb_amount_left, FSG_BUFLEN);
d5e2b67a 1516
b73af61e 1517 /*
04eee25b
AS
1518 * Except at the end of the transfer, amount will be
1519 * equal to the buffer size, which is divisible by
b73af61e
MN
1520 * the bulk-out maxpacket size.
1521 */
fe696765 1522 set_bulk_out_req_length(common, bh, amount);
fe52f792 1523 if (!start_out_transfer(common, bh))
b73af61e 1524 /* Dunno what to do if common->fsg is NULL */
8ea864cf
MN
1525 return -EIO;
1526 common->next_buffhd_to_fill = bh->next;
1527 common->usb_amount_left -= amount;
d5e2b67a
MN
1528 continue;
1529 }
1530
1531 /* Otherwise wait for something to happen */
8ea864cf 1532 rc = sleep_thread(common);
d5e2b67a
MN
1533 if (rc)
1534 return rc;
1535 }
1536 return 0;
1537}
1538
8ea864cf 1539static int finish_reply(struct fsg_common *common)
d5e2b67a 1540{
8ea864cf 1541 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
d5e2b67a
MN
1542 int rc = 0;
1543
8ea864cf 1544 switch (common->data_dir) {
d5e2b67a 1545 case DATA_DIR_NONE:
d26a6aa0 1546 break; /* Nothing to send */
d5e2b67a 1547
b73af61e
MN
1548 /*
1549 * If we don't know whether the host wants to read or write,
d5e2b67a
MN
1550 * this must be CB or CBI with an unknown command. We mustn't
1551 * try to send or receive any data. So stall both bulk pipes
b73af61e
MN
1552 * if we can and wait for a reset.
1553 */
d5e2b67a 1554 case DATA_DIR_UNKNOWN:
8ea864cf
MN
1555 if (!common->can_stall) {
1556 /* Nothing */
1557 } else if (fsg_is_set(common)) {
1558 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1559 rc = halt_bulk_in_endpoint(common->fsg);
1560 } else {
1561 /* Don't know what to do if common->fsg is NULL */
1562 rc = -EIO;
d5e2b67a
MN
1563 }
1564 break;
1565
1566 /* All but the last buffer of data must have already been sent */
1567 case DATA_DIR_TO_HOST:
8ea864cf 1568 if (common->data_size == 0) {
93bcf12e 1569 /* Nothing to send */
d5e2b67a 1570
ee81b3e0
AS
1571 /* Don't know what to do if common->fsg is NULL */
1572 } else if (!fsg_is_set(common)) {
1573 rc = -EIO;
1574
d5e2b67a 1575 /* If there's no residue, simply send the last buffer */
8ea864cf 1576 } else if (common->residue == 0) {
d5e2b67a 1577 bh->inreq->zero = 0;
fe52f792 1578 if (!start_in_transfer(common, bh))
8ea864cf
MN
1579 return -EIO;
1580 common->next_buffhd_to_fill = bh->next;
d5e2b67a 1581
b73af61e 1582 /*
ee81b3e0
AS
1583 * For Bulk-only, mark the end of the data with a short
1584 * packet. If we are allowed to stall, halt the bulk-in
1585 * endpoint. (Note: This violates the Bulk-Only Transport
1586 * specification, which requires us to pad the data if we
1587 * don't halt the endpoint. Presumably nobody will mind.)
b73af61e 1588 */
ee81b3e0 1589 } else {
93bcf12e 1590 bh->inreq->zero = 1;
fe52f792 1591 if (!start_in_transfer(common, bh))
8ea864cf
MN
1592 rc = -EIO;
1593 common->next_buffhd_to_fill = bh->next;
ee81b3e0 1594 if (common->can_stall)
8ea864cf 1595 rc = halt_bulk_in_endpoint(common->fsg);
d5e2b67a
MN
1596 }
1597 break;
1598
b73af61e
MN
1599 /*
1600 * We have processed all we want from the data the host has sent.
1601 * There may still be outstanding bulk-out requests.
1602 */
d5e2b67a 1603 case DATA_DIR_FROM_HOST:
8ea864cf 1604 if (common->residue == 0) {
d26a6aa0 1605 /* Nothing to receive */
d5e2b67a
MN
1606
1607 /* Did the host stop sending unexpectedly early? */
8ea864cf
MN
1608 } else if (common->short_packet_received) {
1609 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
d5e2b67a 1610 rc = -EINTR;
d5e2b67a 1611
b73af61e
MN
1612 /*
1613 * We haven't processed all the incoming data. Even though
d5e2b67a
MN
1614 * we may be allowed to stall, doing so would cause a race.
1615 * The controller may already have ACK'ed all the remaining
1616 * bulk-out packets, in which case the host wouldn't see a
1617 * STALL. Not realizing the endpoint was halted, it wouldn't
b73af61e
MN
1618 * clear the halt -- leading to problems later on.
1619 */
d5e2b67a 1620#if 0
8ea864cf
MN
1621 } else if (common->can_stall) {
1622 if (fsg_is_set(common))
1623 fsg_set_halt(common->fsg,
1624 common->fsg->bulk_out);
1625 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
d5e2b67a 1626 rc = -EINTR;
d5e2b67a
MN
1627#endif
1628
b73af61e
MN
1629 /*
1630 * We can't stall. Read in the excess data and throw it
1631 * all away.
1632 */
d26a6aa0 1633 } else {
8ea864cf 1634 rc = throw_away_data(common);
d26a6aa0 1635 }
d5e2b67a
MN
1636 break;
1637 }
1638 return rc;
1639}
1640
8ea864cf 1641static int send_status(struct fsg_common *common)
d5e2b67a 1642{
8ea864cf 1643 struct fsg_lun *curlun = common->curlun;
d5e2b67a 1644 struct fsg_buffhd *bh;
93bcf12e 1645 struct bulk_cs_wrap *csw;
d5e2b67a 1646 int rc;
775dafdc 1647 u8 status = US_BULK_STAT_OK;
d5e2b67a
MN
1648 u32 sd, sdinfo = 0;
1649
1650 /* Wait for the next buffer to become available */
8ea864cf 1651 bh = common->next_buffhd_to_fill;
d5e2b67a 1652 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 1653 rc = sleep_thread(common);
d5e2b67a
MN
1654 if (rc)
1655 return rc;
1656 }
1657
1658 if (curlun) {
1659 sd = curlun->sense_data;
1660 sdinfo = curlun->sense_data_info;
8ea864cf 1661 } else if (common->bad_lun_okay)
d5e2b67a
MN
1662 sd = SS_NO_SENSE;
1663 else
1664 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1665
8ea864cf
MN
1666 if (common->phase_error) {
1667 DBG(common, "sending phase-error status\n");
775dafdc 1668 status = US_BULK_STAT_PHASE;
d5e2b67a
MN
1669 sd = SS_INVALID_COMMAND;
1670 } else if (sd != SS_NO_SENSE) {
8ea864cf 1671 DBG(common, "sending command-failure status\n");
775dafdc 1672 status = US_BULK_STAT_FAIL;
8ea864cf 1673 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
d5e2b67a
MN
1674 " info x%x\n",
1675 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1676 }
1677
93bcf12e 1678 /* Store and send the Bulk-only CSW */
d26a6aa0 1679 csw = (void *)bh->buf;
d5e2b67a 1680
775dafdc 1681 csw->Signature = cpu_to_le32(US_BULK_CS_SIGN);
8ea864cf
MN
1682 csw->Tag = common->tag;
1683 csw->Residue = cpu_to_le32(common->residue);
93bcf12e 1684 csw->Status = status;
d5e2b67a 1685
775dafdc 1686 bh->inreq->length = US_BULK_CS_WRAP_LEN;
93bcf12e 1687 bh->inreq->zero = 0;
fe52f792 1688 if (!start_in_transfer(common, bh))
8ea864cf
MN
1689 /* Don't know what to do if common->fsg is NULL */
1690 return -EIO;
d5e2b67a 1691
8ea864cf 1692 common->next_buffhd_to_fill = bh->next;
d5e2b67a
MN
1693 return 0;
1694}
1695
1696
1697/*-------------------------------------------------------------------------*/
1698
b73af61e
MN
1699/*
1700 * Check whether the command is properly formed and whether its data size
1701 * and direction agree with the values we already have.
1702 */
8ea864cf 1703static int check_command(struct fsg_common *common, int cmnd_size,
b73af61e
MN
1704 enum data_direction data_dir, unsigned int mask,
1705 int needs_medium, const char *name)
d5e2b67a
MN
1706{
1707 int i;
98f3a1b9 1708 unsigned int lun = common->cmnd[1] >> 5;
d5e2b67a
MN
1709 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1710 char hdlen[20];
1711 struct fsg_lun *curlun;
1712
d5e2b67a 1713 hdlen[0] = 0;
8ea864cf
MN
1714 if (common->data_dir != DATA_DIR_UNKNOWN)
1715 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
b73af61e 1716 common->data_size);
8ea864cf 1717 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
d26a6aa0 1718 name, cmnd_size, dirletter[(int) data_dir],
8ea864cf 1719 common->data_size_from_cmnd, common->cmnd_size, hdlen);
d5e2b67a 1720
b73af61e
MN
1721 /*
1722 * We can't reply at all until we know the correct data direction
1723 * and size.
1724 */
8ea864cf 1725 if (common->data_size_from_cmnd == 0)
d5e2b67a 1726 data_dir = DATA_DIR_NONE;
8ea864cf 1727 if (common->data_size < common->data_size_from_cmnd) {
b73af61e
MN
1728 /*
1729 * Host data size < Device data size is a phase error.
8ea864cf 1730 * Carry out the command, but only transfer as much as
b73af61e
MN
1731 * we are allowed.
1732 */
8ea864cf
MN
1733 common->data_size_from_cmnd = common->data_size;
1734 common->phase_error = 1;
d5e2b67a 1735 }
8ea864cf
MN
1736 common->residue = common->data_size;
1737 common->usb_amount_left = common->data_size;
d5e2b67a
MN
1738
1739 /* Conflicting data directions is a phase error */
b73af61e 1740 if (common->data_dir != data_dir && common->data_size_from_cmnd > 0) {
8ea864cf 1741 common->phase_error = 1;
d5e2b67a
MN
1742 return -EINVAL;
1743 }
1744
1745 /* Verify the length of the command itself */
8ea864cf 1746 if (cmnd_size != common->cmnd_size) {
d5e2b67a 1747
b73af61e
MN
1748 /*
1749 * Special case workaround: There are plenty of buggy SCSI
d5e2b67a
MN
1750 * implementations. Many have issues with cbw->Length
1751 * field passing a wrong command size. For those cases we
1752 * always try to work around the problem by using the length
1753 * sent by the host side provided it is at least as large
1754 * as the correct command length.
1755 * Examples of such cases would be MS-Windows, which issues
1756 * REQUEST SENSE with cbw->Length == 12 where it should
1757 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1758 * REQUEST SENSE with cbw->Length == 10 where it should
1759 * be 6 as well.
1760 */
8ea864cf
MN
1761 if (cmnd_size <= common->cmnd_size) {
1762 DBG(common, "%s is buggy! Expected length %d "
a41ae418 1763 "but we got %d\n", name,
8ea864cf
MN
1764 cmnd_size, common->cmnd_size);
1765 cmnd_size = common->cmnd_size;
d5e2b67a 1766 } else {
8ea864cf 1767 common->phase_error = 1;
d5e2b67a
MN
1768 return -EINVAL;
1769 }
1770 }
1771
1772 /* Check that the LUN values are consistent */
8ea864cf 1773 if (common->lun != lun)
98f3a1b9 1774 DBG(common, "using LUN %u from CBW, not LUN %u from CDB\n",
8ea864cf 1775 common->lun, lun);
d5e2b67a
MN
1776
1777 /* Check the LUN */
144974e7
YL
1778 curlun = common->curlun;
1779 if (curlun) {
0a6a717c 1780 if (common->cmnd[0] != REQUEST_SENSE) {
d5e2b67a
MN
1781 curlun->sense_data = SS_NO_SENSE;
1782 curlun->sense_data_info = 0;
1783 curlun->info_valid = 0;
1784 }
1785 } else {
8ea864cf 1786 common->bad_lun_okay = 0;
d5e2b67a 1787
b73af61e
MN
1788 /*
1789 * INQUIRY and REQUEST SENSE commands are explicitly allowed
1790 * to use unsupported LUNs; all others may not.
1791 */
0a6a717c
MN
1792 if (common->cmnd[0] != INQUIRY &&
1793 common->cmnd[0] != REQUEST_SENSE) {
98f3a1b9 1794 DBG(common, "unsupported LUN %u\n", common->lun);
d5e2b67a
MN
1795 return -EINVAL;
1796 }
1797 }
1798
b73af61e
MN
1799 /*
1800 * If a unit attention condition exists, only INQUIRY and
1801 * REQUEST SENSE commands are allowed; anything else must fail.
1802 */
d5e2b67a 1803 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
b73af61e
MN
1804 common->cmnd[0] != INQUIRY &&
1805 common->cmnd[0] != REQUEST_SENSE) {
d5e2b67a
MN
1806 curlun->sense_data = curlun->unit_attention_data;
1807 curlun->unit_attention_data = SS_NO_SENSE;
1808 return -EINVAL;
1809 }
1810
1811 /* Check that only command bytes listed in the mask are non-zero */
8ea864cf 1812 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
d5e2b67a 1813 for (i = 1; i < cmnd_size; ++i) {
8ea864cf 1814 if (common->cmnd[i] && !(mask & (1 << i))) {
d5e2b67a
MN
1815 if (curlun)
1816 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1817 return -EINVAL;
1818 }
1819 }
1820
1821 /* If the medium isn't mounted and the command needs to access
1822 * it, return an error. */
1823 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1824 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1825 return -EINVAL;
1826 }
1827
1828 return 0;
1829}
1830
144974e7
YL
1831/* wrapper of check_command for data size in blocks handling */
1832static int check_command_size_in_blocks(struct fsg_common *common,
1833 int cmnd_size, enum data_direction data_dir,
1834 unsigned int mask, int needs_medium, const char *name)
1835{
1836 if (common->curlun)
1837 common->data_size_from_cmnd <<= common->curlun->blkbits;
1838 return check_command(common, cmnd_size, data_dir,
1839 mask, needs_medium, name);
1840}
1841
8ea864cf 1842static int do_scsi_command(struct fsg_common *common)
d5e2b67a
MN
1843{
1844 struct fsg_buffhd *bh;
1845 int rc;
1846 int reply = -EINVAL;
1847 int i;
1848 static char unknown[16];
1849
8ea864cf 1850 dump_cdb(common);
d5e2b67a
MN
1851
1852 /* Wait for the next buffer to become available for data or status */
8ea864cf
MN
1853 bh = common->next_buffhd_to_fill;
1854 common->next_buffhd_to_drain = bh;
d5e2b67a 1855 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 1856 rc = sleep_thread(common);
d5e2b67a
MN
1857 if (rc)
1858 return rc;
1859 }
8ea864cf
MN
1860 common->phase_error = 0;
1861 common->short_packet_received = 0;
d5e2b67a 1862
8ea864cf
MN
1863 down_read(&common->filesem); /* We're using the backing file */
1864 switch (common->cmnd[0]) {
d5e2b67a 1865
0a6a717c 1866 case INQUIRY:
8ea864cf
MN
1867 common->data_size_from_cmnd = common->cmnd[4];
1868 reply = check_command(common, 6, DATA_DIR_TO_HOST,
d26a6aa0
MN
1869 (1<<4), 0,
1870 "INQUIRY");
1871 if (reply == 0)
8ea864cf 1872 reply = do_inquiry(common, bh);
d5e2b67a
MN
1873 break;
1874
0a6a717c 1875 case MODE_SELECT:
8ea864cf
MN
1876 common->data_size_from_cmnd = common->cmnd[4];
1877 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
d26a6aa0
MN
1878 (1<<1) | (1<<4), 0,
1879 "MODE SELECT(6)");
1880 if (reply == 0)
8ea864cf 1881 reply = do_mode_select(common, bh);
d5e2b67a
MN
1882 break;
1883
0a6a717c 1884 case MODE_SELECT_10:
8ea864cf
MN
1885 common->data_size_from_cmnd =
1886 get_unaligned_be16(&common->cmnd[7]);
1887 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
d26a6aa0
MN
1888 (1<<1) | (3<<7), 0,
1889 "MODE SELECT(10)");
1890 if (reply == 0)
8ea864cf 1891 reply = do_mode_select(common, bh);
d5e2b67a
MN
1892 break;
1893
0a6a717c 1894 case MODE_SENSE:
8ea864cf
MN
1895 common->data_size_from_cmnd = common->cmnd[4];
1896 reply = check_command(common, 6, DATA_DIR_TO_HOST,
d26a6aa0
MN
1897 (1<<1) | (1<<2) | (1<<4), 0,
1898 "MODE SENSE(6)");
1899 if (reply == 0)
8ea864cf 1900 reply = do_mode_sense(common, bh);
d5e2b67a
MN
1901 break;
1902
0a6a717c 1903 case MODE_SENSE_10:
8ea864cf
MN
1904 common->data_size_from_cmnd =
1905 get_unaligned_be16(&common->cmnd[7]);
1906 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
1907 (1<<1) | (1<<2) | (3<<7), 0,
1908 "MODE SENSE(10)");
1909 if (reply == 0)
8ea864cf 1910 reply = do_mode_sense(common, bh);
d5e2b67a
MN
1911 break;
1912
0a6a717c 1913 case ALLOW_MEDIUM_REMOVAL:
8ea864cf
MN
1914 common->data_size_from_cmnd = 0;
1915 reply = check_command(common, 6, DATA_DIR_NONE,
d26a6aa0
MN
1916 (1<<4), 0,
1917 "PREVENT-ALLOW MEDIUM REMOVAL");
1918 if (reply == 0)
8ea864cf 1919 reply = do_prevent_allow(common);
d5e2b67a
MN
1920 break;
1921
0a6a717c 1922 case READ_6:
8ea864cf 1923 i = common->cmnd[4];
144974e7
YL
1924 common->data_size_from_cmnd = (i == 0) ? 256 : i;
1925 reply = check_command_size_in_blocks(common, 6,
1926 DATA_DIR_TO_HOST,
d26a6aa0
MN
1927 (7<<1) | (1<<4), 1,
1928 "READ(6)");
1929 if (reply == 0)
8ea864cf 1930 reply = do_read(common);
d5e2b67a
MN
1931 break;
1932
0a6a717c 1933 case READ_10:
8ea864cf 1934 common->data_size_from_cmnd =
144974e7
YL
1935 get_unaligned_be16(&common->cmnd[7]);
1936 reply = check_command_size_in_blocks(common, 10,
1937 DATA_DIR_TO_HOST,
d26a6aa0
MN
1938 (1<<1) | (0xf<<2) | (3<<7), 1,
1939 "READ(10)");
1940 if (reply == 0)
8ea864cf 1941 reply = do_read(common);
d5e2b67a
MN
1942 break;
1943
0a6a717c 1944 case READ_12:
8ea864cf 1945 common->data_size_from_cmnd =
144974e7
YL
1946 get_unaligned_be32(&common->cmnd[6]);
1947 reply = check_command_size_in_blocks(common, 12,
1948 DATA_DIR_TO_HOST,
d26a6aa0
MN
1949 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1950 "READ(12)");
1951 if (reply == 0)
8ea864cf 1952 reply = do_read(common);
d5e2b67a
MN
1953 break;
1954
0a6a717c 1955 case READ_CAPACITY:
8ea864cf
MN
1956 common->data_size_from_cmnd = 8;
1957 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
1958 (0xf<<2) | (1<<8), 1,
1959 "READ CAPACITY");
1960 if (reply == 0)
8ea864cf 1961 reply = do_read_capacity(common, bh);
d5e2b67a
MN
1962 break;
1963
0a6a717c 1964 case READ_HEADER:
8ea864cf 1965 if (!common->curlun || !common->curlun->cdrom)
d5e2b67a 1966 goto unknown_cmnd;
8ea864cf
MN
1967 common->data_size_from_cmnd =
1968 get_unaligned_be16(&common->cmnd[7]);
1969 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
1970 (3<<7) | (0x1f<<1), 1,
1971 "READ HEADER");
1972 if (reply == 0)
8ea864cf 1973 reply = do_read_header(common, bh);
d5e2b67a
MN
1974 break;
1975
0a6a717c 1976 case READ_TOC:
8ea864cf 1977 if (!common->curlun || !common->curlun->cdrom)
d5e2b67a 1978 goto unknown_cmnd;
8ea864cf
MN
1979 common->data_size_from_cmnd =
1980 get_unaligned_be16(&common->cmnd[7]);
1981 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
1982 (7<<6) | (1<<1), 1,
1983 "READ TOC");
1984 if (reply == 0)
8ea864cf 1985 reply = do_read_toc(common, bh);
d5e2b67a
MN
1986 break;
1987
0a6a717c 1988 case READ_FORMAT_CAPACITIES:
8ea864cf
MN
1989 common->data_size_from_cmnd =
1990 get_unaligned_be16(&common->cmnd[7]);
1991 reply = check_command(common, 10, DATA_DIR_TO_HOST,
d26a6aa0
MN
1992 (3<<7), 1,
1993 "READ FORMAT CAPACITIES");
1994 if (reply == 0)
8ea864cf 1995 reply = do_read_format_capacities(common, bh);
d5e2b67a
MN
1996 break;
1997
0a6a717c 1998 case REQUEST_SENSE:
8ea864cf
MN
1999 common->data_size_from_cmnd = common->cmnd[4];
2000 reply = check_command(common, 6, DATA_DIR_TO_HOST,
d26a6aa0
MN
2001 (1<<4), 0,
2002 "REQUEST SENSE");
2003 if (reply == 0)
8ea864cf 2004 reply = do_request_sense(common, bh);
d5e2b67a
MN
2005 break;
2006
0a6a717c 2007 case START_STOP:
8ea864cf
MN
2008 common->data_size_from_cmnd = 0;
2009 reply = check_command(common, 6, DATA_DIR_NONE,
d26a6aa0
MN
2010 (1<<1) | (1<<4), 0,
2011 "START-STOP UNIT");
2012 if (reply == 0)
8ea864cf 2013 reply = do_start_stop(common);
d5e2b67a
MN
2014 break;
2015
0a6a717c 2016 case SYNCHRONIZE_CACHE:
8ea864cf
MN
2017 common->data_size_from_cmnd = 0;
2018 reply = check_command(common, 10, DATA_DIR_NONE,
d26a6aa0
MN
2019 (0xf<<2) | (3<<7), 1,
2020 "SYNCHRONIZE CACHE");
2021 if (reply == 0)
8ea864cf 2022 reply = do_synchronize_cache(common);
d5e2b67a
MN
2023 break;
2024
0a6a717c 2025 case TEST_UNIT_READY:
8ea864cf
MN
2026 common->data_size_from_cmnd = 0;
2027 reply = check_command(common, 6, DATA_DIR_NONE,
d5e2b67a
MN
2028 0, 1,
2029 "TEST UNIT READY");
2030 break;
2031
b73af61e
MN
2032 /*
2033 * Although optional, this command is used by MS-Windows. We
2034 * support a minimal version: BytChk must be 0.
2035 */
0a6a717c 2036 case VERIFY:
8ea864cf
MN
2037 common->data_size_from_cmnd = 0;
2038 reply = check_command(common, 10, DATA_DIR_NONE,
d26a6aa0
MN
2039 (1<<1) | (0xf<<2) | (3<<7), 1,
2040 "VERIFY");
2041 if (reply == 0)
8ea864cf 2042 reply = do_verify(common);
d5e2b67a
MN
2043 break;
2044
0a6a717c 2045 case WRITE_6:
8ea864cf 2046 i = common->cmnd[4];
144974e7
YL
2047 common->data_size_from_cmnd = (i == 0) ? 256 : i;
2048 reply = check_command_size_in_blocks(common, 6,
2049 DATA_DIR_FROM_HOST,
d26a6aa0
MN
2050 (7<<1) | (1<<4), 1,
2051 "WRITE(6)");
2052 if (reply == 0)
8ea864cf 2053 reply = do_write(common);
d5e2b67a
MN
2054 break;
2055
0a6a717c 2056 case WRITE_10:
8ea864cf 2057 common->data_size_from_cmnd =
144974e7
YL
2058 get_unaligned_be16(&common->cmnd[7]);
2059 reply = check_command_size_in_blocks(common, 10,
2060 DATA_DIR_FROM_HOST,
d26a6aa0
MN
2061 (1<<1) | (0xf<<2) | (3<<7), 1,
2062 "WRITE(10)");
2063 if (reply == 0)
8ea864cf 2064 reply = do_write(common);
d5e2b67a
MN
2065 break;
2066
0a6a717c 2067 case WRITE_12:
8ea864cf 2068 common->data_size_from_cmnd =
144974e7
YL
2069 get_unaligned_be32(&common->cmnd[6]);
2070 reply = check_command_size_in_blocks(common, 12,
2071 DATA_DIR_FROM_HOST,
d26a6aa0
MN
2072 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2073 "WRITE(12)");
2074 if (reply == 0)
8ea864cf 2075 reply = do_write(common);
d5e2b67a
MN
2076 break;
2077
b73af61e
MN
2078 /*
2079 * Some mandatory commands that we recognize but don't implement.
d5e2b67a
MN
2080 * They don't mean much in this setting. It's left as an exercise
2081 * for anyone interested to implement RESERVE and RELEASE in terms
b73af61e
MN
2082 * of Posix locks.
2083 */
0a6a717c
MN
2084 case FORMAT_UNIT:
2085 case RELEASE:
2086 case RESERVE:
2087 case SEND_DIAGNOSTIC:
d26a6aa0 2088 /* Fall through */
d5e2b67a
MN
2089
2090 default:
d26a6aa0 2091unknown_cmnd:
8ea864cf
MN
2092 common->data_size_from_cmnd = 0;
2093 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2094 reply = check_command(common, common->cmnd_size,
c85dcdac 2095 DATA_DIR_UNKNOWN, ~0, 0, unknown);
d26a6aa0 2096 if (reply == 0) {
8ea864cf 2097 common->curlun->sense_data = SS_INVALID_COMMAND;
d5e2b67a
MN
2098 reply = -EINVAL;
2099 }
2100 break;
2101 }
8ea864cf 2102 up_read(&common->filesem);
d5e2b67a
MN
2103
2104 if (reply == -EINTR || signal_pending(current))
2105 return -EINTR;
2106
2107 /* Set up the single reply buffer for finish_reply() */
2108 if (reply == -EINVAL)
d26a6aa0 2109 reply = 0; /* Error reply length */
8ea864cf 2110 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
b73af61e 2111 reply = min((u32)reply, common->data_size_from_cmnd);
d5e2b67a
MN
2112 bh->inreq->length = reply;
2113 bh->state = BUF_STATE_FULL;
8ea864cf 2114 common->residue -= reply;
d26a6aa0 2115 } /* Otherwise it's already set */
d5e2b67a
MN
2116
2117 return 0;
2118}
2119
2120
2121/*-------------------------------------------------------------------------*/
2122
2123static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2124{
8ea864cf 2125 struct usb_request *req = bh->outreq;
7ac4704c 2126 struct bulk_cb_wrap *cbw = req->buf;
8ea864cf 2127 struct fsg_common *common = fsg->common;
d5e2b67a
MN
2128
2129 /* Was this a real packet? Should it be ignored? */
2130 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2131 return -EINVAL;
2132
2133 /* Is the CBW valid? */
775dafdc 2134 if (req->actual != US_BULK_CB_WRAP_LEN ||
d5e2b67a 2135 cbw->Signature != cpu_to_le32(
775dafdc 2136 US_BULK_CB_SIGN)) {
d5e2b67a
MN
2137 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2138 req->actual,
2139 le32_to_cpu(cbw->Signature));
2140
b73af61e
MN
2141 /*
2142 * The Bulk-only spec says we MUST stall the IN endpoint
d5e2b67a
MN
2143 * (6.6.1), so it's unavoidable. It also says we must
2144 * retain this state until the next reset, but there's
2145 * no way to tell the controller driver it should ignore
2146 * Clear-Feature(HALT) requests.
2147 *
2148 * We aren't required to halt the OUT endpoint; instead
2149 * we can simply accept and discard any data received
b73af61e
MN
2150 * until the next reset.
2151 */
d5e2b67a
MN
2152 wedge_bulk_in_endpoint(fsg);
2153 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2154 return -EINVAL;
2155 }
2156
2157 /* Is the CBW meaningful? */
775dafdc 2158 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~US_BULK_FLAG_IN ||
d5e2b67a
MN
2159 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2160 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2161 "cmdlen %u\n",
2162 cbw->Lun, cbw->Flags, cbw->Length);
2163
b73af61e
MN
2164 /*
2165 * We can do anything we want here, so let's stall the
2166 * bulk pipes if we are allowed to.
2167 */
8ea864cf 2168 if (common->can_stall) {
d5e2b67a
MN
2169 fsg_set_halt(fsg, fsg->bulk_out);
2170 halt_bulk_in_endpoint(fsg);
2171 }
2172 return -EINVAL;
2173 }
2174
2175 /* Save the command for later */
8ea864cf
MN
2176 common->cmnd_size = cbw->Length;
2177 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
775dafdc 2178 if (cbw->Flags & US_BULK_FLAG_IN)
8ea864cf 2179 common->data_dir = DATA_DIR_TO_HOST;
d5e2b67a 2180 else
8ea864cf
MN
2181 common->data_dir = DATA_DIR_FROM_HOST;
2182 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2183 if (common->data_size == 0)
2184 common->data_dir = DATA_DIR_NONE;
2185 common->lun = cbw->Lun;
98f3a1b9 2186 if (common->lun < common->nluns)
144974e7
YL
2187 common->curlun = &common->luns[common->lun];
2188 else
2189 common->curlun = NULL;
8ea864cf 2190 common->tag = cbw->Tag;
d5e2b67a
MN
2191 return 0;
2192}
2193
8ea864cf 2194static int get_next_command(struct fsg_common *common)
d5e2b67a
MN
2195{
2196 struct fsg_buffhd *bh;
2197 int rc = 0;
2198
93bcf12e 2199 /* Wait for the next buffer to become available */
8ea864cf 2200 bh = common->next_buffhd_to_fill;
93bcf12e 2201 while (bh->state != BUF_STATE_EMPTY) {
8ea864cf 2202 rc = sleep_thread(common);
93bcf12e
MN
2203 if (rc)
2204 return rc;
2205 }
d5e2b67a 2206
93bcf12e 2207 /* Queue a request to read a Bulk-only CBW */
775dafdc 2208 set_bulk_out_req_length(common, bh, US_BULK_CB_WRAP_LEN);
fe52f792 2209 if (!start_out_transfer(common, bh))
8ea864cf
MN
2210 /* Don't know what to do if common->fsg is NULL */
2211 return -EIO;
d5e2b67a 2212
b73af61e
MN
2213 /*
2214 * We will drain the buffer in software, which means we
93bcf12e 2215 * can reuse it for the next filling. No need to advance
b73af61e
MN
2216 * next_buffhd_to_fill.
2217 */
d5e2b67a 2218
93bcf12e
MN
2219 /* Wait for the CBW to arrive */
2220 while (bh->state != BUF_STATE_FULL) {
8ea864cf 2221 rc = sleep_thread(common);
93bcf12e
MN
2222 if (rc)
2223 return rc;
d5e2b67a 2224 }
93bcf12e 2225 smp_rmb();
8ea864cf 2226 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
93bcf12e
MN
2227 bh->state = BUF_STATE_EMPTY;
2228
d5e2b67a
MN
2229 return rc;
2230}
2231
2232
2233/*-------------------------------------------------------------------------*/
2234
8ea864cf 2235static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
d5e2b67a
MN
2236 struct usb_request **preq)
2237{
2238 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2239 if (*preq)
2240 return 0;
8ea864cf 2241 ERROR(common, "can't allocate request for %s\n", ep->name);
d5e2b67a
MN
2242 return -ENOMEM;
2243}
2244
b894f60a
MN
2245/* Reset interface setting and re-init endpoint state (toggle etc). */
2246static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
d5e2b67a 2247{
b894f60a
MN
2248 struct fsg_dev *fsg;
2249 int i, rc = 0;
d5e2b67a 2250
8ea864cf
MN
2251 if (common->running)
2252 DBG(common, "reset interface\n");
d5e2b67a
MN
2253
2254reset:
2255 /* Deallocate the requests */
b894f60a
MN
2256 if (common->fsg) {
2257 fsg = common->fsg;
8ea864cf 2258
6fdc5dd2 2259 for (i = 0; i < common->fsg_num_buffers; ++i) {
8ea864cf 2260 struct fsg_buffhd *bh = &common->buffhds[i];
d5e2b67a 2261
8ea864cf
MN
2262 if (bh->inreq) {
2263 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2264 bh->inreq = NULL;
2265 }
2266 if (bh->outreq) {
2267 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2268 bh->outreq = NULL;
2269 }
d5e2b67a 2270 }
8ea864cf
MN
2271
2272 /* Disable the endpoints */
2273 if (fsg->bulk_in_enabled) {
2274 usb_ep_disable(fsg->bulk_in);
7f2ccc8c 2275 fsg->bulk_in->driver_data = NULL;
8ea864cf
MN
2276 fsg->bulk_in_enabled = 0;
2277 }
2278 if (fsg->bulk_out_enabled) {
2279 usb_ep_disable(fsg->bulk_out);
7f2ccc8c 2280 fsg->bulk_out->driver_data = NULL;
8ea864cf 2281 fsg->bulk_out_enabled = 0;
d5e2b67a 2282 }
d5e2b67a 2283
b894f60a
MN
2284 common->fsg = NULL;
2285 wake_up(&common->fsg_wait);
d5e2b67a 2286 }
d5e2b67a 2287
8ea864cf 2288 common->running = 0;
b894f60a 2289 if (!new_fsg || rc)
d5e2b67a
MN
2290 return rc;
2291
b894f60a
MN
2292 common->fsg = new_fsg;
2293 fsg = common->fsg;
d5e2b67a 2294
b894f60a 2295 /* Enable the endpoints */
ea2a1df7
TB
2296 rc = config_ep_by_speed(common->gadget, &(fsg->function), fsg->bulk_in);
2297 if (rc)
2298 goto reset;
2299 rc = usb_ep_enable(fsg->bulk_in);
b894f60a
MN
2300 if (rc)
2301 goto reset;
ea2a1df7 2302 fsg->bulk_in->driver_data = common;
b894f60a 2303 fsg->bulk_in_enabled = 1;
8ea864cf 2304
ea2a1df7
TB
2305 rc = config_ep_by_speed(common->gadget, &(fsg->function),
2306 fsg->bulk_out);
2307 if (rc)
2308 goto reset;
2309 rc = usb_ep_enable(fsg->bulk_out);
b894f60a
MN
2310 if (rc)
2311 goto reset;
ea2a1df7 2312 fsg->bulk_out->driver_data = common;
b894f60a 2313 fsg->bulk_out_enabled = 1;
29cc8897 2314 common->bulk_out_maxpacket = usb_endpoint_maxp(fsg->bulk_out->desc);
b894f60a
MN
2315 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2316
2317 /* Allocate the requests */
6fdc5dd2 2318 for (i = 0; i < common->fsg_num_buffers; ++i) {
b894f60a
MN
2319 struct fsg_buffhd *bh = &common->buffhds[i];
2320
2321 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
8ea864cf 2322 if (rc)
d5e2b67a 2323 goto reset;
b894f60a 2324 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
8ea864cf 2325 if (rc)
d5e2b67a 2326 goto reset;
b894f60a
MN
2327 bh->inreq->buf = bh->outreq->buf = bh->buf;
2328 bh->inreq->context = bh->outreq->context = bh;
2329 bh->inreq->complete = bulk_in_complete;
2330 bh->outreq->complete = bulk_out_complete;
8ea864cf 2331 }
d5e2b67a 2332
b894f60a
MN
2333 common->running = 1;
2334 for (i = 0; i < common->nluns; ++i)
2335 common->luns[i].unit_attention_data = SS_RESET_OCCURRED;
d5e2b67a
MN
2336 return rc;
2337}
2338
2339
d23b0f08
MN
2340/****************************** ALT CONFIGS ******************************/
2341
d23b0f08
MN
2342static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2343{
2344 struct fsg_dev *fsg = fsg_from_func(f);
b894f60a 2345 fsg->common->new_fsg = fsg;
8ea864cf 2346 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
95ed3236 2347 return USB_GADGET_DELAYED_STATUS;
d23b0f08
MN
2348}
2349
2350static void fsg_disable(struct usb_function *f)
2351{
2352 struct fsg_dev *fsg = fsg_from_func(f);
b894f60a 2353 fsg->common->new_fsg = NULL;
8ea864cf 2354 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
d23b0f08
MN
2355}
2356
2357
d5e2b67a
MN
2358/*-------------------------------------------------------------------------*/
2359
8ea864cf 2360static void handle_exception(struct fsg_common *common)
d5e2b67a
MN
2361{
2362 siginfo_t info;
d5e2b67a 2363 int i;
d5e2b67a
MN
2364 struct fsg_buffhd *bh;
2365 enum fsg_state old_state;
d5e2b67a
MN
2366 struct fsg_lun *curlun;
2367 unsigned int exception_req_tag;
d5e2b67a 2368
b73af61e
MN
2369 /*
2370 * Clear the existing signals. Anything but SIGUSR1 is converted
2371 * into a high-priority EXIT exception.
2372 */
d5e2b67a 2373 for (;;) {
b894f60a
MN
2374 int sig =
2375 dequeue_signal_lock(current, &current->blocked, &info);
d5e2b67a
MN
2376 if (!sig)
2377 break;
2378 if (sig != SIGUSR1) {
8ea864cf
MN
2379 if (common->state < FSG_STATE_EXIT)
2380 DBG(common, "Main thread exiting on signal\n");
2381 raise_exception(common, FSG_STATE_EXIT);
d5e2b67a
MN
2382 }
2383 }
2384
2385 /* Cancel all the pending transfers */
b894f60a 2386 if (likely(common->fsg)) {
6fdc5dd2 2387 for (i = 0; i < common->fsg_num_buffers; ++i) {
8ea864cf
MN
2388 bh = &common->buffhds[i];
2389 if (bh->inreq_busy)
2390 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2391 if (bh->outreq_busy)
2392 usb_ep_dequeue(common->fsg->bulk_out,
2393 bh->outreq);
d5e2b67a 2394 }
d5e2b67a 2395
8ea864cf
MN
2396 /* Wait until everything is idle */
2397 for (;;) {
2398 int num_active = 0;
6fdc5dd2 2399 for (i = 0; i < common->fsg_num_buffers; ++i) {
8ea864cf
MN
2400 bh = &common->buffhds[i];
2401 num_active += bh->inreq_busy + bh->outreq_busy;
2402 }
2403 if (num_active == 0)
2404 break;
2405 if (sleep_thread(common))
2406 return;
2407 }
2408
2409 /* Clear out the controller's fifos */
2410 if (common->fsg->bulk_in_enabled)
2411 usb_ep_fifo_flush(common->fsg->bulk_in);
2412 if (common->fsg->bulk_out_enabled)
2413 usb_ep_fifo_flush(common->fsg->bulk_out);
2414 }
d5e2b67a 2415
b73af61e
MN
2416 /*
2417 * Reset the I/O buffer states and pointers, the SCSI
2418 * state, and the exception. Then invoke the handler.
2419 */
8ea864cf 2420 spin_lock_irq(&common->lock);
d5e2b67a 2421
6fdc5dd2 2422 for (i = 0; i < common->fsg_num_buffers; ++i) {
8ea864cf 2423 bh = &common->buffhds[i];
d5e2b67a
MN
2424 bh->state = BUF_STATE_EMPTY;
2425 }
8ea864cf
MN
2426 common->next_buffhd_to_fill = &common->buffhds[0];
2427 common->next_buffhd_to_drain = &common->buffhds[0];
2428 exception_req_tag = common->exception_req_tag;
8ea864cf 2429 old_state = common->state;
d5e2b67a
MN
2430
2431 if (old_state == FSG_STATE_ABORT_BULK_OUT)
8ea864cf 2432 common->state = FSG_STATE_STATUS_PHASE;
d5e2b67a 2433 else {
8ea864cf
MN
2434 for (i = 0; i < common->nluns; ++i) {
2435 curlun = &common->luns[i];
d5e2b67a 2436 curlun->prevent_medium_removal = 0;
d26a6aa0
MN
2437 curlun->sense_data = SS_NO_SENSE;
2438 curlun->unit_attention_data = SS_NO_SENSE;
d5e2b67a
MN
2439 curlun->sense_data_info = 0;
2440 curlun->info_valid = 0;
2441 }
8ea864cf 2442 common->state = FSG_STATE_IDLE;
d5e2b67a 2443 }
8ea864cf 2444 spin_unlock_irq(&common->lock);
d5e2b67a
MN
2445
2446 /* Carry out any extra actions required for the exception */
2447 switch (old_state) {
d5e2b67a 2448 case FSG_STATE_ABORT_BULK_OUT:
8ea864cf
MN
2449 send_status(common);
2450 spin_lock_irq(&common->lock);
2451 if (common->state == FSG_STATE_STATUS_PHASE)
2452 common->state = FSG_STATE_IDLE;
2453 spin_unlock_irq(&common->lock);
d5e2b67a
MN
2454 break;
2455
2456 case FSG_STATE_RESET:
b73af61e
MN
2457 /*
2458 * In case we were forced against our will to halt a
d5e2b67a 2459 * bulk endpoint, clear the halt now. (The SuperH UDC
b73af61e
MN
2460 * requires this.)
2461 */
8ea864cf
MN
2462 if (!fsg_is_set(common))
2463 break;
2464 if (test_and_clear_bit(IGNORE_BULK_OUT,
2465 &common->fsg->atomic_bitflags))
2466 usb_ep_clear_halt(common->fsg->bulk_in);
d5e2b67a 2467
8ea864cf
MN
2468 if (common->ep0_req_tag == exception_req_tag)
2469 ep0_queue(common); /* Complete the status stage */
d5e2b67a 2470
b73af61e
MN
2471 /*
2472 * Technically this should go here, but it would only be
d5e2b67a 2473 * a waste of time. Ditto for the INTERFACE_CHANGE and
b73af61e
MN
2474 * CONFIG_CHANGE cases.
2475 */
8ea864cf
MN
2476 /* for (i = 0; i < common->nluns; ++i) */
2477 /* common->luns[i].unit_attention_data = */
d26a6aa0 2478 /* SS_RESET_OCCURRED; */
d5e2b67a
MN
2479 break;
2480
d5e2b67a 2481 case FSG_STATE_CONFIG_CHANGE:
b894f60a 2482 do_set_interface(common, common->new_fsg);
95ed3236
RQ
2483 if (common->new_fsg)
2484 usb_composite_setup_continue(common->cdev);
d5e2b67a
MN
2485 break;
2486
d5e2b67a
MN
2487 case FSG_STATE_EXIT:
2488 case FSG_STATE_TERMINATED:
b894f60a 2489 do_set_interface(common, NULL); /* Free resources */
8ea864cf
MN
2490 spin_lock_irq(&common->lock);
2491 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2492 spin_unlock_irq(&common->lock);
d5e2b67a 2493 break;
d23b0f08
MN
2494
2495 case FSG_STATE_INTERFACE_CHANGE:
2496 case FSG_STATE_DISCONNECT:
2497 case FSG_STATE_COMMAND_PHASE:
2498 case FSG_STATE_DATA_PHASE:
2499 case FSG_STATE_STATUS_PHASE:
2500 case FSG_STATE_IDLE:
2501 break;
d5e2b67a
MN
2502 }
2503}
2504
2505
2506/*-------------------------------------------------------------------------*/
2507
8ea864cf 2508static int fsg_main_thread(void *common_)
d5e2b67a 2509{
8ea864cf 2510 struct fsg_common *common = common_;
d5e2b67a 2511
b73af61e
MN
2512 /*
2513 * Allow the thread to be killed by a signal, but set the signal mask
2514 * to block everything but INT, TERM, KILL, and USR1.
2515 */
d5e2b67a
MN
2516 allow_signal(SIGINT);
2517 allow_signal(SIGTERM);
2518 allow_signal(SIGKILL);
2519 allow_signal(SIGUSR1);
2520
2521 /* Allow the thread to be frozen */
2522 set_freezable();
2523
b73af61e
MN
2524 /*
2525 * Arrange for userspace references to be interpreted as kernel
d5e2b67a 2526 * pointers. That way we can pass a kernel pointer to a routine
b73af61e
MN
2527 * that expects a __user pointer and it will work okay.
2528 */
d5e2b67a
MN
2529 set_fs(get_ds());
2530
2531 /* The main loop */
8ea864cf
MN
2532 while (common->state != FSG_STATE_TERMINATED) {
2533 if (exception_in_progress(common) || signal_pending(current)) {
2534 handle_exception(common);
d5e2b67a
MN
2535 continue;
2536 }
2537
8ea864cf
MN
2538 if (!common->running) {
2539 sleep_thread(common);
d5e2b67a
MN
2540 continue;
2541 }
2542
8ea864cf 2543 if (get_next_command(common))
d5e2b67a
MN
2544 continue;
2545
8ea864cf
MN
2546 spin_lock_irq(&common->lock);
2547 if (!exception_in_progress(common))
2548 common->state = FSG_STATE_DATA_PHASE;
2549 spin_unlock_irq(&common->lock);
d5e2b67a 2550
8ea864cf 2551 if (do_scsi_command(common) || finish_reply(common))
d5e2b67a
MN
2552 continue;
2553
8ea864cf
MN
2554 spin_lock_irq(&common->lock);
2555 if (!exception_in_progress(common))
2556 common->state = FSG_STATE_STATUS_PHASE;
2557 spin_unlock_irq(&common->lock);
d5e2b67a 2558
8ea864cf 2559 if (send_status(common))
d5e2b67a
MN
2560 continue;
2561
8ea864cf
MN
2562 spin_lock_irq(&common->lock);
2563 if (!exception_in_progress(common))
2564 common->state = FSG_STATE_IDLE;
2565 spin_unlock_irq(&common->lock);
d23b0f08 2566 }
d5e2b67a 2567
8ea864cf
MN
2568 spin_lock_irq(&common->lock);
2569 common->thread_task = NULL;
2570 spin_unlock_irq(&common->lock);
d5e2b67a 2571
8876f5e7
MN
2572 if (!common->ops || !common->ops->thread_exits
2573 || common->ops->thread_exits(common) < 0) {
7f1ee826
MN
2574 struct fsg_lun *curlun = common->luns;
2575 unsigned i = common->nluns;
2576
2577 down_write(&common->filesem);
2578 for (; i--; ++curlun) {
2579 if (!fsg_lun_is_open(curlun))
2580 continue;
2581
2582 fsg_lun_close(curlun);
2583 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2584 }
2585 up_write(&common->filesem);
2586 }
d5e2b67a 2587
00cb636e 2588 /* Let fsg_unbind() know the thread has exited */
8ea864cf 2589 complete_and_exit(&common->thread_notifier, 0);
d5e2b67a
MN
2590}
2591
2592
9c610213 2593/*************************** DEVICE ATTRIBUTES ***************************/
d5e2b67a 2594
6fdc5dd2
AP
2595static ssize_t ro_show(struct device *dev, struct device_attribute *attr, char *buf)
2596{
2597 return fsg_show_ro(dev, attr, buf);
2598}
2599
2600static ssize_t nofua_show(struct device *dev, struct device_attribute *attr,
2601 char *buf)
2602{
2603 return fsg_show_nofua(dev, attr, buf);
2604}
2605
2606static ssize_t file_show(struct device *dev, struct device_attribute *attr,
2607 char *buf)
2608{
2609 return fsg_show_file(dev, attr, buf);
2610}
2611
2612static ssize_t ro_store(struct device *dev, struct device_attribute *attr,
2613 const char *buf, size_t count)
2614{
2615 return fsg_store_ro(dev, attr, buf, count);
2616}
2617
2618static ssize_t nofua_store(struct device *dev, struct device_attribute *attr,
2619 const char *buf, size_t count)
2620{
2621 return fsg_store_nofua(dev, attr, buf, count);
2622}
2623
2624static ssize_t file_store(struct device *dev, struct device_attribute *attr,
2625 const char *buf, size_t count)
2626{
2627 return fsg_store_file(dev, attr, buf, count);
2628}
2629
ce26bd23
GKH
2630static DEVICE_ATTR_RW(ro);
2631static DEVICE_ATTR_RW(nofua);
2632static DEVICE_ATTR_RW(file);
2633
2634static struct device_attribute dev_attr_ro_cdrom = __ATTR_RO(ro);
2635static struct device_attribute dev_attr_file_nonremovable = __ATTR_RO(file);
48a31af7 2636
d5e2b67a 2637
9c610213
MN
2638/****************************** FSG COMMON ******************************/
2639
2640static void fsg_common_release(struct kref *ref);
d5e2b67a 2641
9c610213 2642static void fsg_lun_release(struct device *dev)
d5e2b67a 2643{
9c610213 2644 /* Nothing needs to be done */
d5e2b67a
MN
2645}
2646
9c610213 2647static inline void fsg_common_get(struct fsg_common *common)
d5e2b67a 2648{
9c610213 2649 kref_get(&common->ref);
d5e2b67a
MN
2650}
2651
9c610213
MN
2652static inline void fsg_common_put(struct fsg_common *common)
2653{
2654 kref_put(&common->ref, fsg_common_release);
2655}
2656
6fdc5dd2
AP
2657/* check if fsg_num_buffers is within a valid range */
2658static inline int fsg_num_buffers_validate(unsigned int fsg_num_buffers)
2659{
2660 if (fsg_num_buffers >= 2 && fsg_num_buffers <= 4)
2661 return 0;
2662 pr_err("fsg_num_buffers %u is out of range (%d to %d)\n",
2663 fsg_num_buffers, 2, 4);
2664 return -EINVAL;
2665}
2666
9c610213 2667static struct fsg_common *fsg_common_init(struct fsg_common *common,
481e4929
MN
2668 struct usb_composite_dev *cdev,
2669 struct fsg_config *cfg)
9c610213 2670{
d23b0f08 2671 struct usb_gadget *gadget = cdev->gadget;
9c610213
MN
2672 struct fsg_buffhd *bh;
2673 struct fsg_lun *curlun;
481e4929 2674 struct fsg_lun_config *lcfg;
9c610213 2675 int nluns, i, rc;
d23b0f08 2676 char *pathbuf;
9c610213 2677
6fdc5dd2 2678 rc = fsg_num_buffers_validate(cfg->fsg_num_buffers);
6532c7fd
PF
2679 if (rc != 0)
2680 return ERR_PTR(rc);
2681
9c610213 2682 /* Find out how many LUNs there should be */
481e4929 2683 nluns = cfg->nluns;
9c610213
MN
2684 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2685 dev_err(&gadget->dev, "invalid number of LUNs: %u\n", nluns);
2686 return ERR_PTR(-EINVAL);
2687 }
2688
2689 /* Allocate? */
2690 if (!common) {
2691 common = kzalloc(sizeof *common, GFP_KERNEL);
2692 if (!common)
2693 return ERR_PTR(-ENOMEM);
2694 common->free_storage_on_release = 1;
2695 } else {
a283c03a 2696 memset(common, 0, sizeof *common);
9c610213
MN
2697 common->free_storage_on_release = 0;
2698 }
8ea864cf 2699
6fdc5dd2
AP
2700 common->fsg_num_buffers = cfg->fsg_num_buffers;
2701 common->buffhds = kcalloc(common->fsg_num_buffers,
6532c7fd
PF
2702 sizeof *(common->buffhds), GFP_KERNEL);
2703 if (!common->buffhds) {
2704 if (common->free_storage_on_release)
2705 kfree(common);
2706 return ERR_PTR(-ENOMEM);
2707 }
2708
8876f5e7 2709 common->ops = cfg->ops;
c85efcb9
MN
2710 common->private_data = cfg->private_data;
2711
9c610213 2712 common->gadget = gadget;
8ea864cf
MN
2713 common->ep0 = gadget->ep0;
2714 common->ep0req = cdev->req;
95ed3236 2715 common->cdev = cdev;
8ea864cf
MN
2716
2717 /* Maybe allocate device-global string IDs, and patch descriptors */
2718 if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2719 rc = usb_string_id(cdev);
b9e00088
MN
2720 if (unlikely(rc < 0))
2721 goto error_release;
8ea864cf
MN
2722 fsg_strings[FSG_STRING_INTERFACE].id = rc;
2723 fsg_intf_desc.iInterface = rc;
2724 }
9c610213 2725
b73af61e
MN
2726 /*
2727 * Create the LUNs, open their backing files, and register the
2728 * LUN devices in sysfs.
2729 */
9823a525 2730 curlun = kcalloc(nluns, sizeof(*curlun), GFP_KERNEL);
b9e00088
MN
2731 if (unlikely(!curlun)) {
2732 rc = -ENOMEM;
2733 goto error_release;
9c610213
MN
2734 }
2735 common->luns = curlun;
2736
2737 init_rwsem(&common->filesem);
2738
481e4929
MN
2739 for (i = 0, lcfg = cfg->luns; i < nluns; ++i, ++curlun, ++lcfg) {
2740 curlun->cdrom = !!lcfg->cdrom;
2741 curlun->ro = lcfg->cdrom || lcfg->ro;
3c624d49 2742 curlun->initially_ro = curlun->ro;
481e4929 2743 curlun->removable = lcfg->removable;
9c610213
MN
2744 curlun->dev.release = fsg_lun_release;
2745 curlun->dev.parent = &gadget->dev;
d23b0f08 2746 /* curlun->dev.driver = &fsg_driver.driver; XXX */
9c610213 2747 dev_set_drvdata(&curlun->dev, &common->filesem);
1a12af1a 2748 dev_set_name(&curlun->dev, "lun%d", i);
9c610213
MN
2749
2750 rc = device_register(&curlun->dev);
2751 if (rc) {
2752 INFO(common, "failed to register LUN%d: %d\n", i, rc);
2753 common->nluns = i;
17a93611 2754 put_device(&curlun->dev);
9c610213
MN
2755 goto error_release;
2756 }
2757
48a31af7
MN
2758 rc = device_create_file(&curlun->dev,
2759 curlun->cdrom
2760 ? &dev_attr_ro_cdrom
2761 : &dev_attr_ro);
9c610213
MN
2762 if (rc)
2763 goto error_luns;
48a31af7
MN
2764 rc = device_create_file(&curlun->dev,
2765 curlun->removable
2766 ? &dev_attr_file
2767 : &dev_attr_file_nonremovable);
9cfe745e
MN
2768 if (rc)
2769 goto error_luns;
2770 rc = device_create_file(&curlun->dev, &dev_attr_nofua);
9c610213
MN
2771 if (rc)
2772 goto error_luns;
2773
481e4929
MN
2774 if (lcfg->filename) {
2775 rc = fsg_lun_open(curlun, lcfg->filename);
9c610213
MN
2776 if (rc)
2777 goto error_luns;
481e4929 2778 } else if (!curlun->removable) {
9c610213
MN
2779 ERROR(common, "no file given for LUN%d\n", i);
2780 rc = -EINVAL;
2781 goto error_luns;
2782 }
2783 }
2784 common->nluns = nluns;
2785
9c610213 2786 /* Data buffers cyclic list */
9c610213 2787 bh = common->buffhds;
6fdc5dd2 2788 i = common->fsg_num_buffers;
aae86e8a 2789 goto buffhds_first_it;
9c610213
MN
2790 do {
2791 bh->next = bh + 1;
aae86e8a
MN
2792 ++bh;
2793buffhds_first_it:
2794 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2795 if (unlikely(!bh->buf)) {
2796 rc = -ENOMEM;
2797 goto error_release;
2798 }
2799 } while (--i);
9c610213
MN
2800 bh->next = common->buffhds;
2801
481e4929 2802 /* Prepare inquiryString */
ed9cbda6 2803 i = get_default_bcdDevice();
481e4929 2804 snprintf(common->inquiry_string, sizeof common->inquiry_string,
1ccd7923 2805 "%-8s%-16s%04x", cfg->vendor_name ?: "Linux",
481e4929 2806 /* Assume product name dependent on the first LUN */
1ccd7923 2807 cfg->product_name ?: (common->luns->cdrom
758b463d
AP
2808 ? "File-CD Gadget"
2809 : "File-Stor Gadget"),
481e4929 2810 i);
9c610213 2811
b73af61e
MN
2812 /*
2813 * Some peripheral controllers are known not to be able to
9c610213
MN
2814 * halt bulk endpoints correctly. If one of them is present,
2815 * disable stalls.
2816 */
481e4929 2817 common->can_stall = cfg->can_stall &&
90f79768 2818 !(gadget_is_at91(common->gadget));
9c610213 2819
8ea864cf 2820 spin_lock_init(&common->lock);
9c610213 2821 kref_init(&common->ref);
8ea864cf 2822
8ea864cf
MN
2823 /* Tell the thread to start working */
2824 common->thread_task =
1a12af1a 2825 kthread_create(fsg_main_thread, common, "file-storage");
8ea864cf
MN
2826 if (IS_ERR(common->thread_task)) {
2827 rc = PTR_ERR(common->thread_task);
2828 goto error_release;
2829 }
2830 init_completion(&common->thread_notifier);
b894f60a 2831 init_waitqueue_head(&common->fsg_wait);
e8b6f8c5 2832
d23b0f08
MN
2833 /* Information */
2834 INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2835 INFO(common, "Number of LUNs=%d\n", common->nluns);
2836
2837 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2838 for (i = 0, nluns = common->nluns, curlun = common->luns;
2839 i < nluns;
2840 ++curlun, ++i) {
2841 char *p = "(no medium)";
2842 if (fsg_lun_is_open(curlun)) {
2843 p = "(error)";
2844 if (pathbuf) {
2845 p = d_path(&curlun->filp->f_path,
2846 pathbuf, PATH_MAX);
2847 if (IS_ERR(p))
2848 p = "(error)";
2849 }
2850 }
2851 LINFO(curlun, "LUN: %s%s%sfile: %s\n",
2852 curlun->removable ? "removable " : "",
2853 curlun->ro ? "read only " : "",
2854 curlun->cdrom ? "CD-ROM " : "",
2855 p);
2856 }
2857 kfree(pathbuf);
2858
8ea864cf
MN
2859 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
2860
2861 wake_up_process(common->thread_task);
2862
9c610213
MN
2863 return common;
2864
9c610213
MN
2865error_luns:
2866 common->nluns = i + 1;
2867error_release:
8ea864cf 2868 common->state = FSG_STATE_TERMINATED; /* The thread is dead */
b73af61e 2869 /* Call fsg_common_release() directly, ref might be not initialised. */
9c610213
MN
2870 fsg_common_release(&common->ref);
2871 return ERR_PTR(rc);
2872}
2873
9c610213
MN
2874static void fsg_common_release(struct kref *ref)
2875{
b9e00088 2876 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
9c610213 2877
8ea864cf
MN
2878 /* If the thread isn't already dead, tell it to exit now */
2879 if (common->state != FSG_STATE_TERMINATED) {
2880 raise_exception(common, FSG_STATE_EXIT);
2881 wait_for_completion(&common->thread_notifier);
8ea864cf
MN
2882 }
2883
b9e00088
MN
2884 if (likely(common->luns)) {
2885 struct fsg_lun *lun = common->luns;
2886 unsigned i = common->nluns;
2887
2888 /* In error recovery common->nluns may be zero. */
2889 for (; i; --i, ++lun) {
9cfe745e 2890 device_remove_file(&lun->dev, &dev_attr_nofua);
48a31af7
MN
2891 device_remove_file(&lun->dev,
2892 lun->cdrom
2893 ? &dev_attr_ro_cdrom
2894 : &dev_attr_ro);
2895 device_remove_file(&lun->dev,
2896 lun->removable
2897 ? &dev_attr_file
2898 : &dev_attr_file_nonremovable);
b9e00088
MN
2899 fsg_lun_close(lun);
2900 device_unregister(&lun->dev);
2901 }
9c610213 2902
b9e00088 2903 kfree(common->luns);
9c610213
MN
2904 }
2905
b9e00088
MN
2906 {
2907 struct fsg_buffhd *bh = common->buffhds;
6fdc5dd2 2908 unsigned i = common->fsg_num_buffers;
b9e00088
MN
2909 do {
2910 kfree(bh->buf);
2911 } while (++bh, --i);
2912 }
aae86e8a 2913
6532c7fd 2914 kfree(common->buffhds);
9c610213
MN
2915 if (common->free_storage_on_release)
2916 kfree(common);
2917}
2918
2919
2920/*-------------------------------------------------------------------------*/
2921
d23b0f08 2922static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
d5e2b67a 2923{
d23b0f08 2924 struct fsg_dev *fsg = fsg_from_func(f);
b894f60a 2925 struct fsg_common *common = fsg->common;
d5e2b67a
MN
2926
2927 DBG(fsg, "unbind\n");
b894f60a
MN
2928 if (fsg->common->fsg == fsg) {
2929 fsg->common->new_fsg = NULL;
2930 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2931 /* FIXME: make interruptible or killable somehow? */
2932 wait_event(common->fsg_wait, common->fsg != fsg);
2933 }
2934
2935 fsg_common_put(common);
10287bae 2936 usb_free_all_descriptors(&fsg->function);
9c610213 2937 kfree(fsg);
d5e2b67a
MN
2938}
2939
28824b18 2940static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
d5e2b67a 2941{
d23b0f08
MN
2942 struct fsg_dev *fsg = fsg_from_func(f);
2943 struct usb_gadget *gadget = c->cdev->gadget;
d5e2b67a 2944 int i;
d5e2b67a 2945 struct usb_ep *ep;
10287bae
SAS
2946 unsigned max_burst;
2947 int ret;
d5e2b67a
MN
2948
2949 fsg->gadget = gadget;
d5e2b67a 2950
d23b0f08
MN
2951 /* New interface */
2952 i = usb_interface_id(c, f);
2953 if (i < 0)
2954 return i;
2955 fsg_intf_desc.bInterfaceNumber = i;
2956 fsg->interface_number = i;
d5e2b67a 2957
d5e2b67a 2958 /* Find all the endpoints we will use */
d5e2b67a
MN
2959 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2960 if (!ep)
2961 goto autoconf_fail;
8ea864cf 2962 ep->driver_data = fsg->common; /* claim the endpoint */
d5e2b67a
MN
2963 fsg->bulk_in = ep;
2964
2965 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2966 if (!ep)
2967 goto autoconf_fail;
8ea864cf 2968 ep->driver_data = fsg->common; /* claim the endpoint */
d5e2b67a
MN
2969 fsg->bulk_out = ep;
2970
10287bae
SAS
2971 /* Assume endpoint addresses are the same for both speeds */
2972 fsg_hs_bulk_in_desc.bEndpointAddress =
2973 fsg_fs_bulk_in_desc.bEndpointAddress;
2974 fsg_hs_bulk_out_desc.bEndpointAddress =
2975 fsg_fs_bulk_out_desc.bEndpointAddress;
4bb99b7c 2976
10287bae
SAS
2977 /* Calculate bMaxBurst, we know packet size is 1024 */
2978 max_burst = min_t(unsigned, FSG_BUFLEN / 1024, 15);
4bb99b7c 2979
10287bae
SAS
2980 fsg_ss_bulk_in_desc.bEndpointAddress =
2981 fsg_fs_bulk_in_desc.bEndpointAddress;
2982 fsg_ss_bulk_in_comp_desc.bMaxBurst = max_burst;
4bb99b7c 2983
10287bae
SAS
2984 fsg_ss_bulk_out_desc.bEndpointAddress =
2985 fsg_fs_bulk_out_desc.bEndpointAddress;
2986 fsg_ss_bulk_out_comp_desc.bMaxBurst = max_burst;
4bb99b7c 2987
10287bae
SAS
2988 ret = usb_assign_descriptors(f, fsg_fs_function, fsg_hs_function,
2989 fsg_ss_function);
2990 if (ret)
2991 goto autoconf_fail;
4bb99b7c 2992
d5e2b67a
MN
2993 return 0;
2994
2995autoconf_fail:
2996 ERROR(fsg, "unable to autoconfigure all endpoints\n");
e5fd39d9 2997 return -ENOTSUPP;
d5e2b67a
MN
2998}
2999
d23b0f08 3000/****************************** ADD FUNCTION ******************************/
d5e2b67a 3001
d23b0f08
MN
3002static struct usb_gadget_strings *fsg_strings_array[] = {
3003 &fsg_stringtab,
3004 NULL,
d5e2b67a
MN
3005};
3006
1dc90985
MN
3007static int fsg_bind_config(struct usb_composite_dev *cdev,
3008 struct usb_configuration *c,
3009 struct fsg_common *common)
d5e2b67a 3010{
d23b0f08
MN
3011 struct fsg_dev *fsg;
3012 int rc;
3013
3014 fsg = kzalloc(sizeof *fsg, GFP_KERNEL);
3015 if (unlikely(!fsg))
3016 return -ENOMEM;
d5e2b67a 3017
d23b0f08
MN
3018 fsg->function.name = FSG_DRIVER_DESC;
3019 fsg->function.strings = fsg_strings_array;
d23b0f08
MN
3020 fsg->function.bind = fsg_bind;
3021 fsg->function.unbind = fsg_unbind;
3022 fsg->function.setup = fsg_setup;
3023 fsg->function.set_alt = fsg_set_alt;
3024 fsg->function.disable = fsg_disable;
3025
3026 fsg->common = common;
b73af61e
MN
3027 /*
3028 * Our caller holds a reference to common structure so we
d23b0f08
MN
3029 * don't have to be worry about it being freed until we return
3030 * from this function. So instead of incrementing counter now
3031 * and decrement in error recovery we increment it only when
b73af61e
MN
3032 * call to usb_add_function() was successful.
3033 */
d23b0f08
MN
3034
3035 rc = usb_add_function(c, &fsg->function);
0fb2c2a1 3036 if (unlikely(rc))
e5fd39d9
MN
3037 kfree(fsg);
3038 else
3039 fsg_common_get(fsg->common);
d23b0f08 3040 return rc;
d5e2b67a 3041}
481e4929 3042
481e4929
MN
3043
3044/************************* Module parameters *************************/
3045
481e4929
MN
3046struct fsg_module_parameters {
3047 char *file[FSG_MAX_LUNS];
4b5203f1
FE
3048 bool ro[FSG_MAX_LUNS];
3049 bool removable[FSG_MAX_LUNS];
3050 bool cdrom[FSG_MAX_LUNS];
3051 bool nofua[FSG_MAX_LUNS];
481e4929
MN
3052
3053 unsigned int file_count, ro_count, removable_count, cdrom_count;
9cfe745e 3054 unsigned int nofua_count;
481e4929 3055 unsigned int luns; /* nluns */
4b5203f1 3056 bool stall; /* can_stall */
481e4929
MN
3057};
3058
481e4929
MN
3059#define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
3060 module_param_array_named(prefix ## name, params.name, type, \
3061 &prefix ## params.name ## _count, \
3062 S_IRUGO); \
3063 MODULE_PARM_DESC(prefix ## name, desc)
3064
3065#define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
3066 module_param_named(prefix ## name, params.name, type, \
3067 S_IRUGO); \
3068 MODULE_PARM_DESC(prefix ## name, desc)
3069
6fdc5dd2 3070#define __FSG_MODULE_PARAMETERS(prefix, params) \
481e4929
MN
3071 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
3072 "names of backing files or devices"); \
3073 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
3074 "true to force read-only"); \
3075 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
3076 "true to simulate removable media"); \
3077 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
3078 "true to simulate CD-ROM instead of disk"); \
9cfe745e
MN
3079 _FSG_MODULE_PARAM_ARRAY(prefix, params, nofua, bool, \
3080 "true to ignore SCSI WRITE(10,12) FUA bit"); \
481e4929
MN
3081 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
3082 "number of LUNs"); \
3083 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
3084 "false to prevent bulk stalls")
3085
6fdc5dd2
AP
3086#ifdef CONFIG_USB_GADGET_DEBUG_FILES
3087
3088#define FSG_MODULE_PARAMETERS(prefix, params) \
3089 __FSG_MODULE_PARAMETERS(prefix, params); \
3090 module_param_named(num_buffers, fsg_num_buffers, uint, S_IRUGO);\
3091 MODULE_PARM_DESC(num_buffers, "Number of pipeline buffers")
3092#else
3093
3094#define FSG_MODULE_PARAMETERS(prefix, params) \
3095 __FSG_MODULE_PARAMETERS(prefix, params)
3096
3097#endif
3098
3099
481e4929
MN
3100static void
3101fsg_config_from_params(struct fsg_config *cfg,
6fdc5dd2
AP
3102 const struct fsg_module_parameters *params,
3103 unsigned int fsg_num_buffers)
481e4929
MN
3104{
3105 struct fsg_lun_config *lun;
d26a6aa0 3106 unsigned i;
481e4929
MN
3107
3108 /* Configure LUNs */
d26a6aa0
MN
3109 cfg->nluns =
3110 min(params->luns ?: (params->file_count ?: 1u),
3111 (unsigned)FSG_MAX_LUNS);
3112 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
481e4929
MN
3113 lun->ro = !!params->ro[i];
3114 lun->cdrom = !!params->cdrom[i];
fa84c575 3115 lun->removable = !!params->removable[i];
481e4929
MN
3116 lun->filename =
3117 params->file_count > i && params->file[i][0]
3118 ? params->file[i]
136c489b 3119 : NULL;
481e4929
MN
3120 }
3121
d26a6aa0 3122 /* Let MSF use defaults */
136c489b
JH
3123 cfg->vendor_name = NULL;
3124 cfg->product_name = NULL;
481e4929 3125
8876f5e7
MN
3126 cfg->ops = NULL;
3127 cfg->private_data = NULL;
c85efcb9 3128
481e4929
MN
3129 /* Finalise */
3130 cfg->can_stall = params->stall;
6fdc5dd2 3131 cfg->fsg_num_buffers = fsg_num_buffers;
481e4929
MN
3132}
3133
3134static inline struct fsg_common *
3135fsg_common_from_params(struct fsg_common *common,
3136 struct usb_composite_dev *cdev,
6fdc5dd2
AP
3137 const struct fsg_module_parameters *params,
3138 unsigned int fsg_num_buffers)
481e4929
MN
3139 __attribute__((unused));
3140static inline struct fsg_common *
3141fsg_common_from_params(struct fsg_common *common,
3142 struct usb_composite_dev *cdev,
6fdc5dd2
AP
3143 const struct fsg_module_parameters *params,
3144 unsigned int fsg_num_buffers)
481e4929
MN
3145{
3146 struct fsg_config cfg;
6fdc5dd2 3147 fsg_config_from_params(&cfg, params, fsg_num_buffers);
481e4929
MN
3148 return fsg_common_init(common, cdev, &cfg);
3149}
This page took 0.474711 seconds and 5 git commands to generate.