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