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